aboutsummaryrefslogtreecommitdiff
path: root/src/client/views/ScriptingRepl.tsx
blob: ba2e22b3babacd25fa74c4e2eda266dcac7056fb (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
/* eslint-disable react/no-array-index-key */
/* eslint-disable jsx-a11y/no-static-element-interactions */
/* eslint-disable jsx-a11y/click-events-have-key-events */
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { action, makeObservable, observable } from 'mobx';
import { observer } from 'mobx-react';
import * as React from 'react';
import { DocumentManager } from '../util/DocumentManager';
import { CompileScript, Transformer, ts } from '../util/Scripting';
import { ScriptingGlobals } from '../util/ScriptingGlobals';
import { SettingsManager } from '../util/SettingsManager';
import { undoable } from '../util/UndoManager';
import { ObservableReactComponent } from './ObservableReactComponent';
import { OverlayView } from './OverlayView';
import './ScriptingRepl.scss';
import { DocumentIconContainer } from './nodes/DocumentIcon';

interface replValueProps {
    scrollToBottom: () => void;
    value: any;
    name?: string;
}
@observer
export class ScriptingValueDisplay extends ObservableReactComponent<replValueProps> {
    constructor(props: any) {
        super(props);
        makeObservable(this);
    }

    render() {
        const val = this._props.name ? this._props.value[this._props.name] : this._props.value;
        const title = (name: string) => (
            <>
                {this._props.name ? <b>{this._props.name} : </b> : <> </>}
                {name}
            </>
        );
        if (typeof val === 'object') {
            // eslint-disable-next-line no-use-before-define
            return <ScriptingObjectDisplay scrollToBottom={this._props.scrollToBottom} value={val} name={this._props.name} />;
        }
        if (typeof val === 'function') {
            return <div className="scriptingObject-leaf">{title('[Function]')}</div>;
        }
        return <div className="scriptingObject-leaf">{title(String(val))}</div>;
    }
}
interface ReplProps {
    scrollToBottom: () => void;
    value: { [key: string]: any };
    name?: string;
}
export class ScriptingObjectDisplay extends ObservableReactComponent<ReplProps> {
    @observable collapsed = true;

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

    @action
    toggle = () => {
        this.collapsed = !this.collapsed;
        this._props.scrollToBottom();
    };

    render() {
        const val = this._props.value;
        const proto = Object.getPrototypeOf(val);
        const name = (proto && proto.constructor && proto.constructor.name) || String(val);
        const title = (
            <>
                {this.props.name ? <b>{this._props.name} : </b> : null}
                {name}
            </>
        );
        if (this.collapsed) {
            return (
                <div className="scriptingObject-collapsed">
                    <span onClick={this.toggle} className="scriptingObject-icon scriptingObject-iconCollapsed">
                        <FontAwesomeIcon icon="caret-right" size="sm" />
                    </span>
                    {title} (+{Object.keys(val).length})
                </div>
            );
        }
        return (
            <div className="scriptingObject-open">
                <div>
                    <span onClick={this.toggle} className="scriptingObject-icon">
                        <FontAwesomeIcon icon="caret-down" size="sm" />
                    </span>
                    {title}
                </div>
                <div className="scriptingObject-fields">
                    {Object.keys(val).map(key => (
                        // eslint-disable-next-line react/jsx-props-no-spreading
                        <ScriptingValueDisplay {...this._props} name={key} />
                    ))}
                </div>
            </div>
        );
    }
}

@observer
export class ScriptingRepl extends ObservableReactComponent<{}> {
    constructor(props: any) {
        super(props);
        makeObservable(this);
    }

    @observable private commands: { command: string; result: any }[] = [];
    private commandsHistory: string[] = [];

    @observable private commandString: string = '';
    private commandBuffer: string = '';

    @observable private historyIndex: number = -1;

    private commandsRef = React.createRef<HTMLDivElement>();

    private args: any = {};

    getTransformer = (): Transformer => ({
        transformer: context => {
            const knownVars: { [name: string]: number } = {};
            const usedDocuments: number[] = [];
            ScriptingGlobals.getGlobals().forEach((global: any) => {
                knownVars[global] = 1;
            });
            return root => {
                function visit(nodeIn: ts.Node) {
                    if (ts.isIdentifier(nodeIn)) {
                        if (ts.isParameter(nodeIn.parent)) {
                            knownVars[nodeIn.text] = 1;
                        }
                    }
                    const node = ts.visitEachChild(nodeIn, visit, context);

                    if (ts.isIdentifier(node)) {
                        const isntPropAccess = !ts.isPropertyAccessExpression(node.parent) || node.parent.expression === node;
                        const isntPropAssign = !ts.isPropertyAssignment(node.parent) || node.parent.name !== node;
                        if (ts.isParameter(node.parent)) {
                            // delete knownVars[node.text];
                        } else if (isntPropAccess && isntPropAssign && !(node.text in knownVars) && !(node.text in globalThis)) {
                            const match = node.text.match(/d([0-9]+)/);
                            if (match) {
                                const m = parseInt(match[1]);
                                usedDocuments.push(m);
                            } else {
                                return ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier('args'), node);
                                //  ts.createPropertyAccess(ts.createIdentifier('args'), node);
                            }
                        }
                    }

                    return node;
                }
                return ts.visitNode(root, visit);
            };
        },
    });

    @action
    onKeyDown = (e: React.KeyboardEvent) => {
        let stopProp = true;
        switch (e.key) {
            case 'Enter': {
                e.stopPropagation();
                const docGlobals: { [name: string]: any } = {};
                DocumentManager.Instance.DocumentViews.forEach((dv, i) => {
                    docGlobals[`d${i}`] = dv.Document;
                });
                const globals = ScriptingGlobals.makeMutableGlobalsCopy(docGlobals);
                const script = CompileScript(this.commandString, { typecheck: false, addReturn: true, editable: true, params: { args: 'any' }, transformer: this.getTransformer(), globals });
                if (!script.compiled) {
                    this.commands.push({ command: this.commandString, result: script.errors });
                    return;
                }
                const result = undoable(() => script.run({ args: this.args }, () => this.commands.push({ command: this.commandString, result: e.toString() })), 'run:' + this.commandString)();
                if (result.success) {
                    this.commands.push({ command: this.commandString, result: result.result });
                    this.commandsHistory.push(this.commandString);

                    this.maybeScrollToBottom();

                    this.commandString = '';
                    this.commandBuffer = '';
                    this.historyIndex = -1;
                }
                break;
            }
            case 'ArrowUp': {
                if (this.historyIndex < this.commands.length - 1) {
                    this.historyIndex++;
                    if (this.historyIndex === 0) {
                        this.commandBuffer = this.commandString;
                    }
                    this.commandString = this.commandsHistory[this.commands.length - 1 - this.historyIndex];
                }
                break;
            }
            case 'ArrowDown': {
                if (this.historyIndex >= 0) {
                    this.historyIndex--;
                    if (this.historyIndex === -1) {
                        this.commandString = this.commandBuffer;
                        this.commandBuffer = '';
                    } else {
                        this.commandString = this.commandsHistory[this.commands.length - 1 - this.historyIndex];
                    }
                }
                break;
            }
            default:
                stopProp = false;
                break;
        }

        if (stopProp) {
            e.stopPropagation();
            e.preventDefault();
        }
    };

    @action
    onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        this.commandString = e.target.value;
    };

    private shouldScroll: boolean = false;
    private maybeScrollToBottom = () => {
        const ele = this.commandsRef.current;
        if (ele && ele.scrollTop === ele.scrollHeight - ele.offsetHeight) {
            this.shouldScroll = true;
            this.forceUpdate();
        }
    };

    private scrollToBottom() {
        const ele = this.commandsRef.current;
        ele && ele.scroll({ behavior: 'auto', top: ele.scrollHeight });
    }

    componentDidUpdate(prevProps: Readonly<{}>) {
        super.componentDidUpdate(prevProps);
        if (this.shouldScroll) {
            this.shouldScroll = false;
            this.scrollToBottom();
        }
    }

    overlayDisposer?: () => void;
    onFocus = () => {
        this.overlayDisposer?.();
        this.overlayDisposer = OverlayView.Instance.addElement(<DocumentIconContainer />, { x: 0, y: 0 });
    };

    onBlur = () => this.overlayDisposer?.();

    render() {
        return (
            <div className="scriptingRepl-outerContainer">
                <div className="scriptingRepl-commandsContainer" style={{ background: SettingsManager.userBackgroundColor }} ref={this.commandsRef}>
                    {this.commands.map(({ command, result }, i) => (
                        <div className="scriptingRepl-resultContainer" style={{ background: SettingsManager.userBackgroundColor }} key={i}>
                            <div className="scriptingRepl-commandString" style={{ background: SettingsManager.userBackgroundColor }}>
                                {command || <br />}
                            </div>
                            <div className="scriptingRepl-commandResult" style={{ background: SettingsManager.userBackgroundColor }}>
                                <ScriptingValueDisplay scrollToBottom={this.maybeScrollToBottom} value={result} />
                            </div>
                        </div>
                    ))}
                </div>
                <input
                    className="scriptingRepl-commandInput"
                    style={{ background: SettingsManager.userBackgroundColor }} //
                    onFocus={this.onFocus}
                    onBlur={this.onBlur}
                    value={this.commandString}
                    onChange={this.onChange}
                    onKeyDown={this.onKeyDown}
                />
            </div>
        );
    }
}