-
Notifications
You must be signed in to change notification settings - Fork 429
Expand file tree
/
Copy pathexample-composite-editor-modal-dialog.html
More file actions
578 lines (498 loc) · 22.6 KB
/
Copy pathexample-composite-editor-modal-dialog.html
File metadata and controls
578 lines (498 loc) · 22.6 KB
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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link rel="shortcut icon" type="image/ico" href="favicon.ico" />
<title>SlickGrid example: CompositeEditor</title>
<link rel="stylesheet" href="../dist/styles/css/slick-icons.css" type="text/css"/>
<link rel="stylesheet" href="../dist/styles/css/example-demo.css" type="text/css"/>
<link rel="stylesheet" href="../dist/styles/css/slick-alpine-theme.css" type="text/css"/>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<style>
.cell-title {
font-weight: bold;
}
.cell-effort-driven {
justify-content: center;
}
.close {
background: transparent;
border: 1px solid #9e9e9e;
float: right;
height: 20px;
/* font-size: 1.5rem; */
font-weight: 700;
line-height: 1;
color: #000;
text-shadow: 0 1px 0 #fff;
opacity: .5;
}
.modal {
z-index: 10000;
display: inline-block;
border: 1px solid black;
margin: 8px;
background: #fbfbfb;
box-shadow: 0px 0px 15px black;
position: absolute;
top: 10px;
left: 150px;
width: 300px;
}
.modal h5 {
font-size: 18px;
margin: 0;
line-height: 20px;
}
.modal-body {
padding: 8px;
}
.modal-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
padding: 8px;
height: 25px;
border-bottom: 1px solid #c9c9c9;
}
.modal-footer {
margin-top: 5px;
border-top: 1px solid #c9c9c9;
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: flex-end;
padding: 8px;
}
.modal-footer button {
margin-right: 5px;
}
.item-details-label {
margin-left: 10px;
margin-top: 15px;
display: block;
font-weight: bold;
}
.item-details-editor-container {
border: 1px solid silver;
background: white;
display: block;
margin: 4px 10px;
margin-top: 4px;
padding: 0;
padding-left: 4px;
padding-right: 0px;
line-height: 20px;
}
.item-details-editor-container textarea {
height: inherit;
}
.invalid {
color: red;
}
.item-details-editor-container.invalid {
border: 1px solid red;
}
.item-details-validation {
color: red;
font-style: italic;
margin-left: 12px;
}
.item-details-editor-container.modified {
border: 1px solid orange;
}
.slick-large-editor-text {
border: 1px solid #d2d2d2;
padding: 6px;
}
.slick-large-editor-text textarea {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<h2 class="title">Example - Composite Editor with Modal Dialog</h2>
<div style="position:relative">
<div style="width:640px;">
<div id="myGrid" class="slick-container" style="width:100%;height:500px;"></div>
</div>
<div class="options-panel">
<h2>
<a href="/examples/index.html" style="text-decoration: none; font-size: 22px">⌂</a>
Demonstrates:
</h2>
<ul>
<li>Composite Editor Modal - Edit Form</li>
<li>Composite Editor Modal - Insert New Row</li>
<li>Composite Editor Modal - Mass Update Change (all rows)</li>
<li>Composite Editor Modal - Mass Change on Current Selection</li>
<li>use "onCompositeEditorChange" event to add extra form validation logic</li>
</ul>
<h2>Options:</h2>
<p>
<button data-test="auto-edit-on-btn" onclick="grid.setOptions({autoEdit:true})">Auto-edit ON</button>
<button data-test="auto-edit-off-btn" onclick="grid.setOptions({autoEdit:false})">Auto-edit OFF</button>
</p>
<li>Choose any of the 4 possible options</li>
<li>1. Create New Item</li>
<li>2. Edit Current Item</li>
<li>3. Mass Update</li>
<li>4. Mass Selection Change</li>
<br />
<button style="margin-bottom: 5px" onclick="openDetails('edit')" data-test="edit-button">Open Item Edit for active row</button><br/>
<button style="margin-bottom: 5px" onclick="openDetails('create')" data-test="create-button">Open Add New Row Detail</button><br/>
<button style="margin-bottom: 5px" onclick="openDetails('mass-update')" data-test="mass-update-button">Open Mass Update Detail</button><br/>
<button style="margin-bottom: 5px" onclick="openDetails('mass-selection')" data-test="mass-selection-button">Open Mass Selection
Change</button>
<h2>View Source:</h2>
<ul>
<li><A href="https://github.com/6pac/SlickGrid/blob/master/examples/example-composite-editor-modal-dialog.html"
target="_sourcewindow"> View the source for this example on Github</a></li>
</ul>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
<script src="../dist/browser/slick.core.js"></script>
<script src="../dist/browser/slick.interactions.js"></script>
<script src="../dist/browser/slick.grid.js"></script>
<script src="../dist/browser/plugins/slick.checkboxselectcolumn.js"></script>
<script src="../dist/browser/plugins/slick.cellrangeselector.js"></script>
<script src="../dist/browser/plugins/slick.cellselectionmodel.js"></script>
<script src="../dist/browser/plugins/slick.rowselectionmodel.js"></script>
<script src="../dist/browser/slick.formatters.js"></script>
<script src="../dist/browser/slick.editors.js"></script>
<script src="../dist/browser/slick.compositeeditor.js"></script>
<script>
function taskValidator(newValue, args) {
if ((newValue === null || newValue === undefined || !newValue.length) && (args.compositeEditorOptions && args.compositeEditorOptions.modalType === "create" || args.compositeEditorOptions.modalType === "edit")) {
// we will only check if the field is supplied when it's an inline editing OR a composite editor of type create/edit
return { valid: false, msg: 'This is a required field' };
} else if (!/^(task\s\d+)*$/i.test(newValue)) {
return { valid: false, msg: 'Your title is invalid, it must start with "Task" followed by a number' };
}
return { valid: true, msg: '' };
}
function durationValidator(newValue, args) {
var dataContext = args && args.item;
if (dataContext && (dataContext.effortDriven && (newValue < 5 || !newValue))) {
return { valid: false, msg: 'Duration must be at least 5 days when "Effort-Driven" is enabled' };
}
return { valid: true, msg: '' };
}
function durationFormatter(row, cell, value) {
return value > 1 ? (value + " days") : (value + " day");
}
var lastCompositeEditor = null;
var lastActiveRowNumber = 0;
var grid;
var data = [];
var columns = [
// we use a "massUpdate" flag to know which field(s) will be added to the MassUpdate/MassSelection form in the composite modal window
{ id: "title", name: "Title", field: "title", width: 70, cssClass: "cell-title", editor: Slick.Editors.Text, validator: taskValidator, massUpdate: false, },
{ id: "desc", name: "Description", field: "description", width: 95, editor: Slick.Editors.LongText, massUpdate: false, },
{ id: "duration", name: "Duration", field: "duration", editor: Slick.Editors.Integer, massUpdate: true, validator: durationValidator, formatter: durationFormatter },
{ id: "percent", name: "% Complete", field: "percentComplete", width: 95, resizable: false, formatter: Slick.Formatters.PercentCompleteBar, editor: Slick.Editors.PercentComplete },
{ id: "start", name: "Start", field: "start", minWidth: 60, editor: Slick.Editors.Flatpickr, massUpdate: true, },
{ id: "finish", name: "Finish", field: "finish", minWidth: 60, editor: Slick.Editors.Flatpickr, massUpdate: false, },
{ id: "effort-driven", name: "Effort Driven", width: 90, minWidth: 20, maxWidth: 90, cssClass: "cell-effort-driven", field: "effortDriven", formatter: Slick.Formatters.Checkmark, editor: Slick.Editors.Checkbox, massUpdate: true, }
];
var options = {
editable: true,
enableAddRow: true, // <-- this flag is required to work with these modal types (create/mass-update/mass-selection)
enableCellNavigation: true,
asyncEditorLoading: false,
autoEdit: false
};
function validateCompositeEditors(targetElm) {
var validationResults = { valid: true, msg: "" };
var currentEditor = grid.getCellEditor();
if (currentEditor) {
validationResults = currentEditor.validate(targetElm);
}
return validationResults;
}
// For the Composite Editor to work, the current active cell must have an Editor (because it calls editActiveCell() and that only works with a cell with an Editor)
// so if current active cell doesn't have an Editor, we'll find the first column with an Editor and focus on it (from left to right starting at index 0)
function focusOnFirstCellWithEditor(columns, rowIndex, isWithMassUpdate) {
var columnIndexWithEditor = 0;
const hasEditor = columns[columnIndexWithEditor].editor;
if (!hasEditor) {
if (isWithMassUpdate) {
columnIndexWithEditor = columns.findIndex(function (col) { return col.editor && col.massUpdate });
} else {
columnIndexWithEditor = columns.findIndex(function (col) { return col.editor });
}
if (columnIndexWithEditor === -1) {
throw new Error('We could not find any Editor in your Column Definition');
} else {
grid.setActiveCell(rowIndex, columnIndexWithEditor, false);
if (isWithMassUpdate) {
// when it's a mass change, we'll activate the last row without scrolling to it
// that is possible via the 3rd argument "suppressScrollIntoView" set to "true"
grid.setActiveRow(data.length, columnIndexWithEditor, true);
}
}
}
}
function openDetails(modalType) {
if (grid.getEditorLock().isActive() && !grid.getEditorLock().commitCurrentEdit()) {
return;
}
var activeCell = this.grid.getActiveCell();
var activeRow = activeCell && activeCell.row || 0;
if (!options.enableCellNavigation) {
throw new Error('Composite Editor requires the flag "enableCellNavigation" to be set to True in your Grid Options.');
} else if (!activeCell && modalType === "edit") {
throw new Error('No records selected for edit operation');
} else {
var dataContext = grid.getDataItem(activeRow);
var isWithMassUpdate = (modalType === "mass-update" || modalType === "mass-selection");
lastActiveRowNumber = activeRow;
// focus on a first cell with an Editor (unless current cell already has an Editor then do nothing)
// also when it's a "Create" modal, we'll scroll to the end of the grid
var rowIndex = modalType === "create" ? data.length : activeRow;
focusOnFirstCellWithEditor(columns, rowIndex, isWithMassUpdate);
if (modalType === "edit" && !dataContext) {
alert("Current row is not editable");
return;
} else if (modalType === "mass-selection") {
var selectedRowsIndexes = grid.getSelectedRows();
if (selectedRowsIndexes.length < 1) {
alert("You must select some rows before trying to apply new value(s)");
return;
}
}
var modalColumns;
if (isWithMassUpdate) {
// when using Mass Update, we only care about the columns that have the "massUpdate: true", we disregard anything else
modalColumns = columns.filter(function (col) { return col && col.massUpdate && col.editor });
} else {
modalColumns = columns.filter(function (col) { return col && col.editor });
}
let headerTitle = "";
switch (modalType) {
case "create":
headerTitle = "Inserting New Task";
break;
case "edit":
headerTitle = `Editing ${dataContext.title}`;
break;
case "mass-update":
headerTitle = "Mass Update (all rows)";
break;
case "mass-selection":
headerTitle = "Update on Current Selection";
break;
}
const modalElm = document.createElement('div');
modalElm.className = 'modal slick-composite-editor-modal';
const modalHeaderElm = document.createElement('div');
modalHeaderElm.className = 'modal-header';
modalHeaderElm.innerHTML = `<h5>${headerTitle}</h5>
<button type="button" class="close" data-action="close" aria-label="Close">
<span aria-hidden="true">×</span>
</button>`;
modalElm.appendChild(modalHeaderElm);
const modalBodyElm = document.createElement('div');
modalBodyElm.className = 'modal-body';
for (const column of modalColumns) {
if (column.editor) {
const detailLabelElm = document.createElement('div');
detailLabelElm.className = `item-details-label editor-${column.id}`;
detailLabelElm.textContent = column.name;
const detailContainerElm = document.createElement('div');
detailContainerElm.className = 'item-details-editor-container';
detailContainerElm.dataset.editorid=column.id;
detailContainerElm.style.height = column.id === 'desc' ? 'inherit' : '20px';
const detailValidationElm = document.createElement('div');
detailValidationElm.className = `item-details-validation editor-${column.id}`;
modalBodyElm.appendChild(detailLabelElm);
modalBodyElm.appendChild(detailContainerElm);
modalBodyElm.appendChild(detailValidationElm);
}
}
modalElm.appendChild(modalBodyElm);
let saveActionType = (modalType === "create" || modalType === "edit") ? "save" : modalType;
let saveButtonText = (modalType === "create" || modalType === "edit")
? "Save"
: (modalType === "mass-update")
? "Apply Mass Update"
: "Apply Update to Current Selection";
const modalFooterElm = document.createElement('div');
modalFooterElm.className = 'modal-footer';
const saveBtnElm = document.createElement('button');
saveBtnElm.className = 'slick-btn slick-btn-primary';
saveBtnElm.dataset.action = saveActionType;
saveBtnElm.textContent = saveButtonText;
const cancelBtnElm = document.createElement('button');
cancelBtnElm.className = 'slick-btn slick-btn-default';
cancelBtnElm.dataset.action = 'cancel';
cancelBtnElm.textContent = 'Cancel';
modalFooterElm.appendChild(saveBtnElm);
modalFooterElm.appendChild(cancelBtnElm);
modalElm.appendChild(modalFooterElm);
document.body.appendChild(modalElm);
modalElm.addEventListener('focusout', function (e) {
validateCompositeEditors(e.target);
});
modalElm.addEventListener('keydown', (function (e) {
if (e.which == Slick.keyCode.ESCAPE) {
grid.getEditController().cancelCurrentEdit();
grid.setActiveRow(lastActiveRowNumber);
e.stopPropagation();
e.preventDefault();
} else if (e.which === Slick.keyCode.TAB) {
validateCompositeEditors(e.target);
}
}));
if (modalElm.querySelector("[data-action=save]")) {
modalElm.querySelector("[data-action=save]").addEventListener('click', function () {
grid.getEditController().commitCurrentEdit();
});
}
// Apply a Mass Update change (apply changes to all items in the dataset)
if (modalElm.querySelector("[data-action=mass-update]")) {
modalElm.querySelector("[data-action=mass-update]").addEventListener('click', function () {
var validationResults = validateCompositeEditors();
var isFormValid = validationResults.valid;
if (isFormValid && lastCompositeEditor && lastCompositeEditor.formValues) {
// from the "lastCompositeEditor" object that we kept as reference, it contains all the changes inside the "formValues" property
// we can loop through these changes and apply them on the selected row indexes
for (const itemProp in lastCompositeEditor.formValues) {
if (lastCompositeEditor.formValues.hasOwnProperty(itemProp)) {
data.forEach(function (item) {
if (item.hasOwnProperty(itemProp) && lastCompositeEditor.formValues.hasOwnProperty(itemProp)) {
item[itemProp] = lastCompositeEditor.formValues[itemProp];
}
});
}
}
// change the entire dataset with our updated dataset
grid.setData(data, true);
grid.invalidate();
// once we're done doing the mass update, we can cancel the current editor since we don't want to add any new row
// that will also destroy/close the modal window
grid.getEditController().cancelCurrentEdit();
grid.setActiveCell(0, 0, false);
}
});
}
// Similar to Mass Update except that we apply changes only to the selected items in the grid
if (modalElm.querySelector("[data-action=mass-selection]")) {
modalElm.querySelector("[data-action=mass-selection]").addEventListener('click', function () {
var validationResults = validateCompositeEditors();
var isFormValid = validationResults.valid;
var selectedRowsIndexes = grid.getSelectedRows();
if (isFormValid && lastCompositeEditor && lastCompositeEditor.formValues) {
// from the "lastCompositeEditor" object that we kept as reference, it contains all the changes inside the "formValues" property
// we can loop through these changes and apply them on the selected row indexes
for (const itemProp in lastCompositeEditor.formValues) {
if (lastCompositeEditor.formValues.hasOwnProperty(itemProp)) {
selectedRowsIndexes.forEach(function (rowIndex) {
if (data[rowIndex] && data[rowIndex].hasOwnProperty(itemProp) && lastCompositeEditor.formValues.hasOwnProperty(itemProp)) {
data[rowIndex][itemProp] = lastCompositeEditor.formValues[itemProp];
grid.updateRow(rowIndex);
}
});
}
}
// once we're done doing the mass update, we can cancel the current editor since we don't want to add any new row
// that will also destroy/close the modal window
grid.getEditController().cancelCurrentEdit();
grid.setActiveRow(lastActiveRowNumber);
}
});
}
const closeBtns = modalElm.querySelectorAll("[data-action=cancel],[data-action=close]");
closeBtns.forEach(btn => {
btn.addEventListener('click', function () {
grid.getEditController().cancelCurrentEdit();
grid.setActiveRow(lastActiveRowNumber);
})
});
var containers = modalColumns.map(function (c) {
return modalElm.querySelector(`[data-editorid=${c.id}]`);
});
var compositeEditor = new Slick.CompositeEditor(
modalColumns,
containers,
{
destroy: function () {
modalElm.remove();
},
modalType: modalType,
// validationMsgPrefix: '* '
}
);
grid.editActiveCell(compositeEditor);
}
}
document.addEventListener("DOMContentLoaded", function() {
for (var i = 0; i < 500; i++) {
var d = (data[i] = {});
d["title"] = "Task " + i;
d["description"] = "This is a sample task description.\n It can be multiline";
d["duration"] = 5;
d["percentComplete"] = Math.round(Math.random() * 100);
d["start"] = "01/01/2009";
d["finish"] = "01/05/2009";
d["effortDriven"] = (i % 5 == 0);
}
var checkboxSelectorPlugin = new Slick.CheckboxSelectColumn({ cssClass: "slick-cell-checkboxsel" });
columns.unshift(checkboxSelectorPlugin.getColumnDefinition());
grid = new Slick.Grid("#myGrid", data, columns, options);
grid.setSelectionModel(new Slick.RowSelectionModel({ selectActiveRow: false }));
grid.registerPlugin(checkboxSelectorPlugin);
grid.onAddNewRow.subscribe(function (e, args) {
var item = args.item;
var column = args.column;
grid.invalidateRow(data.length);
data.push(item);
grid.updateRowCount();
grid.render();
grid.onAddNewRow.unsubscribe(); // unsubscribe after closing the modal to avoid multiple entries
});
grid.onCompositeEditorChange.subscribe(function (e, args) {
console.log('composite editor input changed', args.formValues);
// keep reference to the last composite editor, we'll need it when doing a MassUpdate or UpdateSelection
lastCompositeEditor = {
item: args.item,
formValues: args.formValues
};
// add extra css styling to the composite editor input(s) that got modified
const editorElm = document.querySelector(`[data-editorid=${ args.column.id}]`);
editorElm.classList.add("modified");
// make sure "Duration" is valid (higher or equal to 5 days) when changing the "Effort-Driven"
// force a form validation whenever the composite editor input "Effort Driven" changes
if (args.column.id === "effort-driven") {
validateCompositeEditors();
}
});
grid.onCellChange.subscribe(function (e, args) {
console.log('cell changed', args);
});
grid.onValidationError.subscribe(function (e, args) {
// handle validation errors originating from the CompositeEditor
if (args.validationResults) {
let errorMsg = args.validationResults.msg || '';
if (args.editor && (args.editor instanceof Slick.CompositeEditor)) {
if (args.validationResults.errors) {
errorMsg += '\n';
args.validationResults.errors.forEach(function (error, errorIndex) {
const columnName = error.editor.args.column.id;
errorMsg += `${columnName.toUpperCase()}: ${error.msg}`;
});
}
console.log(errorMsg);
}
} else {
alert(errorMessages);
}
});
grid.setActiveCell(0, 0);
});
</script>
</body>
</html>