aboutsummaryrefslogtreecommitdiff
path: root/src/client/views/nodes/DataVizBox/DocCreatorMenu.tsx
blob: bae2d20006d5fe72aeb45bf27c5c002312bd4973 (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
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { IReactionDisposer, ObservableMap, action, computed, makeObservable, observable, reaction, runInAction } from 'mobx';
import { observer } from 'mobx-react';
import * as React from 'react';
import { returnAll, returnFalse, setupMoveUpEvents } from '../../../../ClientUtils';
import { Doc, NumListCast } from '../../../../fields/Doc';
import { DocCast, ImageCast } from '../../../../fields/Types';
import { ImageField } from '../../../../fields/URLField';
import { emptyFunction } from '../../../../Utils';
import { SnappingManager } from '../../../util/SnappingManager';
import { undoable } from '../../../util/UndoManager';
import { ObservableReactComponent } from '../../ObservableReactComponent';
import { DocumentView } from '../DocumentView';
import { DataVizBox } from './DataVizBox';
import './DocCreatorMenu.scss';
import { Id } from '../../../../fields/FieldSymbols';
import { Colors } from 'browndash-components';
import { MakeTemplate } from '../../../util/DropConverter';
import { threadId } from 'worker_threads';
import { ideahub } from 'googleapis/build/src/apis/ideahub';

export enum LayoutType {
    Stacked = 'stacked', 
    Grid = 'grid', 
    Row = 'row', 
    Column = 'column', 
    Custom = 'custom'
}

@observer
export class DocCreatorMenu extends ObservableReactComponent<{}> {

    static Instance: DocCreatorMenu;

    private _ref: HTMLDivElement | null = null;
    private _templateInfo: DataVizTemplateInfo = {};

    @observable _templateDocs: Doc[] = [];
    @observable _templateRefToDoc?: ObservableMap<HTMLDivElement, Doc>;
    @observable _selectedTemplate: Doc | undefined = undefined;

    @observable _layout: {type?: LayoutType, yMargin: number, xMargin: number, rows?:number, columns: number} = {yMargin: 0, xMargin: 0, columns: 1};
    @observable _layoutPreview: boolean = false;
    @observable _layoutPreviewScale: number = 1;

    @observable _pageX: number = 0;
    @observable _pageY: number = 0;
    @observable _display: boolean = false;

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

    @observable _menuContent: 'templates' | 'options' = 'templates';
    @observable _dragging: boolean = false;
    @observable _dataViz?: DataVizBox;

    constructor(props: any) {
        super(props);
        makeObservable(this);
        DocCreatorMenu.Instance = this;
    }

    @action setDataViz = (dataViz: DataVizBox) => { this._dataViz = dataViz };
    @action setTemplateDocs = (docs: Doc[]) => {this._templateDocs = docs.map(doc => doc.annotationOn ? DocCast(doc.annotationOn):doc)};

    @computed get docsToRender() {
        return NumListCast(this._dataViz?.layoutDoc.dataViz_selectedRows);
    }

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

    @computed get columnsCount(){
        switch (this._layout.type) {
            case LayoutType.Row:
                return this.docsToRender.length;
            case LayoutType.Column: case LayoutType.Stacked: 
                return 1;
            case LayoutType.Grid:
                return this._layout.columns ?? 0;
            default:
                return 0;
        }
    }

    setUpButtonClick = (e: any, func: Function) => {
        setupMoveUpEvents(
            this,
            e,
            returnFalse,
            emptyFunction,
            undoable(clickEv => {
                clickEv.stopPropagation();
                func();
            }, 'create docs')
        )
    }

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

    @action
    onPointerUp = (e: PointerEvent) => {
        if (e.button !== 2 && !e.ctrlKey) return;
        const curX = e.clientX;
        const curY = e.clientY;
        if (Math.abs(this._mouseX - curX) > 1 || Math.abs(this._mouseY - curY) > 1) {
            this._shouldDisplay = false;
        }
    };

    _disposer: IReactionDisposer | undefined;
    componentDidMount() {
        document.addEventListener('pointerdown', this.onPointerDown, true);
        document.addEventListener('pointerup', this.onPointerUp);
        this._disposer = reaction(() => this._templateDocs.slice(), (docs) => docs.map(this.getIcon));
    }

    componentWillUnmount() {
        this._disposer?.();
        document.removeEventListener('pointerdown', this.onPointerDown, true);
        document.removeEventListener('pointerup', this.onPointerUp);
    }

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

    @action
    closeMenu = () => {
        const wasOpen = this._display;
        this._display = false;
        this._shouldDisplay = false;
        return wasOpen;
    };

    @action
    onPointerMove = (e: any) => {
        if (this._dragging){
            this._pageX = e.pageX - (this._startPos?.x ?? 0);
            this._pageY = e.pageY - (this._startPos?.y ?? 0);
        }
    }

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

    get templatesPreviewContents(){
        const renderedTemplates: Doc[] = [];
        return (
            <div className='docCreatorMenu-preview-container'>
                {this._templateDocs.map(doc => ({icon: ImageCast(doc.icon), doc})).filter(info => info.icon && info.doc).map(info => {
                    if (renderedTemplates.includes(info.doc)) return undefined;
                    renderedTemplates.push(info.doc);
                    return (<div 
                    className='docCreatorMenu-preview-window'
                    style={{
                        background: this._selectedTemplate === info.doc ? Colors.MEDIUM_BLUE : '',
                        boxShadow: this._selectedTemplate === info.doc ? `0 0 15px rgba(68, 118, 247, .8)` : ''
                    }}
                    onPointerDown={e => this.setUpButtonClick(e, () => runInAction(() => {this._selectedTemplate = info.doc; MakeTemplate(info.doc);}))}>
                        <img className='docCreatorMenu-preview-image' src={info.icon!.url.href.replace(".png", "_o.png")} />
                    </div>
                )})}
            </div>
        );
    }

    @action updateXMargin = (input: string) => { this._layout.xMargin = Number(input) };
    @action updateYMargin = (input: string) => { this._layout.yMargin = Number(input) };
    @action updateColumns = (input: string) => { this._layout.columns = Number(input) };

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

        switch (this._layout.type) {
            case LayoutType.Row:
                return (
                    <div className='docCreatorMenu-configuration-bar'>
                        {optionInput('Margin:', this.updateXMargin, this._layout.xMargin, '0')}
                    </div>
                    );
            case LayoutType.Column:
                return (
                    <div className='docCreatorMenu-configuration-bar'>
                        {optionInput('Margin:', this.updateYMargin, this._layout.yMargin, '1')}
                    </div>
                    );
            case LayoutType.Grid:
                return (
                    <>
                    <div className='docCreatorMenu-configuration-bar'>
                        {optionInput('Y Margin:', this.updateYMargin, this._layout.xMargin, '2')}
                        {optionInput('X Margin:', this.updateXMargin, this._layout.xMargin, '3')}
                    </div>
                    <div className='docCreatorMenu-configuration-bar'>
                        {optionInput('Columns:', this.updateColumns, this._layout.columns, '3', true)}
                    </div>
                    </>
                );
            case LayoutType.Stacked:
                return null;
            default:
                break;
        }
    }

    get layoutPreviewContents() {
        const docWidth = Number(this._selectedTemplate?._width);
        const docHeight = Number(this._selectedTemplate?._height);
        const horizontalSpan: number = (docWidth + this._layout.xMargin) * this.columnsCount - this._layout.xMargin;
        const verticalSpan: number = (docHeight + this._layout.yMargin) * this.rowsCount - this._layout.yMargin;
        const largerSpan: number = horizontalSpan > verticalSpan ? horizontalSpan : verticalSpan;
        const scaledDown = (input: number) => {return input / (largerSpan / 225 * this._layoutPreviewScale)}
        const fontSize = Math.min(scaledDown(docWidth / 3), scaledDown(docHeight / 3));

        return (
            <div className='docCreatorMenu-layout-preview-window-wrapper'>
                <button 
                    className='docCreatorMenu-zoom-button'
                    onPointerDown={e => this.setUpButtonClick(e, () => runInAction(() => this._layoutPreviewScale *= 1.25))}>
                        <FontAwesomeIcon icon={'minus'}/>
                </button>
                <button 
                    className='docCreatorMenu-zoom-button zoom-in'
                    onPointerDown={e => this.setUpButtonClick(e, () => runInAction(() => this._layoutPreviewScale *= .75))}>
                        <FontAwesomeIcon icon={'plus'}/>
                </button>
                <div 
                className='docCreatorMenu-layout-preview-window'
                style={{
                    gridTemplateColumns: `repeat(${this.columnsCount}, ${scaledDown(docWidth)}px`,
                    gridTemplateRows: `${scaledDown(docHeight)}px`,
                    gridAutoRows: `${scaledDown(docHeight)}px`,
                    rowGap: `${scaledDown(this._layout.yMargin)}px`,
                    columnGap: `${scaledDown(this._layout.xMargin)}px`
                }}>
                    {this.docsToRender.map(num => 
                        <div 
                        className='docCreatorMenu-layout-preview-item'
                        style={{
                            width: scaledDown(docWidth), 
                            height: scaledDown(docHeight),
                            fontSize: fontSize,
                        }}
                        >
                            {num}
                        </div>
                    )}

                </div>
            </div>
        );
    }

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

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

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

        return (
            <div className='docCreatorMenu-menu-container'>
                <div className='docCreatorMenu-option-container layout'>
                    <div className='docCreatorMenu-dropdown-hoverable'>
                        <div className="docCreatorMenu-option-title">{this._layout.type ? this._layout.type.toUpperCase() : 'Choose Layout'}</div>
                        <div className="docCreatorMenu-dropdown-content">
                            {layoutOption(LayoutType.Stacked)}
                            {layoutOption(LayoutType.Grid, undefined, () => {this._layout.columns = Math.ceil(Math.sqrt(this.docsToRender.length))})}
                            {layoutOption(LayoutType.Row)}
                            {layoutOption(LayoutType.Column)}
                            {layoutOption(LayoutType.Custom, {borderBottom: `0px`})}
                        </div>
                    </div>
                    <button 
                        className='docCreatorMenu-menu-button'
                        onPointerDown={e => this.setUpButtonClick(e, () => runInAction(() => this._layoutPreview = !this._layoutPreview))}>
                        <FontAwesomeIcon icon={this._layoutPreview ? 'minus' : 'magnifying-glass'}/>
                    </button>
                </div>
                {this._layout.type ? this.layoutConfigOptions: null}
                {this._layoutPreview ? this.layoutPreviewContents : null}
                {selectionBox(100, 30, 'Repeat:', undefined, repeatOptions.map(num => <option onPointerDown={e => this._templateInfo.repeat = num}>{`${num}x`}</option>))}
            </div>
        );
    }

    render() {
        return (
            <div className='docCreatorMenu'>
                {!this._shouldDisplay ? undefined : 
                <div
                    className="docCreatorMenu-cont"
                    ref={r => this._ref = r}
                    style={{
                        display: '',
                        left: this._pageX,
                        top: this._pageY,
                        width: 300,
                        height: 400,
                        background: SnappingManager.userBackgroundColor,
                        color: SnappingManager.userColor,
                    }}>
                        <div 
                        className='docCreatorMenu-menu'
                        onPointerDown={e =>
                            setupMoveUpEvents(
                                this,
                                e,
                                (e) => {
                                    this._dragging = true;
                                    this._startPos = {x: 0, y: 0};
                                    this._startPos.x = e.pageX - (this._ref?.getBoundingClientRect().left ?? 0);
                                    this._startPos.y = e.pageY - (this._ref?.getBoundingClientRect().top ?? 0);
                                    return true;
                                },
                                emptyFunction,
                                undoable(clickEv => {
                                    clickEv.stopPropagation();
                                }, 'drag menu')
                            )
                        }
                        onPointerMove={e => this.onPointerMove(e)}
                        onPointerUp={() => this._dragging = false}
                        >  
                            <button 
                                className='docCreatorMenu-menu-button'
                                onPointerDown={e => this.setUpButtonClick(e, () => runInAction(() => this._menuContent = this._menuContent === 'templates' ? 'options' : 'templates'))}>
                                <FontAwesomeIcon icon={this._menuContent === 'templates' ? 'bars' : 'table-cells'}/>
                            </button>
                            <button 
                            className='docCreatorMenu-menu-button right'
                            onPointerDown={e => setupMoveUpEvents( this, e, returnFalse, emptyFunction,
                                    undoable(clickEv => {
                                        clickEv.stopPropagation();
                                        if (!this._selectedTemplate) return;
                                        const templateInfo: DataVizTemplateInfo = {doc: this._selectedTemplate};
                                        this._dataViz?.createDocsFromTemplate(templateInfo);
                                    }, 'make docs')
                                )
                            }>
                                <FontAwesomeIcon icon={'plus'}/>
                            </button>
                            <button 
                                className='docCreatorMenu-menu-button close-menu'
                                onPointerDown={e => this.setUpButtonClick(e, this.closeMenu)}>
                                <FontAwesomeIcon icon={'minus'}/>
                            </button>
                        </div>
                        <hr className='docCreatorMenu-menu-hr'/>
                        {this._menuContent === 'templates' ? this.templatesPreviewContents : this.optionsMenuContents}
                </div>
                }
            </div>
            )
        }
}

export interface DataVizTemplateInfo {
    doc?: Doc;
    layout?: LayoutType;
    repeat?: number;
}