-
Notifications
You must be signed in to change notification settings - Fork 7
/
ModelSource.js
105 lines (91 loc) · 2.69 KB
/
ModelSource.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
105
import PropTypes from 'prop-types';
import React from 'react';
import { DraftUtils } from 'draftail';
import ModelPicker from '../components/ModelPicker';
const API_BASE_URL = '/admin/modelchoosers/api/v1/model/';
class ModelSource extends React.Component {
constructor(props) {
super(props);
this.onClose = this.onClose.bind(this);
this.onSelected = this.onSelected.bind(this);
}
onClose() {
const { onClose } = this.props;
onClose();
}
onSelected(id, data) {
const { editorState, onUpdate, options: { content_type, display = 'title', pk_name: pkName = 'uuid', type } } = this.props;
let label;
let entityMutability;
if (display === '__selection__') {
const selectionState = editorState.getSelection();
const anchorKey = selectionState.getAnchorKey();
const currentContent = editorState.getCurrentContent();
const currentContentBlock = currentContent.getBlockForKey(anchorKey);
const start = selectionState.getStartOffset();
const end = selectionState.getEndOffset();
label = currentContentBlock.getText().slice(start, end);
entityMutability = 'MUTABLE';
} else {
if (Array.isArray(display)) {
let i;
for (i = 0; i < display.length; i + 1) {
const fieldName = display[i];
if (fieldName in data && data[fieldName]) {
label = data[fieldName];
break;
}
}
} else if (display in data && data[display]) {
label = data[display];
}
if (label === undefined) {
label = data[pkName];
}
entityMutability = 'IMMUTABLE';
}
const nextData = {
id,
label,
content_type,
};
const nextState = DraftUtils.createEntity(
editorState,
type,
nextData,
nextData.label,
entityMutability,
);
onUpdate(nextState);
}
render() {
const { entity, options } = this.props;
const endpoint = `${API_BASE_URL}${options.content_type}`;
return (
<ModelPicker
onChange={this.onSelected}
onSelect={this.onSelected}
onClose={this.onClose}
entity={entity}
endpoint={endpoint}
value={null}
required={false}
{...options}
/>
);
}
}
ModelSource.propTypes = {
// eslint-disable-next-line react/forbid-prop-types
editorState: PropTypes.object.isRequired,
// eslint-disable-next-line react/forbid-prop-types
options: PropTypes.object.isRequired,
// eslint-disable-next-line react/forbid-prop-types
entity: PropTypes.object,
onClose: PropTypes.func.isRequired,
onUpdate: PropTypes.func.isRequired,
};
ModelSource.defaultProps = {
entity: {},
};
export default ModelSource;