-
Notifications
You must be signed in to change notification settings - Fork 0
/
Blame2.js
547 lines (472 loc) · 16.5 KB
/
Blame2.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
// TypeScript
// JScript functions for BasicList.Html.
// This calls TRC APIs and binds to specific HTML elements from the page.
/// <reference path="..\..\trc.ts" />
// Global reference to the current sheet;
var _sheet;
var _filters;
var _deltas;
// Startup function called by the plugin
function PluginMain(sheet) {
_sheet = sheet;
trcGetSheetDeltas(sheet, function (deltas) {
_deltas = deltas;
resetFilters();
});
}
/*
$$$
- column for LastUser per RecId
- count per cell (identify high contention)
color code high contention cells. If it's been changed by more than 1 user?
*/
// Helper for managing a sparse array of deltas.
var DeltaGrid = (function () {
function DeltaGrid() {
this._columns = {}; // set of column names that were modified
this._map = {}; // recId --> (columnName --> value)
this._perCel = {}; // map KEY --> IDeltaInfo[]
// unique users that edited a cell. Helps identify contention
this._uniquePerCel = {}; // map KEY --> (User --> bool)
this._columnCounts = {}; // number of responses for each value of each column
// column names that take on discrete values
// useful for creating histogram of responses
this._discreteColumns = ["Gender", "Supporter", "ResultOfContact", "Party"];
}
DeltaGrid.prototype.AddPerCel = function (recId, columnName, delta) {
// track deltas that modified this specific cell
var key = recId + "_" + columnName;
var l = this._perCel[key];
if (l == undefined) {
l = [];
this._perCel[key] = l;
}
l.push(delta);
// Track number of users that modified this specific cell
var l2 = this._uniquePerCel[key];
if (l2 == undefined) {
l2 = {};
this._uniquePerCel[key] = l2;
}
l2[delta.User] = true;
};
// Get a list of deltas that were applied to this single cell.
// Useful to find contention.
// 0-length array if no changes.
DeltaGrid.prototype.GetDeltasPerCel = function (recId, columnName) {
var key = recId + "_" + columnName;
var l = this._perCel[key];
if (l == undefined) {
l = []; //
}
return l;
};
// Keeps a running total of identical responses for each value a columnName
// can take on.
DeltaGrid.prototype.AggregateResponses = function (columnName, value) {
var l = this._columnCounts[columnName];
if (l == undefined) {
l = {};
this._columnCounts[columnName] = l;
}
if (l[value] == undefined) {
l[value] = 0;
}
l[value] += 1;
};
DeltaGrid.prototype.IsDiscreteColumn = function(columnName) {
if (this._discreteColumns.indexOf(columnName) >= 0) {
return true;
}
};
DeltaGrid.prototype.GetUserCountPerCel = function (recId, columnName) {
var key = recId + "_" + columnName;
var l2 = this._uniquePerCel[key];
var users = dict2array(l2);
return users.length;
};
DeltaGrid.prototype.Add = function (delta) {
var change = delta.Value;
var recIds = change["RecId"];
var len = recIds.length;
for (var columnName in change) {
this._columns[columnName] = true;
if (columnName != "RecId") {
for (var rowId = 0; rowId < len; rowId++) {
var columnData = change[columnName];
var recId = recIds[rowId];
this.AddPerCel(recId, columnName, delta);
this.AddOne(recId, columnName, columnData[rowId]);
if (this.IsDiscreteColumn(columnName)) {
this.AggregateResponses(columnName, columnData[rowId]);
}
}
}
}
};
// Record one entry
DeltaGrid.prototype.AddOne = function (recId, columnName, value) {
var l = this._map[recId];
if (l == undefined) {
l = {};
this._map[recId] = l;
}
l[columnName] = value;
};
// Return the set of column names that have been changed.
DeltaGrid.prototype.GetColumns = function () {
var columnNames = dict2array(this._columns);
return columnNames;
};
return DeltaGrid;
})();
;
// General purpose helper.
// Return the key array for a dictionary
function dict2array(dict) {
var keys = [];
if (dict == undefined) {
return keys;
}
for (var key in dict) {
if (dict.hasOwnProperty(key)) {
keys.push(key);
}
}
return keys;
}
function applyFilters() {
$('#deltaGrid').empty();
$('#deltasPerCel').empty();
startLoading();
renderDeltas(_deltas);
renderFilterList();
finishLoading();
}
function renderFilterList() {
var table = $('.additional-filters table');
table.html("");
for (filter in _filters) {
if (filter != "Timestamp") {
var filterValueObj = _filters[filter];
for (name in filterValueObj) {
var tr = $('<tr>');
var tdName = $('<td>');
tdName.addClass('filter-name');
tdName.html(name + ":");
tr.append(tdName);
var tdValue = $('<td>');
tdValue.addClass('filter-value');
tdValue.html(filterValueObj[name]);
tr.append(tdValue);
table.append(tr);
}
}
}
}
// shows loading indicator
function startLoading() {
$('#loadingIndicator').addClass('loading');
}
// hides loading indicator
function finishLoading() {
$('#loadingIndicator').removeClass("loading");
}
// returns true if delta meets _filters criteria; false otherwise
function isFiltered(delta) {
for (filter in _filters) {
if (filter === "Timestamp") {
var deltaDate = delta[filter];
var filterStart = _filters[filter]["StartDate"];
var filterEnd = _filters[filter]["EndDate"];
if (filterStart != "" && filterStart > deltaDate) {
return false;
}
if (filterEnd != "" && filterEnd < deltaDate) {
return false;
}
} else if (filter === "Value") {
var filterValueObj = _filters[filter];
for (filterValueName in filterValueObj) {
if (filterValueName === "User") {
var deltaUser = delta[filterValueName];
var filterUser = filterValueObj[filterValueName];
if (filterUser != deltaUser) {
return false;
}
} else {
var deltaValueObj = delta[filter];
for (colName in deltaValueObj) {
if (colName != "RecId") {
var value = filterValueObj[colName];
if (value === undefined) {
return false;
} else {
var deltaValue = deltaValueObj[colName][0];
if (value != deltaValue) {
return false;
}
}
}
}
}
}
}
}
return true;
}
function renderHistoryGrid(store) {
var columns = store.GetColumns();
{
var thead = $('<thead>');
var tr = $('<tr>');
for (var i = 0; i < columns.length; i++) {
var columnName = columns[i];
var tCell1 = $('<th>').text(columnName);
tr = tr.append(tCell1);
}
$('#deltaGrid').append(thead).append(tr);
}
for (var recId in store._map) {
var data = store._map[recId];
var tr = $('<tr>');
var td = $('<td>').text(recId);
tr = tr.append(td);
for (var i = 1; i < columns.length; i++) {
var columnName = columns[i];
var val2 = data[columnName]; // or undefined if missing
var highlight = false;
var deltaList = [];
if (val2 != undefined) {
deltaList = store.GetDeltasPerCel(recId, columnName);
var numChanges = deltaList.length;
if (numChanges > 1) {
val2 += " [" + deltaList.length + " changes]";
}
var usersPerCell = store.GetUserCountPerCel(recId, columnName);
if (usersPerCell > 1) {
val2 += " [users: " + usersPerCell + "]";
highlight = true;
}
}
var td = $('<td>');
td.text(val2);
if (columnName != "RecId") {
td.addClass('clickable');
}
if (highlight) {
td.addClass('danger');
}
// When a cell is clicked, show the list
td.click(getFXOnClickCellShowDeltas(deltaList, recId, columnName));
tr = tr.append(td);
}
$('#deltaGrid').append(tr);
}
}
function renderResponsesHistogram(store) {
var numCategories = 0;
var columnCounts = store._columnCounts;
for (var k in columnCounts) {
if (columnCounts.hasOwnProperty(k)) {
++numCategories;
}
}
if (numCategories != 0) {
// var numDivCol = calculateNumColToRender(numCategories);
var div = document.getElementById('responsesHistograms');
removeDOMChildren(div);
// clear children nodes
for (category in columnCounts) {
// create Bootstrap column
var col = document.createElement('div');
col.setAttribute('class', "col-sm-12 col-md-6");
div.appendChild(col);
// add chart title
var title = document.createElement('h4');
title.innerHTML = category;
title.setAttribute('class', 'bar-chart-title');
col.appendChild(title);
// create div to render canvas inside
var canvasDiv = document.createElement('div');
var canvasId = category + "Histogram";
canvasDiv.setAttribute('id', canvasId);
col.appendChild(canvasDiv);
// get responses
var responses = columnCounts[category];
window.responses = responses;
var labels = Object.keys(responses);
var values = [];
for (key in responses) {
values.push(responses[key]);
}
addBarChart(category, canvasDiv, labels, values, randomColor(), getFxOnClickBarChart);
}
}
}
// Calculates the number of columns to render inside a row
// Twitter Bootstrap uses a grid system of 12 columns, so
// based on number of categories to show, figure out how many
// columns to create
function calculateNumColToRender(total) {
return Math.ceil(12/total);
}
// Show compressed grid of just the deltas provided.
function renderDeltas(deltas) {
var store = new DeltaGrid();
var filteredDeltas = { "Results":[] };
for (var i = 0; i < deltas.Results.length; i++) {
var delta = deltas.Results[i];
if (isFiltered(delta)) {
store.Add(delta);
filteredDeltas.Results.push(delta);
}
}
renderHistoryGrid(store);
renderPerUserCountDeltasChart(filteredDeltas);
renderResponsesHistogram(store);
}
// Helper function to give each instance of the handle it's own copy of the parameters.
// Else the closures will all share the same parameter value.
function getFXOnClickCellShowDeltas(deltaList, recId, columnName) {
return function () {
onClickCellShowDeltas(deltaList, recId, columnName);
};
}
// When a cell is clicked, show all the edits for that cell
function onClickCellShowDeltas(deltaList, recId, columnName) {
var root = $('#deltasPerCel');
root.empty();
var t = $('<tr>').append($('<th>').text('Version')).append($('<th>').text('User')).append($('<th>').text('App')).append($('<th>').text('Timestamp')).append($('<th>').text('Value'));
root.append($('<thead>')).append(t);
for (var i in deltaList) {
var delta = deltaList[i];
// Extract this value from the delta
var dataColumn = delta.Value[columnName];
var recIdColumn = delta.Value["RecId"];
var prevValue;
for (var i2 in recIdColumn) {
if (recIdColumn[i2] == recId) {
prevValue = dataColumn[i2];
break;
}
}
t = ($('<tr>')).append($('<td>').text(delta.Version)).append($('<td>').text(delta.User)).append($('<td>').text(delta.App)).append($('<td>').text(delta.Timestamp)).append($('<td>').text(prevValue));
root.append(t);
}
}
function deltaCountPerUser(deltas) {
var counts = {}; // User --> # of deltas for that user
for (var i = 0; i < deltas.Results.length; i++) {
var delta = deltas.Results[i];
var l = counts[delta.User];
if (l == undefined) {
l = 0;
}
l++;
counts[delta.User] = l;
}
return counts;
}
// $$$ also count # of unique records changed
// Show chart of # of deltas per user.
function renderPerUserCountDeltas(deltas) {
var counts = deltaCountPerUser(deltas);
for (var user in counts) {
var count = counts[user];
var tr = $('<tr>').append($('<td>').text(user)).append($('<td>').text(count));
$('#deltas').append(tr);
}
}
function renderPerUserCountDeltasChart(deltas) {
var counts = deltaCountPerUser(deltas);
var labels = [];
var values = [];
for (var user in counts) {
var count = counts[user];
labels.push(user);
values.push(count);
}
var div = document.getElementById('deltasPerUserBarChart');
removeDOMChildren(div);
addBarChart("User", div, labels, values, randomColor(), getFxOnClickBarChart);
}
function removeDOMChildren(element) {
while (element.hasChildNodes()) {
element.removeChild(element.lastChild);
}
}
// add bar chart to DOM element (domEl)
function addBarChart(valueName, domEl, labels, values, fillColor, clickFx) {
var data = {
labels: labels,
datasets: [
{
fillColor: fillColor,
data: values
}
]
}
var options = {
barShowStroke: false,
scaleShowLabels : true,
responsive: true,
scaleFontSize: 11
}
var div = domEl;
var canvas = document.createElement("canvas");
div.appendChild(canvas);
var ctx = canvas.getContext("2d");
var chart = new Chart(ctx).Bar(data, options); // add bar chart
// add event when bars on chart are clicked
canvas.onclick = clickFx(valueName, chart);
}
function getFxOnClickBarChart(valueName, chart) {
return function(event) {
var activeBars = chart.getBarsAtEvent(event);
if (activeBars[0] != undefined) {
_filters["Value"][valueName] = activeBars[0].label;
} else {
delete _filters["Value"][valueName];
}
applyFilters();
}
}
// dateFields is array of objects { name => String, value => String }
// where name is 'startDate' or 'endDate' and value is a unix timestamp
function applyDateFilter(dateFields) {
for (i=0; i < dateFields.length; i++) {
var dateField = dateFields[i];
if (dateField.value === "") {
_filters["Timestamp"][dateField.name] = ""; // set empty value
} else {
var date = new Date(dateField.value);
_filters["Timestamp"][dateField.name] = date.toISOString();
}
}
applyFilters();
}
$('#dateFilterForm').on('submit', function(e) {
e.preventDefault();
var dateFields = $(this).serializeArray();
if (_sheet === undefined) {
alert('Please load sheet first');
} else {
applyDateFilter(dateFields);
}
});
$('#resetFiltersBtn').on('click', function(e) {
e.preventDefault();
resetFilters();
});
// sets filters back to default (blank) values, clears filter form, and applies
// re-render of data via applyFilters() function
function resetFilters() {
_filters = {
"Timestamp": { "StartDate":"", "EndDate": "" },
"Value": {}
};
$('#dateFilterForm')[0].reset(); // reset form fields
applyFilters();
}
//# sourceMappingURL=Blame.js.map