aboutsummaryrefslogtreecommitdiff
path: root/src/debug/Repl.tsx
blob: b8081648fec82f19f33262a645724c788e149a13 (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
import * as React from 'react';
import * as ReactDOM from 'react-dom/client';
import { observer } from 'mobx-react';
import { observable, computed } from 'mobx';
import { CompileScript } from '../client/util/Scripting';
import { makeInterface } from '../fields/Schema';
import { ObjectField } from '../fields/ObjectField';
import { RefField } from '../fields/RefField';
import { DocServer } from '../client/DocServer';
import { resolvedPorts } from '../client/util/CurrentUserUtils';

@observer
class Repl extends React.Component {
    @observable text: string = '';

    @observable executedCommands: { command: string; result: any }[] = [];

    onChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
        this.text = e.target.value;
    };

    onKeyDown = (e: React.KeyboardEvent) => {
        if (!e.ctrlKey && e.key === 'Enter') {
            e.preventDefault();
            const script = CompileScript(this.text, {
                addReturn: true,
                typecheck: false,
                params: { makeInterface: 'any' },
            });
            if (!script.compiled) {
                this.executedCommands.push({ command: this.text, result: 'Compile Error' });
            } else {
                const result = script.run({ makeInterface }, e => this.executedCommands.push({ command: this.text, result: e.message || e }));
                result.success && this.executedCommands.push({ command: this.text, result: result.result });
            }
            this.text = '';
        }
    };

    @computed
    get commands() {
        return this.executedCommands.map(command => {
            return (
                <div style={{ marginTop: '5px' }}>
                    <p>{command.command}</p>
                    {/* <pre>{JSON.stringify(command.result, null, 2)}</pre> */}
                    <pre>{command.result instanceof RefField || command.result instanceof ObjectField ? 'object' : String(command.result)}</pre>
                </div>
            );
        });
    }

    render() {
        return (
            <div>
                <div style={{ verticalAlign: 'bottom' }}>{this.commands}</div>
                <textarea style={{ width: '100%', position: 'absolute', bottom: '0px' }} value={this.text} onChange={this.onChange} onKeyDown={this.onKeyDown} />
            </div>
        );
    }
}

(async function () {
    DocServer.init(window.location.protocol, window.location.hostname, resolvedPorts.socket, 'repl');
    ReactDOM.createRoot(document.getElementById('root')!).render(<Repl />);
})();