aboutsummaryrefslogtreecommitdiff
path: root/src/client/views/nodes/LabelBox.tsx
blob: bcf55fbe850e2e551ff3fe8db84b04b63e55d842 (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
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { Tooltip } from '@mui/material';
import { Property } from 'csstype';
import { action, computed, makeObservable, observable } from 'mobx';
import { observer } from 'mobx-react';
import * as React from 'react';
import * as textfit from 'textfit';
import { returnFalse, setupMoveUpEvents } from '../../../ClientUtils';
import { emptyFunction } from '../../../Utils';
import { Field, FieldType } from '../../../fields/Doc';
import { BoolCast, NumCast, StrCast } from '../../../fields/Types';
import { TraceMobx } from '../../../fields/util';
import { DocumentType } from '../../documents/DocumentTypes';
import { Docs } from '../../documents/Documents';
import { DragManager } from '../../util/DragManager';
import { ViewBoxBaseComponent } from '../DocComponent';
import { PinDocView, PinProps } from '../PinFuncs';
import { StyleProp } from '../StyleProp';
import { FieldView, FieldViewProps } from './FieldView';
import './LabelBox.scss';

@observer
export class LabelBox extends ViewBoxBaseComponent<FieldViewProps>() {
    public static LayoutString(fieldKey: string) {
        return FieldView.LayoutString(LabelBox, fieldKey);
    }
    private dropDisposer?: DragManager.DragDropDisposer;
    private _timeout: NodeJS.Timeout | undefined;
    @observable private _editLabel = false;
    _divRef: HTMLDivElement | null = null;

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

    protected createDropTarget = (ele: HTMLDivElement) => {
        this.dropDisposer?.();
        if (ele) {
            this.dropDisposer = DragManager.MakeDropTarget(ele, this.drop.bind(this), this.Document);
        }
    };

    @computed get Title() {
        return Field.toString(this.dataDoc[this.fieldKey] as FieldType) || StrCast(this.Document.title);
    }

    @computed get backgroundColor() {
        return this._props.styleProvider?.(this.Document, this._props, StyleProp.BackgroundColor) as string;
    }

    @computed get answerIcon() {
        return (
            <Tooltip
                title={
                    <div className="answer-tooltip" style={{ minWidth: '150px' }}>
                        {StrCast(this.Document.quiz)}
                    </div>
                }>
                <div className="answer-tool-tip">
                    <FontAwesomeIcon className="q-icon" icon="circle" color="white" />
                    <FontAwesomeIcon className="answer-icon" icon="question" />
                </div>
            </Tooltip>
        );
    }

    @computed get editAnswer() {
        return (
            <Tooltip
                title={
                    <div className="answer-tooltip" style={{ minWidth: '150px' }}>
                        {this._editLabel ? 'save' : 'edit correct answer'}
                    </div>
                }>
                <div className="answer-tool-tip" onPointerDown={e => setupMoveUpEvents(e.target, e, returnFalse, emptyFunction, () => this.editLabelAnswer())}>
                    <FontAwesomeIcon className="edit-icon" color={this._editLabel ? 'white' : 'black'} icon="pencil" size="sm" />
                </div>
            </Tooltip>
        );
    }

    editLabelAnswer = () => {
        // when click the pencil, set the text to the quiz content. when click off, set the quiz text to that and set textbox to nothing.
        if (!this._editLabel) {
            this.dataDoc.title = StrCast(this.Document.quiz);
        } else {
            this.Document.quiz = this.Title;
            this.dataDoc.title = '';
        }
        this._editLabel = !this._editLabel;
    };

    componentDidMount() {
        this._props.setContentViewBox?.(this);
    }
    componentWillUnMount() {
        this._timeout && clearTimeout(this._timeout);
    }

    specificContextMenu = (): void => {};

    drop = (/* e: Event, de: DragManager.DropEvent */) => {
        return false;
    };

    getAnchor = (addAsAnnotation: boolean, pinProps?: PinProps) => {
        if (!pinProps) return this.Document;
        const anchor = Docs.Create.ConfigDocument({ title: StrCast(this.Document.title), annotationOn: this.Document });

        if (anchor) {
            if (!addAsAnnotation) anchor.backgroundColor = 'transparent';
            //  addAsAnnotation && this.addDocument(anchor);
            PinDocView(anchor, { pinDocLayout: pinProps?.pinDocLayout, pinData: { ...(pinProps?.pinData ?? {}) } }, this.Document);
            return anchor;
        }
        return anchor;
    };

    fitTextToBox = (
        r: HTMLElement | null | undefined
    ): {
        minFontSize: number;
        maxFontSize: number;
        multiLine: boolean;
        alignHoriz: boolean;
        alignVert: boolean;
        detectMultiLine: boolean;
    } => {
        this._timeout && clearTimeout(this._timeout);
        const textfitParams = {
            minFontSize: NumCast(this.layoutDoc._label_minFontSize, 1),
            maxFontSize: NumCast(this.layoutDoc._label_maxFontSize, 100),
            multiLine: BoolCast(this.layoutDoc._singleLine, true) ? false : true,
            alignHoriz: true,
            alignVert: true,
            detectMultiLine: true,
        };
        if (r) {
            if (!r.offsetHeight || !r.offsetWidth) {
                console.log("CAN'T FIT TO EMPTY BOX");
                this._timeout && clearTimeout(this._timeout);
                this._timeout = setTimeout(() => this.fitTextToBox(r));
                return textfitParams;
            }
            textfit(r, textfitParams);
        }
        return textfitParams;
    };
    render() {
        TraceMobx();
        const boxParams = this.fitTextToBox(undefined); // this causes mobx to trigger re-render when data changes
        const label = this.Title.startsWith('#') ? null : this.Title;
        return (
            <div key={label?.length} className="labelBox-outerDiv" ref={this.createDropTarget} onContextMenu={this.specificContextMenu} style={{ boxShadow: this._props.styleProvider?.(this.layoutDoc, this._props, StyleProp.BoxShadow) as string }}>
                <div
                    className="labelBox-mainButton"
                    style={{
                        backgroundColor: this.backgroundColor,
                        // fontSize: StrCast(this.layoutDoc._text_fontSize),
                        color: StrCast(this.layoutDoc._color),
                        fontFamily: StrCast(this.layoutDoc._text_fontFamily) || 'inherit',
                        letterSpacing: StrCast(this.layoutDoc.letterSpacing),
                        textTransform: StrCast(this.layoutDoc.textTransform) as Property.TextTransform,
                        paddingLeft: NumCast(this.layoutDoc._xPadding),
                        paddingRight: NumCast(this.layoutDoc._xPadding),
                        paddingTop: NumCast(this.layoutDoc._yPadding),
                        paddingBottom: NumCast(this.layoutDoc._yPadding),
                        width: this._props.PanelWidth(),
                        height: this._props.PanelHeight(),
                        whiteSpace: 'multiLine' in boxParams && boxParams.multiLine ? 'pre-wrap' : 'pre',
                    }}
                    // onMouseLeave={() => {
                    //     this.hoverFlip(undefined);
                    // }}
                >
                    <div
                        style={{
                            width: this._props.PanelWidth() - 2 * NumCast(this.layoutDoc._xPadding),
                            height: this._props.PanelHeight() - 2 * NumCast(this.layoutDoc._yPadding),
                            outline: 'unset !important',
                        }}
                        onKeyDown={action(e => {
                            e.stopPropagation();
                        })}
                        onKeyUp={action(e => {
                            e.stopPropagation();
                            // if (e.key === 'Enter') {
                            this.dataDoc[this.fieldKey] = this._divRef?.innerText ?? '';
                            setTimeout(() => this._props.select(false));
                            // }
                        })}
                        onBlur={() => {
                            this.dataDoc[this.fieldKey] = this._divRef?.innerText ?? '';
                        }}
                        contentEditable={this._props.onClickScript?.() ? false : true}
                        ref={r => {
                            this._divRef = r;
                            this.fitTextToBox(r);
                            if (this._props.isSelected() && this._divRef) {
                                const range = document.createRange();
                                range.setStart(this._divRef, this._divRef.childNodes.length);
                                range.setEnd(this._divRef, this._divRef.childNodes.length);
                                const sel = window.getSelection();
                                sel?.removeAllRanges();
                                sel?.addRange(range);
                            }
                        }}>
                        {label}
                    </div>
                </div>
                {this.Document.showQuiz ? this.answerIcon : null}
                {this.Document.showQuiz ? this.editAnswer : null}
            </div>
        );
    }
}

Docs.Prototypes.TemplateMap.set(DocumentType.LABEL, {
    layout: { view: LabelBox, dataField: 'title' },
    options: { acl: '', _singleLine: true, _layout_nativeDimEditable: true, _layout_reflowHorizontal: true, _layout_reflowVertical: true },
});
Docs.Prototypes.TemplateMap.set(DocumentType.BUTTON, {
    layout: { view: LabelBox, dataField: 'title' },
    options: { acl: '', _layout_nativeDimEditable: true, _layout_reflowHorizontal: true, _layout_reflowVertical: true },
});