aboutsummaryrefslogtreecommitdiff
path: root/src/client/documents/Documents.ts
blob: 6371c4e9da2b56b432ade6c146dc340c7d096643 (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
/* eslint-disable no-use-before-define */
import { reaction } from 'mobx';
import { basename } from 'path';
import { ClientUtils, OmitKeys } from '../../ClientUtils';
import { DateField } from '../../fields/DateField';
import { CreateLinkToActiveAudio, Doc, FieldType, Opt, updateCachedAcls } from '../../fields/Doc';
import { Id } from '../../fields/FieldSymbols';
import { HtmlField } from '../../fields/HtmlField';
import { InkField } from '../../fields/InkField';
import { List } from '../../fields/List';
import { RichTextField } from '../../fields/RichTextField';
import { SchemaHeaderField } from '../../fields/SchemaHeaderField';
import { ComputedField, ScriptField } from '../../fields/ScriptField';
import { ScriptCast, StrCast } from '../../fields/Types';
import { AudioField, CsvField, ImageField, PdfField, VideoField, WebField } from '../../fields/URLField';
import { SharingPermissions } from '../../fields/util';
import { PointData } from '../../pen-gestures/GestureTypes';
import { DocServer } from '../DocServer';
import { dropActionType } from '../util/DropActionTypes';
import { CollectionViewType, DocumentType } from './DocumentTypes';

class EmptyBox {
    public static LayoutString() {
        return '';
    }
}

export enum FInfoFieldType {
    string = 'string',
    boolean = 'boolean',
    number = 'number',
    // eslint-disable-next-line @typescript-eslint/no-shadow
    Doc = 'Doc',
    enumeration = 'enum',
    date = 'date',
    list = 'list',
    rtf = 'richtext',
    map = 'map',
}
export class FInfo {
    description: string = '';
    readOnly: boolean = false;
    fieldType?: FInfoFieldType;
    values?: FieldType[];
    filterable?: boolean = true; // can be used as a Filter in FilterPanel
    // format?: string; // format to display values (e.g, decimal places, $, etc)
    // parse?: ScriptField; // parse a value from a string
    constructor(d: string, readOnly?: boolean) {
        this.description = d;
        this.readOnly = readOnly ?? false;
    }
    searchable = () => true;
}
class BoolInfo extends FInfo {
    fieldType? = FInfoFieldType.boolean;
    values?: boolean[] = [true, false];
    constructor(d: string, filterable?: boolean) {
        super(d);
        this.filterable = filterable;
    }
    override searchable = () => false;
}
class NumInfo extends FInfo {
    fieldType? = FInfoFieldType.number;
    values?: number[] = [];
    constructor(d: string, filterable?: boolean, readOnly?: boolean, values?: number[]) {
        super(d, readOnly);
        this.values = values;
        this.filterable = filterable;
    }
    override searchable = () => false;
}
class StrInfo extends FInfo {
    fieldType? = FInfoFieldType.string;
    values?: string[] = [];
    constructor(d: string, filterable?: boolean, readOnly?: boolean, values?: string[]) {
        super(d, readOnly);
        this.values = values;
        this.filterable = filterable;
    }
}
class DocInfo extends FInfo {
    fieldType? = FInfoFieldType.Doc;
    values?: Doc[] = [];
    constructor(d: string, filterable?: boolean, values?: Doc[]) {
        super(d, true);
        this.values = values;
        this.filterable = filterable;
    }
    override searchable = () => false;
}
class DimInfo extends FInfo {
    fieldType? = FInfoFieldType.enumeration;
    values? = []; // DimUnit.Pixel, DimUnit.Ratio];
    readOnly = false;
    filterable = false;
    override searchable = () => false;
}
class PEInfo extends FInfo {
    fieldType? = FInfoFieldType.enumeration;
    values? = ['all', 'none'];
    readOnly = false;
    filterable = false;
    override searchable = () => false;
}
class DAInfo extends FInfo {
    fieldType? = FInfoFieldType.enumeration;
    values? = ['embed', 'copy', 'move', 'same', 'add', 'inSame', 'proto'];
    readOnly = false;
    filterable = false;
    override searchable = () => false;
}
class CTypeInfo extends FInfo {
    fieldType? = FInfoFieldType.enumeration;
    values? = Array.from(Object.keys(CollectionViewType));
    readOnly = false;
    filterable = false;
    override searchable = () => false;
}
class DTypeInfo extends FInfo {
    fieldType? = FInfoFieldType.enumeration;
    values? = Array.from(Object.keys(DocumentType));
    override searchable = () => false;
}
class DateInfo extends FInfo {
    constructor(d: string, filterable?: boolean) {
        super(d, true);
        this.filterable = filterable;
    }
    fieldType? = FInfoFieldType.date;
    values?: DateField[] = [];
}
class RtfInfo extends FInfo {
    constructor(d: string, filterable?: boolean) {
        super(d);
        this.filterable = filterable;
    }
    fieldType? = FInfoFieldType.rtf;
}
class ListInfo extends FInfo {
    fieldType? = FInfoFieldType.list;
    values?: List<FieldType>[] = [];
}
type BOOLt = BoolInfo | boolean;
type NUMt = NumInfo | number;
type STRt = StrInfo | string;
type LISTt = ListInfo | List<FieldType>;
type DOCt = DocInfo | Doc;
type RTFt = RtfInfo | RichTextField;
type DIMt = DimInfo; // | typeof DimUnit.Pixel | typeof DimUnit.Ratio;
type PEVt = PEInfo | 'none' | 'all';
type COLLt = CTypeInfo | CollectionViewType;
type DROPt = DAInfo | dropActionType;
type DATEt = DateInfo | number;
type DTYPEt = DTypeInfo | string;
export class DocumentOptions {
    [key: string]: FInfo | FieldType | undefined;
    // coordinate and dimensions depending on view
    x?: NUMt = new NumInfo('horizontal coordinate in freeform view', false);
    y?: NUMt = new NumInfo('vertical coordinate in freeform view', false);
    z?: NUMt = new NumInfo('whether document is in overlay (1) or not (0)', false, false, [1, 0]);
    zIndex?: NUMt = new NumInfo('stacking index of documents in freeform view (higher numbers are towards the top');
    overlayX?: NUMt = new NumInfo('horizontal coordinate in overlay view', false);
    overlayY?: NUMt = new NumInfo('vertical coordinate in overlay view', false);
    embedContainer?: DOCt = new DocInfo('document that displays (contains) this document', false);

    text?: RTFt = new RtfInfo('plain or rich text', true);
    text_html?: STRt = new StrInfo('plain text or html', true);
    _dimMagnitude?: NUMt = new NumInfo("magnitude of collectionMulti{row,col} element's width or height", false);
    _dimUnit?: DIMt = new DimInfo("units of collectionMulti{row,col} element's width or height - 'px' or '*' for pixels or relative units");
    latitude?: NUMt = new NumInfo('latitude coordinate', false);
    longitude?: NUMt = new NumInfo('longitude coordinate', false);
    routeCoordinates?: STRt = new StrInfo("stores a route's/direction's coordinates (stringified version)"); // for a route document, this stores the route's coordinates
    markerType?: STRt = new StrInfo('marker type for a pushpin document');
    markerColor?: STRt = new StrInfo('marker color for a pushpin document');
    map?: STRt = new StrInfo('map location name');
    map_type?: STRt = new StrInfo('type of map view', false);
    map_zoom?: NUMt = new NumInfo('zoom of a map view', false);
    map_pitch?: NUMt = new NumInfo('pitch of a map view', false);
    map_bearing?: NUMt = new NumInfo('bearing of a map view', false);
    map_style?: STRt = new StrInfo('mapbox style for a map view', false);
    identifier?: STRt = new StrInfo('documentIcon displayed for each doc as "d[x]"', false);
    _rotation?: NUMt = new NumInfo('Amount of rotation on a document in degrees', false);

    date_range?: STRt = new StrInfo('date range for calendar', false);

    chat?: STRt = new StrInfo('fields related to chatBox', false);
    chat_history?: STRt = new StrInfo('chat history for chatbox', false);
    chat_thread_id?: STRt = new StrInfo('thread id for chatbox', false);
    chat_assistant_id?: STRt = new StrInfo('assistant id for chatbox', false);
    chat_vector_store_id?: STRt = new StrInfo('assistant id for chatbox', false);

    wikiData?: STRt = new StrInfo('WikiData ID related to map location');
    description?: STRt = new StrInfo('description of document');
    _timecodeToShow?: NUMt = new NumInfo('media timecode when document should appear (e.g., when an annotation shows up as a video plays)', false);
    _timecodeToHide?: NUMt = new NumInfo('media timecode when document should disappear', false);
    _width?: NUMt = new NumInfo("width of document in container's coordinates");
    _height?: NUMt = new NumInfo("height of document in container's coordiantes");
    data_nativeWidth?: NUMt = new NumInfo('native width of data field contents (e.g., the pixel width of an image)', false);
    data_nativeHeight?: NUMt = new NumInfo('native height of data field contents (e.g., the pixel height of an image)', false);
    _nativeWidth?: NUMt = new NumInfo('Deprecated: use nativeWidth. native width of document contents (e.g., the pixel width of an image)', false);
    _nativeHeight?: NUMt = new NumInfo('Deprecated: use nativeHeight. native height of document contents (e.g., the pixel height of an image)', false);
    nativeWidth?: NUMt = new NumInfo('native width of document contents (e.g., the pixel width of an image)', false);
    nativeHeight?: NUMt = new NumInfo('native height of document contents (e.g., the pixel height of an image)', false);

    acl?: STRt = new StrInfo('unused except as a display category in KeyValueBox');
    acl_Guest?: STRt = new StrInfo("permissions granted to users logged in as 'guest' (either view, or private)"); // public permissions
    _acl_Guest?: string; // public permissions
    type?: DTYPEt = new DTypeInfo('type of document', true);
    type_collection?: COLLt = new CTypeInfo('how collection is rendered'); // sub type of a collection
    _type_collection?: COLLt = new CTypeInfo('how collection is rendered'); // sub type of a collection
    title?: STRt = new StrInfo('title of document', true);
    title_custom?: BOOLt = new BoolInfo('whether title is a default or has been intentionally set');
    caption?: RichTextField;
    systemIcon?: STRt = new StrInfo("name of icon to use to represent document's type");
    author?: string; // STRt = new StrInfo('creator of document'); // bcz: don't change this. Otherwise, the userDoc's field Infos will have a FieldInfo assigned to its author field which will render it unreadable
    author_date?: DATEt = new DateInfo('date the document was created', true);
    annotationOn?: DOCt = new DocInfo('document annotated by this document', false);
    rootDocument?: DOCt = new DocInfo('document that stores the data for compound template documents.');
    color?: STRt = new StrInfo('foreground color data doc', false);
    hidden?: BOOLt = new BoolInfo('whether the document is not rendered by its collection', false);
    backgroundColor?: STRt = new StrInfo('background color for data doc', false);
    opacity?: NUMt = new NumInfo('document opacity', false);
    viewTransitionTime?: NUMt = new NumInfo('transition duration for view parameters', false);
    dontRegisterView?: BOOLt = new BoolInfo('are views of this document registered so that they can be found when following links, etc', false);
    _undoIgnoreFields?: List<string>; // 'fields that should not be added to the undo stack (opacity for Undo/Redo/and sidebar) AND whether modifications to document are undoable (true for linearview menu buttons to prevent open/close from entering undo stack)'
    undoIgnoreFields?: List<string>; // 'fields that should not be added to the undo stack (opacity for Undo/Redo/and sidebar) AND whether modifications to document are undoable (true for linearview menu buttons to prevent open/close from entering undo stack)'
    _header_height?: NUMt = new NumInfo('height of document header used for displaying title', false);
    _header_fontSize?: NUMt = new NumInfo('font size of header of custom notes', false);
    _header_pointerEvents?: PEVt = new PEInfo('types of events the header of a custom text document can consume');
    _lockedPosition?: BOOLt = new BoolInfo("lock the x,y coordinates of the document so that it can't be dragged");
    _lockedTransform?: BOOLt = new BoolInfo('lock the freeform_panx,freeform_pany and scale parameters of the document so that it be panned/zoomed');
    _childrenSharedWithSchema?: BOOLt = new BoolInfo("whether this document's children are displayed in its parent schema view", false);
    _lockedSchemaEditing?: BOOLt = new BoolInfo('', false);

    dataViz_title?: string;
    dataViz_line?: string;
    dataViz_pie?: string;
    dataViz_histogram?: string;
    dataViz?: string;
    dataViz_savedTemplates?: LISTt;

    borderWidth?: NUMt = new NumInfo('Width of docuent border', false);
    borderColor?: STRt = new StrInfo('Color of document border', false);
    text_fontColor?: STRt = new StrInfo('Color of text', false);
    hCentering?: 'h-left' | 'h-center' | 'h-right';
    isDefaultTemplateDoc?: BOOLt = new BoolInfo('');
    contentBold?: BOOLt = new BoolInfo('');

    layout?: string | Doc; // default layout string or template document
    layout_isSvg?: BOOLt = new BoolInfo('whether document decorations and other selections should handle pointerEvents for svg content or use doc bounding box');
    layout_keyValue?: STRt = new StrInfo('layout definition for showing keyValue view of document', false);
    layout_explainer?: STRt = new StrInfo('explanation displayed at top of a collection to describe its purpose', false);
    layout_headerButton?: DOCt = new DocInfo('the (button) Doc to display at the top of a collection.', false);
    layout_disableBrushing?: BOOLt = new BoolInfo('whether to suppress border highlighting');
    layout_unrendered?: BOOLt = new BoolInfo('denotes an annotation that is not rendered with a DocumentView (e.g, rtf/pdf text selections and links to scroll locations in web/pdf)');
    layout_hideOpenButton?: BOOLt = new BoolInfo('whether to hide the open full screen button when selected');
    layout_hideDocumentButtonBar?: BOOLt = new BoolInfo('whether to hide the document decorations lower button bar when selected');
    layout_hideLinkAnchors?: BOOLt = new BoolInfo('suppresses link anchor dots from being displayed');
    layout_hideAllLinks?: BOOLt = new BoolInfo('whether all individual blue anchor dots should be hidden');
    layout_hideResizeHandles?: BOOLt = new BoolInfo('whether to hide the resize handles when selected');
    layout_hideLinkButton?: BOOLt = new BoolInfo('whether the blue link counter button should be hidden');
    layout_hideDecorationTitle?: BOOLt = new BoolInfo('whether to suppress the document decortations title when selected');
    layout_hideDecorations?: BOOLt = new BoolInfo('whether to suppress all document decortations when selected');
    _layout_hideContextMenu?: BOOLt = new BoolInfo('whether the context menu can be shown');
    layout_diagramEditor?: STRt = new StrInfo('specify the JSX string for a diagram editor view');
    layout_hideContextMenu?: BOOLt = new BoolInfo('whether the context menu can be shown');
    layout_borderRounding?: string;
    _layout_borderRounding?: STRt = new StrInfo('amount of rounding to document view corners');
    _layout_modificationDate?: DATEt = new DateInfo('last modification date of doc layout', false);
    _layout_nativeDimEditable?: BOOLt = new BoolInfo('native dimensions can be modified using document decoration reizers', false);
    _layout_reflowVertical?: BOOLt = new BoolInfo('permit vertical resizing with content "reflow"');
    _layout_reflowHorizontal?: BOOLt = new BoolInfo('permit horizontal resizing with content reflow');
    _layout_noSidebar?: BOOLt = new BoolInfo('whether to display the sidebar toggle button');
    layout_boxShadow?: string; // box-shadow css string OR "standard" to use dash standard box shadow
    _iframe_sandbox?: STRt = new StrInfo('sandbox attributes for iframes in web documents (e.g., allow-scripts, allow-same-origin)');
    layout_maxShown?: NUMt = new NumInfo('maximum number of children to display at one time (see multicolumnview)');
    _layout_columnWidth?: NUMt = new NumInfo('width of table column', false);
    _layout_columnCount?: NUMt = new NumInfo('number of columns in a masonry view');
    _layout_dontCenter?: STRt = new StrInfo("whether collections will center their content - values of 'x', 'xy', or 'y'");
    _layout_autoHeight?: BOOLt = new BoolInfo('whether document automatically resizes vertically to display contents');
    _layout_autoHeightMargins?: NUMt = new NumInfo('Margin heights to be added to the computed auto height of a Doc');
    _layout_curPage?: NUMt = new NumInfo('current page of a PDF or other? paginated document', false);
    _layout_currentTimecode?: NUMt = new NumInfo('the current timecode of a time-based document (e.g., current time of a video)  value is in seconds', false);
    _layout_fitWidth?: BOOLt = new BoolInfo('whether document should scale its contents to fit its rendered width or not (e.g., for PDFviews)');
    layout_fieldKey?: STRt = new StrInfo('the field key containing the current layout definition', false);
    _layout_enableAltContentUI?: BOOLt = new BoolInfo('whether to show alternate content button');
    _layout_flashcardType?: STRt = new StrInfo('flashcard style to render in ComparisonBox.  currently just "flashcard".');
    _layout_showTitle?: string; // field name to display in header (:hover is an optional suffix)
    _layout_showSidebar?: BOOLt = new BoolInfo('whether an annotationsidebar should be displayed for text docuemnts');
    _layout_showCaption?: string; // which field to display in the caption area.  leave empty to have no caption
    _layout_showTags?: BOOLt = new BoolInfo('whether to show the list of document tags at the bottom of a DocView');

    _chromeHidden?: BOOLt = new BoolInfo('whether the editing chrome for a document is hidden');
    hideClickBehaviors?: BOOLt = new BoolInfo('whether to hide click behaviors in context menu');
    _gridGap?: NUMt = new NumInfo('gap between items in masonry view', false);
    _xMargin?: NUMt = new NumInfo('gap between left edge of document and contents of freeform/masonry/stacking layouts', false);
    _yMargin?: NUMt = new NumInfo('gap between top edge of dcoument and contents offreeform/masonry/stacking layouts', false);
    _createDocOnCR?: boolean; // whether carriage returns and tabs create new text documents
    _columnsHideIfEmpty?: BOOLt = new BoolInfo('whether stacking view column headings should be hidden');
    _caption_xMargin?: NUMt = new NumInfo('x margin of caption inside of a carousel collection', false, true);
    _caption_yMargin?: NUMt = new NumInfo('y margin of caption inside of a carousel collection', false, true);
    icon_nativeWidth?: NUMt = new NumInfo('native width of icon view', false, true);
    icon_nativeHeight?: NUMt = new NumInfo('native height of icon view', false, true);
    text_fontSize?: string;
    text_fontFamily?: string;
    text_fontWeight?: string;
    text_centered?: BOOLt = new BoolInfo('whether text should be vertically centered in Doc');
    text_fitBox?: BOOLt = new BoolInfo("whether text box should be scaled to fit it's containing render box");
    text_align?: STRt = new StrInfo('horizontal text alignment default', undefined, undefined, ['left', 'center', 'right']);
    title_align?: STRt = new StrInfo('horizontal title alignment in label box', undefined, undefined, ['left', 'center', 'right']);
    title_transform?: STRt = new StrInfo('transformation to apply to title in label box (eg., uppercase)', undefined, undefined, ['uppercase', 'lowercase', 'capitalize']);
    text_transform?: STRt = new StrInfo('transformation to apply to text in text box (eg., uppercase)', undefined, undefined, ['uppercase', 'lowercase', 'capitalize']);
    text_placeholder?: BOOLt = new BoolInfo('makes the text act like a placeholder and automatically select when the text box is selected');
    fontSize?: string;
    _pivotField?: string; // field key used to determine headings for sections in stacking, masonry, pivot views

    infoWindowOpen?: BOOLt = new BoolInfo('whether info window corresponding to pin is open (on MapDocuments)');
    _carousel_index?: NUMt = new NumInfo('which item index the carousel viewer is showing');
    _label_minFontSize?: NUMt = new NumInfo('minimum font size for labelBoxes', false);
    _label_maxFontSize?: NUMt = new NumInfo('maximum font size for labelBoxes', false);
    stroke_width?: NUMt = new NumInfo('width of an ink stroke', false);
    stroke_showLabel?: BOOLt = new BoolInfo('show label inside of stroke');
    mediaState?: STRt = new StrInfo(`status of audio/video media document:`); // ${mediaState.PendingRecording}, ${mediaState.Recording}, ${mediaState.Paused}, ${mediaState.Playing}`, false);
    recording?: BOOLt = new BoolInfo('whether WebCam is recording or not');
    slides?: DOCt = new DocInfo('presentation slide associated with video recording (bcz: should be renamed!!)');
    autoPlayAnchors?: BOOLt = new BoolInfo('whether to play audio/video when an anchor is clicked in a stackedTimeline.');
    dontPlayLinkOnSelect?: BOOLt = new BoolInfo('whether an audio/video should start playing when a link is followed to it.');
    openFactoryLocation?: string; // an OpenWhere value to place the factory created document
    openFactoryAsDelegate?: boolean; //
    onViewMounted?: ScriptField; // reactive script invoked Doc is viewed (used by showBackLinks view to update collection of links to Doc)
    toolTip?: string; // tooltip to display on hover
    toolType?: string; // type of pen tool
    expertMode?: BOOLt = new BoolInfo('something available only in expert (not novice) mode');

    contextMenuFilters?: List<ScriptField>;
    contextMenuScripts?: List<ScriptField>;
    contextMenuLabels?: List<string>;
    contextMenuIcons?: List<string>;
    childContentPointerEvents?: string; // pointer events allowed for content of a document view.  eg. set to "none" in menuSidebar for sharedDocs so that you can select a document, but not interact with its contents
    childFilters_boolean?: STRt = new StrInfo('boolean operator to apply to filters on different metadata fields. Value should be AND or OR. Default is AND');
    childFilters?: List<string>;
    childLimitHeight?: NUMt = new NumInfo('whether to limit the height of collection children.  0 - means  height can be no bigger than width', false);
    childLayoutTemplate?: Doc; // template for collection to use to render its children (see PresBox layout in tree view)
    childLayoutString?: STRt = new StrInfo('JSX layout string for rendering children of a (collection) Doc'); // template string for collection to use to render its children
    childDocumentsActive?: BOOLt = new BoolInfo('whether child documents are active when parent is document active');
    childLayoutFitWidth?: BOOLt = new BoolInfo("whether a child doc's fitWith should be overriden by collection");
    childDontRegisterViews?: BOOLt = new BoolInfo('whether child document views should be registered so that they can be found when following links, etc');
    childHideLinkButton?: BOOLt = new BoolInfo('hide link buttons on all children');
    childContextMenuFilters?: List<ScriptField>;
    childContextMenuScripts?: List<ScriptField>;
    childContextMenuLabels?: List<string>;
    childContextMenuIcons?: List<string>;
    targetScriptKey?: string; // where to write a template script (used by collections with click templates which need to target onClick, onDoubleClick, etc)

    lastFrame?: NUMt = new NumInfo('the last frame of a frame-based collection (e.g., progressive slide)', false);
    activeFrame?: NUMt = new NumInfo('the active frame of a document in a frame base collection', false);
    appearFrame?: NUMt = new NumInfo('the frame in which the document appears', false);
    _currentFrame?: NUMt = new NumInfo('the current frame of a frame-based collection (e.g., progressive slide)', false);

    isSystem?: BOOLt = new BoolInfo('is this a system created/owned doc', false);
    isBaseProto?: BOOLt = new BoolInfo('is doc a base level prototype for data documents as opposed to data documents which are prototypes for layout documents.  base protos are not cloned during a deep');
    isTemplateForField?: string; // the field key for which the containing document is a rendering template
    isTemplateDoc?: BOOLt = new BoolInfo('is the document a template for creating other documents');
    isGroup?: BOOLt = new BoolInfo('should collection use a grouping UI behavior');
    isFolder?: BOOLt = new BoolInfo('is document a tree view folder');
    _isTimelineLabel?: BOOLt = new BoolInfo('is document a timeline label');
    isLightbox?: BOOLt = new BoolInfo('whether a collection acts as a lightbox by opening lightbox links by hiding all other documents in collection besides link target');
    cloneOnCopy?: BOOLt = new BoolInfo('if this Doc is a field of another Doc, then it should be copied when the other Doc is copied');

    mapPin?: DOCt = new DocInfo('pin associated with a config anchor', false);
    config_latitude?: NUMt = new NumInfo('latitude of a map', false);
    config_longitude?: NUMt = new NumInfo('longitude of map', false);
    config_map_zoom?: NUMt = new NumInfo('zoom of map', false);
    config_map_type?: STRt = new StrInfo('map view type (e.g, aerial)', false);
    config_map?: STRt = new StrInfo('text location of map', false);
    config_panX?: NUMt = new NumInfo('panX saved as a view spec', false);
    config_panY?: NUMt = new NumInfo('panY saved as a view spec', false);
    config_zoom?: NUMt = new NumInfo('zoom saved as a view spec', false);
    config_carousel_index?: NUMt = new NumInfo('saved carousel index', false);
    config_card_curDoc?: DOCt = new DocInfo('current doc in a collection view, e.g., cardView');
    config_viewScale?: NUMt = new NumInfo('viewScale saved as a view Spec', false);
    presentation_transition?: NUMt = new NumInfo('the time taken for the transition TO a document', false);
    presentation_duration?: NUMt = new NumInfo('the duration of the slide in presentation view', false);
    presentation_zoomText?: BOOLt = new BoolInfo('whether text anchors should shown in a larger box when following links to make them stand out', false);

    data_annotations?: List<Doc>;
    _data_usePath?: STRt = new StrInfo("description of field key to display in image box ('alternate','alternate:hover', 'data:hover'). defaults to primary", false);
    data_alternates?: List<Doc>;
    data?: FieldType;
    data_useCors?: BOOLt = new BoolInfo('whether CORS protocol should be used for web page');
    _face_showImages?: BOOLt = new BoolInfo('whether to show images in uniqe face Doc');
    face?: DOCt = new DocInfo('face document');
    faceDescriptor?: List<number>;
    columnHeaders?: List<SchemaHeaderField>; // headers for stacking views
    schemaHeaders?: List<SchemaHeaderField>; // headers for schema view
    dockingConfig?: STRt = new StrInfo('configuration of golden layout windows (applies only if doc is rendered as a CollectionDockingView)', false);
    icon?: string; // icon used by fonticonbox to render button
    noteType?: string;

    // STOPPING HERE

    // freeform properties
    freeform?: STRt = new StrInfo('');
    _freeform_backgroundGrid?: BOOLt = new BoolInfo('whether background grid is shown on freeform collections');
    _freeform_scale_min?: NUMt = new NumInfo('how far out a view can zoom (used by image/videoBoxes that are clipped');
    _freeform_scale_max?: NUMt = new NumInfo('how far in a view can zoom (used by sidebar freeform views');
    _freeform_scale?: NUMt = new NumInfo('how much a freeform view has been scaled (zoomed)');
    _freeform_panX?: NUMt = new NumInfo('horizontal pan location of a freeform view');
    _freeform_panY?: NUMt = new NumInfo('vertical pan location of a freeform view');
    _freeform_noAutoPan?: BOOLt = new BoolInfo('disables autopanning when this item is dragged');
    _freeform_noZoom?: BOOLt = new BoolInfo('disables zooming (used by Pile docs)');
    _freeform_fitContentsToBox?: BOOLt = new BoolInfo('whether a freeformview should zoom/scale to create a shrinkwrapped view of its content');

    // BUTTONS
    buttonText?: string;
    btnType?: string;
    btnList?: List<string>;
    docColorBtn?: string;
    userColorBtn?: string;
    script?: ScriptField;
    numBtnMax?: NUMt = new NumInfo('maximum value of a number button');
    numBtnMin?: NUMt = new NumInfo('minimum value of a number button');
    switchToggle?: boolean;
    badgeValue?: ScriptField;

    // LINEAR VIEW
    linearView_btnWidth?: NUMt = new NumInfo('unexpanded width of a linear menu button (button "width" changes when it expands)', false);
    linearView_isOpen?: BOOLt = new BoolInfo('is linear view open');
    linearView_expandable?: BOOLt = new BoolInfo('can linear view be expanded');
    flexGap?: NUMt = new NumInfo('Linear view flex gap');
    flexDirection?: 'unset' | 'row' | 'column' | 'row-reverse' | 'column-reverse';

    // Comparison
    data_revealOp?: STRt = new StrInfo("visual reveal type for front and back of comparison - 'slide' or 'flip' ");
    data_revealOp_hover?: BOOLt = new BoolInfo('reveal back of comparison manually or by hovering');
    data_front?: DOCt = new DocInfo('contents of front of flashcard/comparison');
    data_back?: DOCt = new DocInfo('contents of back of flashcard/comparison');

    link?: string;
    link_description?: string; // added for links
    link_relationship?: string; // type of relatinoship a link represents
    link_displayArrow?: BOOLt = new BoolInfo("whether to display link's directional arrowhead");
    link_anchor_1?: DOCt = new DocInfo('start anchor of a link');
    link_anchor_2?: DOCt = new DocInfo('end anchor of a link');
    link_autoMoveAnchors?: BOOLt = new BoolInfo('whether link endpoint should move around the edges of a document to make shortest path to other link endpoint');
    link_anchor_1_useSmallAnchor?: BOOLt = new BoolInfo('whether link_anchor_1 of a link should use a miniature anchor dot (as when the anchor is a text selection)');
    link_anchor_2_useSmallAnchor?: BOOLt = new BoolInfo('whether link_anchor_1 of a link should use a miniature anchor dot (as when the anchor is a text selection)');
    link_relationshipList?: List<string>; // for storing different link relationships (when set by user in the link editor)
    link_relationshipSizes?: List<number>; // stores number of links contained in each relationship
    link_colorList?: List<string>; // colors of links corresponding to specific link relationships
    followLinkZoom?: BOOLt = new BoolInfo('whether to zoom to the target of a link');
    followLinkToggle?: BOOLt = new BoolInfo('whether target of link should be toggled on and off when following a link to it');
    followLinkLocation?: STRt = new StrInfo('where to open link target when following link');
    followLinkAnimEffect?: STRt = new StrInfo('animation effect triggered on target of link');
    followLinkAnimDirection?: STRt = new StrInfo('direction modifier for animation effect');

    ignoreClick?: BOOLt = new BoolInfo('whether clicks on document should be ignored');
    onClick?: ScriptField;
    onDoubleClick?: ScriptField;
    onChildClick?: ScriptField; // script given to children of a collection to execute when they are clicked
    onChildDoubleClick?: ScriptField; // script given to children of a collection to execute when they are double clicked
    onClickScriptDisable?: STRt = new StrInfo('"always" disable click script, "never" disable click script, or default');
    defaultDoubleClick?: 'ignore' | 'default'; // ignore double clicks, or default (undefined) means open document full screen
    waitForDoubleClickToClick?: 'always' | 'never' | 'default'; // whether a click function wait for double click to expire.  'default' undefined = wait only if there's a click handler, "never" = never wait, "always" = alway wait
    onPointerDown?: ScriptField;
    onPointerUp?: ScriptField;
    _forceActive?: BOOLt = new BoolInfo('flag to handle pointer events when not selected (or otherwise active)');
    _dragOnlyWithinContainer?: BOOLt = new BoolInfo('whether the document should remain in its collection when someone tries to drag and drop it elsewhere');
    _keepZWhenDragged?: BOOLt = new BoolInfo('whether a document should keep its z-order when dragged.');
    childDragAction?: DROPt = new DAInfo('what should happen to the child documents when they are dragged from the collection');
    dropConverter?: ScriptField; // script to run when documents are dropped on this Document.
    dropAction?: DROPt = new DAInfo("what should happen to this document when it's dropped somewhere else");
    _dropAction?: DROPt = new DAInfo("what should happen to this document when it's dropped somewhere else");
    _dropPropertiesToRemove?: List<string>; // list of properties that should be removed from a document when it is dropped.  e.g., a creator button may be forceActive to allow it be dragged, but the forceActive property can be removed from the dropped document
    cloneFieldFilter?: List<string>; // fields not to copy when the document is clonedclipboard?: Doc;
    dragWhenActive?: BOOLt = new BoolInfo('should document drag when it is active instead of interacting with its contents - e.g., pileView, group');
    dragAction?: DROPt = new DAInfo('how to drag document when it is active (e.g., tree, groups)');
    dragFactory_count?: NUMt = new NumInfo('number of items created from a drag button (used for setting title with incrementing index)', false, true);
    dragFactory?: DOCt = new DocInfo('document to create when dragging with a suitable onDragStart script', false);
    clickFactory?: DOCt = new DocInfo('document to create when clicking on a button with a suitable onClick script', false);
    onDragStart?: ScriptField; // script to execute at start of drag operation --  e.g., when a "creator" button is dragged this script generates a different document to drop
    target?: Doc; // available for use in scripts.  used to provide a document parameter to the script (Note, this is a convenience entry since any field could be used for parameterizing a script)
    tags?: LISTt = new ListInfo('hashtags added to document, typically using a text view', true);
    tags_chat?: LISTt = new ListInfo('hashtags added to document by chatGPT', true);
    treeView_HideTitle?: BOOLt = new BoolInfo('whether to hide the top document title of a tree view');
    treeView_HideUnrendered?: BOOLt = new BoolInfo("tells tree view not to display documents that have an 'layout_unrendered' tag unless they also have a treeView_FieldKey tag (presBox)");
    treeView_HideHeaderIfTemplate?: BOOLt = new BoolInfo('whether to hide the header for a document in a tree view only if a childLayoutTemplate is provided (presBox)');
    treeView_HideHeader?: BOOLt = new BoolInfo('whether to hide the header for a document in a tree view');
    treeView_HideHeaderFields?: BOOLt = new BoolInfo('whether to hide the drop down options for tree view items.');
    treeView_ChildDoubleClick?: ScriptField; //
    treeView_OpenIsTransient?: BOOLt = new BoolInfo("ignores the treeView_Open Doc flag, allowing a treeView_Item's expand/collapse state to be independent of other views of the same document in the same or any other tree view");
    treeView_Open?: BOOLt = new BoolInfo('whether this document is expanded in a tree view');
    treeView_ExpandedView?: string; // which field/thing is displayed when this item is opened in tree view
    treeView_ExpandedViewLock?: BOOLt = new BoolInfo('whether the expanded view can be changed');
    treeView_Checked?: ScriptField; // script to call when a tree view checkbox is checked
    treeView_TruncateTitleWidth?: NUMt = new NumInfo('maximum width of a treew view title before truncation');
    treeView_HasOverlay?: BOOLt = new BoolInfo('whether the treeview has an overlay for freeform annotations');
    treeView_Type?: string; // whether treeview is a Slide, file system, or (default) collection hierarchy
    treeView_FreezeChildren?: STRt = new StrInfo('set (add, remove, add|remove) to disable adding, removing or both from collection');

    sidebar_color?: string; // background color of text sidebar
    sidebar_type_collection?: string; // collection type of text sidebar

    data_dashboards?: List<FieldType>; // list of dashboards used in shareddocs;
    letterSpacing?: string;
    iconTemplate?: string; // name of icon template style
    icon_fieldKey?: string; // specifies the icon template to use (e.g., icon_fieldKey='george', then the icon template's name is icon_george; otherwise, the template's name would be icon_<type> where type is the Doc's type(pdf,rich text, etc))
    selectedIndex?: NUMt = new NumInfo("which item in a linear view has been selected using the 'thumb doc' ui");

    fieldValues?: List<FieldType>; // possible values a field can have (used by FieldInfo's only)
    fieldType?: string; // display type of a field, e.g. string, number, enumeration (used by FieldInfo's only)

    clipboard?: Doc;
    hoverBackgroundColor?: string; // background color of a label when hovered
    userBackgroundColor?: STRt = new StrInfo('background color associated with a Dash user (seen in header fields of shared documents)');
    userColor?: STRt = new StrInfo('color associated with a Dash user (seen in header fields of shared documents)');

    card_sort?: STRt = new StrInfo('way cards are sorted in deck view');
    card_sort_isDesc?: BOOLt = new BoolInfo('whether the cards are sorted ascending or descending');

    ai?: string; // to mark items as ai generated
    ai_prompt_seed?: NUMt = new NumInfo('seed to GAI engine to make results deterministic');
    ai_prompt?: STRt = new StrInfo('input prompt to GAI engine');
    ai_generatedDocs?: List<Doc>; // list of documents generated by GAI engine

    /**
     * JSON‐stringified slot configuration for ScrapbookBox
     */
    scrapbookConfig?: string;

    /**
     * The list of embedded Doc instances in each Scrapbook slot
     */
    scrapbookContents?: List<Doc>;
}

export const DocOptions = new DocumentOptions();

export namespace Docs {
    export namespace Prototypes {
        type LayoutSource = { LayoutString: (key: string) => string };
        type PrototypeTemplate = {
            layout: {
                view: LayoutSource;
                dataField: string;
            };
            options?: Partial<DocumentOptions>;
        };
        type TemplateMap = Map<DocumentType, PrototypeTemplate>;
        type PrototypeMap = Map<DocumentType, Doc>;
        const defaultDataKey = 'data';

        export const TemplateMap: TemplateMap = new Map([
            [
                DocumentType.GROUPDB,
                {
                    layout: { view: EmptyBox, dataField: defaultDataKey },
                    options: { acl: '', title: 'Global Group Database' },
                },
            ],
            [
                DocumentType.SCRIPTDB,
                {
                    data: new List<Doc>(),
                    layout: { view: EmptyBox, dataField: defaultDataKey },
                    options: { acl: '', title: 'Global Script Database' },
                },
            ],

            [
                DocumentType.CONFIG,
                {
                    layout: { view: EmptyBox, dataField: defaultDataKey },
                    options: { acl: '', config: '', layout_hideLinkButton: true, layout_unrendered: true },
                },
            ],
            [
                DocumentType.MAPROUTE,
                {
                    layout: { view: EmptyBox, dataField: defaultDataKey },
                    options: { acl: '' },
                },
            ],
        ]);

        const suffix = 'Proto';

        /**
         * This function loads or initializes the prototype for each document type.
         *
         * This is an asynchronous function because it has to attempt
         * to fetch the prototype documents from the server.
         *
         * Once we have this object that maps the prototype ids to a potentially
         * undefined document, we either initialize our private prototype
         * variables with the document returned from the server or, if prototypes
         * haven't been initialized, the newly initialized prototype document.
         */
        export async function initialize(): Promise<void> {
            // non-guid string ids for each document prototype
            const prototypeIds = Object.values(DocumentType)
                .filter(type => type !== DocumentType.NONE)
                .map(type => type + suffix);
            // fetch the actual prototype documents from the server
            const actualProtos = await DocServer.GetRefFields(prototypeIds);
            // update this object to include any default values: DocumentOptions for all prototypes
            prototypeIds.forEach(id => {
                const existing = actualProtos.get(id);
                const type = id.replace(suffix, '') as DocumentType;
                // get or create prototype of the specified type...
                const target = buildPrototype(type, id, existing);
                // ...and set it if not undefined (can be undefined only if TemplateMap does not contain
                // an entry dedicated to the given DocumentType)
                target && PrototypeMap.set(type, target);
            });
            reaction(
                () => (proto => StrCast(proto?.BROADCAST_MESSAGE))(DocServer.GetCachedRefField('rtfProto') as Doc),
                msg => msg && alert(msg)
            );
        }

        /**
         * Retrieves the prototype for the given document type, or
         * undefined if that type's proto doesn't have a configuration
         * in the template map.
         * @param type
         */
        const PrototypeMap: PrototypeMap = new Map();
        export function get(type: DocumentType): Doc {
            return PrototypeMap.get(type)!;
        }

        /**
         * A collection of all scripts in the database
         */
        export function MainScriptDocument() {
            return Prototypes.get(DocumentType.SCRIPTDB);
        }

        /**
         * A collection of all user acl groups in the database
         */
        export function MainGroupDocument() {
            return Prototypes.get(DocumentType.GROUPDB);
        }

        /**
         * This is a convenience method that is used to initialize
         * prototype documents for the first time.
         *
         * @param protoId the id of the prototype, indicating the specific prototype
         * to initialize (see the *protoId list at the top of the namespace)
         * @param title the prototype document's title, follows *-PROTO
         * @param layout the layout key for this prototype and thus the
         * layout key that all delegates will inherit
         * @param options any value specified in the DocumentOptions object likewise
         * becomes the default value for that key for all delegates
         */
        function buildPrototype(type: DocumentType, prototypeId: string, existing?: Doc): Opt<Doc> {
            // load template from type
            const template = TemplateMap.get(type);
            if (!template) {
                return undefined;
            }
            const { layout } = template;

            // create title
            const upper = suffix.toUpperCase();
            const title = prototypeId.toUpperCase().replace(upper, `_${upper}`);
            // synthesize the default options, the type and title from computed values and
            // whatever options pertain to this specific prototype
            const options: DocumentOptions = {
                isSystem: true,
                layout_fieldKey: 'layout',
                title,
                type,
                isBaseProto: true,
                _width: 300,
                acl_Guest: SharingPermissions.View,
                ...(template.options || {}),
                layout: layout.view?.LayoutString(layout.dataField),
            };
            Object.entries(options)
                .filter(([, val]) => (val as string)?.startsWith?.('@'))
                .map(([key, val]) => [key, val as string])
                .forEach(([key, val]) => {
                    if (!existing || ScriptCast(existing[key])?.script.originalScript !== val.substring(1)) {
                        options[key] = ComputedField.MakeFunction(val.substring(1));
                    }
                });
            return Doc.assign(existing ?? new Doc(prototypeId, true), OmitKeys(options, Object.keys(existing ?? {})).omit as { [key: string]: FieldType }, undefined, true);
        }
    }

    /**
     * Encapsulates the factory used to create new document instances
     * delegated from top-level prototypes
     */

    export namespace Create {
        /**
         * This function receives the relevant document prototype and uses
         * it to create a new of that base-level prototype, or the
         * underlying data document, which it then delegates again
         * to create the view document.
         *
         * It also takes the opportunity to register the user
         * that created the document and the time of creation.
         *
         * @param proto the specific document prototype off of which to model
         * this new instance (textProto, imageProto, etc.)
         * @param data the Field to store at this new instance's data key
         * @param options any initial values to provide for this new instance
         * @param delegId if applicable, an existing document id. If undefined, Doc's
         * constructor just generates a new GUID. This is currently used
         * only when creating a DockDocument from the current user's already existing
         * main document.
         */
        function InstanceFromProto(proto: Doc, data: FieldType | undefined, options: DocumentOptions, delegId?: string, fieldKey: string = 'data', protoId?: string, placeholderDocIn?: Doc, noView?: boolean) {
            const placeholderDoc = placeholderDocIn;
            const viewKeys = ['x', 'y', 'isSystem', 'overlayX', 'overlayY', 'zIndex', 'embedContainer']; // keys that should be addded to the view document even though they don't begin with an "_"
            const { omit: dataProps, extract: viewProps } = OmitKeys(options, viewKeys, '^_') as { omit: { [key: string]: FieldType | undefined }; extract: { [key: string]: FieldType | undefined } };

            // dataProps.acl_Override = SharingPermissions.Unset;
            dataProps.acl_Guest = options.acl_Guest?.toString() ?? (Doc.defaultAclPrivate ? SharingPermissions.None : SharingPermissions.View);
            dataProps.isSystem = viewProps.isSystem;
            dataProps.isDataDoc = true;
            dataProps.author = ClientUtils.CurrentUserEmail();
            dataProps.author_date = new DateField();
            if (fieldKey) {
                dataProps[`${fieldKey}_modificationDate`] = new DateField();
                dataProps[fieldKey] = (options as unknown as { [key: string]: FieldType | undefined })[fieldKey] ?? data;

                // so that the list of annotations is already initialised, prevents issues in addonly.
                // without this, if a doc has no annotations but the user has AddOnly privileges, they won't be able to add an annotation because they would have needed to create the field's list which they don't have permissions to do.
                dataProps[fieldKey + '_annotations'] = new List<Doc>();
                dataProps[fieldKey + '_sidebar'] = new List<Doc>();
            }

            // users placeholderDoc as proto if it exists
            const dataDoc = Doc.assign(placeholderDoc ? Doc.GetProto(placeholderDoc) : Doc.MakeDelegate(proto, protoId), dataProps, undefined, true);

            if (placeholderDoc) {
                dataDoc.proto = proto;
            }

            if (!noView) {
                const viewFirstProps: { [id: string]: FieldType } = { author: ClientUtils.CurrentUserEmail() };
                viewFirstProps.acl_Guest = options._acl_Guest ?? (Doc.defaultAclPrivate ? SharingPermissions.None : SharingPermissions.View);
                let viewDoc: Doc;
                // determines whether viewDoc should be created using placeholder Doc or default
                if (placeholderDoc) {
                    placeholderDoc._height = options._height !== undefined ? Number(options._height) : undefined;
                    placeholderDoc._width = options._width !== undefined ? Number(options._width) : undefined;
                    viewDoc = Doc.assign(placeholderDoc, viewFirstProps, true, true);
                    Array.from(Object.keys(placeholderDoc))
                        .filter(key => key.startsWith('acl_'))
                        .forEach(key => {
                            dataDoc[key] = viewDoc[key] = placeholderDoc[key];
                        });
                } else {
                    viewDoc = Doc.assign(Doc.MakeDelegate(dataDoc, delegId), viewFirstProps, true, true);
                }
                Doc.assign(viewDoc, viewProps, true, true);
                if (![DocumentType.LINK, DocumentType.CONFIG, DocumentType.LABEL].includes(viewDoc.type as DocumentType)) {
                    CreateLinkToActiveAudio(() => viewDoc);
                }
                updateCachedAcls(dataDoc);
                updateCachedAcls(viewDoc);

                if (data instanceof List) {
                    data.map(item => item instanceof Doc && Doc.SetContainer(item, viewDoc));
                }
                return viewDoc;
            }

            updateCachedAcls(dataDoc);

            return dataDoc;
        }

        export function ImageDocument(url: string | ImageField, options: DocumentOptions = {}, overwriteDoc?: Doc) {
            const imgField = url instanceof ImageField ? url : url ? new ImageField(url) : undefined;
            return InstanceFromProto(Prototypes.get(DocumentType.IMG), imgField, { title: basename(imgField?.url.href ?? '-no image-'), ...options }, undefined, undefined, undefined, overwriteDoc);
        }

        export function PresDocument(options: DocumentOptions = {}) {
            return InstanceFromProto(Prototypes.get(DocumentType.PRES), new List<Doc>(), options);
        }

        /**
         * Creates a Doc to edit a script and write the compiled script into the specified field.
         * Typically, this would be used to create a template that can then be applied to some other Doc
         * in order to customize a behavior, such as onClick.
         * @param script
         * @param options
         * @param fieldKey the field that the compiled script is written into.
         * @returns the Scripting Doc
         */
        export function ScriptingDocument(script: Opt<ScriptField> | null, options: DocumentOptions = {}, fieldKey?: string) {
            return InstanceFromProto(Prototypes.get(DocumentType.SCRIPTING), script || undefined, { ...options, layout: fieldKey ? `<ScriptingBox {...props} fieldKey={'${fieldKey}'}/>` /* ScriptingBox.LayoutString(fieldKey) */ : undefined });
        }

        export function ChatDocument(options?: DocumentOptions) {
            return InstanceFromProto(Prototypes.get(DocumentType.CHAT), undefined, { ...(options || {}) });
        }
        export function VideoDocument(url: string, options: DocumentOptions = {}, overwriteDoc?: Doc) {
            return InstanceFromProto(Prototypes.get(DocumentType.VID), new VideoField(url), options, undefined, undefined, undefined, overwriteDoc);
        }

        export function WebCamDocument(url: string, options: DocumentOptions = {}) {
            return InstanceFromProto(Prototypes.get(DocumentType.WEBCAM), '', options);
        }

        export function ScreenshotDocument(options: DocumentOptions = {}) {
            return InstanceFromProto(Prototypes.get(DocumentType.SCREENSHOT), '', options);
        }

        export function ComparisonDocument(title: string, options: DocumentOptions) {
            return InstanceFromProto(Prototypes.get(DocumentType.COMPARISON), '', options);
        }
        /**
         * Creates a text box where the supplied text (and optional iimage) will be vertically
         * and horizontally centered.  If text_placeholder is set to true, then the text will be
         * treated as placeholder text and automatically selected when the text box is selected.
         * @param title name of text box
         * @param text text to display in text box
         * @param opts metadata fields to set on text box
         * @param img optional image to add to text box
         * @returns
         */
        export function CenteredTextCreator(title: string, text: string, opts: DocumentOptions, img?: Doc) {
            return TextDocument(RichTextField.textToRtf(text, img?.[Id]), {
                title, //
                _layout_autoHeight: true,
                text_centered: true,
                text_align: 'center',
                _layout_fitWidth: true,
                ...opts,
            });
        }

        export function FlashcardDocument(title: string, front?: Doc, back?: Doc, options: DocumentOptions = { title: 'Flashcard' }) {
            return InstanceFromProto(Prototypes.get(DocumentType.COMPARISON), '', {
                data_front: front ?? CenteredTextCreator('question', 'hint: Enter a topic, select this document and click the stack button to have GPT create a deck of cards', { text_placeholder: true, cloneOnCopy: true }, undefined),
                data_back: back ?? CenteredTextCreator('answer', 'answer here', { text_placeholder: true, cloneOnCopy: true }, undefined),
                _layout_fitWidth: true,
                _layout_flashcardType: 'flashcard',
                title,
                ...options,
            });
        }
        export function DiagramDocument(data?: string, options: DocumentOptions = { title: '' }) {
            return InstanceFromProto(Prototypes.get(DocumentType.DIAGRAM), data, options);
        }

        export function AudioDocument(url: string, options: DocumentOptions = {}, overwriteDoc?: Doc) {
            return InstanceFromProto(Prototypes.get(DocumentType.AUDIO), new AudioField(url), options, undefined, undefined, undefined, overwriteDoc);
        }

        export function RecordingDocument(url: string, options: DocumentOptions = {}) {
            return InstanceFromProto(Prototypes.get(DocumentType.REC), '', options);
        }

        export function SearchDocument(options: DocumentOptions = {}) {
            return InstanceFromProto(Prototypes.get(DocumentType.SEARCH), new List<Doc>([]), options);
        }

        export function ImageGrouperDocument(options: DocumentOptions = {}) {
            return InstanceFromProto(Prototypes.get(DocumentType.IMAGEGROUPER), undefined, options);
        }

        export function FaceCollectionDocument(options: DocumentOptions = {}) {
            return InstanceFromProto(Prototypes.get(DocumentType.FACECOLLECTION), undefined, options);
        }

        export function UniqeFaceDocument(options: DocumentOptions = {}) {
            return InstanceFromProto(Prototypes.get(DocumentType.UFACE), undefined, options);
        }

        export function LoadingDocument(file: File | string, options: DocumentOptions) {
            return InstanceFromProto(Prototypes.get(DocumentType.LOADING), undefined, { _height: 150, _width: 200, title: typeof file === 'string' ? file : file.name, ...options }, undefined, '');
        }

        export function RTFDocument(field: RichTextField, options: DocumentOptions = {}, fieldKey: string = 'text') {
            return InstanceFromProto(Prototypes.get(DocumentType.RTF), field, options, undefined, fieldKey);
        }

        export function MessageDocument(field: string, options: DocumentOptions = {}, fieldKey: string = 'data') {
            return InstanceFromProto(Prototypes.get(DocumentType.MESSAGE), field, options, undefined, fieldKey);
        }

        export function TextDocument(text: string | RichTextField, options: DocumentOptions = {}, fieldKey: string = 'text') {
            const rtf = {
                doc: {
                    type: 'doc',
                    content: [
                        {
                            type: 'paragraph',
                            content: [
                                {
                                    type: 'text',
                                    text,
                                },
                            ],
                        },
                    ],
                },
                selection: { type: 'text', anchor: 1, head: 1 },
                storedMarks: [],
            };
            const field = text instanceof RichTextField ? text : text ? new RichTextField(JSON.stringify(rtf), text) : options.text instanceof RichTextField ? options.text : undefined;
            return InstanceFromProto(Prototypes.get(DocumentType.RTF), field, options, undefined, fieldKey);
        }

        export function ScrapbookDocument(items: Doc[] = [], options: DocumentOptions = {}, fieldKey: string = 'items') {
            return InstanceFromProto(
                Prototypes.get(DocumentType.SCRAPBOOK),
                new List<Doc>(items),
                {
                    title:
                        options.title ??
                        new Date().toLocaleDateString(undefined, {
                            year: 'numeric',
                            month: 'short',
                            day: 'numeric',
                        }),
                    ...options,
                },
                undefined,
                fieldKey
            );
        }

        // AARAV ADD //

        export function DailyJournalDocument(text: string | RichTextField, options: DocumentOptions = {}, fieldKey: string = 'text') {
            // const getFormattedDate = () => {
            //     const date = new Date().toLocaleDateString(undefined, {
            //         weekday: 'long',
            //         year: 'numeric',
            //         month: 'long',
            //         day: 'numeric',
            //     });
            //     return date;
            // };

            // const getDailyText = () => {
            //     const placeholderText = 'Start writing here...';
            //     const dateText = `${getFormattedDate()}`;

            //     return RichTextField.textToRtfFormat(
            //         [
            //             { text: 'Journal Entry:', styles: { bold: true, color: 'black', fontSize: 20 } },
            //             { text: dateText, styles: { italic: true, color: 'gray', fontSize: 15 } },
            //             { text: placeholderText, styles: { fontSize: 14, color: 'gray' } },
            //         ],
            //         undefined,
            //         placeholderText.length
            //     );
            // };

            return InstanceFromProto(
                Prototypes.get(DocumentType.JOURNAL),
                '',
                {
                    title: '',
                    ...options,
                },
                undefined,
                fieldKey
            );
        }

        // AARAV ADD //

        export function LinkDocument(source: Doc, target: Doc, options: DocumentOptions = {}, id?: string) {
            const linkDoc = InstanceFromProto(
                Prototypes.get(DocumentType.LINK),
                undefined,
                {
                    link_anchor_1: source,
                    link_anchor_2: target,
                    ...options,
                },
                id,
                'link'
            );

            Doc.AddLink(linkDoc);

            return linkDoc;
        }

        export function InkDocument(points: PointData[], options: DocumentOptions = {}, strokeWidth: number, color: string, strokeBezier: string, fillColor: string, arrowStart: string, arrowEnd: string, dash: string, isInkMask: boolean) {
            const ink = InstanceFromProto(Prototypes.get(DocumentType.INK), '', { title: 'ink', ...options });
            ink.$color = color;
            ink.$fillColor = fillColor && fillColor !== 'transparent' ? fillColor : undefined;
            ink.$stroke = new InkField(points);
            ink.$stroke_width = strokeWidth;
            ink.$stroke_bezier = strokeBezier;
            ink.$stroke_startMarker = arrowStart;
            ink.$stroke_endMarker = arrowEnd;
            ink.$stroke_dash = dash;
            ink.$stroke_isInkMask = isInkMask;
            ink.$text_align = 'center';
            ink.$rotation = 0;
            ink.$width_min = 1;
            ink.$height_min = 1;
            ink.$defaultDoubleClick = 'ignore';
            ink.$author_date = new DateField();
            ink.$acl_Guest = Doc.defaultAclPrivate ? SharingPermissions.None : SharingPermissions.View;

            return ink;
        }

        export function PdfDocument(url: string, options: DocumentOptions = {}, overwriteDoc?: Doc) {
            const width = options._width || undefined;
            const height = options._height || undefined;
            const nwid = options._nativeWidth || undefined;
            const nhght = options._nativeHeight || undefined;
            if (!nhght && width && height && nwid) options._nativeHeight = (Number(nwid) * Number(height)) / Number(width);
            return InstanceFromProto(Prototypes.get(DocumentType.PDF), new PdfField(url), options, undefined, undefined, undefined, overwriteDoc);
        }

        export function WebDocument(url: string, options: DocumentOptions = {}) {
            const width = options._width || undefined;
            const height = options._height || undefined;
            const nwid = options._nativeWidth || undefined;
            const nhght = options._nativeHeight || undefined;
            if (!nhght && width && height && nwid) options._nativeHeight = (Number(nwid) * Number(height)) / Number(width);
            return InstanceFromProto(Prototypes.get(DocumentType.WEB), new WebField(url || 'https://wikipedia.org/'), options);
        }

        export function HtmlDocument(html: string, options: DocumentOptions = {}) {
            return InstanceFromProto(Prototypes.get(DocumentType.WEB), new HtmlField(html), options);
        }

        export function MapDocument(documents: Array<Doc>, options: DocumentOptions = {}) {
            return InstanceFromProto(Prototypes.get(DocumentType.MAP), new List(documents), options);
        }

        export function PushpinDocument(latitude: number, longitude: number, infoWindowOpen: boolean, documents: Array<Doc>, options: DocumentOptions, id?: string) {
            return InstanceFromProto(Prototypes.get(DocumentType.PUSHPIN), new List(documents), { latitude, longitude, infoWindowOpen, ...options }, id);
        }

        export function MapRouteDocument(infoWindowOpen: boolean, documents: Array<Doc>, options: DocumentOptions, id?: string) {
            return InstanceFromProto(Prototypes.get(DocumentType.MAPROUTE), new List(documents), { infoWindowOpen, ...options }, id);
        }

        export function CalendarDocument(options: DocumentOptions, documents: Array<Doc>) {
            return InstanceFromProto(Prototypes.get(DocumentType.COL), new List(documents), {
                _layout_nativeDimEditable: true,
                _layout_reflowHorizontal: true,
                _layout_reflowVertical: true,
                ...options,
                _type_collection: CollectionViewType.Calendar,
            });
        }

        // shouldn't ever need to create a KVP document-- instead set the LayoutTemplateString to be a KeyValueBox for the DocumentView (see addDocTab in TabDocView)
        // export function KVPDocument(document: Doc, options: DocumentOptions = {}) {
        //     return InstanceFromProto(Prototypes.get(DocumentType.KVP), document, { title: document.title + '.kvp', ...options });
        // }

        export function FreeformDocument(documents: Array<Doc>, options: DocumentOptions, id?: string) {
            return InstanceFromProto(Prototypes.get(DocumentType.COL), new List(documents), { ...options, _type_collection: CollectionViewType.Freeform }, id);
        }

        export function ConfigDocument(options: DocumentOptions, id?: string) {
            return InstanceFromProto(Prototypes.get(DocumentType.CONFIG), undefined, options, id, '', undefined, undefined, true);
        }

        export function PileDocument(documents: Array<Doc>, options: DocumentOptions, id?: string) {
            return InstanceFromProto(
                Prototypes.get(DocumentType.COL),
                new List(documents),
                { backgroundColor: 'transparent', dropAction: dropActionType.move, _forceActive: true, _freeform_noZoom: true, _freeform_noAutoPan: true, ...options, _type_collection: CollectionViewType.Pile },
                id
            );
        }

        export function LinearDocument(documents: Array<Doc>, options: DocumentOptions, id?: string) {
            return InstanceFromProto(Prototypes.get(DocumentType.COL), new List(documents), { ...options, _type_collection: CollectionViewType.Linear }, id);
        }

        export function CarouselDocument(documents: Array<Doc>, options: DocumentOptions) {
            return InstanceFromProto(Prototypes.get(DocumentType.COL), new List(documents), { ...options, _type_collection: CollectionViewType.Carousel });
        }

        export function Carousel3DDocument(documents: Array<Doc>, options: DocumentOptions) {
            return InstanceFromProto(Prototypes.get(DocumentType.COL), new List(documents), { ...options, _type_collection: CollectionViewType.Carousel3D });
        }

        export function CardDeckDocument(documents: Array<Doc>, options: DocumentOptions) {
            return InstanceFromProto(Prototypes.get(DocumentType.COL), new List(documents), { ...options, _type_collection: CollectionViewType.Card });
        }

        export function SchemaDocument(schemaHeaders: SchemaHeaderField[], documents: Array<Doc>, options: DocumentOptions) {
            return InstanceFromProto(Prototypes.get(DocumentType.COL), new List(documents), { schemaHeaders: new List(schemaHeaders), ...options, _type_collection: CollectionViewType.Schema });
        }

        export function TreeDocument(documents: Array<Doc>, options: DocumentOptions, id?: string, protoId?: string) {
            const doc = InstanceFromProto(Prototypes.get(DocumentType.COL), new List(documents), { _xMargin: 5, _yMargin: 5, ...options, _type_collection: CollectionViewType.Tree }, id, undefined, protoId);
            Doc.GetProto(doc).treeView = ''; /// not really needed, but makes keyvalue pane look better
            return doc;
        }

        export function StackingDocument(documents: Array<Doc>, options: DocumentOptions, id?: string, protoId?: string) {
            return InstanceFromProto(Prototypes.get(DocumentType.COL), new List(documents), { _layout_dontCenter: 'y', ...options, _type_collection: CollectionViewType.Stacking }, id, undefined, protoId);
        }

        export function NoteTakingDocument(documents: Array<Doc>, options: DocumentOptions, id?: string, protoId?: string) {
            return InstanceFromProto(
                Prototypes.get(DocumentType.COL),
                new List(documents),
                { columnHeaders: new List<SchemaHeaderField>([new SchemaHeaderField('Untitled')]), ...options, _type_collection: CollectionViewType.NoteTaking },
                id,
                undefined,
                protoId
            );
        }

        export function MulticolumnDocument(documents: Array<Doc>, options: DocumentOptions) {
            return InstanceFromProto(Prototypes.get(DocumentType.COL), new List(documents), { ...options, _type_collection: CollectionViewType.Multicolumn });
        }
        export function MultirowDocument(documents: Array<Doc>, options: DocumentOptions) {
            return InstanceFromProto(Prototypes.get(DocumentType.COL), new List(documents), { ...options, _type_collection: CollectionViewType.Multirow });
        }

        export function MasonryDocument(documents: Array<Doc>, options: DocumentOptions) {
            return InstanceFromProto(Prototypes.get(DocumentType.COL), new List(documents), { ...options, _type_collection: CollectionViewType.Masonry });
        }

        export function LabelDocument(options?: DocumentOptions) {
            return InstanceFromProto(Prototypes.get(DocumentType.LABEL), undefined, { ...(options || {}) });
        }

        export function EquationDocument(text?: string, options?: DocumentOptions) {
            return InstanceFromProto(Prototypes.get(DocumentType.EQUATION), text, { ...(options || {}) }, undefined, 'text');
        }

        export function FunctionPlotDocument(documents: Array<Doc>, options?: DocumentOptions) {
            return InstanceFromProto(Prototypes.get(DocumentType.FUNCPLOT), new List(documents), { title: 'func plot', ...(options || {}) });
        }

        export function ButtonDocument(options?: DocumentOptions) {
            return InstanceFromProto(Prototypes.get(DocumentType.BUTTON), undefined, { ...(options || {}) });
        }

        export function FontIconDocument(options?: DocumentOptions) {
            return InstanceFromProto(Prototypes.get(DocumentType.FONTICON), undefined, { ...(options || {}) });
        }

        export function PresSlideDocument() {
            return Prototypes.get(DocumentType.PRESSLIDE);
        }

        export function DataVizDocument(url: string, options?: DocumentOptions, overwriteDoc?: Doc) {
            return InstanceFromProto(Prototypes.get(DocumentType.DATAVIZ), new CsvField(url), { title: 'Data Viz', type: 'dataviz', ...options }, undefined, undefined, undefined, overwriteDoc);
        }

        export function AnnoPaletteDocument(options?: DocumentOptions) {
            return InstanceFromProto(Prototypes.get(DocumentType.ANNOPALETTE), new List([...(Doc.MyStickers ? [Doc.MyStickers] : [])]), { ...(options || {}) });
        }

        export function DockDocument(documents: Array<Doc>, config: string, options: DocumentOptions, id?: string) {
            return InstanceFromProto(Prototypes.get(DocumentType.COL), new List(documents), { treeView_FreezeChildren: 'remove|add', ...options, type_collection: CollectionViewType.Docking, dockingConfig: config }, id);
        }

        export function DelegateDocument(proto: Doc, options: DocumentOptions = {}) {
            return InstanceFromProto(proto, undefined, options);
        }
    }
}