/
client.js
1683 lines (1405 loc) · 55.9 KB
/
client.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
//TODO: clean up
var app = {}, browserSettings = {}, browserStorage = $.localStorage;
(function () {
'use strict';
var BRUSH_TIMEOUT = 300000 // 5 minutes in ms
, DEBOUNCE_MS = 10
, TOOLTIP_TRANS_MS = 200 // milliseconds
, UPDATE_TRANS_MS = 750 // milliseconds
, TEN_SEC_IN_MS = 10000
, ONE_MIN_IN_MS = 60000
, FIVE_MINS_IN_MS = 300000
, THREE_HOURS_MS = 3 * 60 * 60 * 1000
, TWENTY_FIVE_MINS_IN_MS = 1500000
, THIRTY_MINS_IN_MS = 1800000
, SIXTY_MINS_IN_MS = 3600000
, FORMAT_TIME_12 = '%-I:%M %p'
, FORMAT_TIME_12_COMAPCT = '%-I:%M'
, FORMAT_TIME_24 = '%H:%M%'
, FORMAT_TIME_12_SCALE = '%-I %p'
, FORMAT_TIME_24_SCALE = '%H'
, WIDTH_SMALL_DOTS = 400
, WIDTH_BIG_DOTS = 800;
var socket
, isInitialData = false
, SGVdata = []
, MBGdata = []
, latestSGV
, latestUpdateTime
, prevSGV
, treatments
, profile
, cal
, devicestatusData
, padding = { top: 0, right: 10, bottom: 30, left: 10 }
, opacity = {current: 1, DAY: 1, NIGHT: 0.5}
, now = Date.now()
, data = []
, foucusRangeMS = THREE_HOURS_MS
, clientAlarms = {}
, alarmInProgress = false
, alarmMessage
, currentAlarmType = null
, currentAnnouncement
, alarmSound = 'alarm.mp3'
, urgentAlarmSound = 'alarm2.mp3';
var sbx
, rawbg = Nightscout.plugins('rawbg')
, delta = Nightscout.plugins('delta')
, direction = Nightscout.plugins('direction')
, errorcodes = Nightscout.plugins('errorcodes')
, translate = Nightscout.language.translate
, timeAgo = Nightscout.utils.timeAgo;
var jqWindow
, tooltip
, tickValues
, charts
, futureOpacity
, focus
, context
, xScale, xScale2, yScale, yScale2
, xAxis, yAxis, xAxis2, yAxis2
, prevChartWidth = 0
, prevChartHeight = 0
, focusHeight
, contextHeight
, dateFn = function (d) { return new Date(d.mills) }
, documentHidden = false
, brush
, brushTimer
, brushInProgress = false
, clip;
var container = $('.container')
, bgStatus = $('.bgStatus')
, currentBG = $('.bgStatus .currentBG')
, majorPills = $('.bgStatus .majorPills')
, minorPills = $('.bgStatus .minorPills')
, statusPills = $('.status .statusPills')
;
Nightscout.language.set(serverSettings.defaults.language).DOMtranslate();
function formatTime(time, compact) {
var timeFormat = getTimeFormat(false, compact);
time = d3.time.format(timeFormat)(time);
if (!isTimeFormat24()) {
time = time.toLowerCase();
}
return time;
}
function isTimeFormat24() {
return browserSettings && browserSettings.timeFormat && parseInt(browserSettings.timeFormat) === 24;
}
function getTimeFormat(isForScale, compact) {
var timeFormat = FORMAT_TIME_12;
if (isTimeFormat24()) {
timeFormat = isForScale ? FORMAT_TIME_24_SCALE : FORMAT_TIME_24;
} else {
timeFormat = isForScale ? FORMAT_TIME_12_SCALE : (compact ? FORMAT_TIME_12_COMAPCT : FORMAT_TIME_12);
}
return timeFormat;
}
// lixgbg: Convert mg/dL BG value to metric mmol
function scaleBg(bg) {
if (browserSettings.units === 'mmol') {
return Nightscout.units.mgdlToMMOL(bg);
} else {
return bg;
}
}
function generateTitle ( ) {
function s(value, sep) { return value ? value + ' ' : sep || ''; }
var title = '';
var time = latestSGV ? latestSGV.mills : (prevSGV ? prevSGV.mills : -1)
, ago = timeAgo(time, browserSettings);
if (ago && ago.status !== 'current') {
title = s(ago.value) + s(ago.label, ' - ') + title;
} else if (latestSGV) {
var currentMgdl = latestSGV.mgdl;
if (currentMgdl < 39) {
title = s(errorcodes.toDisplay(currentMgdl), ' - ') + title;
} else {
var deltaDisplay = delta.calc(prevSGV, latestSGV, sbx).display;
title = s(scaleBg(currentMgdl)) + s(deltaDisplay) + s(direction.info(latestSGV).label) + title;
}
}
return title;
}
function resetCustomTitle ( ) {
var customTitle = browserSettings.customTitle || 'Nightscout';
$('.customTitle').text(customTitle);
}
function checkAnnouncement() {
var result = {
inProgress: currentAnnouncement ? Date.now() - currentAnnouncement.received < FIVE_MINS_IN_MS : false
};
if (result.inProgress) {
var message = currentAnnouncement.message.length > 1 ? currentAnnouncement.message : currentAnnouncement.title;
result.message = message;
$('.customTitle').text(message);
} else if (currentAnnouncement) {
currentAnnouncement = null;
console.info('cleared announcement');
}
return result;
}
function updateTitle ( ) {
var windowTitle;
var announcementStatus = checkAnnouncement();
if (alarmMessage && alarmInProgress) {
$('.customTitle').text(alarmMessage);
if (!isTimeAgoAlarmType(currentAlarmType)) {
windowTitle = alarmMessage + ': ' + generateTitle();
}
} else if (announcementStatus.inProgress && announcementStatus.message) {
windowTitle = announcementStatus.message + ': ' + generateTitle();
} else {
resetCustomTitle();
}
container.toggleClass('announcing', announcementStatus.inProgress);
$(document).attr('title', windowTitle || generateTitle());
}
// initial setup of chart when data is first made available
function initializeCharts() {
// define the parts of the axis that aren't dependent on width or height
xScale = d3.time.scale()
.domain(d3.extent(data, dateFn));
yScale = d3.scale.log()
.domain([scaleBg(30), scaleBg(510)]);
xScale2 = d3.time.scale()
.domain(d3.extent(data, dateFn));
yScale2 = d3.scale.log()
.domain([scaleBg(36), scaleBg(420)]);
var tickFormat = d3.time.format.multi( [
['.%L', function(d) { return d.getMilliseconds(); }],
[':%S', function(d) { return d.getSeconds(); }],
['%I:%M', function(d) { return d.getMinutes(); }],
[isTimeFormat24() ? '%H:%M' : '%-I %p', function(d) { return d.getHours(); }],
['%a %d', function(d) { return d.getDay() && d.getDate() !== 1; }],
['%b %d', function(d) { return d.getDate() !== 1; }],
['%B', function(d) { return d.getMonth(); }],
['%Y', function() { return true; }]
]);
xAxis = d3.svg.axis()
.scale(xScale)
.tickFormat(tickFormat)
.ticks(4)
.orient('bottom');
yAxis = d3.svg.axis()
.scale(yScale)
.tickFormat(d3.format('d'))
.tickValues(tickValues)
.orient('left');
xAxis2 = d3.svg.axis()
.scale(xScale2)
.tickFormat(tickFormat)
.ticks(6)
.orient('bottom');
yAxis2 = d3.svg.axis()
.scale(yScale2)
.tickFormat(d3.format('d'))
.tickValues(tickValues)
.orient('right');
// setup a brush
brush = d3.svg.brush()
.x(xScale2)
.on('brushstart', brushStarted)
.on('brush', brushed)
.on('brushend', brushEnded);
updateChart(true);
}
// get the desired opacity for context chart based on the brush extent
function highlightBrushPoints(data) {
if (data.mills >= brush.extent()[0].getTime() && data.mills <= brush.extent()[1].getTime()) {
return futureOpacity(data.mills - latestSGV.mills);
} else {
return 0.5;
}
}
function addPlaceholderPoints () {
// TODO: This is a kludge to advance the time as data becomes stale by making old predictor clear (using color = 'none')
// This shouldn't need to be generated and can be fixed by using xScale.domain([x0,x1]) function with
// 2 days before now as x0 and 30 minutes from now for x1 for context plot, but this will be
// required to happen when 'now' event is sent from websocket.js every minute. When fixed,
// remove this code and all references to `type: 'server-forecast'`
var last = _.findLast(data, {type: 'sgv'});
var lastTime = last && last.mills;
if (!lastTime) {
console.error('Bad Data, last point has no mills', last);
lastTime = Date.now();
}
var n = Math.ceil(12 * (1 / 2 + (now - lastTime) / SIXTY_MINS_IN_MS)) + 1;
for (var i = 1; i <= n; i++) {
data.push({
mills: lastTime + (i * FIVE_MINS_IN_MS), mgdl: 100, color: 'none', type: 'server-forecast'
});
}
}
// clears the current user brush and resets to the current real time data
function updateBrushToNow(skipBrushing) {
// get current time range
var dataRange = d3.extent(data, dateFn);
// update brush and focus chart with recent data
d3.select('.brush')
.transition()
.duration(UPDATE_TRANS_MS)
.call(brush.extent([new Date(dataRange[1].getTime() - foucusRangeMS), dataRange[1]]));
addPlaceholderPoints();
if (!skipBrushing) {
brushed(true);
// clear user brush tracking
brushInProgress = false;
}
}
function brushStarted() {
// update the opacity of the context data points to brush extent
context.selectAll('circle')
.data(data)
.style('opacity', 1);
}
function brushEnded() {
// update the opacity of the context data points to brush extent
context.selectAll('circle')
.data(data)
.style('opacity', function (d) { return highlightBrushPoints(d) });
}
function alarmingNow() {
return container.hasClass('alarming');
}
function inRetroMode() {
if (!brush) {
return false;
}
var time = brush.extent()[1].getTime();
return !alarmingNow() && time - TWENTY_FIVE_MINS_IN_MS < now;
}
function brushed(skipTimer) {
if (!skipTimer) {
// set a timer to reset focus chart to real-time data
clearTimeout(brushTimer);
brushTimer = setTimeout(updateBrushToNow, BRUSH_TIMEOUT);
brushInProgress = true;
}
var brushExtent = brush.extent();
// ensure that brush extent is fixed at 3.5 hours
if (brushExtent[1].getTime() - brushExtent[0].getTime() !== foucusRangeMS) {
// ensure that brush updating is with the time range
if (brushExtent[0].getTime() + foucusRangeMS > d3.extent(data, dateFn)[1].getTime()) {
brushExtent[0] = new Date(brushExtent[1].getTime() - foucusRangeMS);
d3.select('.brush')
.call(brush.extent([brushExtent[0], brushExtent[1]]));
} else {
brushExtent[1] = new Date(brushExtent[0].getTime() + foucusRangeMS);
d3.select('.brush')
.call(brush.extent([brushExtent[0], brushExtent[1]]));
}
}
var nowDate = new Date(brushExtent[1] - THIRTY_MINS_IN_MS);
function updateCurrentSGV(entry) {
var value = entry.mgdl
, ago = timeAgo(entry.mills, browserSettings)
, isCurrent = ago.status === 'current';
if (value === 9) {
currentBG.text('');
} else if (value < 39) {
currentBG.html(errorcodes.toDisplay(value));
} else if (value < 40) {
currentBG.text('LOW');
} else if (value > 400) {
currentBG.text('HIGH');
} else {
currentBG.text(scaleBg(value));
}
bgStatus.toggleClass('current', alarmingNow() || (isCurrent && !inRetroMode()));
if (!alarmingNow()) {
container.removeClass('urgent warning inrange');
if (isCurrent && !inRetroMode()) {
container.addClass(sgvToColoredRange(value));
}
}
currentBG.toggleClass('icon-hourglass', value === 9);
currentBG.toggleClass('error-code', value < 39);
currentBG.toggleClass('bg-limit', value === 39 || value > 400);
$('.container').removeClass('loading');
}
function updatePlugins (sgvs, time) {
var pluginBase = Nightscout.plugins.base(majorPills, minorPills, statusPills, bgStatus, tooltip);
sbx = Nightscout.sandbox.clientInit(app
, browserSettings
, new Date(time).getTime() //make sure we send a timestamp
, pluginBase, {
sgvs: sgvs
, cals: [cal]
, treatments: treatments
, profile: Nightscout.profile
, uploaderBattery: devicestatusData && devicestatusData.uploaderBattery
}
);
//all enabled plugins get a chance to set properties, even if they aren't shown
Nightscout.plugins.setProperties(sbx);
//only shown plugins get a chance to update visualisations
Nightscout.plugins.updateVisualisations(sbx);
}
var nowData = data.filter(function(d) {
return d.type === 'sgv';
});
if (inRetroMode()) {
var retroTime = brushExtent[1].getTime() - THIRTY_MINS_IN_MS;
nowData = nowData.filter(function(d) {
return d.mills >= brushExtent[1].getTime() - (2 * THIRTY_MINS_IN_MS) &&
d.mills <= brushExtent[1].getTime() - TWENTY_FIVE_MINS_IN_MS;
});
// sometimes nowData contains duplicates. uniq it.
var lastDate = 0;
nowData = nowData.filter(function(d) {
var ok = lastDate + ONE_MIN_IN_MS < d.mills;
lastDate = d.mills;
return ok;
});
var focusPoint = nowData.length > 0 ? nowData[nowData.length - 1] : null;
if (focusPoint) {
updateCurrentSGV(focusPoint);
} else {
currentBG.text('---');
container.removeClass('urgent warning inrange');
}
updatePlugins(nowData, retroTime);
$('#currentTime')
.text(formatTime(new Date(retroTime), true))
.css('text-decoration','line-through');
updateTimeAgo();
} else {
// if the brush comes back into the current time range then it should reset to the current time and sg
nowData = nowData.slice(nowData.length - 2, nowData.length);
nowDate = now;
updateCurrentSGV(latestSGV);
updateClockDisplay();
updateTimeAgo();
updatePlugins(nowData, nowDate);
}
xScale.domain(brush.extent());
// get slice of data so that concatenation of predictions do not interfere with subsequent updates
var focusData = data.slice();
if (sbx.pluginBase.forecastPoints) {
focusData = focusData.concat(sbx.pluginBase.forecastPoints);
}
// bind up the focus chart data to an array of circles
// selects all our data into data and uses date function to get current max date
var focusCircles = focus.selectAll('circle').data(focusData, dateFn);
var focusRangeAdjustment = foucusRangeMS === THREE_HOURS_MS ? 1 : 1 + ((foucusRangeMS - THREE_HOURS_MS) / THREE_HOURS_MS / 8);
var dotRadius = function(type) {
var radius = prevChartWidth > WIDTH_BIG_DOTS ? 4 : (prevChartWidth < WIDTH_SMALL_DOTS ? 2 : 3);
if (type === 'mbg') {
radius *= 2;
} else if (type === 'forecast') {
radius = Math.min(3, radius - 1);
} else if (type === 'rawbg') {
radius = Math.min(2, radius - 1);
}
return radius / focusRangeAdjustment;
};
function isDexcom(device) {
return device && device.toLowerCase().indexOf('dexcom') === 0;
}
function prepareFocusCircles(sel) {
var badData = [];
sel.attr('cx', function (d) {
if (!d) {
console.error('Bad data', d);
return xScale(new Date(0));
} else if (!d.mills) {
console.error('Bad data, no mills', d);
return xScale(new Date(0));
} else {
return xScale(new Date(d.mills));
}
})
.attr('cy', function (d) {
var scaled = sbx.scaleEntry(d);
if (isNaN(scaled)) {
badData.push(d);
return yScale(scaleBg(450));
} else {
return yScale(scaled);
}
})
.attr('fill', function (d) { return d.type === 'forecast' ? 'none' : d.color; })
.attr('opacity', function (d) { return futureOpacity(d.mills - latestSGV.mills); })
.attr('stroke-width', function (d) { return d.type === 'mbg' ? 2 : d.type === 'forecast' ? 1 : 0; })
.attr('stroke', function (d) {
return (isDexcom(d.device) ? 'white' : d.type === 'forecast' ? d.color : '#0099ff');
})
.attr('r', function (d) { return dotRadius(d.type); });
if (badData.length > 0) {
console.warn('Bad Data: isNaN(sgv)', badData);
}
return sel;
}
// if already existing then transition each circle to its new position
prepareFocusCircles(focusCircles.transition().duration(UPDATE_TRANS_MS));
// if new circle then just display
prepareFocusCircles(focusCircles.enter().append('circle'))
.on('mouseover', function (d) {
if (d.type === 'sgv' || d.type === 'mbg') {
var bgType = (d.type === 'sgv' ? 'CGM' : (isDexcom(d.device) ? 'Calibration' : 'Meter'))
, rawbgValue = 0
, noiseLabel = '';
if (d.type === 'sgv') {
if (rawbg.showRawBGs(d.mgdl, d.noise, cal, sbx)) {
rawbgValue = scaleBg(rawbg.calc(d, cal, sbx));
}
noiseLabel = rawbg.noiseCodeToDisplay(d.mgdl, d.noise);
}
tooltip.transition().duration(TOOLTIP_TRANS_MS).style('opacity', .9);
tooltip.html('<strong>' + bgType + ' BG:</strong> ' + sbx.scaleEntry(d) +
(d.type === 'mbg' ? '<br/><strong>Device: </strong>' + d.device : '') +
(rawbgValue ? '<br/><strong>Raw BG:</strong> ' + rawbgValue : '') +
(noiseLabel ? '<br/><strong>Noise:</strong> ' + noiseLabel : '') +
'<br/><strong>Time:</strong> ' + formatTime(new Date(d.mills)))
.style('left', (d3.event.pageX) + 'px')
.style('top', (d3.event.pageY + 15) + 'px');
}
})
.on('mouseout', function (d) {
if (d.type === 'sgv' || d.type === 'mbg') {
tooltip.transition()
.duration(TOOLTIP_TRANS_MS)
.style('opacity', 0);
}
});
focusCircles.exit()
.remove();
// remove all insulin/carb treatment bubbles so that they can be redrawn to correct location
d3.selectAll('.path').remove();
// add treatment bubbles
// a higher bubbleScale will produce smaller bubbles (it's not a radius like focusDotRadius)
var bubbleScale = (prevChartWidth < WIDTH_SMALL_DOTS ? 4 : (prevChartWidth < WIDTH_BIG_DOTS ? 3 : 2)) * focusRangeAdjustment;
focus.selectAll('circle')
.data(treatments)
.each(function (d) { drawTreatment(d, bubbleScale, true) });
// transition open-top line to correct location
focus.select('.open-top')
.attr('x1', xScale2(brush.extent()[0]))
.attr('y1', yScale(scaleBg(30)))
.attr('x2', xScale2(brush.extent()[1]))
.attr('y2', yScale(scaleBg(30)));
// transition open-left line to correct location
focus.select('.open-left')
.attr('x1', xScale2(brush.extent()[0]))
.attr('y1', focusHeight)
.attr('x2', xScale2(brush.extent()[0]))
.attr('y2', prevChartHeight);
// transition open-right line to correct location
focus.select('.open-right')
.attr('x1', xScale2(brush.extent()[1]))
.attr('y1', focusHeight)
.attr('x2', xScale2(brush.extent()[1]))
.attr('y2', prevChartHeight);
focus.select('.now-line')
.transition()
.duration(UPDATE_TRANS_MS * 1.3)
.attr('x1', xScale(nowDate))
.attr('y1', yScale(scaleBg(36)))
.attr('x2', xScale(nowDate))
.attr('y2', yScale(scaleBg(420)));
context.select('.now-line')
.transition()
.attr('x1', xScale2(brush.extent()[1]- THIRTY_MINS_IN_MS))
.attr('y1', yScale2(scaleBg(36)))
.attr('x2', xScale2(brush.extent()[1]- THIRTY_MINS_IN_MS))
.attr('y2', yScale2(scaleBg(420)));
// update x axis
focus.select('.x.axis')
.call(xAxis);
// add clipping path so that data stays within axis
focusCircles.attr('clip-path', 'url(#clip)');
function prepareTreatCircles(sel) {
function strokeColor (d) {
var color = 'white';
if (d.isAnnouncement) {
color = 'orange';
} else if (d.glucose) {
color = 'grey';
}
return color;
}
function fillColor (d) {
var color ='grey';
if (d.isAnnouncement) {
color = 'orange';
} else if (d.glucose) {
color = 'red';
}
return color;
}
sel.attr('cx', function (d) { return xScale(new Date(d.mills)); })
.attr('cy', function (d) { return yScale(sbx.scaleEntry(d)); })
.attr('r', function () { return dotRadius('mbg'); })
.attr('stroke-width', 2)
.attr('stroke', strokeColor)
.attr('fill', fillColor);
return sel;
}
function treatmentTooltip (d) {
return '<strong>'+translate('Time')+':</strong> ' + formatTime(new Date(d.mills)) + '<br/>' +
(d.eventType ? '<strong>'+translate('Treatment type')+':</strong> ' + d.eventType + '<br/>' : '') +
(d.glucose ? '<strong>'+translate('BG')+':</strong> ' + d.glucose + (d.glucoseType ? ' (' + translate(d.glucoseType) + ')': '') + '<br/>' : '') +
(d.enteredBy ? '<strong>'+translate('Entered by')+':</strong> ' + d.enteredBy + '<br/>' : '') +
(d.notes ? '<strong>'+translate('Notes')+':</strong> ' + d.notes : '');
}
function announcementTooltip (d) {
return '<strong>'+translate('Time')+':</strong> ' + formatTime(new Date(d.mills)) + '<br/>' +
(d.eventType ? '<strong>'+translate('Announcement')+'</strong><br/>' : '') +
(d.notes && d.notes.length > 1 ? '<strong>'+translate('Message')+':</strong> ' + d.notes : '') +
(d.enteredBy ? '<strong>'+translate('Entered by')+':</strong> ' + d.enteredBy + '<br/>' : '');
}
//NOTE: treatments with insulin or carbs are drawn by drawTreatment()
// bind up the focus chart data to an array of circles
var treatCircles = focus.selectAll('rect').data(treatments.filter(function(treatment) {
return !treatment.carbs && !treatment.insulin;
}));
// if already existing then transition each circle to its new position
prepareTreatCircles(treatCircles.transition().duration(UPDATE_TRANS_MS));
// if new circle then just display
prepareTreatCircles(treatCircles.enter().append('circle'))
.on('mouseover', function (d) {
tooltip.transition().duration(TOOLTIP_TRANS_MS).style('opacity', .9);
tooltip.html(d.isAnnouncement ? announcementTooltip(d) : treatmentTooltip(d))
.style('left', (d3.event.pageX) + 'px')
.style('top', (d3.event.pageY + 15) + 'px');
})
.on('mouseout', function () {
tooltip.transition()
.duration(TOOLTIP_TRANS_MS)
.style('opacity', 0);
});
treatCircles.attr('clip-path', 'url(#clip)');
}
// called for initial update and updates for resize
var updateChart = _.debounce(function debouncedUpdateChart(init) {
if (documentHidden && !init) {
console.info('Document Hidden, not updating - ' + (new Date()));
return;
}
// get current data range
var dataRange = d3.extent(data, dateFn);
// get the entire container height and width subtracting the padding
var chartWidth = (document.getElementById('chartContainer')
.getBoundingClientRect().width) - padding.left - padding.right;
var chartHeight = (document.getElementById('chartContainer')
.getBoundingClientRect().height) - padding.top - padding.bottom;
// get the height of each chart based on its container size ratio
focusHeight = chartHeight * .7;
contextHeight = chartHeight * .2;
// get current brush extent
var currentBrushExtent = brush.extent();
// only redraw chart if chart size has changed
if ((prevChartWidth !== chartWidth) || (prevChartHeight !== chartHeight)) {
prevChartWidth = chartWidth;
prevChartHeight = chartHeight;
//set the width and height of the SVG element
charts.attr('width', chartWidth + padding.left + padding.right)
.attr('height', chartHeight + padding.top + padding.bottom);
// ranges are based on the width and height available so reset
xScale.range([0, chartWidth]);
xScale2.range([0, chartWidth]);
yScale.range([focusHeight, 0]);
yScale2.range([chartHeight, chartHeight - contextHeight]);
if (init) {
// if first run then just display axis with no transition
focus.select('.x')
.attr('transform', 'translate(0,' + focusHeight + ')')
.call(xAxis);
focus.select('.y')
.attr('transform', 'translate(' + chartWidth + ',0)')
.call(yAxis);
// if first run then just display axis with no transition
context.select('.x')
.attr('transform', 'translate(0,' + chartHeight + ')')
.call(xAxis2);
context.append('g')
.attr('class', 'x brush')
.call(d3.svg.brush().x(xScale2).on('brush', brushed))
.selectAll('rect')
.attr('y', focusHeight)
.attr('height', chartHeight - focusHeight);
// disable resizing of brush
d3.select('.x.brush').select('.background').style('cursor', 'move');
d3.select('.x.brush').select('.resize.e').style('cursor', 'move');
d3.select('.x.brush').select('.resize.w').style('cursor', 'move');
// create a clipPath for when brushing
clip = charts.append('defs')
.append('clipPath')
.attr('id', 'clip')
.append('rect')
.attr('height', chartHeight)
.attr('width', chartWidth);
// add a line that marks the current time
focus.append('line')
.attr('class', 'now-line')
.attr('x1', xScale(new Date(now)))
.attr('y1', yScale(scaleBg(30)))
.attr('x2', xScale(new Date(now)))
.attr('y2', yScale(scaleBg(420)))
.style('stroke-dasharray', ('3, 3'))
.attr('stroke', 'grey');
// add a y-axis line that shows the high bg threshold
focus.append('line')
.attr('class', 'high-line')
.attr('x1', xScale(dataRange[0]))
.attr('y1', yScale(scaleBg(app.thresholds.bg_high)))
.attr('x2', xScale(dataRange[1]))
.attr('y2', yScale(scaleBg(app.thresholds.bg_high)))
.style('stroke-dasharray', ('1, 6'))
.attr('stroke', '#777');
// add a y-axis line that shows the high bg threshold
focus.append('line')
.attr('class', 'target-top-line')
.attr('x1', xScale(dataRange[0]))
.attr('y1', yScale(scaleBg(app.thresholds.bg_target_top)))
.attr('x2', xScale(dataRange[1]))
.attr('y2', yScale(scaleBg(app.thresholds.bg_target_top)))
.style('stroke-dasharray', ('3, 3'))
.attr('stroke', 'grey');
// add a y-axis line that shows the low bg threshold
focus.append('line')
.attr('class', 'target-bottom-line')
.attr('x1', xScale(dataRange[0]))
.attr('y1', yScale(scaleBg(app.thresholds.bg_target_bottom)))
.attr('x2', xScale(dataRange[1]))
.attr('y2', yScale(scaleBg(app.thresholds.bg_target_bottom)))
.style('stroke-dasharray', ('3, 3'))
.attr('stroke', 'grey');
// add a y-axis line that shows the low bg threshold
focus.append('line')
.attr('class', 'low-line')
.attr('x1', xScale(dataRange[0]))
.attr('y1', yScale(scaleBg(app.thresholds.bg_low)))
.attr('x2', xScale(dataRange[1]))
.attr('y2', yScale(scaleBg(app.thresholds.bg_low)))
.style('stroke-dasharray', ('1, 6'))
.attr('stroke', '#777');
// add a y-axis line that opens up the brush extent from the context to the focus
focus.append('line')
.attr('class', 'open-top')
.attr('stroke', 'black')
.attr('stroke-width', 2);
// add a x-axis line that closes the the brush container on left side
focus.append('line')
.attr('class', 'open-left')
.attr('stroke', 'white');
// add a x-axis line that closes the the brush container on right side
focus.append('line')
.attr('class', 'open-right')
.attr('stroke', 'white');
// add a line that marks the current time
context.append('line')
.attr('class', 'now-line')
.attr('x1', xScale(new Date(now)))
.attr('y1', yScale2(scaleBg(36)))
.attr('x2', xScale(new Date(now)))
.attr('y2', yScale2(scaleBg(420)))
.style('stroke-dasharray', ('3, 3'))
.attr('stroke', 'grey');
// add a y-axis line that shows the high bg threshold
context.append('line')
.attr('class', 'high-line')
.attr('x1', xScale(dataRange[0]))
.attr('y1', yScale2(scaleBg(app.thresholds.bg_target_top)))
.attr('x2', xScale(dataRange[1]))
.attr('y2', yScale2(scaleBg(app.thresholds.bg_target_top)))
.style('stroke-dasharray', ('3, 3'))
.attr('stroke', 'grey');
// add a y-axis line that shows the low bg threshold
context.append('line')
.attr('class', 'low-line')
.attr('x1', xScale(dataRange[0]))
.attr('y1', yScale2(scaleBg(app.thresholds.bg_target_bottom)))
.attr('x2', xScale(dataRange[1]))
.attr('y2', yScale2(scaleBg(app.thresholds.bg_target_bottom)))
.style('stroke-dasharray', ('3, 3'))
.attr('stroke', 'grey');
} else {
// for subsequent updates use a transition to animate the axis to the new position
var focusTransition = focus.transition().duration(UPDATE_TRANS_MS);
focusTransition.select('.x')
.attr('transform', 'translate(0,' + focusHeight + ')')
.call(xAxis);
focusTransition.select('.y')
.attr('transform', 'translate(' + chartWidth + ', 0)')
.call(yAxis);
var contextTransition = context.transition().duration(UPDATE_TRANS_MS);
contextTransition.select('.x')
.attr('transform', 'translate(0,' + chartHeight + ')')
.call(xAxis2);
if (clip) {
// reset clip to new dimensions
clip.transition()
.attr('width', chartWidth)
.attr('height', chartHeight);
}
// reset brush location
context.select('.x.brush')
.selectAll('rect')
.attr('y', focusHeight)
.attr('height', chartHeight - focusHeight);
// clear current brush
d3.select('.brush').call(brush.clear());
// redraw old brush with new dimensions
d3.select('.brush').transition().duration(UPDATE_TRANS_MS).call(brush.extent(currentBrushExtent));
// transition lines to correct location
focus.select('.high-line')
.transition()
.duration(UPDATE_TRANS_MS)
.attr('x1', xScale(currentBrushExtent[0]))
.attr('y1', yScale(scaleBg(app.thresholds.bg_high)))
.attr('x2', xScale(currentBrushExtent[1]))
.attr('y2', yScale(scaleBg(app.thresholds.bg_high)));
focus.select('.target-top-line')
.transition()
.duration(UPDATE_TRANS_MS)
.attr('x1', xScale(currentBrushExtent[0]))
.attr('y1', yScale(scaleBg(app.thresholds.bg_target_top)))
.attr('x2', xScale(currentBrushExtent[1]))
.attr('y2', yScale(scaleBg(app.thresholds.bg_target_top)));
focus.select('.target-bottom-line')
.transition()
.duration(UPDATE_TRANS_MS)
.attr('x1', xScale(currentBrushExtent[0]))
.attr('y1', yScale(scaleBg(app.thresholds.bg_target_bottom)))
.attr('x2', xScale(currentBrushExtent[1]))
.attr('y2', yScale(scaleBg(app.thresholds.bg_target_bottom)));
focus.select('.low-line')
.transition()
.duration(UPDATE_TRANS_MS)
.attr('x1', xScale(currentBrushExtent[0]))
.attr('y1', yScale(scaleBg(app.thresholds.bg_low)))
.attr('x2', xScale(currentBrushExtent[1]))
.attr('y2', yScale(scaleBg(app.thresholds.bg_low)));
// transition open-top line to correct location
focus.select('.open-top')
.transition()
.duration(UPDATE_TRANS_MS)
.attr('x1', xScale2(currentBrushExtent[0]))
.attr('y1', yScale(scaleBg(30)))
.attr('x2', xScale2(currentBrushExtent[1]))
.attr('y2', yScale(scaleBg(30)));
// transition open-left line to correct location
focus.select('.open-left')
.transition()
.duration(UPDATE_TRANS_MS)
.attr('x1', xScale2(currentBrushExtent[0]))
.attr('y1', focusHeight)
.attr('x2', xScale2(currentBrushExtent[0]))
.attr('y2', chartHeight);
// transition open-right line to correct location
focus.select('.open-right')
.transition()
.duration(UPDATE_TRANS_MS)
.attr('x1', xScale2(currentBrushExtent[1]))
.attr('y1', focusHeight)
.attr('x2', xScale2(currentBrushExtent[1]))
.attr('y2', chartHeight);
// transition high line to correct location
context.select('.high-line')
.transition()
.duration(UPDATE_TRANS_MS)
.attr('x1', xScale2(dataRange[0]))
.attr('y1', yScale2(scaleBg(app.thresholds.bg_target_top)))
.attr('x2', xScale2(dataRange[1]))
.attr('y2', yScale2(scaleBg(app.thresholds.bg_target_top)));
// transition low line to correct location
context.select('.low-line')
.transition()
.duration(UPDATE_TRANS_MS)
.attr('x1', xScale2(dataRange[0]))
.attr('y1', yScale2(scaleBg(app.thresholds.bg_target_bottom)))
.attr('x2', xScale2(dataRange[1]))
.attr('y2', yScale2(scaleBg(app.thresholds.bg_target_bottom)));
}
}
// update domain
xScale2.domain(dataRange);
// only if a user brush is not active, update brush and focus chart with recent data
// else, just transition brush
var updateBrush = d3.select('.brush').transition().duration(UPDATE_TRANS_MS);
if (!brushInProgress) {
updateBrush
.call(brush.extent([new Date(dataRange[1].getTime() - foucusRangeMS), dataRange[1]]));
brushed(true);
} else {
updateBrush
.call(brush.extent([new Date(currentBrushExtent[1].getTime() - foucusRangeMS), currentBrushExtent[1]]));
brushed(true);
}
// bind up the context chart data to an array of circles
var contextCircles = context.selectAll('circle')
.data(data);