-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathplateViewer.js
1028 lines (932 loc) · 31.3 KB
/
plateViewer.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
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
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
*
* @class PlateViewer
*
* Shows the plate information
*
* @param {string} target The name of the target container for the plate viewer
* @param {int} plateId OPTIONAL The id of the plate to visualize
* @param {int} rows OPTIONAL If plateId is not provided, the number of rows
* @param {int} cols OPTIONAL If plateId is not provided, the number of columns
*
* @return {PlateViewer}
* @constructs PlateViewer
*
**/
function PlateViewer(target, plateId, processId, rows, cols) {
this.container = $("#" + target);
/*
* HACK: SlickGrid doesn't currently support frozen columns hence we are
* using two grids to make it look like the first column is frozen. Once
* the feature makes it into the SlickGrid repo, we can remove this. See
* this GitHub issue: https://github.com/6pac/SlickGrid/issues/26
*/
this.target = $('<div name="main-grid"></div>');
this._frozenColumnTarget = $(
'<div name="frozen-column" ' + 'class="spreadsheet-frozen-column"></div>'
);
this.container.append(this._frozenColumnTarget);
this.container.append(this.target);
this.plateId = null;
this.processId = null;
this._undoRedoBuffer = null;
this.notes = null;
var that = this;
if (!plateId) {
if (!rows || !cols) {
// This error should never show up in production
bootstrapAlert(
"PlateViewer developer error: rows and cols should be provided if plateId is not provided"
);
} else {
this.initialize(rows, cols);
}
} else {
// Ignore rows and cols and use the plateId to retrieve the plate
// information and initialize the object
this.plateId = plateId;
this.processId = processId;
$.get("/plate/" + this.plateId + "/", function(data) {
var rows, cols, pcId;
// Magic numbers. The plate configuration is a list of elements
// Element 2 -> number of rows
// Element 3 -> number of cols
rows = data["plate_configuration"][2];
cols = data["plate_configuration"][3];
$.each(data["studies"], function(idx, elem) {
add_study(elem);
});
that.initialize(rows, cols);
$.each(data["duplicates"], function(idx, elem) {
that.wellClasses[elem[0] - 1][elem[1] - 1].push("well-duplicated");
});
$.each(data["previous_plates"], function(idx, elem) {
var r = elem[0][0] - 1;
var c = elem[0][1] - 1;
that.wellPreviousPlates[r][c] = elem[1];
that.wellClasses[r][c].push("well-prev-plated");
});
$.each(data["unknowns"], function(idx, elem) {
that.wellClasses[elem[0] - 1][elem[1] - 1].push("well-unknown");
});
that.loadPlateLayout();
}).fail(function(jqXHR, textStatus, errorThrown) {
bootstrapAlert(jqXHR.responseText, "danger");
});
}
}
/**
*
* Initializes SlickGrid to show the plate layout
*
* @param {int} rows The number of rows
* @param {int} cols The number of columns
*
**/
PlateViewer.prototype.initialize = function(rows, cols) {
var that = this;
var height = "250px";
this.rows = rows;
this.cols = cols;
this.data = [];
this.frozenData = [];
this.wellComments = [];
this.wellPreviousPlates = [];
this.wellClasses = [];
// Make sure all rows fit on screen. we need to have enough space so that we
// don't have to synchronize the scrolling events between the two elements
if (rows > 8) {
height = "450px";
}
this.container.height(height);
this.target.height(height);
this._frozenColumnTarget.height(height);
var sgOptions = {
editable: true,
enableCellNavigation: true,
asyncEditorLoading: false,
enableColumnReorder: false,
autoEdit: true,
resizable: true
};
var frozenColumnOptions = {
editable: false,
enableCellNavigation: false,
enableColumnReorder: false,
autoEdit: false
};
// Use the slick-header-column but with mouse events disabled
// Without the the header will be smaller than for the main grid
var frozenColumn = [
{
id: "selector",
name: " ",
field: "header",
width: 22,
cssClass: "slick-header-column",
headerCssClass: "full-height-header"
}
];
// Fetch the blank names before initializing the grid. This way we only make
// one request to get this data instead of one per cell instantiation.
// When no search term is specified in the request, we get all available
// blank types.
var blanksRequest = $.get({
dataType: "json",
url: "/sample/control?term=",
error: function(jqXHR, textStatus, errorThrown) {
bootstrapAlert(
"Could not fetch known <i>Control Types</i> needed for " +
"plating samples. Try reloading the page. <br>" +
jqXHR.responseText,
"danger"
);
}
});
var sgCols = [];
for (var i = 0; i < this.cols; i++) {
// We need to add the plate Viewer as an element of this list so it gets
// available in the formatter.
sgCols.push({
plateViewer: this,
id: i,
name: i + 1,
field: i,
editor: SampleCellEditor,
options: { blankNamesRequest: blanksRequest },
formatter: this.wellFormatter,
width: 100,
minWidth: 80,
headerCssClass: "full-height-header"
});
}
var rowId = "A";
for (var i = 0; i < this.rows; i++) {
var d = (this.data[i] = {});
var c = (this.wellComments[i] = {});
var cl = (this.wellClasses[i] = {});
var pp = (this.wellPreviousPlates[i] = {});
this.frozenData.push({ header: rowId });
for (var j = 0; j < this.cols; j++) {
d[j] = null;
c[j] = null;
cl[j] = [];
pp[j] = null;
}
rowId = getNextRowId(rowId);
}
/*
* Taken from the example here:
* https://github.com/6pac/SlickGrid/blob/master/examples/example-excel-compatible-spreadsheet.html
*/
this._undoRedoBuffer = {
commandQueue: [],
commandCtr: 0,
queueAndExecuteCommand: function(editCommand) {
this.commandQueue[this.commandCtr] = editCommand;
this.commandCtr++;
editCommand.execute();
},
undo: function() {
if (this.commandCtr == 0) {
return;
}
this.commandCtr--;
var command = this.commandQueue[this.commandCtr];
if (command && Slick.GlobalEditorLock.cancelCurrentEdit()) {
command.undo();
}
},
redo: function() {
if (this.commandCtr >= this.commandQueue.length) {
return;
}
var command = this.commandQueue[this.commandCtr];
this.commandCtr++;
if (command && Slick.GlobalEditorLock.cancelCurrentEdit()) {
command.execute();
}
}
};
var sgOptions = {
editable: true,
enableCellNavigation: true,
asyncEditorLoading: false,
enableColumnReorder: false,
autoEdit: true,
editCommandHandler: function(item, column, editCommand) {
that._undoRedoBuffer.queueAndExecuteCommand(editCommand);
}
};
// Handle the callbacks to CTRL + Z and CTRL + SHIFT + Z
$(document).keydown(function(e) {
if (e.which == 90 && (e.ctrlKey || e.metaKey)) {
// CTRL + (shift) + Z
if (e.shiftKey) {
that._undoRedoBuffer.redo();
} else {
that._undoRedoBuffer.undo();
}
}
// ESC enters selection mode, so autoEdit should be turned off to allow
// users to navigate between cells with the arrow keys
if (e.keyCode === 27) {
that.grid.setOptions({ autoEdit: false });
}
});
var pluginOptions = {
clipboardCommandHandler: function(editCommand) {
that._undoRedoBuffer.queueAndExecuteCommand.call(
that._undoRedoBuffer,
editCommand
);
},
readOnlyMode: false,
includeHeaderWhenCopying: false
};
this._frozenColumn = new Slick.Grid(
this._frozenColumnTarget,
this.frozenData,
frozenColumn,
frozenColumnOptions
);
this.grid = new Slick.Grid(this.target, this.data, sgCols, sgOptions);
// don't select the active cell, otherwise cell navigation won't work
this.grid.setSelectionModel(
new Slick.CellSelectionModel({ selectActiveCell: false })
);
$("#multiSelectCheckbox").on("change", function() {
// In this callback function, "this" is the m.s. checkbox's <input> element
// "that" is defined as this (see the start of this function), which lets
// us refer to this particular PlateViewer object from within callback
// functions like this one.
if (this.checked) {
that.grid.registerPlugin(that.cellExternalCopyManager);
} else {
that.grid.unregisterPlugin(that.cellExternalCopyManager);
}
});
// This paradigm inspired by
// https://github.com/mleibman/SlickGrid/blob/master/examples/example-spreadsheet.html
this.cellExternalCopyManager = new Slick.CellExternalCopyManager(
pluginOptions
);
// Whether or not we register the CECM plugin depends on whether or not the
// corresponding checkbox is checked. This should normally be true by
// default, but it's possible that the user could e.g. navigate "back" or
// "forward" to this page while the checkbox is unchecked.
//
// We make the choice here to respect that, instead of another workaround
// like using $(document).ready() to always ensure that the checkbox starts
// out checked. Either choice is valid -- this one just ensures that the JS
// code for handling this checkbox is mostly localized to one place (here),
// which should make life a little bit easier for us :)
if ($("#multiSelectCheckbox").prop("checked")) {
this.grid.registerPlugin(this.cellExternalCopyManager);
}
// When a cell changes, update the server with the new cell information
this.grid.onCellChange.subscribe(function(e, args) {
var row = args.row;
var col = args.cell;
var content = args.item[col];
// The plate already exists, simply plate the sample
that.modifyWell(row, col, content);
});
// When the user right-clicks on a cell
this.grid.onContextMenu.subscribe(function(e) {
e.preventDefault();
var cell = that.grid.getCellFromEvent(e);
$("#wellContextMenu")
.data("row", cell.row)
.data("col", cell.cell)
.css("top", e.pageY)
.css("left", e.pageX)
.show();
$("body").one("click", function() {
$("#wellContextMenu").hide();
});
});
// Add the functionality to the context menu
$("#wellContextMenu").click(function(e) {
if (!$(e.target).is("li")) {
return;
}
if (!that.grid.getEditorLock().commitCurrentEdit()) {
return;
}
var row = $(this).data("row");
var col = $(this).data("col");
var func = $(e.target).attr("data");
// Set up the modal to add a comment to the well
$("#addWellCommentBtn").off("click");
$("#addWellCommentBtn").on("click", function() {
that.commentWell(row, col, $("#wellTextArea").val());
});
$("#wellTextArea").val(that.wellComments[row][col]);
// Set the previous comment in the input
// Show the modal
$("#addWellComment").modal("show");
});
};
PlateViewer.prototype.wellFormatter = function(
row,
col,
value,
columnDef,
dataContext
) {
var spanId = "well-" + row + "-" + col;
var classes = "";
// For some reason that goes beyond my knowledge, although this function
// is part of the PlateViewer class, when accessing to "this" I do not retrieve
// the plateViewer object. SlickGrid must be calling it in a weird way
var vp = columnDef.plateViewer;
if (vp.wellClasses[row][col].length > 0) {
classes = ' class="' + vp.wellClasses[row][col][0];
for (var i = 1; i < vp.wellClasses[row][col].length; i++) {
classes = classes + " " + vp.wellClasses[row][col][i];
}
classes = classes + '"';
}
if (value === null) {
value = "";
}
return '<span id="' + spanId + '"' + classes + ">" + value + "</span>";
};
/**
*
* Loads the plate layout in the current grid
*
**/
PlateViewer.prototype.loadPlateLayout = function() {
var that = this;
$.get("/plate/" + this.plateId + "/layout", function(data) {
// Update the Grid data with the received information
data = $.parseJSON(data);
that.grid.invalidateAllRows();
for (var i = 0; i < that.rows; i++) {
for (var j = 0; j < that.cols; j++) {
that.data[i][j] = data[i][j]["sample"];
that.wellComments[i][j] = data[i][j]["notes"];
if (that.wellComments[i][j] !== null) {
that.wellClasses[i][j].push("well-commented");
}
}
}
that.grid.render();
that.updateWellCommentsArea();
}).fail(function(jqXHR, textStatus, errorThrown) {
bootstrapAlert(jqXHR.responseText, "danger");
});
};
/**
* Fetch the study that is currently selected in the UI.
* If there is NO selected study in the UI, then the
* method returns 0 (which is not a valid study id).
* This special non-valid value is checked for in the
* back end (in sample_plating_process_handler_patch_request)
* so do not change here without changing there.
*/
PlateViewer.prototype.getActiveStudy = function() {
studyID = get_active_studies().pop();
if (studyID === undefined) {
return 0;
}
return studyID;
};
/**
*
* Actually updates a well's content in the backend. This code was ripped out
* of PlateViewer.modifyWell().
*
* @param {int} row The row of the well being modified
* @param {int} col The column of the well being modified
* @param {string} content The new content of the well
* @param {string} studyID The output of getActiveStudy() -- this paradigm
* should really be changed in the future to accommodate multiple studies.
*
*/
PlateViewer.prototype.patchWell = function(row, col, content, studyID) {
var that = this;
$.ajax({
url: "/process/sample_plating/" + this.processId,
type: "PATCH",
data: {
op: "replace",
path: "/well/" + (row + 1) + "/" + (col + 1) + "/" + studyID + "/sample",
value: content
},
success: function(data) {
that.data[row][that.grid.getColumns()[col].field] = data["sample_id"];
// NOTE: this pretty much checks the status of every well, and this is
// called in patchWell (i.e. every time a well is updated). Should be a
// lot more efficient to minimize the impact of this by just checking for
// changes relative to this well?
that.updateUnknownsAndDuplicates();
var classIdx = that.wellClasses[row][col].indexOf("well-prev-plated");
if (data["previous_plates"].length > 0) {
that.wellPreviousPlates[row][col] = data["previous_plates"];
addIfNotPresent(that.wellClasses[row][col], "well-prev-plated");
} else {
safeArrayDelete(that.wellClasses[row][col], "well-prev-plated");
that.wellPreviousPlates[row][col] = null;
}
// here and in the rest of the source we use updateRow instead of
// invalidateRow(s) and render so that we don't lose any active
// editors in the current grid
that.grid.updateRow(row);
that.updateWellCommentsArea();
},
error: function(jqXHR, textStatus, errorThrown) {
bootstrapAlert(jqXHR.responseText, "danger");
}
});
};
/**
*
* Modify the contents of a well
*
* @param {int} row The row of the well being modified
* @param {int} col The column of the well being modified
* @param {string} content The new content of the well
*
**/
PlateViewer.prototype.modifyWell = function(row, col, content) {
var that = this,
studyID = this.getActiveStudy();
// Perform automatic matching. Note that this is currently done every time
// modifyWell() is called, even if the user types in something like "blank"
// or even if the user selects something from a dropdown list. (That later
// case could probably be detected in order to avoid doing matching here.)
//
// I expect the actual matching to be pretty fast (assuming that there
// aren't thousands of active samples); the main bottleneck is how requests
// are made to the server from modifyWell() and patchWell() instead of in
// batch operations.
var possiblyNewContent = content;
// TODO: cache list of active samples so that we don't have to make this
// particular request every time modifyWell() is called.
get_active_samples().then(
function(sampleIDs) {
// If there is *exactly one* match with an active sample ID, use
// that instead. In any other case (0 matches or > 1 matches),
// manual resolution is required -- so we don't bother changing the
// cell content.
var matchingSamples = getSubstringMatches(content, sampleIDs);
if (matchingSamples.length === 1) {
possiblyNewContent = matchingSamples[0];
safeArrayDelete(that.wellClasses[row][col], "well-indeterminate");
} else if (matchingSamples.length > 1) {
addIfNotPresent(that.wellClasses[row][col], "well-indeterminate");
} else {
safeArrayDelete(that.wellClasses[row][col], "well-indeterminate");
}
that.patchWell(row, col, possiblyNewContent, studyID);
},
function(rejectionReason) {
bootstrapAlert(
"Attempting to get a list of sample IDs failed: " + rejectionReason,
"danger"
);
}
);
};
/**
**/
PlateViewer.prototype.commentWell = function(row, col, comment) {
var that = this,
studyID = this.getActiveStudy();
$.ajax({
url: "/process/sample_plating/" + this.processId,
type: "PATCH",
data: {
op: "replace",
path: "/well/" + (row + 1) + "/" + (col + 1) + "/" + studyID + "/notes",
value: comment
},
success: function(data) {
that.wellComments[row][col] = data["comment"];
var classIdx = that.wellClasses[row][col].indexOf("well-commented");
if (data["comment"] === null && classIdx > -1) {
that.wellClasses[row][col].splice(classIdx, 1);
} else if (data["comment"] !== null && classIdx === -1) {
that.wellClasses[row][col].push("well-commented");
}
that.grid.updateRow(row);
// Close the modal
$("#addWellComment").modal("hide");
that.updateWellCommentsArea();
},
error: function(jqXHR, textStatus, errorThrown) {
bootstrapAlert(jqXHR.responseText, "danger");
}
});
};
/**
* Update the contents of the grid
*
* This method is mainly motivated by updateUnknownsAndDuplicates,
* which may need to update cells that were not recently updated.
*
* Here and in the rest of the source we use updateRow instead of
* invalidateRows and render so that we don't lose any active editors in the
* current grid
*
*/
PlateViewer.prototype.updateAllRows = function() {
for (var i = 0; i < this.rows; i++) {
this.grid.updateRow(i);
}
};
PlateViewer.prototype.updateUnknownsAndDuplicates = function() {
var that = this;
var successFunction = function(data) {
var classIdx;
// First remove all the instances of the unknown and duplicated css classes from wells
for (var i = 0; i < that.rows; i++) {
for (var j = 0; j < that.cols; j++) {
safeArrayDelete(that.wellClasses[i][j], "well-unknown");
safeArrayDelete(that.wellClasses[i][j], "well-duplicated");
}
}
// Add the unknown class to all the current unknowns
$.each(data["unknowns"], function(idx, elem) {
var row = elem[0] - 1;
var col = elem[1] - 1;
that.wellClasses[row][col].push("well-unknown");
});
// Add the duplicated class to all the current duplicates
$.each(data["duplicates"], function(idx, elem) {
var row = elem[0] - 1;
var col = elem[1] - 1;
that.wellClasses[row][col].push("well-duplicated");
});
that.updateAllRows();
};
$.ajax({
url: "/plate/" + this.plateId + "/",
dataType: "json",
// A value of 0 means there will be no timeout.
// from https://api.jquery.com/jquery.ajax/#jQuery-ajax-settings
timeout: 0,
success: successFunction,
error: function(jqXHR, textStatus, errorThrown) {
bootstrapAlert(jqXHR.responseText, "danger");
}
});
};
PlateViewer.prototype.updateWellCommentsArea = function() {
var that = this;
var msg;
$("#well-plate-comments").empty();
var rowId = "A";
var wellId;
for (var i = 0; i < that.rows; i++) {
for (var j = 0; j < that.cols; j++) {
wellId = rowId + (j + 1);
if (that.wellComments[i][j] !== null) {
msg =
"Well " +
wellId +
" (" +
that.data[i][j] +
"): " +
that.wellComments[i][j];
$("<p>")
.append(msg)
.appendTo("#well-plate-comments");
} else if (that.wellPreviousPlates[i][j] !== null) {
msg = "Well " + wellId + " (" + that.data[i][j] + "): Plated in :";
$.each(that.wellPreviousPlates[i][j], function(idx, elem) {
msg = msg + ' "' + elem["plate_name"] + '"';
});
$("<p>")
.addClass("well-prev-plated")
.append(msg)
.appendTo("#well-plate-comments");
}
}
rowId = getNextRowId(rowId);
}
};
/**
*
* @class SampleCellEditor
*
* This class represents a Sample cell editor defined by the SlickGrid project
*
* This is heavily based on SlickGrid's TextEditor
* (https://github.com/6pac/SlickGrid/blob/master/slick.editors.js)
* And the SlickGrid's example of autocomplete:
* (https://github.com/6pac/SlickGrid/blob/master/examples/example-autocomplete-editor.html)
*
* @param {Object} args Arguments passed by SlickGrid
*
**/
function SampleCellEditor(args) {
var $input;
var defaultValue;
var that = this;
// Do not use the up and down arrow to navigate the cells so they can be used
// to choose the sample from the autocomplete dropdown menu
this.keyCaptureList = [Slick.keyCode.UP, Slick.keyCode.DOWN];
// Get the parsed values from the request. Alternatively, if the request
// didn't complete yet use an empty list as a fallback.
this.blankNames = args.column.options.blankNamesRequest.responseJSON || [];
// styling taken from SlickGrid's examples/examples.css file
this.init = function() {
$input = $("<input type='text'>")
.appendTo(args.container)
.on("keydown.nav", function(e) {
if (
e.keyCode === $.ui.keyCode.LEFT ||
e.keyCode === $.ui.keyCode.RIGHT
) {
e.stopImmediatePropagation();
}
})
.css({
width: "100%",
height: "100%",
border: "0",
margin: "0",
background: "transparent",
outline: "0",
padding: "0"
});
$input.autocomplete({ source: autocomplete_search_samples });
args.grid.setOptions({ autoEdit: true });
};
this.destroy = function() {
$input.remove();
};
this.focus = function() {
$input.focus();
};
this.getValue = function() {
return $input.val();
};
this.setValue = function(val) {
$input.val(val);
};
this.loadValue = function(item) {
defaultValue = item[args.column.field] || "";
$input.val(defaultValue);
$input[0].defaultValue = defaultValue;
$input.select();
};
this.serializeValue = function() {
return $input.val();
};
this.applyValue = function(item, state) {
var activeStudies,
studyPrefix = "";
// account for the callback when copying or pasting
if (state === null) {
state = "";
}
if (state.replace(/\s/g, "").length === 0) {
// The user introduced an empty string. An empty string in a plate is a blank
state = "blank";
}
item[args.column.field] = state;
};
this.isValueChanged = function() {
return (
!($input.val() == "" && defaultValue == null) &&
$input.val() != defaultValue
);
};
this.validate = function() {
if (args.column.validator) {
var validationResults = args.column.validator($input.val());
if (!validationResults.valid) {
return validationResults;
}
}
return {
valid: true,
msg: null
};
};
this.init();
}
/**
*
* Function to fill up the autocomplete dropdown menu for the samples
*
* @param {object} request Request object sent by JQuery UI autocomple
* @param {function} response Callback function sent by JQuery UI autocomplete
*
**/
function autocomplete_search_samples(request, response) {
// Check if there is any study chosen
var studyIds = get_active_studies();
// Perform all the requests to the server
var requests = [$.get("/sample/control?term=" + request.term)];
$.each(studyIds, function(index, value) {
requests.push(
$.get("/study/" + value + "/samples?limit=20&term=" + request.term)
);
});
$.when.apply($, requests).then(
function() {
// The nature of arguments change based on the number of requests performed
// If only one request was performed, then arguments only contain the output
// of that request. On the other hand, if there was more than one request,
// then arguments is a list of results
var arg = requests.length === 1 ? [arguments] : arguments;
var samples = merge_sample_responses(arg);
// Format the samples in the way that autocomplete needs
var results = [];
$.each(samples, function(index, value) {
results.push({ label: value, value: value });
});
response(results);
},
// If any of the requests fail, the arguments to this "rejection"
// function match the arguments to the corresponding request's
// "error" function: see https://api.jquery.com/jquery.when/, towards the
// bottom of the page. (So we can just show the user jqXHR.responseText.)
function(jqXHR, textStatus, errorThrown) {
bootstrapAlert(
"Attempting to get sample IDs while filling up the autocomplete " +
"dropdown menu failed: " +
jqXHR.responseText,
"danger"
);
}
);
}
/**
* Given an array of responses of sample IDs (where each element in the array
* is a string representation of an array of sample IDs), returns a single
* array of sample IDs.
*
* This function was created in order to store redundant code between
* autocomplete_search_samples() (where this code was taken from) and
* get_active_samples().
*
* NOTE that this assumes that the sample IDs in the response array are all
* unique. If for whatever reason a sample ID is repeated in a study -- or
* multiple studies share a sample ID -- then this function won't have a
* problem with that, and will accordingly return an array containing duplicate
* sample IDs. (That should never happen, though.)
*
* @param {Array} responseArray: an array of request(s') output.
* @returns {Array} A list of the sample IDs contained within responseArray.
*/
function merge_sample_responses(responseArray) {
var samples = [];
$.each(responseArray, function(index, value) {
samples = samples.concat($.parseJSON(value[0]));
});
return samples;
}
/**
* Function to retrieve the selected studies from the UI
* @returns {Array} A list of study identifiers that are currently selected.
*/
function get_active_studies() {
var $studies = $(".study-list-item.active");
var studyIds = [];
if ($studies.length === 0) {
// There are no studies chosen - search over all studies in the list:
$.each($(".study-list-item"), function(index, value) {
studyIds.push($(value).attr("pm-data-study-id"));
});
} else {
$.each($studies, function(index, value) {
studyIds.push($(value).attr("pm-data-study-id"));
});
}
return studyIds;
}
/**
* Function to retrieve every sample ID associated with every active study.
*
* A lot of this code was based on autocomplete_search_samples() -- however,
* not using a sample count limit or taking into account control types means
* that this function is inherently simpler.
*
* This returns a Promise because this function does a few asynchronous calls
* under the hood (in particular, it issues one request per active study). In
* order to be consistent, a Promise is returned even if no studies are active
* (in this case the Promise will just resolve to []).
*
* @returns {Promise} A Promise that resolves to a list of sample IDs from all
* active studies.
*/
function get_active_samples() {
var studyIDs = get_active_studies();
if (studyIDs.length > 0) {
// Create an array of all the requests to be made (one request per study)
var requests = [];
$.each(studyIDs, function(index, value) {
requests.push($.get("/study/" + value + "/samples"));
});
// Wait for each request to be handled, then merge responses to get a list of
// sample IDs from all active studies
// We're going to return a Promise, and this Promise's value will be the
// array of all sample IDs from all active studies.
return $.when.apply($, requests).then(
function() {
var arg = requests.length === 1 ? [arguments] : arguments;
return merge_sample_responses(arg);
},
function(jqXHR, textStatus, errorThrown) {
bootstrapAlert(
"Attempting to get a list of sample IDs failed: " +
jqXHR.responseText,
"danger"
);
}
);
} else {
return Promise.resolve([]);
}
}
/**
* Small widget to add notes and save them to a URI
*
* @param {Node} container The HTML container where the widget will be appended
* to.
* @param {String} uri The route where the data is written to.
* @param {Integer} id The process identifier for the uri.
* @param {Object} options Object with custom parameters to modify the
* behaviour of the widget.
*/
function NotesBox(container, uri, id, options) {
var that = this;
options = options || {};
this.title = options.title || "Notes";
this.placeholder =
options.placeholder || "Enter your notes and click " + "the save button";
this.text = "";
this.uri = uri;
this.id = id;
this.$container = $(container);
this.$main = $("<div></div>")
.addClass("form-group")
.width("100%");
this.$container.append(this.$main);
this.$label = $("<label></label>").width("100%");
this.$textArea = $('<textarea class="form-control"></textarea>');
this.$textArea.css({ width: "100%" });
this.$saveButton = $('<button type="button">Save Notes</button>');
this.$saveButton.addClass("btn btn-primary");
this.$label.html(this.title);
this.$label.append(this.$textArea);
this.$main.append(this.$label);
this.$main.append(this.$saveButton);
this.$textArea.on("input", function() {
that.$saveButton.removeClass("btn-primary btn-danger btn-success");
that.$saveButton.addClass("btn-primary");
that.$saveButton.html("Save Notes");
that.text = that.$textArea.val();
});
this.$textArea.attr("placeholder", this.placeholder);
this.$saveButton.on("click", function() {
that.save();
$(this).addClass("disabled");
});
}
/**
* Method to set the text value to the object.
*
* @param {String} text The text you want set in the NotesBox.
* @param {Bool} save Whether or not the text should be saved to the server.
* Useful when preloading text into the UI. Default is False.
*/
NotesBox.prototype.setText = function(text, save) {
this.text = text;
this.$textArea.val(text);
if (save) {
this.save();
}
};