aboutsummaryrefslogtreecommitdiff
path: root/src/client/views/EditableView.tsx
blob: 2e784d3f9031ce3a09b3423a979c2ce0e74d84f8 (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
import React = require('react')
import { observer } from 'mobx-react';
import { observable, action } from 'mobx';

export interface EditableProps {
    GetValue(): string;
    SetValue(value: string): boolean;
    contents: any;
}

@observer
export class EditableView extends React.Component<EditableProps> {
    @observable
    editing: boolean = false;

    @action
    onKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
        if (e.key == "Enter" && !e.ctrlKey) {
            this.props.SetValue(e.currentTarget.value);
            this.editing = false;
        } else if (e.key == "Escape") {
            this.editing = false;
        }
    }

    render() {
        if (this.editing) {
            return <input defaultValue={this.props.GetValue()} onKeyDown={this.onKeyDown} autoFocus onBlur={action(() => this.editing = false)}
                style={{ width: "100%" }}></input>
        } else {
            return (
                <div>
                    {this.props.contents}
                    <button onClick={action(() => this.editing = true)}>Edit</button>
                </div>
            )
        }
    }
}