aboutsummaryrefslogtreecommitdiff
path: root/src/client/views/nodes/CollectionFreeFormDocumentView.tsx
blob: ad5aabc215c3d913c4ac1cab1847e5dc57033d31 (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
import { action, computed, makeObservable, observable } from 'mobx';
import { observer } from 'mobx-react';
import * as React from 'react';
import { OmitKeys, numberRange } from '../../../Utils';
import { Doc, DocListCast, Opt } from '../../../fields/Doc';
import { List } from '../../../fields/List';
import { listSpec } from '../../../fields/Schema';
import { ComputedField } from '../../../fields/ScriptField';
import { Cast, NumCast, StrCast } from '../../../fields/Types';
import { TraceMobx } from '../../../fields/util';
import { DocumentManager } from '../../util/DocumentManager';
import { ScriptingGlobals } from '../../util/ScriptingGlobals';
import { SelectionManager } from '../../util/SelectionManager';
import { DocComponent } from '../DocComponent';
import { StyleProp } from '../StyleProvider';
import { CollectionFreeFormView } from '../collections/collectionFreeForm/CollectionFreeFormView';
import './CollectionFreeFormDocumentView.scss';
import { DocumentView, DocumentViewInternalProps, DocumentViewProps, OpenWhere } from './DocumentView';
import { FieldViewProps } from './FieldView';

export interface CollectionFreeFormDocumentViewWrapperProps extends DocumentViewProps {
    x: number;
    y: number;
    z: number;
    width: number;
    height: number;
    zIndex?: number;
    autoDim?: number; // 1 means use Panel Width/Height, 0 means use width/height
    rotation?: number;
    color?: string;
    backgroundColor?: string;
    opacity?: number;
    highlight?: boolean;
    transition?: string;
    dataTransition?: string;
    RenderCutoffProvider: (doc: Doc) => boolean;
    CollectionFreeFormView: CollectionFreeFormView;
}
@observer
export class CollectionFreeFormDocumentViewWrapper extends DocComponent<CollectionFreeFormDocumentViewWrapperProps & { fieldKey: string }>() implements CollectionFreeFormDocumentViewProps {
    constructor(props: any) {
        super(props);
        makeObservable(this);
    }
    @observable X = this.props.x;
    @observable Y = this.props.y;
    @observable Z = this.props.z;
    @observable ZIndex = this.props.zIndex;
    @observable Rotation = this.props.rotation;
    @observable Opacity = this.props.opacity;
    @observable BackgroundColor = this.props.backgroundColor;
    @observable Color = this.props.color;
    @observable Highlight = this.props.highlight;
    @observable Width = this.props.width;
    @observable Height = this.props.height;
    @observable AutoDim = this.props.autoDim;
    @observable Transition = this.props.transition;
    @observable DataTransition = this.props.dataTransition;
    CollectionFreeFormView = this.props.CollectionFreeFormView; // needed for type checking
    RenderCutoffProvider = this.props.RenderCutoffProvider; // needed for type checking

    @computed get WrapperKeys() {
        return Object.keys(this).filter(key => key.startsWith('w_')).map(key => key.replace('w_', ''))
                  .map(key => ({upper:key, lower:key[0].toLowerCase() + key.substring(1)})); // prettier-ignore
    }

    // wrapper functions around prop fields that have been converted to observables to keep 'props' from ever changing.
    // this way, downstream code only invalidates when it uses a specific prop, not when any prop changes
    w_X = ()               => this.X; // prettier-ignore
    w_Y = ()               => this.Y; // prettier-ignore
    w_Z = ()               => this.Z; // prettier-ignore
    w_ZIndex = ()          => this.ZIndex ?? NumCast(this.Document.zIndex); // prettier-ignore
    w_Rotation = ()        => this.Rotation ?? NumCast(this.Document._rotation); // prettier-ignore
    w_Opacity = ()         => this.Opacity; // prettier-ignore
    w_BackgroundColor = () => this.BackgroundColor ?? Cast(this.Document._backgroundColor, 'string', null); // prettier-ignore
    w_Color = ()           => this.Color ?? Cast(this.Document._color, 'string', null); // prettier-ignore
    w_Highlight = ()       => this.Highlight; // prettier-ignore
    w_Width = ()           => this.Width; // prettier-ignore
    w_Height = ()          => this.Height; // prettier-ignore
    w_AutoDim = ()         => this.AutoDim; // prettier-ignore
    w_Transition = ()      => this.Transition; // prettier-ignore
    w_DataTransition = ()  => this.DataTransition; // prettier-ignore

    PanelWidth = ()        => this._props.autoDim ? this._props.PanelWidth?.() : this.Width; // prettier-ignore
    PanelHeight = ()       => this._props.autoDim ? this._props.PanelHeight?.() : this.Height; // prettier-ignore

    componentDidUpdate(prevProps: Readonly<React.PropsWithChildren<CollectionFreeFormDocumentViewWrapperProps & { fieldKey: string }>>) {
        super.componentDidUpdate(prevProps);
        this.WrapperKeys.forEach(action(keys => ((this as any)[keys.upper] = (this.props as any)[keys.lower])));
    }
    render() {
        const layoutProps = this.WrapperKeys.reduce((val, keys) => [(val['w_' + keys.upper] = (this as any)['w_' + keys.upper]), val][1], {} as { [key: string]: Function });
        return (
            <CollectionFreeFormDocumentView
                {...OmitKeys(this._props, this.WrapperKeys.map(keys => keys.lower) ).omit} // prettier-ignore
                {...layoutProps}
                PanelWidth={this.PanelWidth}
                PanelHeight={this.PanelHeight}
            />
        );
    }
}
export interface CollectionFreeFormDocumentViewProps {
    w_X: () => number;
    w_Y: () => number;
    w_Z: () => number;
    w_ZIndex?: () => number;
    w_Rotation?: () => number;
    w_Color: () => string;
    w_BackgroundColor: () => string;
    w_Opacity: () => number | undefined;
    w_Highlight: () => boolean | undefined;
    w_Transition: () => string | undefined;
    w_Width: () => number;
    w_Height: () => number;
    w_DataTransition: () => string | undefined;
    PanelWidth: () => number;
    PanelHeight: () => number;
    RenderCutoffProvider: (doc: Doc) => boolean;
    CollectionFreeFormView: CollectionFreeFormView;
}

@observer
export class CollectionFreeFormDocumentView extends DocComponent<CollectionFreeFormDocumentViewProps & DocumentViewProps>() {
    constructor(props: any) {
        super(props);
        makeObservable(this);
    }
    get displayName() { // this makes mobx trace() statements more descriptive
        return 'CollectionFreeFormDocumentView(' + this.Document.title + ')';
    } // prettier-ignore
    public static animFields: { key: string; val?: number }[] = [
        { key: 'x' },
        { key: 'y' },
        { key: 'opacity', val: 1 },
        { key: '_height' },
        { key: '_width' },
        { key: '_rotation', val: 0 },
        { key: '_layout_scrollTop' },
        { key: '_currentFrame' },
        { key: 'freeform_scale', val: 1 },
        { key: 'freeform_panX' },
        { key: 'freeform_panY' },
    ]; // fields that are configured to be animatable using animation frames
    public static animStringFields = ['backgroundColor', 'color', 'fillColor']; // fields that are configured to be animatable using animation frames
    public static animDataFields = (doc: Doc) => (Doc.LayoutFieldKey(doc) ? [Doc.LayoutFieldKey(doc)] : []); // fields that are configured to be animatable using animation frames

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

    styleProvider = (doc: Doc | undefined, props: Opt<DocumentViewInternalProps | FieldViewProps>, property: string) => {
        if (doc === this.layoutDoc) {
            switch (property) {
                case StyleProp.Opacity:         return this._props.w_Opacity(); // only change the opacity for this specific document, not its children
                case StyleProp.BackgroundColor: return this._props.w_BackgroundColor();
                case StyleProp.Color:           return this._props.w_Color();
            } // prettier-ignore
        }
        return this._props.styleProvider?.(doc, props, property);
    };

    public static getValues(doc: Doc, time: number, fillIn: boolean = true) {
        return CollectionFreeFormDocumentView.animFields.reduce(
            (p, val) => {
                p[val.key] = Cast(doc[`${val.key}_indexed`], listSpec('number'), fillIn ? [NumCast(doc[val.key], val.val)] : []).reduce((p, v, i) => ((i <= Math.round(time) && v !== undefined) || p === undefined ? v : p), undefined as any as number);
                return p;
            },
            {} as { [val: string]: Opt<number> }
        );
    }

    public static getStringValues(doc: Doc, time: number) {
        return CollectionFreeFormDocumentView.animStringFields.reduce(
            (p, val) => {
                p[val] = Cast(doc[`${val}_indexed`], listSpec('string'), [StrCast(doc[val])]).reduce((p, v, i) => ((i <= Math.round(time) && v !== undefined) || p === undefined ? v : p), undefined as any as string);
                return p;
            },
            {} as { [val: string]: Opt<string> }
        );
    }

    public static setStringValues(time: number, d: Doc, vals: { [val: string]: Opt<string> }) {
        const timecode = Math.round(time);
        Object.keys(vals).forEach(val => {
            const findexed = Cast(d[`${val}_indexed`], listSpec('string'), []).slice();
            findexed[timecode] = vals[val] as any as string;
            d[`${val}_indexed`] = new List<string>(findexed);
        });
    }

    public static setValues(time: number, d: Doc, vals: { [val: string]: Opt<number> }) {
        const timecode = Math.round(time);
        Object.keys(vals).forEach(val => {
            const findexed = Cast(d[`${val}_indexed`], listSpec('number'), []).slice();
            findexed[timecode] = vals[val] as any as number;
            d[`${val}_indexed`] = new List<number>(findexed);
        });
    }
    public static gotoKeyFrame(doc: Doc, newFrame: number) {
        if (doc) {
            const childDocs = DocListCast(doc[Doc.LayoutFieldKey(doc)]);
            const currentFrame = Cast(doc._currentFrame, 'number', null);
            if (currentFrame === undefined) {
                doc._currentFrame = 0;
                CollectionFreeFormDocumentView.setupKeyframes(childDocs, 0);
            }
            CollectionFreeFormView.updateKeyframe(undefined, [...childDocs, doc], currentFrame || 0);
            doc._currentFrame = newFrame === undefined ? 0 : Math.max(0, newFrame);
        }
    }

    public static setupKeyframes(docs: Doc[], currTimecode: number, makeAppear: boolean = false) {
        docs.forEach(doc => {
            if (doc.appearFrame === undefined) doc.appearFrame = currTimecode;
            if (!doc['opacity_indexed']) {
                // opacity is unlike other fields because it's value should not be undefined before it appears to enable it to fade-in
                doc['opacity_indexed'] = new List<number>(numberRange(currTimecode + 1).map(t => (!doc.z && makeAppear && t < NumCast(doc.appearFrame) ? 0 : 1)));
            }
            CollectionFreeFormDocumentView.animFields.forEach(val => (doc[val.key] = ComputedField.MakeInterpolatedNumber(val.key, 'activeFrame', doc, currTimecode, val.val)));
            CollectionFreeFormDocumentView.animStringFields.forEach(val => (doc[val] = ComputedField.MakeInterpolatedString(val, 'activeFrame', doc, currTimecode)));
            CollectionFreeFormDocumentView.animDataFields(doc).forEach(val => (doc[val] = ComputedField.MakeInterpolatedDataField(val, 'activeFrame', doc, currTimecode)));
            const targetDoc = doc; // data fields, like rtf 'text' exist on the data doc, so
            //doc !== targetDoc && (targetDoc.embedContainer = doc.embedContainer); // the computed fields don't see the layout doc -- need to copy the embedContainer to the data doc (HACK!!!) and set the activeFrame on the data doc (HACK!!!)
            targetDoc.activeFrame = ComputedField.MakeFunction('this.embedContainer?._currentFrame||0');
            targetDoc.dataTransition = 'inherit';
        });
    }

    @action public float = () => {
        const topDoc = this.Document;
        const containerDocView = this._props.docViewPath().lastElement();
        const screenXf = containerDocView?.screenToContentsTransform();
        if (screenXf) {
            SelectionManager.DeselectAll();
            if (topDoc.z) {
                const spt = screenXf.inverse().transformPoint(NumCast(topDoc.x), NumCast(topDoc.y));
                topDoc.z = 0;
                topDoc.x = spt[0];
                topDoc.y = spt[1];
                this._props.removeDocument?.(topDoc);
                this._props.addDocTab(topDoc, OpenWhere.inParentFromScreen);
            } else {
                const spt = this.screenToLocalTransform().inverse().transformPoint(0, 0);
                const fpt = screenXf.transformPoint(spt[0], spt[1]);
                topDoc.z = 1;
                topDoc.x = fpt[0];
                topDoc.y = fpt[1];
            }
            setTimeout(() => SelectionManager.SelectView(DocumentManager.Instance.getDocumentView(topDoc, containerDocView), false), 0);
        }
    };

    nudge = (x: number, y: number) => {
        const [locX, locY] = this.ScreenToLocalBoxXf().transformDirection(x, y);
        this._props.Document.x = this._props.w_X() + locX;
        this._props.Document.y = this._props.w_Y() + locY;
    };
    screenToLocalTransform = () =>
        this._props
            .ScreenToLocalTransform()
            .translate(-this._props.w_X(), -this._props.w_Y())
            .rotateDeg(-(this._props.w_Rotation?.() || 0));
    returnThis = () => this;

    /// this indicates whether the doc view is activated because of its relationshop to a group
    //  'group' - this is a group that is activated because it's on an active canvas, but is not part of some other group
    //  'child' - this is a group child that is activated because its containing group is activated
    //  'inactive' - this is a group child but it is not active
    //  undefined - this is not activated by a group
    isGroupActive = () => {
        if (this.CollectionFreeFormView.isAnyChildContentActive()) return undefined;
        const isGroup = this.dataDoc.isGroup && (!this.layoutDoc.backgroundColor || this.layoutDoc.backgroundColor === 'transparent');
        return isGroup ? (this._props.isDocumentActive?.() ? 'group' : this._props.isGroupActive?.() ? 'child' : 'inactive') : this._props.isGroupActive?.() ? 'child' : undefined;
    };
    public static CollectionFreeFormDocViewClassName = 'collectionFreeFormDocumentView-container';
    render() {
        TraceMobx();
        const passOnProps = OmitKeys(this._props, Object.keys(this._props).filter(key => key.startsWith('w_'))).omit; // prettier-ignore
        return (
            <div
                className={CollectionFreeFormDocumentView.CollectionFreeFormDocViewClassName}
                style={{
                    width: this._props.PanelWidth(),
                    height: this._props.PanelHeight(),
                    transform: `translate(${this._props.w_X()}px, ${this._props.w_Y()}px) rotate(${NumCast(this._props.w_Rotation?.())}deg)`,
                    transition: this._props.w_Transition?.() ?? (this._props.w_DataTransition?.() || this._props.w_Transition?.()),
                    zIndex: this._props.w_ZIndex?.(),
                    display: this._props.w_Width?.() ? undefined : 'none',
                }}>
                {this._props.RenderCutoffProvider(this._props.Document) ? (
                    <div style={{ position: 'absolute', width: this._props.PanelWidth(), height: this._props.PanelHeight(), background: 'lightGreen' }} />
                ) : (
                    <DocumentView {...passOnProps} CollectionFreeFormDocumentView={this.returnThis} styleProvider={this.styleProvider} ScreenToLocalTransform={this.screenToLocalTransform} isGroupActive={this.isGroupActive} />
                )}
            </div>
        );
    }
}
ScriptingGlobals.add(function gotoFrame(doc: any, newFrame: any) {
    CollectionFreeFormDocumentView.gotoKeyFrame(doc, newFrame);
});