aboutsummaryrefslogtreecommitdiff
path: root/src/client/views/EditableView.tsx
blob: e2490cec8e8358ef3394800826b3b534ab6f095e (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
import { action, IReactionDisposer, makeObservable, observable, reaction, runInAction } from 'mobx';
import { observer } from 'mobx-react';
import * as React from 'react';
import * as Autosuggest from 'react-autosuggest';
import './EditableView.scss';
import { DocumentIconContainer } from './nodes/DocumentIcon';
import { FieldView, FieldViewProps } from './nodes/FieldView';
import { ObservableReactComponent } from './ObservableReactComponent';
import { OverlayView } from './OverlayView';

export interface EditableProps {
    /**
     * Called to get the initial value for editing
     *  */
    GetValue(): string | undefined;
    /**
     * Called to apply changes
     * @param value - The string entered by the user to set the value to
     * @returns `true` if setting the value was successful, `false` otherwise
     *  */
    SetValue(value: string, shiftDown?: boolean, enterKey?: boolean): boolean;
    OnFillDown?(value: string): void;
    OnTab?(shift?: boolean): void;
    OnEmpty?(): void;

    /**
     * The contents to render when not editing
     */
    contents: JSX.Element | string;
    fieldContents?: FieldViewProps;
    fontStyle?: string;
    fontSize?: number;
    height?: number | 'auto';
    sizeToContent?: boolean;
    maxHeight?: number;
    display?: string;
    overflow?: string;
    autosuggestProps?: {
        resetValue: () => void;
        value: string;
        onChange: (e: React.FormEvent, { newValue }: { newValue: string }) => void;
        autosuggestProps: Autosuggest.AutosuggestProps<string, unknown>;
    };
    oneLine?: boolean; // whether to display the editable view as a single input line or as a textarea
    allowCRs?: boolean; // can carriage returns be entered
    editing?: boolean;
    isEditingCallback?: (isEditing: boolean) => void;
    menuCallback?: (x: number, y: number) => void;
    textCallback?: (char: string) => boolean;
    showMenuOnLoad?: boolean;
    background?: string | undefined;
    placeholder?: string;
    wrap?: string; // nowrap, pre-wrap, etc

    inputString?: boolean;
    inputStringPlaceholder?: string;
    prohibitedText?: Array<string>;
    onClick?: () => void;
    updateAlt?: (newAlt: string) => void;
    updateSearch?: (value: string) => void;
    highlightCells?: (text: string) => void;
}

/**
 * Customizable view that can be given an arbitrary view to render normally,
 * but can also be edited with customizable functions to get a string version
 * of the content, and set the value based on the entered string.
 */
@observer
export class EditableView extends ObservableReactComponent<EditableProps> {
    private _ref = React.createRef<HTMLDivElement>();
    private _inputref: HTMLInputElement | HTMLTextAreaElement | null = null;
    private _disposers: { [name: string]: IReactionDisposer } = {};
    _overlayDisposer?: () => void;
    @observable _editing: boolean = false;

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

    componentDidMount(): void {
        this._disposers.editing = reaction(
            () => this._editing,
            editing => {
                if (editing) {
                    setTimeout(() => {
                        if (this._inputref?.value.startsWith('=') || this._inputref?.value.startsWith(':=')) {
                            this._overlayDisposer?.();
                            this._overlayDisposer = OverlayView.Instance.addElement(<DocumentIconContainer />, { x: 0, y: 0 });
                            this._props.highlightCells?.(this._props.GetValue() ?? '');
                        }
                    });
                } else {
                    this._overlayDisposer?.();
                    this._overlayDisposer = undefined;
                    this._props.highlightCells?.('');
                }
            },
            { fireImmediately: true }
        );
    }

    componentDidUpdate(prevProps: Readonly<EditableProps>) {
        super.componentDidUpdate(prevProps);
        if (this._editing && this._props.editing === false) {
            this._inputref?.value && this.finalizeEdit(this._inputref.value, false, true, false);
        } else
            runInAction(() => {
                if (this._props.editing !== undefined) this._editing = this._props.editing;
            });
    }

    componentWillUnmount() {
        this._overlayDisposer?.();
        this._disposers.editing?.();
        this._inputref?.value && this.finalizeEdit(this._inputref.value, false, true, false);
    }

    onChange = (e: React.ChangeEvent) => {
        const targVal = (e.target as HTMLSelectElement).value;
        if (!(targVal?.startsWith(':=') || targVal?.startsWith('='))) {
            this._overlayDisposer?.();
            this._overlayDisposer = undefined;
        } else if (!this._overlayDisposer) {
            this._overlayDisposer = OverlayView.Instance.addElement(<DocumentIconContainer />, { x: 0, y: 0 });
        }
        this._props.updateSearch && this._props.updateSearch(targVal);
        this._props.highlightCells?.(targVal);
    };

    @action
    onKeyDown = (e: React.KeyboardEvent<HTMLInputElement | HTMLTextAreaElement>) => {
        if (e.nativeEvent.defaultPrevented) return; // hack .. DashFieldView grabs native events, but react ignores stoppedPropagation and preventDefault, so we need to check it here
        switch (e.key) {
            case 'Tab':
                e.stopPropagation();
                this.finalizeEdit(e.currentTarget.value, e.shiftKey, false, false);
                this._props.OnTab?.(e.shiftKey);
                break;
            case 'Backspace':
                e.stopPropagation();
                if (!e.currentTarget.value) this._props.OnEmpty?.();
                break;
            case 'Enter':
                if (this._props.allowCRs !== true) {
                    e.stopPropagation();
                    if (!e.ctrlKey) {
                        this.finalizeEdit(e.currentTarget.value, e.shiftKey, false, true);
                    } else if (this._props.OnFillDown) {
                        this._props.OnFillDown(e.currentTarget.value);
                        this._editing = false;
                        this._props.isEditingCallback?.(false);
                    }
                }
                break;
            case 'Escape':
                e.stopPropagation();
                this._editing = false;
                this._props.isEditingCallback?.(false);
                break;
            case 'ArrowUp':
            case 'ArrowDown':
            case 'ArrowLeft':
            case 'ArrowRight':
                //e.stopPropagation();
                break;
            case 'Shift':
            case 'Alt':
            case 'Meta':
            case 'Control':
                break;
            case ':':
                if (this._props.menuCallback) {
                    e.stopPropagation();
                    this._props.menuCallback(e.currentTarget.getBoundingClientRect().x, e.currentTarget.getBoundingClientRect().y);
                    break;
                }
            // eslint-disable-next-line no-fallthrough
            default:
                if (this._props.textCallback?.(e.key)) {
                    e.stopPropagation();
                    this._editing = false;
                    this._props.isEditingCallback?.(false);
                }
        }
    };

    @action
    onClick = (e?: React.MouseEvent) => {
        this._props.onClick && this._props.onClick();
        if (this._props.editing !== false) {
            e?.nativeEvent.stopPropagation();
            if (this._ref.current && this._props.showMenuOnLoad) {
                this._props.menuCallback?.(this._ref.current.getBoundingClientRect().x, this._ref.current.getBoundingClientRect().y);
            } else {
                this._editing = true;
                this._props.isEditingCallback?.(true);
            }
        }
    };

    @action
    finalizeEdit(value: string, shiftDown: boolean, lostFocus: boolean, enterKey: boolean) {
        if (this._props.SetValue(value, shiftDown, enterKey)) {
            this._editing = false;
            this._props.isEditingCallback?.(false);
        } else {
            this._editing = false;
            this._props.isEditingCallback?.(false);
            !lostFocus &&
                setTimeout(
                    action(() => {
                        this._editing = true;
                        this._props.isEditingCallback?.(true);
                    }),
                    0
                );
        }
    }

    stopPropagation(e: React.SyntheticEvent) {
        e.stopPropagation();
    }

    @action
    setIsFocused = (value: boolean) => {
        const wasFocused = this._editing;
        this._editing = value;
        return wasFocused !== this._editing;
    };

    @action
    setIsEditing = (value: boolean) => {
        this._editing = value;
        return this._editing;
    };

    renderEditor() {
        return this._props.autosuggestProps ? (
            <Autosuggest
                {...this._props.autosuggestProps.autosuggestProps}
                inputProps={{
                    className: 'editableView-input',
                    onKeyDown: this.onKeyDown,
                    autoFocus: true,
                    onBlur: e => this.finalizeEdit((e.currentTarget as HTMLSelectElement).value, false, true, false),
                    onPointerDown: this.stopPropagation,
                    onClick: this.stopPropagation,
                    onPointerUp: this.stopPropagation,
                    value: this._props.autosuggestProps.value,
                    onChange: this._props.autosuggestProps.onChange,
                }}
            />
        ) : this._props.oneLine !== false && this._props.GetValue()?.toString().indexOf('\n') === -1 ? (
            <input
                className="editableView-input"
                ref={r => { this._inputref = r; }} // prettier-ignore
                style={{ display: this._props.display, overflow: 'auto', fontSize: this._props.fontSize, minWidth: 20, background: this._props.background }}
                placeholder={this._props.placeholder}
                onBlur={e => this.finalizeEdit(e.currentTarget.value, false, true, false)}
                defaultValue={this._props.GetValue()}
                autoFocus
                onChange={this.onChange}
                onKeyDown={this.onKeyDown}
                onPointerDown={this.stopPropagation}
                onClick={this.stopPropagation}
                onPointerUp={this.stopPropagation}
            />
        ) : (
            <textarea
                className="editableView-input"
                ref={r => { this._inputref = r; }} // prettier-ignore
                style={{ display: this._props.display, overflow: 'auto', fontSize: this._props.fontSize, minHeight: `min(100%, ${(this._props.GetValue()?.split('\n').length || 1) * 15})`, minWidth: 20, background: this._props.background }}
                placeholder={this._props.placeholder}
                onBlur={e => this.finalizeEdit(e.currentTarget.value, false, true, false)}
                defaultValue={this._props.GetValue()}
                autoFocus
                onChange={this.onChange}
                onKeyDown={this.onKeyDown}
                onPointerDown={this.stopPropagation}
                onClick={this.stopPropagation}
                onPointerUp={this.stopPropagation}
            />
        );
    }

    staticDisplay = () => {
        let toDisplay;
        const gval = this._props.GetValue()?.replace(/\n/g, '\\r\\n');
        if (this._props.inputString) {
            toDisplay = (
                <input
                    className="editableView-input"
                    value={gval}
                    placeholder={this._props.inputStringPlaceholder}
                    readOnly
                    style={{ display: this._props.display, overflow: 'auto', pointerEvents: 'none', fontSize: this._props.fontSize, width: '100%', margin: 0, background: this._props.background }}
                />
            );
        } else {
            toDisplay = (
                <span
                    className="editableView-static"
                    style={{
                        fontStyle: this._props.fontStyle,
                        fontSize: this._props.fontSize,
                    }}>
                    {this._props.fieldContents ? <FieldView {...this._props.fieldContents} /> : (this.props.contents ?? '')}
                </span>
            );
        }

        return toDisplay;
    };

    render() {
        const gval = this._props.GetValue()?.replace(/\n/g, '\\r\\n');
        if (this._editing && gval !== undefined) {
            return this._props.sizeToContent ? (
                <div style={{ display: 'grid', minWidth: 100 }}>
                    <div style={{ display: 'inline-block', position: 'relative', height: 0, width: '100%', overflow: 'hidden' }}>{this.renderEditor()}</div>
                </div>
            ) : (
                this.renderEditor()
            );
        }
        setTimeout(() => this._props.autosuggestProps?.resetValue());
        return (
            <div
                className={`editableView-container-editing${this._props.oneLine ? '-oneLine' : ''}`}
                ref={this._ref}
                style={{
                    display: this._props.display, //
                    textOverflow: this._props.overflow,
                    minHeight: '10px',
                    whiteSpace: this._props.oneLine ? 'nowrap' : 'pre-line',
                    height: this._props.height,
                    width: '100%',
                    maxHeight: this._props.maxHeight,
                    fontStyle: this._props.fontStyle,
                    fontSize: this._props.fontSize,
                }}
                onClick={this.onClick}>
                {this.staticDisplay()}
            </div>
        );
    }
}