aboutsummaryrefslogtreecommitdiff
path: root/src/client/views/nodes/FontIconBox/FontIconBox.tsx
blob: ffb668b03d6167017464f8af7a214ba0d5d9cc86 (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
/* eslint-disable react/jsx-props-no-spreading */
import { IconProp } from '@fortawesome/fontawesome-svg-core';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { Button, ColorPicker, Dropdown, DropdownType, IconButton, IListItemProps, MultiToggle, NumberDropdown, NumberDropdownType, Popup, Size, Toggle, ToggleType, Type } from 'browndash-components';
import { action, computed, makeObservable, observable } from 'mobx';
import { observer } from 'mobx-react';
import * as React from 'react';
import { ClientUtils, returnFalse, returnTrue, setupMoveUpEvents } from '../../../../ClientUtils';
import { Doc, DocListCast, StrListCast } from '../../../../fields/Doc';
import { BoolCast, DocCast, NumCast, ScriptCast, StrCast } from '../../../../fields/Types';
import { emptyFunction } from '../../../../Utils';
import { Docs } from '../../../documents/Documents';
import { CollectionViewType, DocumentType } from '../../../documents/DocumentTypes';
import { SnappingManager } from '../../../util/SnappingManager';
import { undoable, UndoManager } from '../../../util/UndoManager';
import { ContextMenu } from '../../ContextMenu';
import { ViewBoxBaseComponent } from '../../DocComponent';
import { EditableView } from '../../EditableView';
import { SelectedDocView } from '../../selectedDoc';
import { StyleProp } from '../../StyleProp';
import { FieldView, FieldViewProps } from '../FieldView';
import { OpenWhere } from '../OpenWhere';
import './FontIconBox.scss';
import TrailsIcon from './TrailsIcon';

export enum ButtonType {
    TextButton = 'textBtn',
    MenuButton = 'menuBtn',
    DropdownList = 'dropdownList',
    ClickButton = 'clickBtn',
    ToggleButton = 'toggleBtn',
    ColorButton = 'colorBtn',
    ToolButton = 'toolBtn',
    MultiToggleButton = 'multiToggleBtn',
    NumberSliderButton = 'numSliderBtn',
    NumberDropdownButton = 'numDropdownBtn',
    NumberInlineButton = 'numInlineBtn',
    EditText = 'editableText',
}

export interface ButtonProps extends FieldViewProps {
    type?: ButtonType;
}
@observer
export class FontIconBox extends ViewBoxBaseComponent<ButtonProps>() {
    public static LayoutString(fieldKey: string) {
        return FieldView.LayoutString(FontIconBox, fieldKey);
    }

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

    @observable noTooltip = false;

    showTemplate = (dragFactory: Doc) => this._props.addDocTab(dragFactory, OpenWhere.addRight);
    specificContextMenu = (): void => {
        const dragFactory = DocCast(this.layoutDoc.dragFactory);
        if (!Doc.noviceMode && dragFactory) {
            ContextMenu.Instance.addItem({ description: 'Show Template', event: () => this.showTemplate(dragFactory), icon: 'tag' });
        }
    };

    /**
     * this chooses the appropriate title for the label
     * if the Document is a template, then we use the title of the data doc that it renders
     * otherwise, we use the Document's title itself.
     */
    @computed get label() {
        return StrCast(this.Document.isTemplateDoc ? this.dataDoc.title : this.Document.title);
    }
    Icon = (color: string, iconFalse?: boolean) => {
        let icon;
        if (iconFalse) {
            icon = StrCast(this.dataDoc[this.fieldKey ?? 'iconFalse'] ?? this.dataDoc.icon, 'user') as any;
            if (icon) return <FontAwesomeIcon className={`fontIconBox-icon-${this.type}`} icon={icon} color={color} />;
            return null;
        }
        icon = StrCast(this.dataDoc[this.fieldKey ?? 'icon'] ?? this.dataDoc.icon, 'user') as any;
        return !icon ? null : icon === 'pres-trail' ? TrailsIcon(color) : <FontAwesomeIcon className={`fontIconBox-icon-${this.type}`} icon={icon} color={color} />;
    };
    @computed get dropdown() {
        return BoolCast(this.Document.dropDownOpen);
    }
    @computed get buttonList() {
        return StrListCast(this.Document.btnList);
    }
    @computed get type() {
        return StrCast(this.Document.btnType);
    }

    /**
     * Types of buttons in dash:
     * - Main menu button (LHS)
     * - Tool button
     * - Expandable button (CollectionLinearView)
     * - Button inside of CollectionLinearView vs. outside of CollectionLinearView
     * - Action button
     * - Dropdown button
     * - Color button
     * - Dropdown list
     * - Number button
     * */

    _batch: UndoManager.Batch | undefined = undefined;
    /**
     * Number button
     */
    @computed get numberDropdown() {
        let type: NumberDropdownType;
        switch (this.type) {
            case ButtonType.NumberDropdownButton:  type = 'dropdown'; break;
            case ButtonType.NumberInlineButton:    type = 'input';  break;
            case ButtonType.NumberSliderButton:
            default:                               type = 'slider';
                break;
        } // prettier-ignore
        const numScript = (value?: number) => ScriptCast(this.Document.script).script.run({ this: this.Document, value, _readOnly_: value === undefined });
        const color = this._props.styleProvider?.(this.layoutDoc, this._props, StyleProp.Color);
        // Script for checking the outcome of the toggle
        const checkResult = Number(Number(numScript().result ?? 0).toPrecision(NumCast(this.dataDoc.numPrecision, 3)));

        return (
            <NumberDropdown
                color={color}
                background={SnappingManager.userBackgroundColor}
                numberDropdownType={type}
                showPlusMinus={false}
                tooltip={this.label}
                type={Type.PRIM}
                min={NumCast(this.dataDoc.numBtnMin, 0)}
                max={NumCast(this.dataDoc.numBtnMax, 100)}
                number={checkResult}
                setNumber={undoable(value => numScript(value), `${this.Document.title} button set from list`)}
                fillWidth
            />
        );
    }

    dropdownItemDown = (e: React.PointerEvent, value: string | number) => {
        setupMoveUpEvents(
            this,
            e,
            () => ScriptCast(this.Document.onDragScript)?.script.run({ this: this.Document, value: { doc: value, e } }).result,
            emptyFunction,
            emptyFunction
        ); // prettier-ignore
        return false;
    };

    /**
     * Dropdown list
     */
    @computed get dropdownListButton() {
        const script = ScriptCast(this.Document.script);

        let noviceList: string[] = [];
        let text: string | undefined;
        let getStyle: (val: string) => any = () => {};
        let icon: IconProp = 'caret-down';
        const isViewDropdown = script?.script.originalScript.startsWith('{ return setView');
        if (isViewDropdown) {
            const selected = Array.from(script?.script.run({ _readOnly_: true }).result) as Doc[];
            // const selected = DocumentView.SelectedDocs();
            if (selected.lastElement()) {
                if (StrCast(selected.lastElement().type) === DocumentType.COL) {
                    text = StrCast(selected.lastElement()._type_collection);
                } else {
                    if (selected.length > 1) {
                        text = selected.length + ' selected';
                    } else {
                        text = ClientUtils.cleanDocumentType(StrCast(selected.lastElement().type) as DocumentType, '' as CollectionViewType);
                        icon = Doc.toIcon(selected.lastElement());
                    }
                    return (
                        <Popup
                            icon={<FontAwesomeIcon size="1x" icon={icon} />}
                            text={text}
                            type={Type.TERT}
                            color={SnappingManager.userColor}
                            background={SnappingManager.userVariantColor}
                            popup={<SelectedDocView selectedDocs={selected} />}
                            fillWidth
                        />
                    );
                }
            } else {
                return <Button text="None Selected" type={Type.TERT} color={SnappingManager.userColor} background={SnappingManager.userVariantColor} fillWidth inactive />;
            }
            noviceList = [CollectionViewType.Freeform, CollectionViewType.Schema, CollectionViewType.Carousel3D, CollectionViewType.Stacking, CollectionViewType.NoteTaking];
        } else {
            text = script?.script.run({ this: this.Document, value: '', _readOnly_: true }).result;
            // text = StrCast((RichTextMenu.Instance?.TextView?.EditorView ? RichTextMenu.Instance : Doc.UserDoc()).fontFamily);
            getStyle = (val: string) => ({ fontFamily: val });
        }

        // Get items to place into the list
        const list: IListItemProps[] = this.buttonList
            .filter(value => !Doc.noviceMode || !noviceList.length || noviceList.includes(value))
            .map(value => ({
                text: typeof value === 'string' ? value.charAt(0).toUpperCase() + value.slice(1) : StrCast(DocCast(value)?.title),
                val: value,
                style: getStyle(value),
                // shortcut: '#',
            }));

        return (
            <Dropdown
                selectedVal={text}
                setSelectedVal={undoable(value => script.script.run({ this: this.Document, value }), `dropdown select ${this.label}`)}
                color={SnappingManager.userColor}
                background={SnappingManager.userVariantColor}
                type={Type.TERT}
                closeOnSelect={false}
                dropdownType={DropdownType.SELECT}
                onItemDown={this.dropdownItemDown}
                items={list}
                tooltip={this.label}
                fillWidth
            />
        );
    }

    @computed get colorScript() {
        return ScriptCast(this.Document.script);
    }

    colorBatch: UndoManager.Batch | undefined;
    /**
     * Color button
     */
    @computed get colorButton() {
        const color = this._props.styleProvider?.(this.layoutDoc, this._props, StyleProp.Color);
        const curColor = this.colorScript?.script.run({ this: this.Document, value: undefined, _readOnly_: true }).result ?? 'transparent';
        const tooltip: string = StrCast(this.Document.toolTip);

        return (
            <ColorPicker
                setSelectedColor={value => {
                    if (!this.colorBatch) this.colorBatch = UndoManager.StartBatch(`Set ${tooltip} color`);
                    this.colorScript?.script.run({ this: this.Document, value: value, _readOnly_: false });
                }}
                setFinalColor={value => {
                    this.colorScript?.script.run({ this: this.Document, value: value, _readOnly_: false });
                    this.colorBatch?.end();
                    this.colorBatch = undefined;
                }}
                defaultPickerType="Classic"
                selectedColor={curColor}
                type={Type.PRIM}
                color={color}
                background={SnappingManager.userBackgroundColor}
                icon={this.Icon(color)!}
                tooltip={tooltip}
                label={this.label}
            />
        );
    }
    @computed get multiToggleButton() {
        // Determine the type of toggle button
        const tooltip: string = StrCast(this.Document.toolTip);

        const script = ScriptCast(this.Document.onClick)?.script;
        const toggleStatus = script?.run({ this: this.Document, self: this.Document, value: undefined, _readOnly_: true }).result;
        // Colors
        const color = this._props.styleProvider?.(this.layoutDoc, this._props, StyleProp.Color);
        const items = DocListCast(this.dataDoc.data);
        const multiDoc = this.Document;
        return (
            <MultiToggle
                tooltip={`Toggle ${tooltip}`}
                type={Type.PRIM}
                color={color}
                onPointerDown={e => script && !toggleStatus && setupMoveUpEvents(this, e, returnFalse, emptyFunction, e => script.run({ this: multiDoc, value: undefined, _readOnly_: false }))}
                isToggle={script ? true : false}
                toggleStatus={toggleStatus}
                //background={SnappingManager.userBackgroundColor}
                label={this.label}
                items={DocListCast(this.dataDoc.data).map(item => ({
                    icon: <FontAwesomeIcon className={`fontIconBox-icon-${this.type}`} icon={StrCast(item.icon) as any} color={color} />,
                    tooltip: StrCast(item.toolTip),
                    val: StrCast(item.toolType),
                }))}
                selectedVal={StrCast(items.find(itemDoc => ScriptCast(itemDoc.onClick).script.run({ this: itemDoc, value: undefined, _readOnly_: true }).result)?.toolType ?? StrCast(multiDoc.toolType))}
                setSelectedVal={(val: string | number) => {
                    const itemDoc = items.find(item => item.toolType === val);
                    itemDoc && ScriptCast(itemDoc.onClick).script.run({ this: itemDoc, value: val, _readOnly_: false });
                }}
            />
        );
    }

    @observable _hackToRecompute = 0; // bcz: ugh ... <Toggle>'s toggleStatus initializes but doesn't track its value after a click.  so a click that does nothing to the toggle state will toggle the button anyway.  this forces the Toggle to re-read the ToggleStatus value.

    @computed get toggleButton() {
        // Determine the type of toggle button
        const buttonText = StrCast(this.dataDoc.buttonText);
        const tooltip = StrCast(this.Document.toolTip);

        const script = ScriptCast(this.Document.onClick);
        const double = ScriptCast(this.Document.onDoubleClick);
        const toggleStatus = script?.script.run({ this: this.Document, value: undefined, _readOnly_: true }).result ?? false;
        // Colors
        const color = this._props.styleProvider?.(this.layoutDoc, this._props, StyleProp.Color);
        // const backgroundColor = this._props.styleProvider?.(this.layoutDoc, this._props, StyleProp.BackgroundColor);

        return (
            <Toggle
                tooltip={`Toggle ${tooltip}`}
                toggleType={ToggleType.BUTTON}
                type={Type.PRIM}
                toggleStatus={toggleStatus}
                text={buttonText}
                color={color}
                // background={SnappingManager.userBackgroundColor}
                icon={this.Icon(color)!}
                label={this.label}
                onPointerDown={e =>
                    setupMoveUpEvents(
                        this,
                        e,
                        returnTrue,
                        emptyFunction,
                        action((clickEv, doubleTap) => {
                            (!doubleTap || !double) && script?.script.run({ this: this.Document, value: !toggleStatus, _readOnly_: false });
                            doubleTap && double?.script.run({ this: this.Document, value: !toggleStatus, _readOnly_: false });
                            this._hackToRecompute += 1;
                        })
                    )
                }
            />
        );
    }

    /**
     * Default
     */
    @computed get defaultButton() {
        const color = this._props.styleProvider?.(this.layoutDoc, this._props, StyleProp.Color);
        const tooltip: string = StrCast(this.Document.toolTip);

        return <IconButton tooltip={tooltip} icon={this.Icon(color)!} label={this.label} />;
    }

    @computed get editableText() {
        const script = ScriptCast(this.Document.script);
        const checkResult = script?.script.run({ this: this.Document, value: '', _readOnly_: true }).result;

        const setValue = (value: string): boolean => script?.script.run({ this: this.Document, value, _readOnly_: false }).result;

        return (
            <div className="menuButton editableText">
                <FontAwesomeIcon className={`fontIconBox-icon-${this.type}`} icon="lock" />
                <div style={{ width: 'calc(100% - .875em)', paddingLeft: '4px' }}>
                    <EditableView GetValue={() => script?.script.run({ this: this.Document, value: '', _readOnly_: true }).result} SetValue={setValue} oneLine contents={checkResult} />
                </div>
            </div>
        );
    }

    renderButton = () => {
        const color = this._props.styleProvider?.(this.layoutDoc, this._props, StyleProp.Color);
        const tooltip = StrCast(this.Document.toolTip);
        const scriptFunc = () => ScriptCast(this.Document.onClick)?.script.run({ this: this.Document, _readOnly_: false });
        const btnProps = { tooltip, icon: this.Icon(color)!, label: this.label };
        // prettier-ignore
        switch (this.type) {
            case ButtonType.NumberDropdownButton: 
            case ButtonType.NumberInlineButton:
            case ButtonType.NumberSliderButton: return this.numberDropdown;
            case ButtonType.EditText:           return this.editableText; 
            case ButtonType.DropdownList:       return this.dropdownListButton;
            case ButtonType.ColorButton:        return this.colorButton; 
            case ButtonType.MultiToggleButton:  return this.multiToggleButton;
            case ButtonType.ToggleButton:       return this.toggleButton;
            case ButtonType.ClickButton:return <IconButton {...btnProps} size={Size.MEDIUM} color={color} />;
            case ButtonType.ToolButton: return <IconButton {...btnProps} size={Size.LARGE} color={color} />;
            case ButtonType.TextButton: return <Button     {...btnProps} color={color} 
                        background={SnappingManager.userBackgroundColor} text={StrCast(this.dataDoc.buttonText)}/>;
            case ButtonType.MenuButton: return <IconButton {...btnProps} color={color} 
                        background={SnappingManager.userBackgroundColor} size={Size.LARGE} tooltipPlacement='right' onPointerDown={scriptFunc} />; 
            default: 
        }
        return this.defaultButton;
    };

    render() {
        return (
            <div style={{ margin: 'auto', width: '100%' }} onContextMenu={this.specificContextMenu}>
                {this.renderButton()}
            </div>
        );
    }
}

Docs.Prototypes.TemplateMap.set(DocumentType.FONTICON, {
    layout: { view: FontIconBox, dataField: 'icon' },
    options: { acl: '', defaultDoubleClick: 'ignore', waitForDoubleClickToClick: 'never', layout_hideContextMenu: true, layout_hideLinkButton: true, _width: 40, _height: 40 },
});