forked from folio-org/stripes-components
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEditableListForm.js
458 lines (426 loc) · 13.2 KB
/
EditableListForm.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
import isEqual from 'lodash/isEqual';
import cloneDeep from 'lodash/cloneDeep';
import uniqueId from 'lodash/uniqueId';
import React from 'react';
import { intlShape } from 'react-intl';
import stripesForm from '@folio/stripes-form';
import { FieldArray } from 'redux-form';
import { Row, Col } from 'react-flexbox-grid';
import PropTypes from 'prop-types';
import injectIntl from '../InjectIntl';
import Headline from '../Headline';
import Button from '../Button';
import EditableItem from './EditableItem';
import MultiColumnList from '../MultiColumnList';
import css from './EditableList.css';
import IconButton from '../IconButton';
const propTypes = {
/**
* Object containing properties of list action names: 'delete', 'edit' and
* values of sentinel functions that return objects to destructure onto the
* action button props:
* { delete: (item) => {return { disabled: item.item.inUse } } }
*/
actionProps: PropTypes.object,
/**
* Object containing properties of list action names: 'delete', 'edit' and
* values of sentinel functions that return booleans based on object
* properties" { delete: (item) => {return (!item.item.inUse)} }
*/
actionSuppression: PropTypes.object,
/**
* Additional fields that require building.
*/
additionalFields: PropTypes.object,
/**
* set custom rendered column names
*/
columnMapping: PropTypes.object,
/**
* manually set column widths, if necessary.
*/
columnWidths: PropTypes.object,
/**
* Label for the 'Add' button
*/
createButtonLabel: PropTypes.string,
/**
* set custom component for editing
*/
fieldComponents: PropTypes.object,
/**
* passed to MultiColumnList, formatter allows control over how the data is rendered in the cells of the grid.
*/
formatter: PropTypes.object,
/**
* id for Add action.
*/
id: PropTypes.string,
/**
* Callback provided by redux-form to set the initialValues to something else.
*/
initialize: PropTypes.func,
/**
* Initial form values
*/
initialValues: PropTypes.object,
intl: intlShape.isRequired,
/**
* boolean that indicates if there are validation errors.
*/
invalid: PropTypes.bool,
/**
* Message to display for an empty list.
*/
isEmptyMessage: PropTypes.string,
/**
* Object where each key's value is the default value for that field.
* { resourceType: 'book' }
*/
itemTemplate: PropTypes.object,
/**
* The text for the H3 tag in the header of the component
*/
label: PropTypes.string,
/**
* Callback for creating new list items.
*/
onCreate: PropTypes.func,
/**
* Callback for list item deletion.
*/
onDelete: PropTypes.func,
/**
* Callback for saving editted list items.
*/
onUpdate: PropTypes.func,
/**
* boolean that shows if the form has been modified.
*/
pristine: PropTypes.bool,
/**
* List of read-only fields
*/
readOnlyFields: PropTypes.arrayOf(PropTypes.string),
/**
* Callback provided by redux-form to set the field values to their initialValues
*/
reset: PropTypes.func,
/**
* boolean that indicates that the form is being submitted.
*/
submitting: PropTypes.bool,
/**
* Fieldname that includes the unique identifier for the list.
*/
uniqueField: PropTypes.string,
/**
* Array of fields to render. These will also be editable.
*/
visibleFields: PropTypes.arrayOf(PropTypes.string).isRequired,
};
const defaultProps = {
actionProps: {},
actionSuppression: { delete: () => false, edit: () => false },
createButtonLabel: '+ Add new',
fieldComponents: {},
itemTemplate: {},
uniqueField: 'id',
};
class EditableListForm extends React.Component { // eslint-disable-line react/no-deprecated
constructor(props) {
super(props);
let status = [];
if (props.initialValues) {
status = this.buildStatusArray(props.initialValues.items);
}
this.state = {
status,
lastAction: {},
};
this.RenderItems = this.RenderItems.bind(this);
this.setError = this.setError.bind(this);
this.buildStatusArray = this.buildStatusArray.bind(this);
this.getColumnWidths = this.getColumnWidths.bind(this);
this.getVisibleColumns = this.getVisibleColumns.bind(this);
this.getReadOnlyColumns = this.getReadOnlyColumns.bind(this);
if (this.props.id) {
this.testingId = this.props.id;
} else if (this.props.label) {
this.testingId = this.props.label.replace(/\s/, '').toLowerCase();
} else {
this.testingId = uniqueId();
}
}
componentWillReceiveProps(nextProps) {
if (!isEqual(this.props.initialValues, nextProps.initialValues)) {
this.setState({
status: this.buildStatusArray(nextProps.initialValues.items),
});
}
}
buildStatusArray(items) {
return items.map(() => ({ editing: false, error: false }));
}
onAdd(fields) {
const { itemTemplate } = this.props;
const item = { ...itemTemplate };
fields.unshift(item);
// add field to edit-tracking in edit mode.
this.setState((curState) => {
const newState = cloneDeep(curState);
if (newState.status.length === 0 && fields.length > 0) {
newState.status = this.buildStatusArray();
}
newState.status.unshift({ editing: true, error: false });
return newState;
});
}
onCancel(fields, index) {
const { uniqueField } = this.props;
const item = fields.get(index);
// if the item has a unique identifier, toggle its edit mode... if not, remove it.
if (item[uniqueField]) {
this.toggleEdit(index);
} else {
fields.remove(index);
this.setState((curState) => {
const newState = cloneDeep(curState);
newState.status.splice(index, 1);
return newState;
});
}
// Reset the field values.
this.props.reset();
}
onSave(fields, index) {
const item = fields.get(index);
// if item has no id, it's new...
const callback = (item.id) ?
this.props.onUpdate :
this.props.onCreate;
const res = callback(item);
Promise.resolve(res).then(
() => {
// Set props.initialValues to the currently-saved field values.
this.props.initialize(fields.getAll());
this.toggleEdit(index);
},
() => this.setError(index, 'Error on saving data'),
);
}
onEdit(index) {
this.toggleEdit(index);
}
onDelete(fields, index) {
const { uniqueField } = this.props;
const item = fields.get(index);
const res = this.props.onDelete(item[uniqueField]);
Promise.resolve(res).then(
() => {
fields.remove(index);
// remove item from editable tracking...
this.setState((curState) => {
const newState = cloneDeep(curState);
newState.status.splice(index, 1);
return newState;
});
},
() => this.setError(index, 'Error on removing data'),
);
}
setError(index, errorMsg) {
this.setState((curState) => {
const newState = cloneDeep(curState);
newState.status[index].error = errorMsg;
newState.lastAction = new Date().getTime();
return newState;
});
}
getColumnWidths() {
if (!this.props.columnWidths) {
const visibleColumns = this.getVisibleColumns();
const totalColumns = visibleColumns.length - 1;
const staticWidth = 80 / totalColumns;
const widthsObject = {};
visibleColumns.forEach((f) => {
if (f !== 'actions') {
widthsObject[f] = `${staticWidth}%`;
}
});
widthsObject.actions = '20%';
return widthsObject;
}
return this.props.columnWidths;
}
getVisibleColumns() {
return this.props.visibleFields.concat(['actions']);
}
getReadOnlyColumns() {
const actionsArray = ['actions'];
if (this.props.readOnlyFields) {
return this.props.readOnlyFields.concat(actionsArray);
}
return actionsArray;
}
toggleEdit(index) {
if (this.state.status.length === 0) {
this.buildStatusArray();
}
this.setState((curState) => {
const newState = cloneDeep(curState);
if (newState.status.length === 0) {
newState.status = this.buildStatusArray();
}
newState.status[index].editing = !newState.status[index].editing;
newState.lastAction = new Date().getTime();
return newState;
});
}
ItemFormatter = ({
rowIndex,
rowData,
cells,
fields,
columnWidths,
rowProps,
}) => {
let isEditing;
let hasError;
if (this.state.status.length > 0) {
isEditing = this.state.status[rowIndex].editing;
hasError = this.state.status[rowIndex].error;
} else {
isEditing = false;
hasError = false;
}
return (
<EditableItem
editing={isEditing}
error={hasError}
key={rowIndex}
field="items"
item={rowData}
rowIndex={rowIndex}
columnMapping={this.props.columnMapping}
actionSuppression={this.props.actionSuppression}
actionProps={this.props.actionProps}
visibleFields={this.getVisibleColumns()}
onCancel={() => this.onCancel(fields, rowIndex)}
onSave={() => this.onSave(fields, rowIndex)}
onEdit={() => this.onEdit(rowIndex)}
onDelete={() => this.onDelete(fields, rowIndex)}
additionalFields={this.props.additionalFields}
readOnlyFields={this.getReadOnlyColumns()}
fieldComponents={this.props.fieldComponents}
widths={columnWidths}
cells={cells}
{...rowProps}
/>
);
}
getActions = (fields, item) => {
const { actionProps, actionSuppression, pristine, submitting, invalid } = this.props;
if (this.state.status[item.rowIndex].editing) {
return (
<div style={{ display: 'flex' }}>
<Button
disabled={pristine || submitting || invalid}
marginBottom0
id={`clickable-save-${this.testingId}-${item.rowIndex}`}
title={this.props.intl.formatMessage({ id: 'stripes-components.saveChangesToThisItem' })}
onClick={() => this.onSave(fields, item.rowIndex)}
{...(typeof actionProps.save === 'function' ? actionProps.save(item) : {})}
>
Save
</Button>
<Button
marginBottom0
id={`clickable-cancel-${this.testingId}-${item.rowIndex}`}
title={this.props.intl.formatMessage({ id: 'stripes-components.cancelEditingThisItem' })}
onClick={() => this.onCancel(fields, item.rowIndex)}
{...(typeof actionProps.cancel === 'function' ? actionProps.cancel(item) : {})}
>
Cancel
</Button>
</div>
);
}
return (
<div style={{ display: 'flex' }}>
{!actionSuppression.edit(item) &&
<IconButton
icon="edit"
size="small"
id={`clickable-edit-${this.testingId}-${item.rowIndex}`}
onClick={() => this.onEdit(item.rowIndex)}
title={this.props.intl.formatMessage({ id: 'stripes-components.editThisItem' })}
{...(typeof actionProps.edit === 'function' ? actionProps.edit(item) : {})}
/>
}
{!actionSuppression.delete(item) &&
<IconButton
icon="trashBin"
size="small"
id={`clickable-delete-${this.testingId}-${item.rowIndex}`}
onClick={() => this.onDelete(fields, item.rowIndex)}
title={this.props.intl.formatMessage({ id: 'stripes-components.deleteThisItem' })}
{...(typeof actionProps.delete === 'function' ? actionProps.delete(item) : {})}
/>
}
</div>
);
};
RenderItems({ fields }) {
const cellFormatters = Object.assign({}, this.props.formatter, { actions: item => this.getActions(fields, item) });
return (
<div>
<Row between="xs" className={css.editableListFormHeader}>
<Col xs>
<Headline size="medium" margin="none">{this.props.label}</Headline>
</Col>
<Col xs>
<Row end="xs">
<Col xs>
<Button onClick={() => this.onAdd(fields)} marginBottom0 id={`clickable-add-${this.testingId}`}>
{this.props.createButtonLabel}
</Button>
</Col>
</Row>
</Col>
</Row>
<Row>
<Col xs={12}>
<MultiColumnList
{...this.props}
visibleColumns={this.getVisibleColumns()}
contentData={fields.getAll()}
rowFormatter={this.ItemFormatter}
rowProps={{ fields }}
formatter={cellFormatters}
columnWidths={this.getColumnWidths()}
isEmptyMessage={this.props.isEmptyMessage}
headerRowClass={css.editListHeaders}
id={`editList-${this.testingId}`}
/>
</Col>
</Row>
</div>
);
}
render() {
return (
<form>
<FieldArray name="items" component={this.RenderItems} toUpdate={this.state.lastAction} />
</form>
);
}
}
EditableListForm.propTypes = propTypes;
EditableListForm.defaultProps = defaultProps;
export default stripesForm({
form: 'editableListForm',
navigationCheck: true,
enableReinitialize: true,
destroyOnUnmount: false,
})(injectIntl(EditableListForm));