-
Notifications
You must be signed in to change notification settings - Fork 411
/
Main.js
104 lines (101 loc) · 2.39 KB
/
Main.js
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
import React from 'react'
import Undoable from './lib/Undoable'
import Schema from '@sanity/schema'
import {FormBuilder} from '../../src'
import applyPatch from '../../src/simplePatch'
const schema = Schema.compile({
name: 'simple',
types: [
{
name: 'book',
type: 'object',
fields: [
{
name: 'title',
type: 'string',
title: 'Book title'
},
{
name: 'author',
type: 'string',
title: 'Name of author'
},
{
name: 'isbn',
type: 'string',
title: 'ISBN'
}
]
}
]
})
export default class SimpleExample extends React.Component {
state = {
value: new Undoable(undefined),
shouldInspect: false
}
setValue(nextValue) {
this.setState(prevState => ({
value: prevState.value.set(nextValue)
}))
}
getValue() {
return this.state.value
}
handleChange = event => {
this.setValue(applyPatch(this.getValue(), event.patch))
}
undo() {
this.setState(prevState => ({
value: prevState.value.undo()
}))
}
redo() {
this.setState(prevState => ({
value: prevState.value.redo()
}))
}
handleCommand = event => {
const command = event.currentTarget.dataset.command
switch (command) {
case 'undo':
this.undo()
break
case 'redo':
this.redo()
break
case 'inspect':
this.setState(prevState => ({shouldInspect: !prevState.shouldInspect}))
break
default:
}
}
render() {
const {value, shouldInspect} = this.state
return (
<div style={{padding: 100}}>
<div>
<button onClick={this.handleCommand} data-command="undo" disabled={!value.canUndo}>
Undo
</button>
<button onClick={this.handleCommand} data-command="redo" disabled={!value.canRedo}>
Redo
</button>
</div>
<FormBuilder schema={schema} value={value.get()} onChange={this.handleChange} />
<div>
<label>
<input
type="checkbox"
checked={shouldInspect}
onChange={this.handleCommand}
data-command="inspect"
/>{' '}
Inspect as you type
</label>
</div>
{shouldInspect && <pre>{JSON.stringify(value.get(), null, 2)}</pre>}
</div>
)
}
}