forked from sanity-io/sanity-recipes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CustomObjectInputWithLanguageFilter.js
80 lines (71 loc) · 2.25 KB
/
CustomObjectInputWithLanguageFilter.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
import PropTypes from 'prop-types'
import React from 'react'
import Fieldset from 'part:@sanity/components/fieldsets/default'
import {setIfMissing} from 'part:@sanity/form-builder/patch-event'
import {FormBuilderInput} from 'part:@sanity/form-builder'
import filterFieldFn$ from 'part:@sanity/desk-tool/filter-fields-fn?'
export default class CustomObjectInput extends React.PureComponent {
static propTypes = {
type: PropTypes.shape({
title: PropTypes.string,
name: PropTypes.string
}).isRequired,
level: PropTypes.number,
value: PropTypes.shape({
_type: PropTypes.string
}),
focusPath: PropTypes.array.isRequired,
onFocus: PropTypes.func.isRequired,
onChange: PropTypes.func.isRequired,
onBlur: PropTypes.func.isRequired
}
state = {
filterField: () => true
}
firstFieldInput = React.createRef()
handleFieldChange = (field, fieldPatchEvent) => {
const {onChange, type} = this.props
onChange(fieldPatchEvent.prefixAll(field.name).prepend(setIfMissing({_type: type.name})))
}
focus() {
this.firstFieldInput.current.focus()
}
componentDidMount(props) {
if (filterFieldFn$) {
this.filterFieldFnSubscription = filterFieldFn$.subscribe(filterField =>
this.setState({filterField})
)
}
}
componentWillUnmount(props) {
if (this.filterFieldFnSubscription) {
this.filterFieldFnSubscription.unsubscribe()
}
}
render() {
const {type, value, level, focusPath, onFocus, onBlur} = this.props
const {filterField} = this.state
return (
<Fieldset level={level} legend={type.title} description={type.description}>
Custom input, yeah!
<div>
{type.fields.map((field, i) => (
<FormBuilderInput
level={level + 1}
ref={i === 0 ? this.firstFieldInput : null}
key={field.name}
type={field.type}
value={value && value[field.name]}
onChange={patchEvent => this.handleFieldChange(field, patchEvent)}
path={[field.name]}
focusPath={focusPath}
onFocus={onFocus}
onBlur={onBlur}
filterField={filterField}
/>
))}
</div>
</Fieldset>
)
}
}