aboutsummaryrefslogtreecommitdiff
path: root/src/client/views/DocComponent.tsx
blob: 97ff346e46d08b3186623ca53f035a849706c722 (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
import { action, computed, makeObservable, observable } from 'mobx';
import * as React from 'react';
import { returnFalse } from '../../ClientUtils';
import { DateField } from '../../fields/DateField';
import { Doc, DocListCast, FieldType, Opt } from '../../fields/Doc';
import { AclAdmin, AclAugment, AclEdit, AclPrivate, AclReadonly, DocData, DocViews } from '../../fields/DocSymbols';
import { List } from '../../fields/List';
import { RefField } from '../../fields/RefField';
import { toList } from '../../fields/Types';
import { GetEffectiveAcl, inheritParentAcls } from '../../fields/util';
import { DocumentType } from '../documents/DocumentTypes';
import { DragManager } from '../util/DragManager';
import { ObservableReactComponent } from './ObservableReactComponent';
import { PinProps } from './PinFuncs';
import { DocumentView } from './nodes/DocumentView';
import { FocusViewOptions } from './nodes/FocusViewOptions';
import { FieldViewProps } from './nodes/FieldView';
import { OpenWhere } from './nodes/OpenWhere';
// import { DocUtils } from '../documents/Documents';

/**
 * Shared interface among all viewBox'es (ie, react classes that render the contents of a Doc)
 * Many of these methods only make sense for specific viewBox'es, but they should be written to
 * be as general as possible
 */
export interface ViewBoxInterface {
    fieldKey?: string;
    annotationKey?: string;
    promoteCollection?: () => void; // moves contents of collection to parent
    updateIcon?: () => void; // updates the icon representation of the document
    getAnchor?: (addAsAnnotation: boolean, pinData?: PinProps) => Doc; // returns an Anchor Doc that represents the current state of the doc's componentview (e.g., the current playhead location of a an audio/video box)
    restoreView?: (viewSpec: Doc) => boolean;
    scrollPreview?: (docView: DocumentView, doc: Doc, focusSpeed: number, options: FocusViewOptions) => Opt<number>; // returns the duration of the focus
    brushView?: (view: { width: number; height: number; panX: number; panY: number }, transTime: number, holdTime: number) => void; // highlight a region of a view (used by freeforms)
    getView?: (doc: Doc, options: FocusViewOptions) => Promise<Opt<DocumentView>>; // returns a nested DocumentView for the specified doc or undefined
    addDocTab?: (doc: Doc, where: OpenWhere) => boolean; // determines how to add a document - used in following links to open the target ina local lightbox
    addDocument?: (doc: Doc | Doc[], annotationKey?: string) => boolean; // add a document (used only by collections)
    removeDocument?: (doc: Doc | Doc[], annotationKey?: string, leavePushpin?: boolean, dontAddToRemoved?: boolean) => boolean; // add a document (used only by collections)
    select?: (ctrlKey: boolean, shiftKey: boolean) => void;
    focus?: (textAnchor: Doc, options: FocusViewOptions) => Opt<number>;
    viewTransition?: () => Opt<string>; // duration of a view transition animation
    isAnyChildContentActive?: () => boolean; // is any child content of the document active
    onClickScriptDisable?: () => 'never' | 'always'; // disable click scripts : never, always, or undefined = only when selected
    getKeyFrameEditing?: () => boolean; // whether the document is in keyframe editing mode (if it is, then all hidden documents that are not active at the keyframe time will still be shown)
    setKeyFrameEditing?: (set: boolean) => void; // whether the document is in keyframe editing mode (if it is, then all hidden documents that are not active at the keyframe time will still be shown)
    playTrail?: (docs: Doc[]) => void;
    playFrom?: (time: number, endTime?: number) => void;
    Pause?: () => void; // pause a media document (eg, audio/video)
    IsPlaying?: () => boolean; // is a media document playing
    TogglePause?: (keep?: boolean) => void; // toggle media document playing state
    setFocus?: () => void; // sets input focus to the componentView
    setData?: (data: FieldType | Promise<RefField | undefined>) => boolean;
    componentUI?: (boundsLeft: number, boundsTop: number) => JSX.Element | null;
    dragStarting?: (snapToDraggedDoc: boolean, showGroupDragTarget: boolean, visited: Set<Doc>) => void;
    dragConfig?: (dragData: DragManager.DocumentDragData) => void; // function to setup dragData in custom way (see TreeViews which add a tree view flag)
    incrementalRendering?: () => void;
    infoUI?: () => JSX.Element | null;
    screenBounds?: () => Opt<{ left: number; top: number; right: number; bottom: number; transition?: string }>;
    ptToScreen?: (pt: { X: number; Y: number }) => { X: number; Y: number };
    ptFromScreen?: (pt: { X: number; Y: number }) => { X: number; Y: number };
    snapPt?: (pt: { X: number; Y: number }, excludeSegs?: number[]) => { nearestPt: { X: number; Y: number }; distance: number };
    search?: (str: string, bwd?: boolean, clear?: boolean) => boolean;
    dontRegisterView?: () => boolean; // KeyValueBox's don't want to register their views
    isUnstyledView?: () => boolean; // SchemaView and KeyValue are untyled -- not tiles, no opacity
}
/**
 * DocComponent returns a React base class used by Doc views with accessors for unpacking the Document,layoutDoc, and dataDoc's
 *  (note: this should not be used for the 'Box' views that render the contents of Doc views)
 *  Example derived views: CollectionFreeFormDocumentView, DocumentView, DocumentViewInternal)
 * */
export interface DocComponentProps {
    Document: Doc;
    LayoutTemplate?: () => Opt<Doc>;
    LayoutTemplateString?: string;
}
export function DocComponent<P extends DocComponentProps>() {
    class Component extends ObservableReactComponent<React.PropsWithChildren<P>> {
        constructor(props: P) {
            super(props);
            makeObservable(this);
        }

        /**
         * This is the document being rendered.  In the case of a compound template, it
         * may not be the actual document rendered and it also may not be the 'real' root document.
         * Rather, it specifies the shared properties of all layouts of the document (eg, x,y,)
         */
        get Document() {
            return this._props.Document;
        }

        /**
         * This is the document being rendered.  It may be a template so it may or may no inherit from the data doc.
         */
        @computed get layoutDoc() {
            return this._props.LayoutTemplateString ? this.Document : Doc.Layout(this.Document, this._props.LayoutTemplate?.());
        }

        /**
         * This is the unique data repository for a dcoument that stores the intrinsic document data
         */
        @computed get dataDoc() {
            return this.Document[DocData];
        }
    }
    return Component;
}

/**
 *   base class for non-annotatable views that render the interior contents of a DocumentView.
 *   this unpacks the Document/layout/data docs as well as the fieldKey being rendered,
 *   and provides accessors for DocumentView and ScreenToLocalBoxXf
 *   Example views include: InkingStroke, FontIconBox, EquationBox, etc
 */
export function ViewBoxBaseComponent<P extends FieldViewProps>() {
    class Component extends ObservableReactComponent<React.PropsWithChildren<P>> {
        constructor(props: P) {
            super(props);
            makeObservable(this);
        }

        ScreenToLocalBoxXf = () => this._props.ScreenToLocalTransform();

        get DocumentView() {
            return this._props.DocumentView;
        }

        /**
         * This is the document being rendered.  In the case of a compound template, it
         * may not be the actual document rendered and it also may not be the 'real' root document.
         * Rather, it specifies the shared properties of all layouts of the document (eg, x,y,)
         */
        get Document() {
            return this._props.Document;
        }
        /**
         * This is the document being rendered.  It may be a template so it may or may no inherit from the data doc.
         */
        @computed get layoutDoc() {
            return Doc.Layout(this.Document);
        }

        /**
         * This is the unique data repository for a dcoument that stores the intrinsic document data
         */
        @computed get dataDoc() {
            return this.Document.isTemplateForField || this.Document.isTemplateDoc ? this._props.TemplateDataDocument ?? this.Document[DocData] : this.Document[DocData];
        }

        /**
         * this is the field key where the primary rendering data is stored for the layout doc (e.g., it's often the 'data' field for a collection, or the 'text' field for rich text)
         */
        get fieldKey() {
            return this._props.fieldKey;
        }
    }
    return Component;
}

/**
 * base class for annotatable views that render the interior contents of a DocumentView
 * This does what ViewBoxBaseComponent does and additionally provides accessor for the
 * field key where annotations are stored as well as add/move/remove methods for handing
 * annotations.
 * This also provides methods to determine when the contents should be interactive
 * (respond to pointerEvents) such as when the DocumentView container is selected or a
 * peer child of the container is selected
 * Example views include: PDFBox, ImageBox, MapBox, etc
 */
export function ViewBoxAnnotatableComponent<P extends FieldViewProps>() {
    class Component extends ObservableReactComponent<React.PropsWithChildren<P>> {
        @observable _annotationKeySuffix = () => 'annotations';
        @observable _isAnyChildContentActive = false;

        constructor(props: P) {
            super(props);
            makeObservable(this);
        }

        ScreenToLocalBoxXf = () => this._props.ScreenToLocalTransform();

        get DocumentView() {
            return this._props.DocumentView;
        }

        /**
         * This is the document being rendered.  In the case of a compound template, it
         * may not be the actual document rendered and it also may not be the 'real' root document.
         * Rather, it specifies the shared properties of all layouts of the document (eg, x,y,)
         */
        @computed get Document() {
            return this._props.Document;
        }
        /**
         * This is the document being rendered.  It may be a template so it may or may no inherit from the data doc.
         */
        @computed get layoutDoc() {
            return Doc.Layout(this.Document);
        }

        /**
         * This is the unique data repository for a dcoument that stores the intrinsic document data
         */
        @computed get dataDoc() {
            return this.Document.isTemplateForField || this.Document.isTemplateDoc ? this._props.TemplateDataDocument ?? this.Document[DocData] : this.Document[DocData];
        }

        /**
         * this is the field key where the primary rendering data is stored for the layout doc (e.g., it's often the 'data' field for a collection, or the 'text' field for rich text)
         */
        @computed get fieldKey() {
            return this._props.fieldKey;
        }

        /**
         * this is field key where the list of annotations is stored
         */
        @computed public get annotationKey() {
            return this.fieldKey + (this._annotationKeySuffix() ? '_' + this._annotationKeySuffix() : '');
        }

        @action.bound
        removeDocument(docIn: Doc | Doc[], annotationKey?: string, leavePushpin?: boolean, dontAddToRemoved?: boolean): boolean {
            const effectiveAcl = GetEffectiveAcl(this.dataDoc);
            const docs = toList(docIn).filter(fdoc => [AclEdit, AclAdmin].includes(effectiveAcl) || GetEffectiveAcl(fdoc) === AclAdmin);

            // docs.forEach(doc => doc.annotationOn === this.Document && Doc.SetInPlace(doc, 'annotationOn', undefined, true));
            const targetDataDoc = this.Document[DocData]; // this.dataDoc;  // we want to write to the template, not the actual data doc
            const value = DocListCast(targetDataDoc[annotationKey ?? this.annotationKey]);
            const toRemove = value.filter(v => docs.includes(v));

            if (toRemove.length !== 0) {
                const recentlyClosed = this.Document !== Doc.MyRecentlyClosed ? Doc.MyRecentlyClosed : undefined;
                toRemove.forEach(rdoc => {
                    // leavePushpin && DocUtils.LeavePushpin(doc, annotationKey ?? this.annotationKey);
                    Doc.RemoveDocFromList(targetDataDoc, annotationKey ?? this.annotationKey, rdoc, true);
                    rdoc.embedContainer = undefined;
                    if (recentlyClosed && !dontAddToRemoved && rdoc.type !== DocumentType.LOADING) {
                        Doc.AddDocToList(recentlyClosed, 'data', rdoc, undefined, true, true);
                        Doc.RemoveEmbedding(rdoc, rdoc);
                    }
                });
                if (targetDataDoc.isGroup && DocListCast(targetDataDoc[annotationKey ?? this.annotationKey]).length < 2) {
                    Array.from(targetDataDoc[DocViews])[0]?.ComponentView?.promoteCollection?.();
                } else {
                    this.isAnyChildContentActive() && this._props.select(false);
                }
                return true;
            }

            return false;
        }
        // this is called with the document that was dragged and the collection to move it into.
        // if the target collection is the same as this collection, then the move will be allowed.
        // otherwise, the document being moved must be able to be removed from its container before
        // moving it into the target.
        @action.bound
        moveDocument = (docs: Doc | Doc[], targetCollection: Doc | undefined, addDocument: (doc: Doc | Doc[], annotationKey?: string) => boolean, annotationKey?: string): boolean => {
            if (Doc.AreProtosEqual(this._props.Document, targetCollection)) {
                return true;
            }
            const first = toList(docs)[0];
            if (!first?._dragOnlyWithinContainer && addDocument !== returnFalse) {
                return this.removeDocument(docs, annotationKey, false, true) && addDocument(docs, annotationKey);
            }
            return false;
        };
        @action.bound
        addDocument = (docIn: Doc | Doc[], annotationKey?: string): boolean => {
            const docs = toList(docIn);
            if (this._props.filterAddDocument?.(docs) === false || docs.find(fdoc => Doc.AreProtosEqual(fdoc, this.Document) && Doc.LayoutField(fdoc) === Doc.LayoutField(this.Document))) {
                return false;
            }
            const targetDataDoc = this.Document[DocData]; // this.dataDoc;  // we want to write to the template, not the actual data doc
            const effectiveAcl = GetEffectiveAcl(targetDataDoc);

            if (effectiveAcl === AclPrivate || effectiveAcl === AclReadonly) {
                return false;
            }
            const added = docs;
            if (added.length) {
                if ([AclAugment, AclEdit, AclAdmin].includes(effectiveAcl)) {
                    added.forEach(adoc => {
                        adoc._dragOnlyWithinContainer = undefined;
                        if (annotationKey ?? this._annotationKeySuffix()) adoc[DocData].annotationOn = this.Document;
                        else adoc[DocData].annotationOn = undefined;
                        Doc.SetContainer(adoc, this.Document);
                        inheritParentAcls(targetDataDoc, adoc, true);
                    });

                    const annoDocs = Doc.Get(targetDataDoc, annotationKey ?? this.annotationKey, true) as List<Doc>; // get the dataDoc directly ... when using templates there may be some default items already there, but we can't change them, so we copy them below (should really be some kind of inheritance since the template contents could change)
                    if (annoDocs instanceof List) annoDocs.push(...added.filter(add => !annoDocs.includes(add)));
                    else targetDataDoc[annotationKey ?? this.annotationKey] = new List<Doc>([...added, ...(annoDocs === undefined ? DocListCast(targetDataDoc[annotationKey ?? this.annotationKey]) : [])]);
                    targetDataDoc[(annotationKey ?? this.annotationKey) + '_modificationDate'] = new DateField();
                }
            }
            return true;
        };

        isAnyChildContentActive = () => this._isAnyChildContentActive;

        whenChildContentsActiveChanged = action((isActive: boolean) => {
            this._isAnyChildContentActive = isActive;
            this._props.whenChildContentsActiveChanged(isActive);
        });
    }
    return Component;
}