-
Notifications
You must be signed in to change notification settings - Fork 3
/
bgraph.js
5982 lines (5482 loc) · 228 KB
/
bgraph.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
/**
* Beebrain graph generation and red line editing provided as a UMD module.
* Provides a {@link bgraph} class, which can be used to construct independent
* graph generating objects each with their own internal state, possibly linked
* to particular div elements on the DOM.<br/>
* <br/>Copyright 2017-2021 Uluc Saranli and Daniel Reeves
@module bgraph
@requires d3
@requires moment
@requires butil
@requires broad
@requires beebrain
*/
;((function (root, factory) { // BEGIN PREAMBLE --------------------------------
'use strict'
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
//console.log("bgraph: Using AMD module definition")
define(['d3', 'moment', 'butil', 'broad', 'beebrain'], factory)
} else if (typeof module === 'object' && module.exports) {
// Node. Does not work with strict CommonJS, but only CommonJS-like
// environments that support module.exports, like Node.
//console.log("bgraph: Using CommonJS module.exports")
module.exports = factory(require('d3'),
require('./moment'),
require('./butil'),
require('./broad'),
require('./beebrain'))
} else {
//console.log("bgraph: Using Browser globals")
root.bgraph = factory(root.d3,
root.moment,
root.butil,
root.broad,
root.beebrain)
}
})(this, function (d3, moment, bu, br, bb) { // END PREAMBLE -- BEGIN MAIN -----
'use strict'
const nosteppy = false
// -----------------------------------------------------------------------------
// --------------------------- CONVENIENCE CONSTANTS ---------------------------
const max = Math.max
const min = Math.min
const abs = Math.abs
const floor = Math.floor
const ceil = Math.ceil
const round = Math.round
const DIY = 365.25
const SID = 86400
// -----------------------------------------------------------------------------
// ------------------------------ FACTORY GLOBALS ------------------------------
/** Global counter to generate unique IDs for multiple bgraph instances. */
let gid = 1
/** Default settings */
let defaults = {
/** Generates an empty graph and JSON */
noGraph: false,
/** Binds the graph to a div element */
divGraph: null,
/** Binds the road table to a div element */
divTable: null,
/** Binds the datapoint table to a div element */
divPoints: null,
/** Binds the dueby table to a div element */
divDueby: null,
/** Binds the data table to a div element */
divData: null,
/** Binds the goal JSON output to a div element */
divJSON: null,
/** Size of the SVG element to hold the graph */
svgSize: { width: 700, height: 450 },
/** Boundaries of the SVG group to hold the focus graph */
focusRect: { x:0, y:0, width:700, height: 370 },
/** Initial padding within the focus graph. */
focusPad: { left:25, right:5, top:25, bottom:30 },
/** Boundaries of the SVG group to hold the context graph */
ctxRect: { x:0, y:370, width:700, height: 80 },
/** Initial padding within the context graph. */
ctxPad: { left:25, right:5, top:0, bottom:30 },
/** Height of the graph matrix table. Choose 0 for unspecified */
tableHeight: 387,
/** Visual parameters for the zoom in/out buttons. "factor"
indicates how much to zoom in/out per click. */
zoomButton: { size: 40, opacity: 0.6, factor: 1.5 },
/** Size of the bullseye image in the focus and context graphs */
bullsEye: { size: 40, ctxsize: 20 },
/** Visual parameters for draggable road dots */
roadDot: { size: 5, ctxsize: 3, border: 1.5, ctxborder: 1 },
/** Visual parameters for draggable road knots and removal buttons */
roadKnot: { width: 3, rmbtnscale: 0.6 },
/** Visual parameters for draggable road lines */
roadLine: { width: 3, ctxwidth: 2 },
/** Visual parameters for fixed lines for the original road */
oldRoadLine: { width: 3, ctxwidth: 2, dash: 32, ctxdash: 16 },
/** Visual parameters for data points (past, flatlined and hollow) */
dataPoint: { size: 5, fsize: 5, hsize: 2.5, border:1 },
/** Visual parameters for the akrasia horizon */
horizon: { width: 2, ctxwidth: 1, dash: 8, ctxdash: 6,
font: 10, ctxfont: 9 },
/** Visual parameters for vertical line for asof */
today: { width: 2, ctxwidth: 1, font: 12, ctxfont: 9 },
/** Parameters for d3 axes */
axis: {font: 11},
/** Visual parameters for watermarks */
watermark: { height:170, fntsize:150, color:"#000000" }, // was #f0f0f0
guidelines: { width:2, weekwidth:4 },
maxfluxline: 4, // width
stdfluxline: 2, // width
razrline: 3, // trying thicker bright red line: 2 -> 4 (see also mobile)
/** Visual parameters for text boxes shown during dragging */
textBox: { margin: 3 },
/** Visual parameters for odometer resets */
odomReset: { width: 0.5, dash: 8 },
roadLineCol: { valid: "black", invalid:"#ca1212", selected:"yellow" },
roadDotCol: { fixed: "darkgray", editable:"#c2c2c2", selected: "yellow" },
roadKnotCol: { dflt: "#c2c2c2", selected: "yellow",
rmbtn: "black", rmbtnsel: "red" },
textBoxCol: { bg: "#ffffff", stroke:"#d0d0d0" },
roadTableCol: { bg:"#ffffff", bgHighlight: "#fffb55",
text:"#000000", textDisabled: "#aaaaaa",
bgDisabled:"#f2f2f2"},
dataPointCol: { future: "#909090", stroke: "#eeeeee" },
halfPlaneCol: { fill: "#ffffe8" },
pastBoxCol: { fill: "#f8f8f8", opacity:0.5 },
odomResetCol: { dflt: "#c2c2c2" },
/** Strips the graph of all details except what is needed for svg output */
headless: false,
/** Enables zooming by scrollwheel. When disabled, only the context graph and
the zoom buttons will allow zooming. */
scrollZoom: true,
/** Enables zooming with buttons */
buttonZoom: true,
/** Enables the road editor. When disabled, the generated graph mirrors
Beebrain output as closely as possible. */
roadEditor: false,
/** Enables the display of the context graph within the SVG */
showContext: false,
/** Enables showing a dashed rectangle in the context graph visualizing the
current graph limits on the y-axis */
showFocusRect: false,
/** Enables displaying datapoints on the graph */
showData: true,
/** When datapoint display is enabled, indicates the number of days before
asof to show data for. This can be used to speed up display refresh for
large goals. Use -1 to display all datapoints. */
maxDataDays: -1,
/** Indicates how many days beyond asof should be included in the fully
zoomed out graph. This is useful for when the goal date is too far beyond
asof, making the context graph somewhat useless in the UI. */
maxFutureDays: 365,
/** Indicates whether slopes for segments beyond the currently dragged
element should be kept constant during editing */
keepSlopes: true,
/** Indicates whether guidelines should be shown in the interactive editor */
showGuidelines: true,
/** Indicates whether intervals between the knots for segments beyond the
currently dragged element should be kept constant during editing */
keepIntervals: false,
/** Indicates whether the graph matrix table should be shown with the earliest
rows first (normal) or most recent rows first (reversed) */
reverseTable: false,
/** Indicates whether the auto-scrolling feature for the graph matrix table
should be enabled such that when the mouse moves over knots, dots, or road
elements, the corresponding table row is scrolled to be visible in the
table. This is particularly useful when tableHeight is explicitly
specified and is nonzero. */
tableAutoScroll: true,
/** Chooses whether the graph matrix table should be dynamically updated
during the dragging of road knots, dots, and segments. Enabling this may
induce some lagginess, particularly on Firefox due to more components
being updated during dragging. */
tableUpdateOnDrag: false,
/** Chooses whether the dueby table should be dynamically updated
during the dragging of road knots, dots, and segments. */
duebyUpdateOnDrag: true,
/** Chooses whether the graph matrix table should include checkboxes for
choosing the field to be automatically computed */
tableCheckboxes: true,
/** Callback function that gets invoked when the road is edited by the user.
Various interface functions can then be used to retrieve the new road
state. This is also useful to update the state of undo/redo and submit
buttons based on how many edits have been done on the original road. */
onRoadChange: null,
/** Callback function that gets invoked when a datapoint is edited
or deleted. onDataEdit(id, data) indicates that the datapoint
with the given id is edited with the new content "data =
[daystamp, value, cmt]" or deleted if data=null */
onDataEdit: null,
/** Number of entries visible on the data table */
dataTableSize: 11,
dataAutoScroll: true,
/** Callback function that gets invoked when an error is encountered in
loading, processing, drawing, or editing the road */
onError: null,
}
/** This object defines default options for mobile browsers, where larger dots,
knots, and lines are necessary to make editing through dragging feasible. */
const mobiledefaults = {
svgSize: { width: 700, height: 530 },
focusRect: { x:0, y:0, width: 700, height: 400 },
focusPad: { left: 25, right: 10, top: 35, bottom: 30 },
ctxRect: { x: 0, y: 400, width: 700, height: 80 },
ctxPad: { left: 25, right: 10, top: 0, bottom: 30 },
tableHeight: 540, // Choose 0 for unspecified
zoomButton: { size: 50, opacity: 0.7, factor: 1.5 },
bullsEye: { size: 40, ctxsize: 20 },
roadDot: { size: 10, ctxsize: 4, border: 1.5, ctxborder: 1 },
roadKnot: { width: 7, rmbtnscale: 0.9 },
roadLine: { width: 7, ctxwidth: 2 },
oldRoadLine: { width: 3, ctxwidth: 1, dash: 32, ctxdash: 16 },
dataPoint: { size: 4, fsize: 6 },
horizon: { width: 2, ctxwidth: 1, dash: 8, ctxdash: 8,
font: 14, ctxfont: 10 },
today: { width: 2, ctxwidth: 1, font: 16, ctxfont: 10 },
watermark: { height: 150, fntsize: 100, color: "#000000" }, // was #f0f0f0
guidelines: { width: 2, weekwidth: 4 },
maxfluxline: 4, // width
stdfluxline: 2, // width
razrline: 3, // trying thicker bright red line: 2 -> 4 (also for desktop)
textBox: { margin: 3 },
}
/** Style text embedded in the SVG object for proper saving of the SVG */
const SVGStyle =
".svg{shape-rendering:crispEdges}"
+ ".axis path,.axis line{fill:none;stroke:black;shape-rendering:crispEdges}"
+ ".axis .minor line{stroke:#777;stroke-dasharray:0,2,4,3}"
+ ".grid line"
+ "{fill:none;stroke:#dddddd;stroke-width:1px;shape-rendering:crispEdges}"
+ ".aura{fill-opacity:0.3;stroke-opacity:0.3;}"
+ ".aurapast{fill-opacity:0.15;stroke-opacity:0.3}"
+ ".grid .minor line{stroke:none}"
+ ".axis text{font-family:sans-serif;font-size:11px;}"
+ ".axislabel{font-family:sans-serif;font-size:11px;text-anchor:middle}"
+ "circle.dots{stroke:black}"
+ "line.roads{stroke:black}"
+ ".pasttext,.ctxtodaytext,.ctxhortext,.horizontext,.hashtag"
+ "{text-anchor:middle;font-family:sans-serif}"
+ ".waterbuf,.waterbux{opacity:0.05882353;" //stroke:#dddddd;stroke-width:1;"
+ "text-anchor:middle;font-family:Dejavu Sans,sans-serif}"
+ ".loading{text-anchor:middle;font-family:Dejavu Sans,sans-serif}"
+ ".zoomarea{fill:none}"
+ "circle.ap{stroke:none}"
+ "circle.rd{stroke:none;pointer-events:none;fill:"+bu.BHUE.ROSE+"}"
+ "circle.std{stroke:none;pointer-events:none;fill:"+(nosteppy?"#c0c0c0":bu.BHUE.PURP)+"}"
+ "circle.hp{stroke:none;fill:"+bu.BHUE.WITE+"}"
+ ".dp.gra,.ap.gra{fill:"+bu.BHUE.GRADOT+"}"
+ ".dp.grn,.ap.grn{fill:"+bu.BHUE.GRNDOT+"}"
+ ".dp.blu,.ap.blu{fill:"+bu.BHUE.BLUDOT+"}"
+ ".dp.orn,.ap.orn{fill:"+bu.BHUE.ORNDOT+"}"
+ ".dp.red,.ap.red{fill:"+bu.BHUE.REDDOT+"}"
+ ".dp.blk,.ap.blk{fill:"+bu.BHUE.BLCK+"}"
+ ".dp.fuda,.ap.fuda{fill-opacity:0.3}"
+ ".guides{pointer-events:none;fill:none;stroke:"+bu.BHUE.LYEL+"}"
+ ".ybhp{pointer-events:none}"
+ ".rosy{fill:none;stroke:"+bu.BHUE.ROSE+";pointer-events:none}"
+ ".steppy{fill:none;stroke:"+(nosteppy?"#c0c0c0":bu.BHUE.PURP)+";pointer-events:none}"
+ ".steppyppr{fill:none;stroke-opacity:0.8;stroke:"+bu.BHUE.LPURP+";pointer-events:none}"
+ ".derails{fill:"+bu.BHUE.REDDOT+";pointer-events:none}"
+ ".overlay .textbox{fill:#ffffcc;fill-opacity:0.5;stroke:black;"
+ "stroke-width:1;pointer-events:none;rx:5;ry:5}"
/** Fraction of plot range that the axes extend beyond */
const PRAF = 0.015
/** Seconds to milliseconds (Javascript unixtime is the latter) */
const SMS = 1000
/** Enum object to identify error types */
const ErrType = { NOBBFILE: 0, BADBBFILE: 1, BBERROR: 2 }
/** Enum object to identify error types */
const ErrMsgs = [ "Could not find goal (.bb) file.",
"Bad .bb file.",
"Beeminder error" ]
/** This atrocity attempts to determine whether the page was loaded from a
mobile device. It might be from 2019 and in want of updating. */
const onMobileOrTablet = () => {
if (typeof navigator == 'undefined' && typeof window == 'undefined')
return false
var check = false;
(function(a){if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))) check = true})(navigator.userAgent||navigator.vendor||window.opera)
return check
}
/** Configure functionality (private) */
let config = (obj, options) => {
if (!obj.opts) obj.opts = bu.extendo({}, defaults, true)
if (onMobileOrTablet()) bu.extendo(obj.opts, mobiledefaults)
let opts = bu.extendo(obj.opts, options, true)
opts.divGraph = opts.divGraph && opts.divGraph.nodeName ? opts.divGraph : null
if (opts.headless) { // Override options for svg output
opts.divTable = null
opts.divPoints = null
opts.divDueby = null
opts.divData = null
opts.scrollZoom = false
opts.roadEditor = false
opts.showContext = false
opts.showFocusRect = false
} else {
opts.divTable =
opts.divTable && opts.divTable.nodeName ? opts.divTable : null
opts.divPoints =
opts.divPoints && opts.divPoints.nodeName ? opts.divPoints : null
}
return opts
}
// -----------------------------------------------------------------------------
// ---------------------------- BGRAPH CONSTRUCTOR -----------------------------
/** @typedef BGraphOptions
@global
@type {object}
@property {boolean} noGraph Generates an empty graph and JSON if true
@property {Boolean} headless Strips the graph of all details except what is needed for svg output.
@property {Boolean} roadEditor Enables the road editor. When disabled, the generated graph mirrors beebrain output as closely as possible.
@property {object} divJSON Binds the goal JSON output to a div element
@property {object} divGraph Binds the graph to a div element
@property {object} svgSize Size of the SVG element to hold the graph e.g. { width: 700, height: 450 }
@property {object} focusRect Boundaries of the SVG group to hold the focus graph e.g. { x:0, y:0, width:700, height: 370 }
@property {object} focusPad Initial padding within the focus graph e.g. { left:25, right:5, top:25, bottom:30 }
@property {object} ctxRect Boundaries of the SVG group to hold the context graph e.g. { x:0, y:370, width:700, height: 80 }
@property {object} ctxPad Initial padding within the context graph e.g. { left:25, right:5, top:0, bottom:30 }
@property {Boolean} scrollZoom Enables zooming by scrollwheel. When disabled, only the context graph and the zoom buttons will allow zooming.
@property {Boolean} showContext Enables the display of the context graph within the SVG
@property {Boolean} showFocusRect Enables showing a dashed rectange in the context graph visualizing the current graph limits on the y-axis
@property {Boolean} keepSlopes Indicates whether slopes for segments beyond the currently dragged element should be kept constant during editing.
@property {Boolean} keepIntervals Indicates whether intervals between the knots for segments beyond the currently dragged element should be kept constant during editing.
@property {Boolean} showData Enables displaying datapoints on the graph
@property {Integer} maxDataDays When datapoint display is enabled, indicates the number of days before asof to show data for. This can be used to speed up display refresh for large goals. Choose -1 to display all datapoints. Choose -1 to show all points.
@property {Integer} maxFutureDays Indicates how many days beyond asof should be included in the fully zoomed out graph. This is useful for when the goal date is too far beyond asof, making the context graph somewhat useless in terms of its interface utility.
@property {object} divTable Binds the road table to a div element
@property {Number} tableHeight Height of the graph matrix table. Choose 0 for unspecified
@property {Boolean} tableCheckboxes Chooses whether the graph matrix table should include checkboxes for choosing the field to be automatically computed.
@property {Boolean} reverseTable Indicates whether the graph matrix table should be shown with the earliest rows first (normal) or most recent rows first(reversed).
@property {Boolean} tableAutoScroll Indicates whether the auto-scrolling feature for the graph matrix table should be enabled such that when the mouse moves over knots, dots or road elements, the corresponding table row is scrolled to be visible in the table. This is particularly useful when tableHeight is explicitly specified and is nonzero.
@property {Boolean} tableUpdateOnDrag Chooses whether the graph matrix table should be dynamically updated during the dragging of road knots, dots and segments. Enabling this may induce some lagginess, particularly on Firefox due to more components being updated during dragging
@property {function} onRoadChange Callback function that gets invoked when the road is finished loading or has been edited by the user. Various interface functions can then be used to retrieve the new road state. This is also useful to update the state of undo/redo and submit buttons based on how many edits have been done on the original road.
@property {function} onError Callback function that gets invoked when an error is encountered in loading, processing, drawing or editing the road.
@property {object} zoomButton Visual parameters for the zoom in/out buttons. "factor" indicates how much to zoom in/out per click. e.g. { size: 40, opacity: 0.6, factor: 1.5 }
@property {object} bullsEye Size of the bullseye image in the focus and context graphs e.g. { size: 40, ctxsize: 20 }
@property {object} roadDot Visual parameters for draggable road dots e.g. { size: 5, ctxsize: 3, border: 1.5, ctxborder: 1 }
@property {object} roadKnot Visual parameters for draggable road knots and removal buttons e.g. { width: 3, rmbtnscale: 0.6 }
@property {object} roadLine Visual parameters for draggable road lines e.g. { width: 3, ctxwidth: 2 }
@property {object} oldRoadLine Visual parameters for fixed lines for the original road e.g. { width: 3, ctxwidth: 2, dash: 32, ctxdash: 16 }
@property {object} dataPoint Visual parameters for data points (past, flatlined and hollow) e.g. { size: 5, fsize: 5, hsize: 2.5 }
@property {object} horizon Visual parameters for the akrasia horizon e.g. { width: 2, ctxwidth: 1, dash: 8, ctxdash: 6, font: 12, ctxfont: 9 }
@property {object} today Visual parameters for vertical line for asof e.g. { width: 2, ctxwidth: 1, font: 12, ctxfont: 9 }
@property {object} watermark Visual parameters for watermarks e.g. { height:170, fntsize:130 }
@property {object} guidelines Visual parameters for guidelines e.g. { width:2, weekwidth:4 }
@property {object} maxfluxline Visual parameter for maxfluxline (width)
@property {object} stdfluxline Visual parameter for stdfluxline (width)
@property {object} textBox Visual parameters for text boxes shown during dragging e.g. { margin: 3 }
@property {object} odomReset Visual parameters for odometer resets e.g. { width: 0.5, dash: 8 }
@property {object} roadLineCol Colors for road segments for the editor, e.g. { valid: "black", invalid:"#ca1212", selected:"yellow"}
@property {object} roadDotCol Colors for the road dots for the editor, e.g. { fixed: "darkgray", editable:"#c2c2c2", selected: "yellow"}
@property {object} roadKnotCol Colors for the road knots (vertical) for the editor, e.g. { dflt: "#c2c2c2", selected: "yellow", rmbtn: "black", rmbtnsel: "red"}
@property {object} textBoxCol Colors for text boxes e.g. { bg: "#ffffff", stroke:"#d0d0d0"}
@property {object} roadTableCol Colors for the road table e.g. { bg:"#ffffff", bgHighlight: "#fffb55", text:"#000000", textDisabled: "#aaaaaa", bgDisabled:"#f2f2f2"}
@property {object} dataPointCol Colors for datapoints, e.g. { future: "#909090", stroke: "lightgray"}
@property {object} halfPlaneCol Colors for the yellow brick half plane. e.g. { fill: "#ffffe8" }
@property {object} pastBoxCol Colors for the past, e.g. { fill: "#f8f8f8", opacity:0.5 }
@property {object} odomResetCol Colors for odometer reset indicators, e.g. { dflt: "#c2c2c2" }
*/
/** bgraph object constructor. Creates an empty beeminder graph and/or road
* matrix table with the supplied options. Particular goal details may later be
* loaded with {@link bgraph~loadGoal} or {@link loadGoalFromURL} functions.
@memberof module:bgraph
@constructs bgraph
@param {BGraphOptions} options JSON input with various graph options
*/
const bgraph = function(options) { // BEGIN bgraph object constructor ------------
//console.debug("beebrain constructor ("+gid+"): ")
const self = this // what OOP magic is this? can we just use "this" on next line?
let opts = config(self, options)
const curid = gid
gid++
// Various dimensions and boxes
let yaxisw = 50
let sw = opts.svgSize.width
let sh = opts.svgSize.height
let plotbox, brushbox, plotpad, contextpad
let zoombtnsize = opts.zoomButton.size
let zoombtnscale = zoombtnsize / 540
let zoombtntr
// Graph components
let svg, defs, graphs, buttonarea, stathead, focus, focusclip, plot,
context, ctxclip, ctxplot,
xSc, nXSc, xAxis, xAxisT, xGrid, xAxisObj, xAxisObjT, xGridObj,
ySc, nYSc, yAxis, yAxisR, yAxisObj, yAxisObjR, yAxisLabel,
xScB, xAxisB, xAxisObjB, yScB,
gPB, gYBHP, gYBHPlines, gPink, gPinkPat, gTapePat, gGrid, gOResets,
gPastText,
gGuides, gMaxflux, gStdflux, gRazr, gOldBullseye,
gKnots, gSteppy, gSteppyPts, gRosy, gRosyPts, gMovingAv,
gAura, gDerails, gAllpts, gDpts, gHollow, gFlat,
gBullseye, gRoads, gDots, gWatermark, gHashtags, gHorizon, gHorizonText,
gRedTape,
zoomarea, axisZoom, zoomin, zoomout,
brushObj, brush, focusrect, topLeft, dataTopLeft,
scf = 1, oldscf = 0
// These are svg defs that will created dynamically only when needed
let beyegrp, beyepgrp, infgrp, sklgrp, smlgrp
// Internal state for the graph
let lastError = null
let undoBuffer = [] // Array of previous roads for undo
let redoBuffer = [] // Array of future roads for redo
let processing = false
let loading = false
let hidden = false
let mobileOrTablet = onMobileOrTablet()
let dataf, alldataf
let horindex = null // Road segment index including the horizon
let iroad = [] // Initial road
let igoal = {} // Initial goal object
// Beebrain state objects
let bbr, gol = {}, road = []
let data = [], rawdata = [], alldata = [], dtd = [], iso = []
function getiso(val) {
if (iso[val] === undefined) iso[val] = br.isoline(road, dtd, gol, val)
return iso[val]
}
function getisopath( val, xr ) {
const isoline = getiso(val)
if (xr == null) xr = [-Infinity, Infinity]
let x = isoline[0][0]
let y = isoline[0][1]
if (x < xr[0]) { x = xr[0]; y = br.isoval(isoline, x) }
let d = "M"+r1(nXSc(x*SMS))+" "+r1(nYSc(y))
let a = bu.searchHigh(isoline, p => p[0] < xr[0] ? -1 : 1)
let b = bu.searchHigh(isoline, p => p[0] < xr[1] ? -1 : 1)
if (b > isoline.length - 1) b = isoline.length - 1
for (let i = a; i <= b; i++) {
d += " L"+r1(nXSc(isoline[i][0]*SMS))+" "+r1(nYSc(isoline[i][1]))
}
return d
}
// Compute lane width (the delta between yellow guiding lines) based on
// isolines on the left or right border for the graph depending on dir*yaw. If
// dir*yaw > 0 (like do-more), the left side is considered, otherwise the right
// side. The average lane width is computed by computing isolines for dtd=0 and
// dtd=365 and dividing it by 365 to overcome isolines coinciding for flat
// regions.
function isolnwborder(xr) {
let lnw = 0
const numdays = min(opts.maxFutureDays, ceil((gol.tfin-gol.tini)/SID))
const center = getiso(0)
const oneday = getiso(numdays)
//TODO: switch to this version
//const edge = gol.yaw*gol.dir > 0 ? 0 : 1 // left edge for MOAR/PHAT
//return abs(br.isoval(center, xr[edge])-br.isoval(oneday, xr[edge])) / numdays
if (gol.yaw*gol.dir > 0) {
lnw = abs(br.isoval(center, xr[0])-br.isoval(oneday, xr[0])) / numdays
} else {
lnw = abs(br.isoval(center, xr[1])-br.isoval(oneday, xr[1])) / numdays
}
return lnw
}
/** Limits an svg coordinate to 1 or 3 digits after the decimal
@param {Number} x Input number
*/
function r1(x) { return round(x*10)/10 }
function r3(x) { return round(x*1000)/1000 }
/** Resets the internal goal object, clearing out previous data. */
function resetGoal() {
// Initialize goal with sane values
gol = {}
gol.yaw = +1; gol.dir = +1
gol.tcur = 0; gol.vcur = 0
const now = moment.utc()
now.hour(0); now.minute(0); now.second(0); now.millisecond(0)
gol.asof = now.unix()
gol.horizon = gol.asof + bu.AKH - SID
gol.xMin = gol.asof; gol.xMax = gol.horizon
gol.tmin = gol.asof; gol.tmax = gol.horizon
gol.yMin = -1; gol.yMax = 1
igoal = bu.deepcopy(gol); road = []; iroad = []; data = []; alldata = []
}
resetGoal()
/** Recompute padding value and bounding boxes for various components in the
* graph. In particular, plotpad, contextpad, plotbox, and contextbox. */
function computeBoxes() {
plotpad = bu.extendo({}, opts.focusPad)
contextpad = bu.extendo({}, opts.ctxPad)
if (gol.stathead && !opts.roadEditor) plotpad.top += 15
plotpad.left += yaxisw
plotpad.right += yaxisw+(gol.hidey?8:0) // Extra padding if yaxis text hidden
contextpad.left += yaxisw
contextpad.right += yaxisw+(gol.hidey?8:0)
plotbox = {
x: opts.focusRect.x + plotpad.left,
y: opts.focusRect.y + plotpad.top,
width: opts.focusRect.width - plotpad.left - plotpad.right,
height: opts.focusRect.height - plotpad.top - plotpad.bottom,
}
brushbox = {
x: opts.ctxRect.x + contextpad.left,
y: opts.ctxRect.y + contextpad.top,
width: opts.ctxRect.width - contextpad.left - contextpad.right,
height: opts.ctxRect.height - contextpad.top - contextpad.bottom,
}
zoombtntr = {
botin: "translate("+(plotbox.width-2*(zoombtnsize+5))
+","+(plotbox.height -(zoombtnsize+5))
+") scale("+zoombtnscale+","+zoombtnscale+")",
botout: "translate("+(plotbox.width -(zoombtnsize+5))
+","+(plotbox.height-(zoombtnsize+5))
+") scale("+zoombtnscale+","+zoombtnscale+")",
topin: "translate("+(plotbox.width-2*(zoombtnsize+5))
+",5) scale("+zoombtnscale+","+zoombtnscale+")",
topout: "translate("+(plotbox.width-(zoombtnsize+5))
+",5) scale("+zoombtnscale+","+zoombtnscale+")" }
}
computeBoxes()
/** Utility function to show a shaded overlay with a message consisting of
multiple lines supplied in the array argument.
@param {String[]} msgs Array of messages, one for each line
@param {Number} [fs=-1] Font size. height/15 if -1
@param {String} [fw="bold"} Font weight
@param {Object} [box=null] Bounding box {x,y,w,h} for the overlay; default null
@param {String} [cls="overlay} CSS class of the created overlay
@param {Boolean} [shd=true] Shade out graph if true
*/
function showOverlay(msgs, fs=-1, fw="bold",
box=null, cls="overlay", shd=true, animate=false,
parent=null) {
if (opts.divGraph == null) return
if (box == null) box ={x:sw/20, y:sh/5, w:sw-2*sw/20, h:sh-2*sh/5}
if (parent == null) parent = svg
let pg = parent.select("g."+cls)
if (pg.empty()) {
pg = parent.append('g').attr('class', cls)
if (shd) {
pg.append('svg:rect').attr('x', 0)
.attr('y', 0)
.attr('width', sw)
.attr('height', sh)
.style('fill', bu.BHUE.WITE)
.style('fill-opacity', 0.5)
}
pg.append('svg:rect').attr("class", "textbox")
.attr('x', box.x)
.attr('y', box.y)
.attr('width', box.w)
.attr('height', box.h)
}
pg.selectAll(".loading").remove()
const nummsgs = msgs.length
if (fs < 0) fs = sh/15
const lh = fs * 1.1
for (let i = 0; i < nummsgs; i++) {
pg.append('svg:text').attr('class', 'loading')
.attr('x', box.x+box.w/2)
.attr('y', (box.y+box.h/2) - ((nummsgs-1)*lh)/2+i*lh+fs/2-3)
.attr('font-size', fs)
.style('font-size', fs)
.style('font-weight', fw)
.text(msgs[i])
}
if (animate)
pg.style("opacity", 0).transition().duration(200).style("opacity", 1)
}
/** Removes the message overlay created by {@link
bgraph~showOverlay showOverlay()}
@param {String} [cls="overlay"] CSS class for the overlay to remove
*/
function removeOverlay(cls = "overlay", animate = false, parent = null) {
//console.debug("removeOverlay("+self.id+")")
if (opts.divGraph == null) return
if (parent == null) parent = svg
let pg = parent.selectAll("g."+cls)
if (animate) pg.style("opacity", 1).transition().duration(200)
.style("opacity", 0).remove()
else pg.remove()
}
/** Creates all SVG graph components if a graph DIV is provided. Called once
when the bgraph object is created. */
function createGraph() {
const div = opts.divGraph
if (div === null) return
// First, remove all children from the div
while (div.firstChild) div.removeChild(div.firstChild)
// Initialize the div and the SVG
svg = d3.select(div).attr("class", "bmndrgraph")
.append('svg:svg')
.attr("id", "svg"+curid)
.attr("xmlns", "http://www.w3.org/2000/svg")
.attr("xmlns:xlink", "http://www.w3.org/1999/xlink")
.attr("preserveAspectRatio", "xMinYMin meet")
.attr("viewBox", "0 0 "+sw+" "+sh)
.attr('width', "100%")
.attr('height', "100%")
.attr('class', 'bmndrsvg')
// Common SVG definitions, including clip paths
defs = svg.append('defs')
defs.insert('style').attr('type','text/css').text(SVGStyle)
// Dot types:
// col r
// Rosy dots : ROSE
// Steppy pts : PURP
// All pts :
// Editor data :
// Graph data :
// Graph hollow:
defs.insert('style').attr("id", "dynstyle"+curid).attr('type','text/css').text("")
defs.append("clipPath")
.attr("id", "plotclip"+curid)
.append("rect").attr("x", 0).attr("y", 0)
.attr("width", plotbox.width).attr("height", plotbox.height)
defs.append("clipPath")
.attr("id", "brushclip"+curid)
.append("rect").attr("x", 0).attr("y", 0)
.attr("width", brushbox.width).attr("height", brushbox.height)
defs.append("clipPath")
.attr("id", "buttonareaclip"+curid)
.append("rect").attr("x", plotbox.x).attr("y", 0)
.attr("width", plotbox.width).attr("height", plotpad.top)
defs.append("path")
.style("stroke", "none").attr("id", "rightarrow")
.attr("d", "M 55,0 -35,45 -35,-45 z")
defs.append("path")
.style("stroke", "none").attr("id", "downarrow")
.attr("d", "M 0,40 45,-50 -45,-50 z")
defs.append("path")
.style("stroke", "none").attr("id", "uparrow")
.attr("d", "M 0,-40 45,50 -45,50 z")
gPinkPat = defs.append("pattern").attr("id", "pinkzonepat"+curid)
.attr("x", 0)
.attr("y", 0)
.attr("width", 10)
.attr("height", 10)
.attr("patternTransform", "rotate(45)")
.attr("patternUnits", "userSpaceOnUse")
gPinkPat.append("rect").attr("x", 0)
.attr("y", 0)
.attr("width", 10)
.attr("height", 10)
.attr("fill", bu.BHUE.PINK)
gPinkPat.append("line").attr("x1", 0)
.attr("y1", 0)
.attr("x2", 0)
.attr("y2", 10)
.style("stroke", "#aaaaaa")
.style("stroke-width", 1)
gTapePat = defs.append("pattern").attr("id", "tapepat"+curid)
.attr("x", 0)
.attr("y", 0)
.attr("width", 20)
.attr("height", 20)
.attr("patternTransform", "rotate(45)")
.attr("patternUnits", "userSpaceOnUse")
gTapePat.append("rect").attr("x", 0)
.attr("y", 0)
.attr("width", 20)
.attr("height", 20)
.attr("fill", "#ffffff")
gTapePat.append("line").attr("x1", 0)
.attr("y1", 0)
.attr("x2", 20)
.attr("y2", 0)
.style("stroke", "#ff5555")
.style("stroke-width", 25)
const buttongrp = defs.append("g").attr("id", "removebutton")
buttongrp.append("circle").attr("cx", 14)
.attr("cy", 14)
.attr("r", 16)
.attr('fill', 'white')
buttongrp.append("path")
.attr("d", "M13.98,0C6.259,0,0,6.261,0,13.983c0,7.721,6.259,13.982,13.98,13.982c7.725,0,13.985-6.262,13.985-13.982C27.965,6.261,21.705,0,13.98,0z M19.992,17.769l-2.227,2.224c0,0-3.523-3.78-3.786-3.78c-0.259,0-3.783,3.78-3.783,3.78l-2.228-2.224c0,0,3.784-3.472,3.784-3.781c0-0.314-3.784-3.787-3.784-3.787l2.228-2.229c0,0,3.553,3.782,3.783,3.782c0.232,0,3.786-3.782,3.786-3.782l2.227,2.229c0,0-3.785,3.523-3.785,3.787C16.207,14.239,19.992,17.769,19.992,17.769z")
const zoomingrp = defs.append("g").attr("id", "zoominbtn")
if (!opts.headless && opts.buttonZoom) {
// Zoom buttons are not visible for SVG output in headless mode
zoomingrp.append("path").style("fill", "white")
.attr("d", "m 530.86356,264.94116 a 264.05649,261.30591 0 1 1 -528.1129802,0 264.05649,261.30591 0 1 1 528.1129802,0 z")
zoomingrp.append("path")
.attr("d", "m 308.21,155.10302 -76.553,0 0,76.552 -76.552,0 0,76.553 76.552,0 0,76.552 76.553,0 0,-76.552 76.552,0 0,-76.553 -76.552,0 z m 229.659,114.829 C 537.869,119.51007 420.50428,1.9980234 269.935,1.9980234 121.959,1.9980234 2.0000001,121.95602 2.0000001,269.93202 c 0,147.976 117.2473599,267.934 267.9339999,267.934 150.68664,0 267.935,-117.51205 267.935,-267.934 z m -267.935,191.381 c -105.681,0 -191.381,-85.7 -191.381,-191.381 0,-105.681 85.701,-191.380996 191.381,-191.380996 105.681,0 191.381,85.700996 191.381,191.380996 0,105.681 -85.7,191.381 -191.381,191.381 z")
}
const zoomoutgrp = defs.append("g").attr("id", "zoomoutbtn")
if (!opts.headless && opts.buttonZoom) {
// Zoom buttons are not visible for SVG output in headless mode
zoomoutgrp.append("path").style("fill", "white")
.attr("d", "m 530.86356,264.94116 a 264.05649,261.30591 0 1 1 -528.1129802,0 264.05649,261.30591 0 1 1 528.1129802,0 z")
zoomoutgrp.append("path")
.attr("d", "m 155.105,231.65502 0,76.553 229.657,0 0,-76.553 c -76.55233,0 -153.10467,0 -229.657,0 z m 382.764,38.277 C 537.869,119.51007 420.50428,1.9980234 269.935,1.9980234 121.959,1.9980234 2.0000001,121.95602 2.0000001,269.93202 c 0,147.976 117.2473599,267.934 267.9339999,267.934 150.68664,0 267.935,-117.51205 267.935,-267.934 z m -267.935,191.381 c -105.681,0 -191.381,-85.7 -191.381,-191.381 0,-105.681 85.701,-191.380996 191.381,-191.380996 105.681,0 191.381,85.700996 191.381,191.380996 0,105.681 -85.7,191.381 -191.381,191.381 z")
}
// Create rectange to monitor zoom events and install handlers
zoomarea = svg.append('rect').attr("class", "zoomarea")
.attr("x", plotbox.x)
.attr("y", plotbox.y)
.attr("color", bu.BHUE.REDDOT)
.attr("width", plotbox.width)
.attr("height", plotbox.height)
const oldscroll = zoomarea.on("wheel.scroll")
const scrollinfo = {shown: false, timeout: null}
const onscroll = function() {
if (scrollinfo.timeout != null) {
clearTimeout(scrollinfo.timeout)
scrollinfo.timeout = null
}
if (d3.event.ctrlKey) {
removeOverlay("zoominfo",true, plot)
scrollinfo.shown = false
return
}
if (!scrollinfo.shown) {
showOverlay(["Use ctrl+scroll to zoom"], -1,"normal",
{x:0,y:0,w:plotbox.width,h:plotbox.height},
"zoominfo", false, true, plot)
scrollinfo.shown = true
}
scrollinfo.timeout= setTimeout(() => {removeOverlay("zoominfo", true);
scrollinfo.shown = false},1000)
}
const onmove = function() {
if (scrollinfo.timeout != null) {
clearTimeout(scrollinfo.timeout)
scrollinfo.timeout = null
}
removeOverlay("zoominfo",true)
scrollinfo.shown = false
}
zoomarea.on("wheel.scroll", onscroll, {passive:false})
zoomarea.on("mousedown.move", onmove)
//zoomarea.on("touchstart", ()=>{console.log("touchstart")} )
//zoomarea.on("touchmove", ()=>{console.log("touchmove")} )
//zoomarea.on("touchend", ()=>{console.log("touchend")} )
axisZoom = d3.zoom()
.extent([[0, 0], [plotbox.width, plotbox.height]])
.scaleExtent([1, Infinity])
.translateExtent([[0, 0], [plotbox.width, plotbox.height]])
.filter(function(){ return (d3.event.type != "wheel" || d3.event.ctrlKey) })
.on("zoom", zoomed)
zoomarea.call(axisZoom)
if (onMobileOrTablet()) {
let pressTimer = null, pressX
const oldTouchStart = zoomarea.on("touchstart.zoom")
const oldTouchMove = zoomarea.on("touchmove.zoom")
const oldTouchEnd = zoomarea.on("touchend.zoom")
zoomarea
.on("touchstart.zoom", function(){
const bbox = this.getBoundingClientRect()
pressX = d3.event.touches.item(0).pageX - bbox.left
const newx = nXSc.invert(pressX)
if (pressTimer == null && d3.event.touches.length == 1)
pressTimer = window.setTimeout(
() => { if (newx != null) addNewDot(newx/SMS) }, 1000)
oldTouchStart.apply(this, arguments)} )
.on("touchmove.zoom", function(){ window.clearTimeout(pressTimer); pressTimer = null; oldTouchMove.apply(this, arguments)})
.on("touchend.zoom", function(){ clearTimeout(pressTimer); pressTimer = null; oldTouchEnd.apply(this, arguments)} )
}
function dotAdded() {
const mouse = d3.mouse(svg.node())
const newx = nXSc.invert(mouse[0]-plotpad.left)
addNewDot(newx/SMS)
}
function dotAddedShift() {
if (d3.event.shiftKey) dotAdded()
else clearSelection()
}
if (opts.roadEditor) {
zoomarea.on("click", dotAddedShift)
zoomarea.on("dblclick.zoom", dotAdded)
} else {
zoomarea.on("dblclick.zoom", null)
}
focus = svg.append('g')
.attr('class', 'focus')
.attr('transform', 'translate('+opts.focusRect.x
+','+opts.focusRect.y+')');
buttonarea = focus.append('g')
.attr('clip-path', 'url(#buttonareaclip'+curid+')')
.attr('class', 'buttonarea');
focusclip = focus.append('g')
.attr('class', 'focusclip')
.attr('clip-path', 'url(#plotclip'+curid+')')
.attr('transform', 'translate('+plotpad.left
+','+plotpad.top+')');
plot = focusclip.append('g').attr('class', 'plot');
stathead = focus.append('svg:text').attr("x", sw/2).attr("y", 15)
.attr("width", plotbox.width)
.attr('class', 'svgtxt')
.style("font-size", "80%")
.attr('text-anchor', 'middle')
// Order here determines z-order...
// (The commented z-values are to remember previous order for experimenting)
gPB = plot.append('g').attr('id', 'pastboxgrp') // z = 01
gYBHP = plot.append('g').attr('id', 'ybhpgrp') // z = 02
gWatermark = plot.append('g').attr('id', 'wmarkgrp') // z = 03
gGuides = plot.append('g').attr('id', 'guidegrp') // z = 04
gMaxflux = plot.append('g').attr('id', 'maxfluxgrp') // z = 05
gStdflux = plot.append('g').attr('id', 'stdfluxgrp') // z = 06
gYBHPlines = plot.append('g').attr('id', 'ybhplinesgrp') // z = 07
gRazr = plot.append('g').attr('id', 'razrgrp') // z = 08
gAura = plot.append('g').attr('id', 'auragrp') // z = 09
gPink = plot.append('g').attr('id', 'pinkgrp') // z = 10
gOldBullseye = plot.append('g').attr('id', 'oldbullseyegrp') // z = 11
gBullseye = plot.append('g').attr('id', 'bullseyegrp') // z = 12
gGrid = plot.append('g').attr('id', 'grid') // z = 13
gOResets = plot.append('g').attr('id', 'oresetgrp') // z = 14
gKnots = plot.append('g').attr('id', 'knotgrp') // z = 15
gSteppy = plot.append('g').attr('id', 'steppygrp') // z = 16
gRosy = plot.append('g').attr('id', 'rosygrp') // z = 17
gRosyPts = plot.append('g').attr('id', 'rosyptsgrp') // z = 18
gDerails = plot.append('g').attr('id', 'derailsgrp') // z = 19
gAllpts = plot.append('g').attr('id', 'allptsgrp') // z = 20
gMovingAv = plot.append('g').attr('id', 'movingavgrp') // z = 21
gSteppyPts = plot.append('g').attr('id', 'steppyptsgrp') // z = 22
gDpts = plot.append('g').attr('id', 'datapointgrp') // z = 23
gHollow = plot.append('g').attr('id', 'hollowgrp') // z = 24
gFlat = plot.append('g').attr('id', 'flatlinegrp') // z = 25
gHashtags = plot.append('g').attr('id', 'hashtaggrp') // z = 26
gRoads = plot.append('g').attr('id', 'roadgrp') // z = 27
gDots = plot.append('g').attr('id', 'dotgrp') // z = 28
gHorizon = plot.append('g').attr('id', 'horgrp') // z = 29
gHorizonText = plot.append('g').attr('id', 'hortxtgrp') // z = 30
gPastText = plot.append('g').attr('id', 'pasttxtgrp') // z = 31
gRedTape = plot.append('g').attr('visibility', 'hidden')
// wwidth and height will be set by resizeGraph later
gRedTape.append('rect').attr('x', 0).attr('y', 0)
.attr('stroke-width', 20).attr('stroke', "url(#tapepat"+curid+")")
.attr('fill', 'none')
// x coordinate will be set by resizeGraph later
gRedTape.append('text').attr('y', 45)
.attr('paint-order', 'stroke')
.attr('stroke-width', '2px').attr('stroke', '#a00000')
.attr('font-size', "35px").attr('text-anchor', 'middle')
.attr('fill', '#ff0000')
.text("Error") // originally "road can't get easier"
zoomin = focusclip.append("svg:use")
.attr("class","zoomin")
.attr("xlink:href", "#zoominbtn")
.attr("opacity",opts.zoomButton.opacity)
.attr("transform", zoombtntr.botin)
.on("click", () => { zoomarea.call(axisZoom.scaleBy,
opts.zoomButton.factor) })
.on("mouseover", () =>{
if (!mobileOrTablet) d3.select(this).style("fill", "red")})
.on("mouseout",(d,i) => {d3.select(this).style("fill", "black")})
zoomout = focusclip.append("svg:use")
.attr("class", "zoomout")
.attr("xlink:href", "#zoomoutbtn")
.attr("opacity", opts.zoomButton.opacity)
.attr("transform", zoombtntr.botout)
.on("click", () => { zoomarea.call(axisZoom.scaleBy,
1/opts.zoomButton.factor) })
.on("mouseover", () => {
if (!mobileOrTablet) d3.select(this).style("fill", "red") })
.on("mouseout",(d,i) => { d3.select(this).style("fill", "black") })
// Create and initialize the x and y axes
xSc = d3.scaleUtc().range([0,plotbox.width])
xAxis = d3.axisBottom(xSc).ticks(6)
xAxisObj = focus.append('g')
.attr("class", "axis")
.attr("transform", "translate("+plotbox.x+","
+ (plotpad.top+plotbox.height) + ")")
.call(xAxis)
xGrid = d3.axisTop(xSc).ticks(6).tickFormat("")
xGridObj = gGrid.append('g')
.attr("class", "grid")
.attr("transform", "translate(0,"+(plotbox.height)+")")
.call(xGrid)
xAxisT = d3.axisTop(xSc).ticks(6)
xAxisObjT = focus.append('g')
.attr("class", "axis")
.attr("transform", "translate("+plotbox.x+"," + (plotpad.top) + ")")
.call(xAxisT)
if (opts.roadEditor) {
xGridObj.attr('display', 'none')
xAxisObjT.attr('display', 'none')
}
ySc = d3.scaleLinear().range([plotbox.height, 0])
yAxis = d3.axisLeft(ySc).ticks(8).tickSize(6).tickSizeOuter(0)
yAxisR = d3.axisRight(ySc).ticks(8).tickSize(6).tickSizeOuter(0)
yAxisObj = focus.append('g')
.attr("class", "axis")
.attr("transform", "translate(" + plotpad.left + ","+plotpad.top+")")
.call(yAxis)
yAxisObjR = focus.append('g').attr("class", "axis")
.attr("transform", "translate("
+ (plotpad.left+plotbox.width) + ","+plotpad.top+")")
.call(yAxisR)
yAxisLabel = focus.append('text')
.attr("class", "axislabel")
.attr("transform",
"translate(15,"+(plotbox.height/2+plotpad.top)+") rotate(-90)")
.text("") // used to say "deneme" but was user-visible in error graphs
// Create brush area
context = svg.append('g')
.attr('class', 'brush')
.attr('transform', 'translate('+opts.ctxRect.x+','+opts.ctxRect.y+')')
ctxclip = context.append('g')
.attr('clip-path', 'url(#brushclip'+curid+')')
.attr('transform', 'translate('+contextpad.left+','+contextpad.top+')')
ctxplot = ctxclip.append('g').attr('class', 'context')
xScB = d3.scaleUtc().range([0,brushbox.width])
xAxisB = d3.axisBottom(xScB).ticks(6)
xAxisObjB = context.append('g')
.attr("class", "axis")
.attr("transform", "translate("+brushbox.x+","
+ (contextpad.top+brushbox.height) + ")")
.call(xAxisB)
yScB = d3.scaleLinear().range([brushbox.height, 0])
brushObj = d3.brushX()
.extent([[0, 0], [brushbox.width, brushbox.height]])
.on("brush", brushed);
brush = ctxplot.append("g").attr("class", "brush").call(brushObj)
focusrect = ctxclip.append("rect")
.attr("class", "focusrect")
.attr("x", 1)
.attr("y", 1)
.attr("width", brushbox.width-2)
.attr("height", brushbox.height-2)
.attr("fill", "none")
.style("stroke", "black")
.style("stroke-width", 1)
.style("stroke-dasharray", "8,4,2,4")
nXSc = xSc; nYSc = ySc