1 // You can set the following variables before loading this script:
3 // var netdataNoDygraphs = true; // do not use dygraph
4 // var netdataNoSparklines = true; // do not use sparkline
5 // var netdataNoPeitys = true; // do not use peity
6 // var netdataNoGoogleCharts = true; // do not use google
7 // var netdataNoMorris = true; // do not use morris
8 // var netdataNoEasyPieChart = true; // do not use easy pie chart
9 // var netdataNoGauge = true; // do not use gauge.js
10 // var netdataNoD3 = true; // do not use D3
11 // var netdataNoC3 = true; // do not use C3
12 // var netdataNoBootstrap = true; // do not load bootstrap
13 // var netdataDontStart = true; // do not start the thread to process the charts
15 // You can also set the default netdata server, using the following.
16 // When this variable is not set, we assume the page is hosted on your
17 // netdata server already.
18 // var netdataServer = "http://yourhost:19999"; // set your NetData server
20 //(function(window, document, undefined) {
21 // fix IE issue with console
22 if(!window.console){ window.console = {log: function(){} }; }
25 var NETDATA = window.NETDATA || {};
27 // ----------------------------------------------------------------------------------------------------------------
28 // Detect the netdata server
30 // http://stackoverflow.com/questions/984510/what-is-my-script-src-url
31 // http://stackoverflow.com/questions/6941533/get-protocol-domain-and-port-from-url
32 NETDATA._scriptSource = function() {
35 if(typeof document.currentScript !== 'undefined') {
36 script = document.currentScript;
39 var all_scripts = document.getElementsByTagName('script');
40 script = all_scripts[all_scripts.length - 1];
43 if (typeof script.getAttribute.length !== 'undefined')
46 script = script.getAttribute('src', -1);
51 if(typeof netdataServer !== 'undefined')
52 NETDATA.serverDefault = netdataServer;
54 var s = NETDATA._scriptSource();
55 NETDATA.serverDefault = s.replace(/\/dashboard.js(\?.*)*$/g, "");
58 if(NETDATA.serverDefault === null)
59 NETDATA.serverDefault = '';
60 else if(NETDATA.serverDefault.slice(-1) !== '/')
61 NETDATA.serverDefault += '/';
63 // default URLs for all the external files we need
64 // make them RELATIVE so that the whole thing can also be
65 // installed under a web server
66 NETDATA.jQuery = NETDATA.serverDefault + 'lib/jquery-1.12.0.min.js';
67 NETDATA.peity_js = NETDATA.serverDefault + 'lib/jquery.peity.min.js';
68 NETDATA.sparkline_js = NETDATA.serverDefault + 'lib/jquery.sparkline.min.js';
69 NETDATA.easypiechart_js = NETDATA.serverDefault + 'lib/jquery.easypiechart.min.js';
70 NETDATA.gauge_js = NETDATA.serverDefault + 'lib/gauge.min.js';
71 NETDATA.dygraph_js = NETDATA.serverDefault + 'lib/dygraph-combined.js';
72 NETDATA.dygraph_smooth_js = NETDATA.serverDefault + 'lib/dygraph-smooth-plotter.js';
73 NETDATA.raphael_js = NETDATA.serverDefault + 'lib/raphael-min.js';
74 NETDATA.morris_js = NETDATA.serverDefault + 'lib/morris.min.js';
75 NETDATA.d3_js = NETDATA.serverDefault + 'lib/d3.min.js';
76 NETDATA.c3_js = NETDATA.serverDefault + 'lib/c3.min.js';
77 NETDATA.c3_css = NETDATA.serverDefault + 'css/c3.min.css';
78 NETDATA.morris_css = NETDATA.serverDefault + 'css/morris.css';
79 NETDATA.dashboard_css = NETDATA.serverDefault + 'dashboard.css';
80 NETDATA.google_js = 'https://www.google.com/jsapi';
82 // these are the colors Google Charts are using
83 // we have them here to attempt emulate their look and feel on the other chart libraries
84 // http://there4.io/2012/05/02/google-chart-color-list/
85 //NETDATA.colors = [ '#3366CC', '#DC3912', '#FF9900', '#109618', '#990099', '#3B3EAC', '#0099C6',
86 // '#DD4477', '#66AA00', '#B82E2E', '#316395', '#994499', '#22AA99', '#AAAA11',
87 // '#6633CC', '#E67300', '#8B0707', '#329262', '#5574A6', '#3B3EAC' ];
89 NETDATA.colors = [ '#3366CC', '#DC3912', '#109618', '#FF9900', '#990099', '#DD4477', '#3B3EAC',
90 '#66AA00', '#0099C6', '#B82E2E', '#AAAA11', '#5574A6', '#994499', '#22AA99',
91 '#6633CC', '#E67300', '#316395', '#8B0707', '#329262', '#3B3EAC' ];
93 // http://www.mulinblog.com/a-color-palette-optimized-for-data-visualization/
94 // (blue) (red) (orange) (green) (pink) (brown) (purple) (yellow) (gray)
95 //NETDATA.colors = [ '#5DA5DA', '#F15854', '#FAA43A', '#60BD68', '#F17CB0', '#B2912F', '#B276B2', '#DECF3F', '#4D4D4D' ];
97 // ----------------------------------------------------------------------------------------------------------------
98 // the defaults for all charts
100 // if the user does not specify any of these, the following will be used
102 NETDATA.chartDefaults = {
103 host: NETDATA.serverDefault, // the server to get data from
104 width: '100%', // the chart width - can be null
105 height: '100%', // the chart height - can be null
106 min_width: null, // the chart minimum width - can be null
107 library: 'dygraph', // the graphing library to use
108 method: 'average', // the grouping method
109 before: 0, // panning
110 after: -600, // panning
111 pixels_per_point: 1, // the detail of the chart
112 fill_luminance: 0.8 // luminance of colors in solit areas
115 // ----------------------------------------------------------------------------------------------------------------
119 pauseCallback: null, // a callback when we are really paused
121 pause: false, // when enabled we don't auto-refresh the charts
123 targets: null, // an array of all the state objects that are
124 // currently active (independently of their
125 // viewport visibility)
127 updated_dom: true, // when true, the DOM has been updated with
128 // new elements we have to check.
130 auto_refresher_fast_weight: 0, // this is the current time in ms, spent
131 // rendering charts continiously.
132 // used with .current.fast_render_timeframe
134 page_is_visible: true, // when true, this page is visible
136 auto_refresher_stop_until: 0, // timestamp in ms - used internaly, to stop the
137 // auto-refresher for some time (when a chart is
138 // performing pan or zoom, we need to stop refreshing
139 // all other charts, to have the maximum speed for
140 // rendering the chart that is panned or zoomed).
141 // Used with .current.global_pan_sync_time
143 last_resized: new Date().getTime(), // the timestamp of the last resize request
145 crossDomainAjax: false, // enable this to request crossDomain AJAX
147 last_page_scroll: 0, // the timestamp the last time the page was scrolled
149 // the current profile
150 // we may have many...
152 pixels_per_point: 1, // the minimum pixels per point for all charts
153 // increase this to speed javascript up
154 // each chart library has its own limit too
155 // the max of this and the chart library is used
156 // the final is calculated every time, so a change
157 // here will have immediate effect on the next chart
160 idle_between_charts: 100, // ms - how much time to wait between chart updates
162 fast_render_timeframe: 200, // ms - render continously until this time of continious
163 // rendering has been reached
164 // this setting is used to make it render e.g. 10
165 // charts at once, sleep idle_between_charts time
166 // and continue for another 10 charts.
168 idle_between_loops: 500, // ms - if all charts have been updated, wait this
169 // time before starting again.
171 idle_parallel_loops: 100, // ms - the time between parallel refresher updates
173 idle_lost_focus: 500, // ms - when the window does not have focus, check
174 // if focus has been regained, every this time
176 global_pan_sync_time: 1000, // ms - when you pan or zoon a chart, the background
177 // autorefreshing of charts is paused for this amount
180 sync_selection_delay: 1500, // ms - when you pan or zoom a chart, wait this amount
181 // of time before setting up synchronized selections
184 sync_selection: true, // enable or disable selection sync
186 pan_and_zoom_delay: 50, // when panning or zooming, how ofter to update the chart
188 sync_pan_and_zoom: true, // enable or disable pan and zoom sync
190 pan_and_zoom_data_padding: true, // fetch more data for the master chart when panning or zooming
192 update_only_visible: true, // enable or disable visibility management
194 parallel_refresher: true, // enable parallel refresh of charts
196 concurrent_refreshes: true, // when parallel_refresher is enabled, sync also the charts
198 destroy_on_hide: false, // destroy charts when they are not visible
200 eliminate_zero_dimensions: true, // do not show dimensions with just zeros
202 stop_updates_when_focus_is_lost: true, // boolean - shall we stop auto-refreshes when document does not have user focus
203 stop_updates_while_resizing: 1000, // ms - time to stop auto-refreshes while resizing the charts
205 double_click_speed: 500, // ms - time between clicks / taps to detect double click/tap
207 smooth_plot: true, // enable smooth plot, where possible
209 charts_selection_animation_delay: 50, // delay to animate charts when syncing selection
211 color_fill_opacity_line: 1.0,
212 color_fill_opacity_area: 0.2,
213 color_fill_opacity_stacked: 0.8,
215 setOptionCallback: function() { ; }
223 chart_data_url: false,
224 chart_errors: false, // FIXME
233 // ----------------------------------------------------------------------------------------------------------------
234 // local storage options
236 NETDATA.localStorage = {
239 callback: {} // only used for resetting back to defaults
242 NETDATA.localStorageGet = function(key, def, callback) {
245 if(typeof NETDATA.localStorage.default[key.toString()] === 'undefined') {
246 NETDATA.localStorage.default[key.toString()] = def;
247 NETDATA.localStorage.callback[key.toString()] = callback;
250 if(typeof Storage !== "undefined" && typeof localStorage === 'object') {
252 // console.log('localStorage: loading "' + key.toString() + '"');
253 ret = localStorage.getItem(key.toString());
254 if(ret === null || ret === 'undefined') {
255 // console.log('localStorage: cannot load it, saving "' + key.toString() + '" with value "' + JSON.stringify(def) + '"');
256 localStorage.setItem(key.toString(), JSON.stringify(def));
260 // console.log('localStorage: got "' + key.toString() + '" with value "' + ret + '"');
261 ret = JSON.parse(ret);
262 // console.log('localStorage: loaded "' + key.toString() + '" as value ' + ret + ' of type ' + typeof(ret));
266 console.log('localStorage: failed to read "' + key.toString() + '", using default: "' + def.toString() + '"');
271 if(typeof ret === 'undefined' || ret === 'undefined') {
272 console.log('localStorage: LOADED UNDEFINED "' + key.toString() + '" as value ' + ret + ' of type ' + typeof(ret));
276 NETDATA.localStorage.current[key.toString()] = ret;
280 NETDATA.localStorageSet = function(key, value, callback) {
281 if(typeof value === 'undefined' || value === 'undefined') {
282 console.log('localStorage: ATTEMPT TO SET UNDEFINED "' + key.toString() + '" as value ' + value + ' of type ' + typeof(value));
285 if(typeof NETDATA.localStorage.default[key.toString()] === 'undefined') {
286 NETDATA.localStorage.default[key.toString()] = value;
287 NETDATA.localStorage.current[key.toString()] = value;
288 NETDATA.localStorage.callback[key.toString()] = callback;
291 if(typeof Storage !== "undefined" && typeof localStorage === 'object') {
292 // console.log('localStorage: saving "' + key.toString() + '" with value "' + JSON.stringify(value) + '"');
294 localStorage.setItem(key.toString(), JSON.stringify(value));
297 console.log('localStorage: failed to save "' + key.toString() + '" with value: "' + value.toString() + '"');
301 NETDATA.localStorage.current[key.toString()] = value;
305 NETDATA.localStorageGetRecursive = function(obj, prefix, callback) {
307 if(typeof obj[i] === 'object') {
308 //console.log('object ' + prefix + '.' + i.toString());
309 NETDATA.localStorageGetRecursive(obj[i], prefix + '.' + i.toString(), callback);
313 obj[i] = NETDATA.localStorageGet(prefix + '.' + i.toString(), obj[i], callback);
317 NETDATA.setOption = function(key, value) {
318 if(key.toString() === 'setOptionCallback') {
319 if(typeof NETDATA.options.current.setOptionCallback === 'function') {
320 NETDATA.options.current[key.toString()] = value;
321 NETDATA.options.current.setOptionCallback();
324 else if(NETDATA.options.current[key.toString()] !== value) {
325 var name = 'options.' + key.toString();
327 if(typeof NETDATA.localStorage.default[name.toString()] === 'undefined')
328 console.log('localStorage: setOption() on unsaved option: "' + name.toString() + '", value: ' + value);
330 //console.log(NETDATA.localStorage);
331 //console.log('setOption: setting "' + key.toString() + '" to "' + value + '" of type ' + typeof(value) + ' original type ' + typeof(NETDATA.options.current[key.toString()]));
332 //console.log(NETDATA.options);
333 NETDATA.options.current[key.toString()] = NETDATA.localStorageSet(name.toString(), value, null);
335 if(typeof NETDATA.options.current.setOptionCallback === 'function')
336 NETDATA.options.current.setOptionCallback();
342 NETDATA.getOption = function(key) {
343 return NETDATA.options.current[key.toString()];
346 // read settings from local storage
347 NETDATA.localStorageGetRecursive(NETDATA.options.current, 'options', null);
349 // always start with this option enabled.
350 NETDATA.setOption('stop_updates_when_focus_is_lost', true);
352 NETDATA.resetOptions = function() {
353 for(var i in NETDATA.localStorage.default) {
354 var a = i.split('.');
356 if(a[0] === 'options') {
357 if(a[1] === 'setOptionCallback') continue;
358 if(typeof NETDATA.localStorage.default[i] === 'undefined') continue;
359 if(NETDATA.options.current[i] === NETDATA.localStorage.default[i]) continue;
361 NETDATA.setOption(a[1], NETDATA.localStorage.default[i]);
363 else if(a[0] === 'chart_heights') {
364 if(typeof NETDATA.localStorage.callback[i] === 'function' && typeof NETDATA.localStorage.default[i] !== 'undefined') {
365 NETDATA.localStorage.callback[i](NETDATA.localStorage.default[i]);
371 // ----------------------------------------------------------------------------------------------------------------
373 if(NETDATA.options.debug.main_loop === true)
374 console.log('welcome to NETDATA');
376 NETDATA.onresize = function() {
377 NETDATA.options.last_resized = new Date().getTime();
381 NETDATA.onscroll = function() {
382 // console.log('onscroll');
384 NETDATA.options.last_page_scroll = new Date().getTime();
385 if(NETDATA.options.targets === null) return;
387 // when the user scrolls he sees that we have
388 // hidden all the not-visible charts
389 // using this little function we try to switch
390 // the charts back to visible quickly
391 var targets = NETDATA.options.targets;
392 var len = targets.length;
393 while(len--) targets[len].isVisible();
396 window.onresize = NETDATA.onresize;
397 window.onscroll = NETDATA.onscroll;
399 // ----------------------------------------------------------------------------------------------------------------
402 NETDATA.errorCodes = {
403 100: { message: "Cannot load chart library", alert: true },
404 101: { message: "Cannot load jQuery", alert: true },
405 402: { message: "Chart library not found", alert: false },
406 403: { message: "Chart library not enabled/is failed", alert: false },
407 404: { message: "Chart not found", alert: false }
409 NETDATA.errorLast = {
415 NETDATA.error = function(code, msg) {
416 NETDATA.errorLast.code = code;
417 NETDATA.errorLast.message = msg;
418 NETDATA.errorLast.datetime = new Date().getTime();
420 console.log("ERROR " + code + ": " + NETDATA.errorCodes[code].message + ": " + msg);
422 if(NETDATA.errorCodes[code].alert)
423 alert("ERROR " + code + ": " + NETDATA.errorCodes[code].message + ": " + msg);
426 NETDATA.errorReset = function() {
427 NETDATA.errorLast.code = 0;
428 NETDATA.errorLast.message = "You are doing fine!";
429 NETDATA.errorLast.datetime = 0;
432 // ----------------------------------------------------------------------------------------------------------------
435 // When multiple charts need the same chart, we avoid downloading it
436 // multiple times (and having it in browser memory multiple time)
437 // by using this registry.
439 // Every time we download a chart definition, we save it here with .add()
440 // Then we try to get it back with .get(). If that fails, we download it.
442 NETDATA.chartRegistry = {
445 fixid: function(id) {
446 return id.replace(/:/g, "_").replace(/\//g, "_");
449 add: function(host, id, data) {
450 host = this.fixid(host);
453 if(typeof this.charts[host] === 'undefined')
454 this.charts[host] = {};
456 //console.log('added ' + host + '/' + id);
457 this.charts[host][id] = data;
460 get: function(host, id) {
461 host = this.fixid(host);
464 if(typeof this.charts[host] === 'undefined')
467 if(typeof this.charts[host][id] === 'undefined')
470 //console.log('cached ' + host + '/' + id);
471 return this.charts[host][id];
474 downloadAll: function(host, callback) {
475 while(host.slice(-1) === '/')
476 host = host.substring(0, host.length - 1);
481 url: host + '/api/v1/charts',
482 crossDomain: NETDATA.options.crossDomainAjax,
486 .done(function(data) {
487 var h = NETDATA.chartRegistry.fixid(host);
488 //console.log('downloaded all charts from ' + host + ' (' + h + ')');
489 self.charts[h] = data.charts;
490 if(typeof callback === 'function')
494 if(typeof callback === 'function')
500 // ----------------------------------------------------------------------------------------------------------------
501 // Global Pan and Zoom on charts
503 // Using this structure are synchronize all the charts, so that
504 // when you pan or zoom one, all others are automatically refreshed
505 // to the same timespan.
507 NETDATA.globalPanAndZoom = {
508 seq: 0, // timestamp ms
509 // every time a chart is panned or zoomed
510 // we set the timestamp here
511 // then we use it as a sequence number
512 // to find if other charts are syncronized
515 master: null, // the master chart (state), to which all others
518 force_before_ms: null, // the timespan to sync all other charts
519 force_after_ms: null,
522 setMaster: function(state, after, before) {
523 if(NETDATA.options.current.sync_pan_and_zoom === false)
526 if(this.master !== null && this.master !== state)
527 this.master.resetChart(true, true);
529 var now = new Date().getTime();
532 this.force_after_ms = after;
533 this.force_before_ms = before;
534 NETDATA.options.auto_refresher_stop_until = now + NETDATA.options.current.global_pan_sync_time;
538 clearMaster: function() {
539 if(this.master !== null) {
540 var st = this.master;
547 this.force_after_ms = null;
548 this.force_before_ms = null;
549 NETDATA.options.auto_refresher_stop_until = 0;
552 // is the given state the master of the global
553 // pan and zoom sync?
554 isMaster: function(state) {
555 if(this.master === state) return true;
559 // are we currently have a global pan and zoom sync?
560 isActive: function() {
561 if(this.master !== null && this.force_before_ms !== null && this.force_after_ms !== null && this.seq !== 0) return true;
565 // check if a chart, other than the master
566 // needs to be refreshed, due to the global pan and zoom
567 shouldBeAutoRefreshed: function(state) {
568 if(this.master === null || this.seq === 0)
571 //if(state.needsRecreation())
574 if(state.tm.pan_and_zoom_seq === this.seq)
581 // ----------------------------------------------------------------------------------------------------------------
582 // dimensions selection
585 // move color assignment to dimensions, here
587 dimensionStatus = function(parent, label, name_div, value_div, color) {
588 this.enabled = false;
589 this.parent = parent;
591 this.name_div = null;
592 this.value_div = null;
595 if(parent.selected === parent.unselected)
596 this.selected = true;
598 this.selected = false;
600 this.setOptions(name_div, value_div, color);
603 dimensionStatus.prototype.invalidate = function() {
604 this.name_div = null;
605 this.value_div = null;
606 this.enabled = false;
609 dimensionStatus.prototype.setOptions = function(name_div, value_div, color) {
612 if(this.name_div != name_div) {
613 this.name_div = name_div;
614 this.name_div.title = this.label;
615 this.name_div.style.color = this.color;
616 if(this.selected === false)
617 this.name_div.className = 'netdata-legend-name not-selected';
619 this.name_div.className = 'netdata-legend-name selected';
622 if(this.value_div != value_div) {
623 this.value_div = value_div;
624 this.value_div.title = this.label;
625 this.value_div.style.color = this.color;
626 if(this.selected === false)
627 this.value_div.className = 'netdata-legend-value not-selected';
629 this.value_div.className = 'netdata-legend-value selected';
636 dimensionStatus.prototype.setHandler = function() {
637 if(this.enabled === false) return;
641 // this.name_div.onmousedown = this.value_div.onmousedown = function(e) {
642 this.name_div.onclick = this.value_div.onclick = function(e) {
644 if(ds.isSelected()) {
646 if(e.shiftKey === true || e.ctrlKey === true) {
647 // control or shift key is pressed -> unselect this (except is none will remain selected, in which case select all)
650 if(ds.parent.countSelected() === 0)
651 ds.parent.selectAll();
654 // no key is pressed -> select only this (except if it is the only selected already, in which case select all)
655 if(ds.parent.countSelected() === 1) {
656 ds.parent.selectAll();
659 ds.parent.selectNone();
665 // this is not selected
666 if(e.shiftKey === true || e.ctrlKey === true) {
667 // control or shift key is pressed -> select this too
671 // no key is pressed -> select only this
672 ds.parent.selectNone();
677 ds.parent.state.redrawChart();
681 dimensionStatus.prototype.select = function() {
682 if(this.enabled === false) return;
684 this.name_div.className = 'netdata-legend-name selected';
685 this.value_div.className = 'netdata-legend-value selected';
686 this.selected = true;
689 dimensionStatus.prototype.unselect = function() {
690 if(this.enabled === false) return;
692 this.name_div.className = 'netdata-legend-name not-selected';
693 this.value_div.className = 'netdata-legend-value hidden';
694 this.selected = false;
697 dimensionStatus.prototype.isSelected = function() {
698 return(this.enabled === true && this.selected === true);
701 // ----------------------------------------------------------------------------------------------------------------
703 dimensionsVisibility = function(state) {
706 this.dimensions = {};
707 this.selected_count = 0;
708 this.unselected_count = 0;
711 dimensionsVisibility.prototype.dimensionAdd = function(label, name_div, value_div, color) {
712 if(typeof this.dimensions[label] === 'undefined') {
714 this.dimensions[label] = new dimensionStatus(this, label, name_div, value_div, color);
717 this.dimensions[label].setOptions(name_div, value_div, color);
719 return this.dimensions[label];
722 dimensionsVisibility.prototype.dimensionGet = function(label) {
723 return this.dimensions[label];
726 dimensionsVisibility.prototype.invalidateAll = function() {
727 for(var d in this.dimensions)
728 this.dimensions[d].invalidate();
731 dimensionsVisibility.prototype.selectAll = function() {
732 for(var d in this.dimensions)
733 this.dimensions[d].select();
736 dimensionsVisibility.prototype.countSelected = function() {
738 for(var d in this.dimensions)
739 if(this.dimensions[d].isSelected()) i++;
744 dimensionsVisibility.prototype.selectNone = function() {
745 for(var d in this.dimensions)
746 this.dimensions[d].unselect();
749 dimensionsVisibility.prototype.selected2BooleanArray = function(array) {
750 var ret = new Array();
751 this.selected_count = 0;
752 this.unselected_count = 0;
754 for(var i = 0, len = array.length; i < len ; i++) {
755 var ds = this.dimensions[array[i]];
756 if(typeof ds === 'undefined') {
757 // console.log(array[i] + ' is not found');
762 if(ds.isSelected()) {
764 this.selected_count++;
768 this.unselected_count++;
772 if(this.selected_count === 0 && this.unselected_count !== 0) {
774 return this.selected2BooleanArray(array);
781 // ----------------------------------------------------------------------------------------------------------------
782 // global selection sync
784 NETDATA.globalSelectionSync = {
791 if(this.state !== null)
792 this.state.globalSelectionSyncStop();
796 if(this.state !== null) {
797 this.state.globalSelectionSyncDelay();
802 // ----------------------------------------------------------------------------------------------------------------
803 // Our state object, where all per-chart values are stored
805 chartState = function(element) {
806 var self = $(element);
807 this.element = element;
810 // all private functions should use 'that', instead of 'this'
814 * show an error instead of the chart
816 var error = function(msg) {
817 that.element.innerHTML = that.id + ': ' + msg;
818 that.enabled = false;
819 that.current = that.pan;
822 // GUID - a unique identifier for the chart
823 this.uuid = NETDATA.guid();
825 // string - the name of chart
826 this.id = self.data('netdata');
828 // string - the key for localStorage settings
829 this.settings_id = self.data('id') || null;
831 // the user given dimensions of the element
832 this.width = self.data('width') || NETDATA.chartDefaults.width;
833 this.height = self.data('height') || NETDATA.chartDefaults.height;
835 if(this.settings_id !== null) {
836 this.height = NETDATA.localStorageGet('chart_heights.' + this.settings_id, this.height, function(height) {
837 // this is the callback that will be called
838 // if and when the user resets all localStorage variables
841 resizeChartToHeight(height);
845 // string - the netdata server URL, without any path
846 this.host = self.data('host') || NETDATA.chartDefaults.host;
848 // make sure the host does not end with /
849 // all netdata API requests use absolute paths
850 while(this.host.slice(-1) === '/')
851 this.host = this.host.substring(0, this.host.length - 1);
853 // string - the grouping method requested by the user
854 this.method = self.data('method') || NETDATA.chartDefaults.method;
856 // the time-range requested by the user
857 this.after = self.data('after') || NETDATA.chartDefaults.after;
858 this.before = self.data('before') || NETDATA.chartDefaults.before;
860 // the pixels per point requested by the user
861 this.pixels_per_point = self.data('pixels-per-point') || 1;
862 this.points = self.data('points') || null;
864 // the dimensions requested by the user
865 this.dimensions = self.data('dimensions') || null;
867 // the chart library requested by the user
868 this.library_name = self.data('chart-library') || NETDATA.chartDefaults.library;
870 // object - the chart library used
875 this.colors_assigned = {};
876 this.colors_available = null;
878 // the element already created by the user
879 this.element_message = null;
881 // the element with the chart
882 this.element_chart = null;
884 // the element with the legend of the chart (if created by us)
885 this.element_legend = null;
886 this.element_legend_childs = {
896 this.chart_url = null; // string - the url to download chart info
897 this.chart = null; // object - the chart as downloaded from the server
899 this.title = self.data('title') || null; // the title of the chart
900 this.units = self.data('units') || null; // the units of the chart dimensions
901 this.append_options = self.data('append-options') || null; // the units of the chart dimensions
903 this.validated = false; // boolean - has the chart been validated?
904 this.enabled = true; // boolean - is the chart enabled for refresh?
905 this.paused = false; // boolean - is the chart paused for any reason?
906 this.selected = false; // boolean - is the chart shown a selection?
907 this.debug = false; // boolean - console.log() debug info about this chart
909 this.netdata_first = 0; // milliseconds - the first timestamp in netdata
910 this.netdata_last = 0; // milliseconds - the last timestamp in netdata
911 this.requested_after = null; // milliseconds - the timestamp of the request after param
912 this.requested_before = null; // milliseconds - the timestamp of the request before param
913 this.requested_padding = null;
915 this.view_before = 0;
920 force_update_at: 0, // the timestamp to force the update at
921 force_before_ms: null,
927 force_update_at: 0, // the timestamp to force the update at
928 force_before_ms: null,
934 force_update_at: 0, // the timestamp to force the update at
935 force_before_ms: null,
939 // this is a pointer to one of the sub-classes below
941 this.current = this.auto;
943 // check the requested library is available
944 // we don't initialize it here - it will be initialized when
945 // this chart will be first used
946 if(typeof NETDATA.chartLibraries[that.library_name] === 'undefined') {
947 NETDATA.error(402, that.library_name);
948 error('chart library "' + that.library_name + '" is not found');
951 else if(NETDATA.chartLibraries[that.library_name].enabled === false) {
952 NETDATA.error(403, that.library_name);
953 error('chart library "' + that.library_name + '" is not enabled');
957 that.library = NETDATA.chartLibraries[that.library_name];
959 // milliseconds - the time the last refresh took
960 this.refresh_dt_ms = 0;
962 // if we need to report the rendering speed
963 // find the element that needs to be updated
964 var refresh_dt_element_name = self.data('dt-element-name') || null; // string - the element to print refresh_dt_ms
966 if(refresh_dt_element_name !== null)
967 this.refresh_dt_element = document.getElementById(refresh_dt_element_name) || null;
969 this.refresh_dt_element = null;
971 this.dimensions_visibility = new dimensionsVisibility(this);
973 this._updating = false;
975 // ============================================================================================================
978 var createDOM = function() {
979 if(that.enabled === false) return;
981 if(that.element_message !== null) that.element_message.innerHTML = '';
982 if(that.element_legend !== null) that.element_legend.innerHTML = '';
983 if(that.element_chart !== null) that.element_chart.innerHTML = '';
985 that.element.innerHTML = '';
987 that.element_message = document.createElement('div');
988 that.element_message.className = ' netdata-message hidden';
989 that.element.appendChild(that.element_message);
991 that.element_chart = document.createElement('div');
992 that.element_chart.id = that.library_name + '-' + that.uuid + '-chart';
993 that.element.appendChild(that.element_chart);
995 if(that.hasLegend() === true) {
996 that.element.className = "netdata-container-with-legend";
997 that.element_chart.className = 'netdata-chart-with-legend-right netdata-' + that.library_name + '-chart-with-legend-right';
999 that.element_legend = document.createElement('div');
1000 that.element_legend.className = 'netdata-chart-legend netdata-' + that.library_name + '-legend';
1001 that.element.appendChild(that.element_legend);
1004 that.element.className = "netdata-container";
1005 that.element_chart.className = ' netdata-chart netdata-' + that.library_name + '-chart';
1007 that.element_legend = null;
1009 that.element_legend_childs.series = null;
1011 if(typeof(that.width) === 'string')
1012 $(that.element).css('width', that.width);
1013 else if(typeof(that.width) === 'number')
1014 $(that.element).css('width', that.width + 'px');
1016 if(typeof(that.library.aspect_ratio) === 'undefined') {
1017 if(typeof(that.height) === 'string')
1018 $(that.element).css('height', that.height);
1019 else if(typeof(that.height) === 'number')
1020 $(that.element).css('height', that.height + 'px');
1023 var w = that.element.offsetWidth;
1024 if(w === null || w === 0) {
1025 // the div is hidden
1026 // this is resize the chart when next viewed
1027 that.tm.last_resized = 0;
1030 $(that.element).css('height', (that.element.offsetWidth * that.library.aspect_ratio / 100).toString() + 'px');
1033 if(NETDATA.chartDefaults.min_width !== null)
1034 $(that.element).css('min-width', NETDATA.chartDefaults.min_width);
1036 that.tm.last_dom_created = new Date().getTime();
1042 * initialize state viariables
1043 * destroy all (possibly) created state elements
1044 * create the basic DOM for a chart
1046 var init = function() {
1047 if(that.enabled === false) return;
1049 that.paused = false;
1050 that.selected = false;
1052 that.chart_created = false; // boolean - is the library.create() been called?
1053 that.updates_counter = 0; // numeric - the number of refreshes made so far
1054 that.updates_since_last_unhide = 0; // numeric - the number of refreshes made since the last time the chart was unhidden
1055 that.updates_since_last_creation = 0; // numeric - the number of refreshes made since the last time the chart was created
1058 last_initialized: 0, // milliseconds - the timestamp it was last initialized
1059 last_dom_created: 0, // milliseconds - the timestamp its DOM was last created
1060 last_mode_switch: 0, // milliseconds - the timestamp it switched modes
1062 last_info_downloaded: 0, // milliseconds - the timestamp we downloaded the chart
1063 last_updated: 0, // the timestamp the chart last updated with data
1064 pan_and_zoom_seq: 0, // the sequence number of the global synchronization
1066 // Used with NETDATA.globalPanAndZoom.seq
1067 last_visible_check: 0, // the time we last checked if it is visible
1068 last_resized: 0, // the time the chart was resized
1069 last_hidden: 0, // the time the chart was hidden
1070 last_unhidden: 0, // the time the chart was unhidden
1071 last_autorefreshed: 0 // the time the chart was last refreshed
1074 that.data = null; // the last data as downloaded from the netdata server
1075 that.data_url = 'invalid://'; // string - the last url used to update the chart
1076 that.data_points = 0; // number - the number of points returned from netdata
1077 that.data_after = 0; // milliseconds - the first timestamp of the data
1078 that.data_before = 0; // milliseconds - the last timestamp of the data
1079 that.data_update_every = 0; // milliseconds - the frequency to update the data
1081 that.tm.last_initialized = new Date().getTime();
1084 that.setMode('auto');
1087 var maxMessageFontSize = function() {
1088 // normally we want a font size, as tall as the element
1089 var h = that.element_message.clientHeight;
1091 // but give it some air, 20% let's say, or 5 pixels min
1092 var lost = Math.max(h * 0.2, 5);
1095 // center the text, verically
1096 var paddingTop = (lost - 5) / 2;
1098 // but check the width too
1099 // it should fit 10 characters in it
1100 var w = that.element_message.clientWidth / 10;
1102 paddingTop += (h - w) / 2;
1106 // and don't make it too huge
1107 // 5% of the screen size is good
1108 if(h > screen.height / 20) {
1109 paddingTop += (h - (screen.height / 20)) / 2;
1110 h = screen.height / 20;
1114 that.element_message.style.fontSize = h.toString() + 'px';
1115 that.element_message.style.paddingTop = paddingTop.toString() + 'px';
1118 var showMessage = function(msg) {
1119 that.element_message.className = 'netdata-message';
1120 that.element_message.innerHTML = msg;
1121 this.element_message.style.fontSize = 'x-small';
1122 that.element_message.style.paddingTop = '0px';
1123 that.___messageHidden___ = undefined;
1126 var showMessageIcon = function(icon) {
1127 that.element_message.innerHTML = icon;
1128 that.element_message.className = 'netdata-message icon';
1129 maxMessageFontSize();
1130 that.___messageHidden___ = undefined;
1133 var hideMessage = function() {
1134 if(typeof that.___messageHidden___ === 'undefined') {
1135 that.___messageHidden___ = true;
1136 that.element_message.className = 'netdata-message hidden';
1140 var showRendering = function() {
1142 if(that.chart !== null) {
1143 if(that.chart.chart_type === 'line')
1144 icon = '<i class="fa fa-line-chart"></i>';
1146 icon = '<i class="fa fa-area-chart"></i>';
1149 icon = '<i class="fa fa-area-chart"></i>';
1151 showMessageIcon(icon + ' netdata');
1154 var showLoading = function() {
1155 if(that.chart_created === false) {
1156 showMessageIcon('<i class="fa fa-refresh"></i> netdata');
1162 var isHidden = function() {
1163 if(typeof that.___chartIsHidden___ !== 'undefined')
1169 // hide the chart, when it is not visible - called from isVisible()
1170 var hideChart = function() {
1171 // hide it, if it is not already hidden
1172 if(isHidden() === true) return;
1174 if(that.chart_created === true) {
1175 // we should destroy it
1176 if(NETDATA.options.current.destroy_on_hide === true) {
1181 that.element_chart.style.display = 'none';
1182 if(that.element_legend !== null) that.element_legend.style.display = 'none';
1183 that.tm.last_hidden = new Date().getTime();
1187 that.___chartIsHidden___ = true;
1190 // unhide the chart, when it is visible - called from isVisible()
1191 var unhideChart = function() {
1192 if(isHidden() === false) return;
1194 that.___chartIsHidden___ = undefined;
1195 that.updates_since_last_unhide = 0;
1197 if(that.chart_created === false) {
1198 // we need to re-initialize it, to show our background
1199 // logo in bootstrap tabs, until the chart loads
1203 that.tm.last_unhidden = new Date().getTime();
1204 that.element_chart.style.display = '';
1205 if(that.element_legend !== null) that.element_legend.style.display = '';
1211 var canBeRendered = function() {
1212 if(isHidden() === true || that.isVisible(true) === false)
1218 // https://github.com/petkaantonov/bluebird/wiki/Optimization-killers
1219 var callChartLibraryUpdateSafely = function(data) {
1222 if(canBeRendered() === false)
1225 if(NETDATA.options.debug.chart_errors === true)
1226 status = that.library.update(that, data);
1229 status = that.library.update(that, data);
1236 if(status === false) {
1237 error('chart failed to be updated as ' + that.library_name);
1244 // https://github.com/petkaantonov/bluebird/wiki/Optimization-killers
1245 var callChartLibraryCreateSafely = function(data) {
1248 if(canBeRendered() === false)
1251 if(NETDATA.options.debug.chart_errors === true)
1252 status = that.library.create(that, data);
1255 status = that.library.create(that, data);
1262 if(status === false) {
1263 error('chart failed to be created as ' + that.library_name);
1267 that.chart_created = true;
1268 that.updates_since_last_creation = 0;
1272 // ----------------------------------------------------------------------------------------------------------------
1275 // resizeChart() - private
1276 // to be called just before the chart library to make sure that
1277 // a properly sized dom is available
1278 var resizeChart = function() {
1279 if(that.isVisible() === true && that.tm.last_resized < NETDATA.options.last_resized) {
1280 if(that.chart_created === false) return;
1282 if(that.needsRecreation()) {
1285 else if(typeof that.library.resize === 'function') {
1286 that.library.resize(that);
1288 if(that.element_legend_childs.nano !== null && that.element_legend_childs.nano_options !== null)
1289 $(that.element_legend_childs.nano).nanoScroller();
1291 maxMessageFontSize();
1294 that.tm.last_resized = new Date().getTime();
1298 // this is the actual chart resize algorithm
1300 // - resize the entire container
1301 // - update the internal states
1302 // - resize the chart as the div changes height
1303 // - update the scrollbar of the legend
1304 var resizeChartToHeight = function(h) {
1306 that.element.style.height = h;
1308 if(that.settings_id !== null)
1309 NETDATA.localStorageSet('chart_heights.' + that.settings_id, h);
1311 var now = new Date().getTime();
1312 NETDATA.options.last_page_scroll = now;
1313 NETDATA.options.auto_refresher_stop_until = now + NETDATA.options.current.stop_updates_while_resizing;
1316 that.tm.last_resized = 0;
1320 this.resizeHandler = function(e) {
1323 if(typeof this.event_resize === 'undefined'
1324 || this.event_resize.chart_original_w === 'undefined'
1325 || this.event_resize.chart_original_h === 'undefined')
1326 this.event_resize = {
1327 chart_original_w: this.element.clientWidth,
1328 chart_original_h: this.element.clientHeight,
1332 if(e.type === 'touchstart') {
1333 this.event_resize.mouse_start_x = e.touches.item(0).pageX;
1334 this.event_resize.mouse_start_y = e.touches.item(0).pageY;
1337 this.event_resize.mouse_start_x = e.clientX;
1338 this.event_resize.mouse_start_y = e.clientY;
1341 this.event_resize.chart_start_w = this.element.clientWidth;
1342 this.event_resize.chart_start_h = this.element.clientHeight;
1343 this.event_resize.chart_last_w = this.element.clientWidth;
1344 this.event_resize.chart_last_h = this.element.clientHeight;
1346 var now = new Date().getTime();
1347 if(now - this.event_resize.last <= NETDATA.options.current.double_click_speed) {
1348 // double click / double tap event
1350 // the optimal height of the chart
1351 // showing the entire legend
1352 var optimal = this.event_resize.chart_last_h
1353 + this.element_legend_childs.content.scrollHeight
1354 - this.element_legend_childs.content.clientHeight;
1356 // if we are not optimal, be optimal
1357 if(this.event_resize.chart_last_h != optimal)
1358 resizeChartToHeight(optimal.toString() + 'px');
1360 // else if we do not have the original height
1361 // reset to the original height
1362 else if(this.event_resize.chart_last_h != this.event_resize.chart_original_h)
1363 resizeChartToHeight(this.event_resize.chart_original_h.toString() + 'px');
1366 this.event_resize.last = now;
1368 // process movement event
1369 document.onmousemove =
1370 document.ontouchmove =
1371 this.element_legend_childs.resize_handler.onmousemove =
1372 this.element_legend_childs.resize_handler.ontouchmove =
1377 case 'mousemove': y = e.clientY; break;
1378 case 'touchmove': y = e.touches.item(e.touches - 1).pageY; break;
1382 var newH = that.event_resize.chart_start_h + y - that.event_resize.mouse_start_y;
1384 if(newH >= 70 && newH !== that.event_resize.chart_last_h) {
1385 resizeChartToHeight(newH.toString() + 'px');
1386 that.event_resize.chart_last_h = newH;
1391 // process end event
1392 document.onmouseup =
1393 document.ontouchend =
1394 this.element_legend_childs.resize_handler.onmouseup =
1395 this.element_legend_childs.resize_handler.ontouchend =
1397 // remove all the hooks
1398 document.onmouseup =
1399 document.onmousemove =
1400 document.ontouchmove =
1401 document.ontouchend =
1402 that.element_legend_childs.resize_handler.onmousemove =
1403 that.element_legend_childs.resize_handler.ontouchmove =
1404 that.element_legend_childs.resize_handler.onmouseout =
1405 that.element_legend_childs.resize_handler.onmouseup =
1406 that.element_legend_childs.resize_handler.ontouchend =
1409 // allow auto-refreshes
1410 NETDATA.options.auto_refresher_stop_until = 0;
1416 var noDataToShow = function() {
1417 showMessageIcon('<i class="fa fa-warning"></i> empty');
1418 that.legendUpdateDOM();
1419 that.tm.last_autorefreshed = new Date().getTime();
1420 // that.data_update_every = 30 * 1000;
1421 //that.element_chart.style.display = 'none';
1422 //if(that.element_legend !== null) that.element_legend.style.display = 'none';
1423 //that.___chartIsHidden___ = true;
1426 // ============================================================================================================
1429 this.error = function(msg) {
1433 this.setMode = function(m) {
1434 if(this.current !== null && this.current.name === m) return;
1437 this.current = this.auto;
1438 else if(m === 'pan')
1439 this.current = this.pan;
1440 else if(m === 'zoom')
1441 this.current = this.zoom;
1443 this.current = this.auto;
1445 this.current.force_update_at = 0;
1446 this.current.force_before_ms = null;
1447 this.current.force_after_ms = null;
1449 this.tm.last_mode_switch = new Date().getTime();
1452 // ----------------------------------------------------------------------------------------------------------------
1453 // global selection sync
1455 // prevent to global selection sync for some time
1456 this.globalSelectionSyncDelay = function(ms) {
1457 if(NETDATA.options.current.sync_selection === false)
1460 if(typeof ms === 'number')
1461 NETDATA.globalSelectionSync.dont_sync_before = new Date().getTime() + ms;
1463 NETDATA.globalSelectionSync.dont_sync_before = new Date().getTime() + NETDATA.options.current.sync_selection_delay;
1466 // can we globally apply selection sync?
1467 this.globalSelectionSyncAbility = function() {
1468 if(NETDATA.options.current.sync_selection === false)
1471 if(NETDATA.globalSelectionSync.dont_sync_before > new Date().getTime())
1477 this.globalSelectionSyncIsMaster = function() {
1478 if(NETDATA.globalSelectionSync.state === this)
1484 // this chart is the master of the global selection sync
1485 this.globalSelectionSyncBeMaster = function() {
1487 if(this.globalSelectionSyncIsMaster()) {
1488 if(this.debug === true)
1489 this.log('sync: I am the master already.');
1494 if(NETDATA.globalSelectionSync.state) {
1495 if(this.debug === true)
1496 this.log('sync: I am not the sync master. Resetting global sync.');
1498 this.globalSelectionSyncStop();
1501 // become the master
1502 if(this.debug === true)
1503 this.log('sync: becoming sync master.');
1505 this.selected = true;
1506 NETDATA.globalSelectionSync.state = this;
1508 // find the all slaves
1509 var targets = NETDATA.options.targets;
1510 var len = targets.length;
1515 if(this.debug === true)
1516 st.log('sync: not adding me to sync');
1518 else if(st.globalSelectionSyncIsEligible()) {
1519 if(this.debug === true)
1520 st.log('sync: adding to sync as slave');
1522 st.globalSelectionSyncBeSlave();
1526 // this.globalSelectionSyncDelay(100);
1529 // can the chart participate to the global selection sync as a slave?
1530 this.globalSelectionSyncIsEligible = function() {
1531 if(this.enabled === true
1532 && this.library !== null
1533 && typeof this.library.setSelection === 'function'
1534 && this.isVisible() === true
1535 && this.chart_created === true)
1541 // this chart becomes a slave of the global selection sync
1542 this.globalSelectionSyncBeSlave = function() {
1543 if(NETDATA.globalSelectionSync.state !== this)
1544 NETDATA.globalSelectionSync.slaves.push(this);
1547 // sync all the visible charts to the given time
1548 // this is to be called from the chart libraries
1549 this.globalSelectionSync = function(t) {
1550 if(this.globalSelectionSyncAbility() === false) {
1551 if(this.debug === true)
1552 this.log('sync: cannot sync (yet?).');
1557 if(this.globalSelectionSyncIsMaster() === false) {
1558 if(this.debug === true)
1559 this.log('sync: trying to be sync master.');
1561 this.globalSelectionSyncBeMaster();
1563 if(this.globalSelectionSyncAbility() === false) {
1564 if(this.debug === true)
1565 this.log('sync: cannot sync (yet?).');
1571 NETDATA.globalSelectionSync.last_t = t;
1572 $.each(NETDATA.globalSelectionSync.slaves, function(i, st) {
1577 // stop syncing all charts to the given time
1578 this.globalSelectionSyncStop = function() {
1579 if(NETDATA.globalSelectionSync.slaves.length) {
1580 if(this.debug === true)
1581 this.log('sync: cleaning up...');
1583 $.each(NETDATA.globalSelectionSync.slaves, function(i, st) {
1585 if(that.debug === true)
1586 st.log('sync: not adding me to sync stop');
1589 if(that.debug === true)
1590 st.log('sync: removed slave from sync');
1592 st.clearSelection();
1596 NETDATA.globalSelectionSync.last_t = 0;
1597 NETDATA.globalSelectionSync.slaves = [];
1598 NETDATA.globalSelectionSync.state = null;
1601 this.clearSelection();
1604 this.setSelection = function(t) {
1605 if(typeof this.library.setSelection === 'function') {
1606 if(this.library.setSelection(this, t) === true)
1607 this.selected = true;
1609 this.selected = false;
1611 else this.selected = true;
1613 if(this.selected === true && this.debug === true)
1614 this.log('selection set to ' + t.toString());
1616 return this.selected;
1619 this.clearSelection = function() {
1620 if(this.selected === true) {
1621 if(typeof this.library.clearSelection === 'function') {
1622 if(this.library.clearSelection(this) === true)
1623 this.selected = false;
1625 this.selected = true;
1627 else this.selected = false;
1629 if(this.selected === false && this.debug === true)
1630 this.log('selection cleared');
1635 return this.selected;
1638 // find if a timestamp (ms) is shown in the current chart
1639 this.timeIsVisible = function(t) {
1640 if(t >= this.data_after && t <= this.data_before)
1645 this.calculateRowForTime = function(t) {
1646 if(this.timeIsVisible(t) === false) return -1;
1647 return Math.floor((t - this.data_after) / this.data_update_every);
1650 // ----------------------------------------------------------------------------------------------------------------
1653 this.log = function(msg) {
1654 console.log(this.id + ' (' + this.library_name + ' ' + this.uuid + '): ' + msg);
1657 this.pauseChart = function() {
1658 if(this.paused === false) {
1659 if(this.debug === true)
1660 this.log('pauseChart()');
1666 this.unpauseChart = function() {
1667 if(this.paused === true) {
1668 if(this.debug === true)
1669 this.log('unpauseChart()');
1671 this.paused = false;
1675 this.resetChart = function(dont_clear_master, dont_update) {
1676 if(this.debug === true)
1677 this.log('resetChart(' + dont_clear_master + ', ' + dont_update + ') called');
1679 if(typeof dont_clear_master === 'undefined')
1680 dont_clear_master = false;
1682 if(typeof dont_update === 'undefined')
1683 dont_update = false;
1685 if(dont_clear_master !== true && NETDATA.globalPanAndZoom.isMaster(this) === true) {
1686 if(this.debug === true)
1687 this.log('resetChart() diverting to clearMaster().');
1688 // this will call us back with master === true
1689 NETDATA.globalPanAndZoom.clearMaster();
1693 this.clearSelection();
1695 this.tm.pan_and_zoom_seq = 0;
1697 this.setMode('auto');
1698 this.current.force_update_at = 0;
1699 this.current.force_before_ms = null;
1700 this.current.force_after_ms = null;
1701 this.tm.last_autorefreshed = 0;
1702 this.paused = false;
1703 this.selected = false;
1704 this.enabled = true;
1705 // this.debug = false;
1707 // do not update the chart here
1708 // or the chart will flip-flop when it is the master
1709 // of a selection sync and another chart becomes
1712 if(dont_update !== true && this.isVisible() === true) {
1717 this.updateChartPanOrZoom = function(after, before) {
1718 var logme = 'updateChartPanOrZoom(' + after + ', ' + before + '): ';
1721 if(this.debug === true)
1724 if(before < after) {
1725 this.log(logme + 'flipped parameters, rejecting it.');
1729 if(typeof this.fixed_min_duration === 'undefined')
1730 this.fixed_min_duration = Math.round((this.chartWidth() / 30) * this.chart.update_every * 1000);
1732 var min_duration = this.fixed_min_duration;
1733 var current_duration = Math.round(this.view_before - this.view_after);
1735 // round the numbers
1736 after = Math.round(after);
1737 before = Math.round(before);
1739 // align them to update_every
1740 // stretching them further away
1741 after -= after % this.data_update_every;
1742 before += this.data_update_every - (before % this.data_update_every);
1744 // the final wanted duration
1745 var wanted_duration = before - after;
1747 // to allow panning, accept just a point below our minimum
1748 if((current_duration - this.data_update_every) < min_duration)
1749 min_duration = current_duration - this.data_update_every;
1751 // we do it, but we adjust to minimum size and return false
1752 // when the wanted size is below the current and the minimum
1754 if(wanted_duration < current_duration && wanted_duration < min_duration) {
1755 if(this.debug === true)
1756 this.log(logme + 'too small: min_duration: ' + (min_duration / 1000).toString() + ', wanted: ' + (wanted_duration / 1000).toString());
1758 min_duration = this.fixed_min_duration;
1760 var dt = (min_duration - wanted_duration) / 2;
1763 wanted_duration = before - after;
1767 var tolerance = this.data_update_every * 2;
1768 var movement = Math.abs(before - this.view_before);
1770 if(Math.abs(current_duration - wanted_duration) <= tolerance && movement <= tolerance && ret === true) {
1771 if(this.debug === true)
1772 this.log(logme + 'REJECTING UPDATE: current/min duration: ' + (current_duration / 1000).toString() + '/' + (this.fixed_min_duration / 1000).toString() + ', wanted duration: ' + (wanted_duration / 1000).toString() + ', duration diff: ' + (Math.round(Math.abs(current_duration - wanted_duration) / 1000)).toString() + ', movement: ' + (movement / 1000).toString() + ', tolerance: ' + (tolerance / 1000).toString() + ', returning: ' + false);
1776 if(this.current.name === 'auto') {
1777 this.log(logme + 'caller called me with mode: ' + this.current.name);
1778 this.setMode('pan');
1781 if(this.debug === true)
1782 this.log(logme + 'ACCEPTING UPDATE: current/min duration: ' + (current_duration / 1000).toString() + '/' + (this.fixed_min_duration / 1000).toString() + ', wanted duration: ' + (wanted_duration / 1000).toString() + ', duration diff: ' + (Math.round(Math.abs(current_duration - wanted_duration) / 1000)).toString() + ', movement: ' + (movement / 1000).toString() + ', tolerance: ' + (tolerance / 1000).toString() + ', returning: ' + ret);
1784 this.current.force_update_at = new Date().getTime() + NETDATA.options.current.pan_and_zoom_delay;
1785 this.current.force_after_ms = after;
1786 this.current.force_before_ms = before;
1787 NETDATA.globalPanAndZoom.setMaster(this, after, before);
1791 this.legendFormatValue = function(value) {
1792 if(value === null || value === 'undefined') return '-';
1793 if(typeof value !== 'number') return value;
1795 var abs = Math.abs(value);
1796 if(abs >= 1000) return (Math.round(value)).toLocaleString();
1797 if(abs >= 100 ) return (Math.round(value * 10) / 10).toLocaleString();
1798 if(abs >= 1 ) return (Math.round(value * 100) / 100).toLocaleString();
1799 if(abs >= 0.1 ) return (Math.round(value * 1000) / 1000).toLocaleString();
1800 return (Math.round(value * 10000) / 10000).toLocaleString();
1803 this.legendSetLabelValue = function(label, value) {
1804 var series = this.element_legend_childs.series[label];
1805 if(typeof series === 'undefined') return;
1806 if(series.value === null && series.user === null) return;
1808 // if the value has not changed, skip DOM update
1809 //if(series.last === value) return;
1812 if(typeof value === 'number') {
1813 var v = Math.abs(value);
1814 s = r = this.legendFormatValue(value);
1816 if(typeof series.last === 'number') {
1817 if(v > series.last) s += '<i class="fa fa-angle-up" style="width: 8px; text-align: center; overflow: hidden; vertical-align: middle;"></i>';
1818 else if(v < series.last) s += '<i class="fa fa-angle-down" style="width: 8px; text-align: center; overflow: hidden; vertical-align: middle;"></i>';
1819 else s += '<i class="fa fa-angle-left" style="width: 8px; text-align: center; overflow: hidden; vertical-align: middle;"></i>';
1821 else s += '<i class="fa fa-angle-right" style="width: 8px; text-align: center; overflow: hidden; vertical-align: middle;"></i>';
1826 series.last = value;
1829 if(series.value !== null) series.value.innerHTML = s;
1830 if(series.user !== null) series.user.innerHTML = r;
1833 this.legendSetDate = function(ms) {
1834 if(typeof ms !== 'number') {
1835 this.legendShowUndefined();
1839 var d = new Date(ms);
1841 if(this.element_legend_childs.title_date)
1842 this.element_legend_childs.title_date.innerHTML = d.toLocaleDateString();
1844 if(this.element_legend_childs.title_time)
1845 this.element_legend_childs.title_time.innerHTML = d.toLocaleTimeString();
1847 if(this.element_legend_childs.title_units)
1848 this.element_legend_childs.title_units.innerHTML = this.units;
1851 this.legendShowUndefined = function() {
1852 if(this.element_legend_childs.title_date)
1853 this.element_legend_childs.title_date.innerHTML = ' ';
1855 if(this.element_legend_childs.title_time)
1856 this.element_legend_childs.title_time.innerHTML = this.chart.name;
1858 if(this.element_legend_childs.title_units)
1859 this.element_legend_childs.title_units.innerHTML = ' ';
1861 if(this.data && this.element_legend_childs.series !== null) {
1862 var labels = this.data.dimension_names;
1863 var i = labels.length;
1865 var label = labels[i];
1867 if(typeof label === 'undefined') continue;
1868 if(typeof this.element_legend_childs.series[label] === 'undefined') continue;
1869 this.legendSetLabelValue(label, null);
1874 this.legendShowLatestValues = function() {
1875 if(this.chart === null) return;
1876 if(this.selected) return;
1878 if(this.data === null || this.element_legend_childs.series === null) {
1879 this.legendShowUndefined();
1883 var show_undefined = true;
1884 if(Math.abs(this.netdata_last - this.view_before) <= this.data_update_every)
1885 show_undefined = false;
1887 if(show_undefined) {
1888 this.legendShowUndefined();
1892 this.legendSetDate(this.view_before);
1894 var labels = this.data.dimension_names;
1895 var i = labels.length;
1897 var label = labels[i];
1899 if(typeof label === 'undefined') continue;
1900 if(typeof this.element_legend_childs.series[label] === 'undefined') continue;
1903 this.legendSetLabelValue(label, null);
1905 this.legendSetLabelValue(label, this.data.view_latest_values[i]);
1909 this.legendReset = function() {
1910 this.legendShowLatestValues();
1913 // this should be called just ONCE per dimension per chart
1914 this._chartDimensionColor = function(label) {
1915 if(this.colors === null) this.chartColors();
1917 if(typeof this.colors_assigned[label] === 'undefined') {
1918 if(this.colors_available.length === 0) {
1919 for(var i = 0, len = NETDATA.colors.length; i < len ; i++)
1920 this.colors_available.push(NETDATA.colors[i]);
1923 this.colors_assigned[label] = this.colors_available.shift();
1925 if(this.debug === true)
1926 this.log('label "' + label + '" got color "' + this.colors_assigned[label]);
1929 if(this.debug === true)
1930 this.log('label "' + label + '" already has color "' + this.colors_assigned[label] + '"');
1933 this.colors.push(this.colors_assigned[label]);
1934 return this.colors_assigned[label];
1937 this.chartColors = function() {
1938 if(this.colors !== null) return this.colors;
1940 this.colors = new Array();
1941 this.colors_available = new Array();
1943 var c = $(this.element).data('colors');
1944 // this.log('read colors: ' + c);
1945 if(typeof c !== 'undefined' && c !== null) {
1946 if(typeof c !== 'string') {
1947 this.log('invalid color given: ' + c + ' (give a space separated list of colors)');
1954 for(var i = 0, len = c.length; i < len ; i++) {
1956 this.colors_available.push(c[i]);
1957 // this.log('adding color: ' + c[i]);
1963 // push all the standard colors too
1964 for(var i = 0, len = NETDATA.colors.length; i < len ; i++)
1965 this.colors_available.push(NETDATA.colors[i]);
1970 this.legendUpdateDOM = function() {
1973 // check that the legend DOM is up to date for the downloaded dimensions
1974 if(typeof this.element_legend_childs.series !== 'object' || this.element_legend_childs.series === null) {
1975 // this.log('the legend does not have any series - requesting legend update');
1978 else if(this.data === null) {
1979 // this.log('the chart does not have any data - requesting legend update');
1982 else if(typeof this.element_legend_childs.series.labels_key === 'undefined') {
1986 var labels = this.data.dimension_names.toString();
1987 if(labels !== this.element_legend_childs.series.labels_key) {
1990 if(this.debug === true)
1991 this.log('NEW LABELS: "' + labels + '" NOT EQUAL OLD LABELS: "' + this.element_legend_childs.series.labels_key + '"');
1995 if(needed === false) {
1996 // make sure colors available
1999 // do we have to update the current values?
2000 // we do this, only when the visible chart is current
2001 if(Math.abs(this.netdata_last - this.view_before) <= this.data_update_every) {
2002 if(this.debug === true)
2003 this.log('chart is in latest position... updating values on legend...');
2005 //var labels = this.data.dimension_names;
2006 //var i = labels.length;
2008 // this.legendSetLabelValue(labels[i], this.data.latest_values[i]);
2012 if(this.colors === null) {
2013 // this is the first time we update the chart
2014 // let's assign colors to all dimensions
2015 if(this.library.track_colors() === true)
2016 for(var dim in this.chart.dimensions)
2017 this._chartDimensionColor(this.chart.dimensions[dim].name);
2019 // we will re-generate the colors for the chart
2020 // based on the selected dimensions
2023 if(this.debug === true)
2024 this.log('updating Legend DOM');
2026 // mark all dimensions as invalid
2027 this.dimensions_visibility.invalidateAll();
2029 var genLabel = function(state, parent, name, count) {
2030 var color = state._chartDimensionColor(name);
2032 var user_element = null;
2033 var user_id = self.data('show-value-of-' + name + '-at') || null;
2034 if(user_id !== null) {
2035 user_element = document.getElementById(user_id) || null;
2036 if(user_element === null)
2037 me.log('Cannot find element with id: ' + user_id);
2040 state.element_legend_childs.series[name] = {
2041 name: document.createElement('span'),
2042 value: document.createElement('span'),
2047 var label = state.element_legend_childs.series[name];
2049 // create the dimension visibility tracking for this label
2050 state.dimensions_visibility.dimensionAdd(name, label.name, label.value, color);
2052 var rgb = NETDATA.colorHex2Rgb(color);
2053 label.name.innerHTML = '<table class="netdata-legend-name-table-'
2054 + state.chart.chart_type
2055 + '" style="background-color: '
2056 + 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + NETDATA.options.current['color_fill_opacity_' + state.chart.chart_type] + ')'
2057 + '"><tr class="netdata-legend-name-tr"><td class="netdata-legend-name-td"></td></tr></table>'
2059 var text = document.createTextNode(' ' + name);
2060 label.name.appendChild(text);
2063 parent.appendChild(document.createElement('br'));
2065 parent.appendChild(label.name);
2066 parent.appendChild(label.value);
2069 var content = document.createElement('div');
2071 if(this.hasLegend()) {
2072 this.element_legend_childs = {
2074 resize_handler: document.createElement('div'),
2075 title_date: document.createElement('span'),
2076 title_time: document.createElement('span'),
2077 title_units: document.createElement('span'),
2078 nano: document.createElement('div'),
2080 paneClass: 'netdata-legend-series-pane',
2081 sliderClass: 'netdata-legend-series-slider',
2082 contentClass: 'netdata-legend-series-content',
2083 enabledClass: '__enabled',
2084 flashedClass: '__flashed',
2085 activeClass: '__active',
2087 alwaysVisible: true,
2093 this.element_legend.innerHTML = '';
2095 this.element_legend_childs.resize_handler.className += " netdata-legend-resize-handler";
2096 this.element_legend_childs.resize_handler.innerHTML = '<i class="fa fa-chevron-up"></i><i class="fa fa-chevron-down"></i>';
2097 this.element.appendChild(this.element_legend_childs.resize_handler);
2100 this.element_legend_childs.resize_handler.onmousedown =
2102 that.resizeHandler(e);
2106 this.element_legend_childs.resize_handler.addEventListener('touchstart', function(e) {
2107 that.resizeHandler(e);
2110 this.element_legend_childs.title_date.className += " netdata-legend-title-date";
2111 this.element_legend.appendChild(this.element_legend_childs.title_date);
2113 this.element_legend.appendChild(document.createElement('br'));
2115 this.element_legend_childs.title_time.className += " netdata-legend-title-time";
2116 this.element_legend.appendChild(this.element_legend_childs.title_time);
2118 this.element_legend.appendChild(document.createElement('br'));
2120 this.element_legend_childs.title_units.className += " netdata-legend-title-units";
2121 this.element_legend.appendChild(this.element_legend_childs.title_units);
2123 this.element_legend.appendChild(document.createElement('br'));
2125 this.element_legend_childs.nano.className = 'netdata-legend-series';
2126 this.element_legend.appendChild(this.element_legend_childs.nano);
2128 content.className = 'netdata-legend-series-content';
2129 this.element_legend_childs.nano.appendChild(content);
2132 this.element_legend_childs = {
2134 resize_handler: null,
2145 this.element_legend_childs.series.labels_key = this.data.dimension_names.toString();
2146 if(this.debug === true)
2147 this.log('labels from data: "' + this.element_legend_childs.series.labels_key + '"');
2149 for(var i = 0, len = this.data.dimension_names.length; i < len ;i++) {
2150 genLabel(this, content, this.data.dimension_names[i], i);
2154 var tmp = new Array();
2155 for(var dim in this.chart.dimensions) {
2156 tmp.push(this.chart.dimensions[dim].name);
2157 genLabel(this, content, this.chart.dimensions[dim].name, i);
2159 this.element_legend_childs.series.labels_key = tmp.toString();
2160 if(this.debug === true)
2161 this.log('labels from chart: "' + this.element_legend_childs.series.labels_key + '"');
2164 // create a hidden div to be used for hidding
2165 // the original legend of the chart library
2166 var el = document.createElement('div');
2167 if(this.element_legend !== null)
2168 this.element_legend.appendChild(el);
2169 el.style.display = 'none';
2171 this.element_legend_childs.hidden = document.createElement('div');
2172 el.appendChild(this.element_legend_childs.hidden);
2174 if(this.element_legend_childs.nano !== null && this.element_legend_childs.nano_options !== null)
2175 $(this.element_legend_childs.nano).nanoScroller(this.element_legend_childs.nano_options);
2177 this.legendShowLatestValues();
2180 this.hasLegend = function() {
2181 if(typeof this.___hasLegendCache___ !== 'undefined')
2182 return this.___hasLegendCache___;
2185 if(this.library && this.library.legend(this) === 'right-side') {
2186 var legend = $(this.element).data('legend') || 'yes';
2187 if(legend === 'yes') leg = true;
2190 this.___hasLegendCache___ = leg;
2194 this.legendWidth = function() {
2195 return (this.hasLegend())?140:0;
2198 this.legendHeight = function() {
2199 return $(this.element).height();
2202 this.chartWidth = function() {
2203 return $(this.element).width() - this.legendWidth();
2206 this.chartHeight = function() {
2207 return $(this.element).height();
2210 this.chartPixelsPerPoint = function() {
2211 // force an options provided detail
2212 var px = this.pixels_per_point;
2214 if(this.library && px < this.library.pixels_per_point(this))
2215 px = this.library.pixels_per_point(this);
2217 if(px < NETDATA.options.current.pixels_per_point)
2218 px = NETDATA.options.current.pixels_per_point;
2223 this.needsRecreation = function() {
2225 this.chart_created === true
2227 && this.library.autoresize() === false
2228 && this.tm.last_resized < NETDATA.options.last_resized
2232 this.chartURL = function() {
2233 var after, before, points_multiplier = 1;
2234 if(NETDATA.globalPanAndZoom.isActive() && NETDATA.globalPanAndZoom.isMaster(this) === false) {
2235 this.tm.pan_and_zoom_seq = NETDATA.globalPanAndZoom.seq;
2237 after = Math.round(NETDATA.globalPanAndZoom.force_after_ms / 1000);
2238 before = Math.round(NETDATA.globalPanAndZoom.force_before_ms / 1000);
2239 this.view_after = after * 1000;
2240 this.view_before = before * 1000;
2242 this.requested_padding = null;
2243 points_multiplier = 1;
2245 else if(this.current.force_before_ms !== null && this.current.force_after_ms !== null) {
2246 this.tm.pan_and_zoom_seq = 0;
2248 before = Math.round(this.current.force_before_ms / 1000);
2249 after = Math.round(this.current.force_after_ms / 1000);
2250 this.view_after = after * 1000;
2251 this.view_before = before * 1000;
2253 if(NETDATA.options.current.pan_and_zoom_data_padding === true) {
2254 this.requested_padding = Math.round((before - after) / 2);
2255 after -= this.requested_padding;
2256 before += this.requested_padding;
2257 this.requested_padding *= 1000;
2258 points_multiplier = 2;
2261 this.current.force_before_ms = null;
2262 this.current.force_after_ms = null;
2265 this.tm.pan_and_zoom_seq = 0;
2267 before = this.before;
2269 this.view_after = after * 1000;
2270 this.view_before = before * 1000;
2272 this.requested_padding = null;
2273 points_multiplier = 1;
2276 this.requested_after = after * 1000;
2277 this.requested_before = before * 1000;
2279 this.data_points = this.points || Math.round(this.chartWidth() / this.chartPixelsPerPoint());
2281 // build the data URL
2282 this.data_url = this.host + this.chart.data_url;
2283 this.data_url += "&format=" + this.library.format();
2284 this.data_url += "&points=" + (this.data_points * points_multiplier).toString();
2285 this.data_url += "&group=" + this.method;
2286 this.data_url += "&options=" + this.library.options(this);
2287 this.data_url += '|jsonwrap';
2289 if(NETDATA.options.current.eliminate_zero_dimensions === true)
2290 this.data_url += '|nonzero';
2292 if(this.append_options !== null)
2293 this.data_url += '|' + this.append_options.toString();
2296 this.data_url += "&after=" + after.toString();
2299 this.data_url += "&before=" + before.toString();
2302 this.data_url += "&dimensions=" + this.dimensions;
2304 if(NETDATA.options.debug.chart_data_url === true || this.debug === true)
2305 this.log('chartURL(): ' + this.data_url + ' WxH:' + this.chartWidth() + 'x' + this.chartHeight() + ' points: ' + this.data_points + ' library: ' + this.library_name);
2308 this.redrawChart = function() {
2309 if(this.data !== null)
2310 this.updateChartWithData(this.data);
2313 this.updateChartWithData = function(data) {
2314 if(this.debug === true)
2315 this.log('updateChartWithData() called.');
2317 this._updating = false;
2319 // this may force the chart to be re-created
2323 this.updates_counter++;
2324 this.updates_since_last_unhide++;
2325 this.updates_since_last_creation++;
2327 var started = new Date().getTime();
2329 // if the result is JSON, find the latest update-every
2330 this.data_update_every = data.view_update_every * 1000;
2331 this.data_after = data.after * 1000;
2332 this.data_before = data.before * 1000;
2333 this.netdata_first = data.first_entry * 1000;
2334 this.netdata_last = data.last_entry * 1000;
2335 this.data_points = data.points;
2338 if(NETDATA.options.current.pan_and_zoom_data_padding === true && this.requested_padding !== null) {
2339 if(this.view_after < this.data_after) {
2340 // console.log('adusting view_after from ' + this.view_after + ' to ' + this.data_after);
2341 this.view_after = this.data_after;
2344 if(this.view_before > this.data_before) {
2345 // console.log('adusting view_before from ' + this.view_before + ' to ' + this.data_before);
2346 this.view_before = this.data_before;
2350 this.view_after = this.data_after;
2351 this.view_before = this.data_before;
2354 if(this.debug === true) {
2355 this.log('UPDATE No ' + this.updates_counter + ' COMPLETED');
2357 if(this.current.force_after_ms)
2358 this.log('STATUS: forced : ' + (this.current.force_after_ms / 1000).toString() + ' - ' + (this.current.force_before_ms / 1000).toString());
2360 this.log('STATUS: forced : unset');
2362 this.log('STATUS: requested : ' + (this.requested_after / 1000).toString() + ' - ' + (this.requested_before / 1000).toString());
2363 this.log('STATUS: downloaded: ' + (this.data_after / 1000).toString() + ' - ' + (this.data_before / 1000).toString());
2364 this.log('STATUS: rendered : ' + (this.view_after / 1000).toString() + ' - ' + (this.view_before / 1000).toString());
2365 this.log('STATUS: points : ' + (this.data_points).toString());
2368 if(this.data_points === 0) {
2373 if(this.updates_since_last_creation >= this.library.max_updates_to_recreate()) {
2374 if(this.debug === true)
2375 this.log('max updates of ' + this.updates_since_last_creation.toString() + ' reached. Forcing re-generation.');
2377 this.chart_created = false;
2380 // check and update the legend
2381 this.legendUpdateDOM();
2383 if(this.chart_created === true
2384 && typeof this.library.update === 'function') {
2386 if(this.debug === true)
2387 this.log('updating chart...');
2389 if(callChartLibraryUpdateSafely(data) === false)
2393 if(this.debug === true)
2394 this.log('creating chart...');
2396 if(callChartLibraryCreateSafely(data) === false)
2400 this.legendShowLatestValues();
2401 if(this.selected === true)
2402 NETDATA.globalSelectionSync.stop();
2404 // update the performance counters
2405 var now = new Date().getTime();
2406 this.tm.last_updated = now;
2408 // don't update last_autorefreshed if this chart is
2409 // forced to be updated with global PanAndZoom
2410 if(NETDATA.globalPanAndZoom.isActive())
2411 this.tm.last_autorefreshed = 0;
2413 if(NETDATA.options.current.parallel_refresher === true && NETDATA.options.current.concurrent_refreshes)
2414 this.tm.last_autorefreshed = Math.round(now / this.data_update_every) * this.data_update_every;
2416 this.tm.last_autorefreshed = now;
2419 this.refresh_dt_ms = now - started;
2420 NETDATA.options.auto_refresher_fast_weight += this.refresh_dt_ms;
2422 if(this.refresh_dt_element !== null)
2423 this.refresh_dt_element.innerHTML = this.refresh_dt_ms.toString();
2426 this.updateChart = function(callback) {
2427 if(this.debug === true)
2428 this.log('updateChart() called.');
2430 if(this._updating === true) {
2431 if(this.debug === true)
2432 this.log('I am already updating...');
2434 if(typeof callback === 'function') callback();
2438 // due to late initialization of charts and libraries
2439 // we need to check this too
2440 if(this.enabled === false) {
2441 if(this.debug === true)
2442 this.log('I am not enabled');
2444 if(typeof callback === 'function') callback();
2448 if(canBeRendered() === false) {
2449 if(typeof callback === 'function') callback();
2453 if(this.chart === null) {
2454 this.getChart(function() { that.updateChart(callback); });
2458 if(this.library.initialized === false) {
2459 if(this.library.enabled === true) {
2460 this.library.initialize(function() { that.updateChart(callback); });
2464 error('chart library "' + this.library_name + '" is not available.');
2465 if(typeof callback === 'function') callback();
2470 this.clearSelection();
2473 if(this.debug === true)
2474 this.log('updating from ' + this.data_url);
2476 this._updating = true;
2478 this.xhr = $.ajax( {
2480 crossDomain: NETDATA.options.crossDomainAjax,
2484 .success(function(data) {
2485 if(that.debug === true)
2486 that.log('data received. updating chart.');
2488 that.updateChartWithData(data);
2491 error('data download failed for url: ' + that.data_url);
2493 .always(function() {
2494 this._updating = false;
2495 if(typeof callback === 'function') callback();
2501 this.isVisible = function(nocache) {
2502 if(typeof nocache === 'undefined')
2505 // this.log('last_visible_check: ' + this.tm.last_visible_check + ', last_page_scroll: ' + NETDATA.options.last_page_scroll);
2507 // caching - we do not evaluate the charts visibility
2508 // if the page has not been scrolled since the last check
2509 if(nocache === false && this.tm.last_visible_check > NETDATA.options.last_page_scroll)
2510 return this.___isVisible___;
2512 this.tm.last_visible_check = new Date().getTime();
2514 var wh = window.innerHeight;
2515 var x = this.element.getBoundingClientRect();
2519 if(x.width === 0 || x.height === 0) {
2521 this.___isVisible___ = false;
2522 return this.___isVisible___;
2525 if(x.top < 0 && -x.top > x.height) {
2526 // the chart is entirely above
2527 ret = -x.top - x.height;
2529 else if(x.top > wh) {
2530 // the chart is entirely below
2534 if(ret > tolerance) {
2535 // the chart is too far
2538 this.___isVisible___ = false;
2539 return this.___isVisible___;
2542 // the chart is inside or very close
2545 this.___isVisible___ = true;
2546 return this.___isVisible___;
2550 this.isAutoRefreshed = function() {
2551 return (this.current.autorefresh);
2554 this.canBeAutoRefreshed = function() {
2555 now = new Date().getTime();
2557 if(this.enabled === false) {
2558 if(this.debug === true)
2559 this.log('I am not enabled');
2564 if(this.library === null || this.library.enabled === false) {
2565 error('charting library "' + this.library_name + '" is not available');
2566 if(this.debug === true)
2567 this.log('My chart library ' + this.library_name + ' is not available');
2572 if(this.isVisible() === false) {
2573 if(NETDATA.options.debug.visibility === true || this.debug === true)
2574 this.log('I am not visible');
2579 if(this.current.force_update_at !== 0 && this.current.force_update_at < now) {
2580 if(this.debug === true)
2581 this.log('timed force update detected - allowing this update');
2583 this.current.force_update_at = 0;
2587 if(this.isAutoRefreshed() === true) {
2588 // allow the first update, even if the page is not visible
2589 if(this.updates_counter && this.updates_since_last_unhide && NETDATA.options.page_is_visible === false) {
2590 if(NETDATA.options.debug.focus === true || this.debug === true)
2591 this.log('canBeAutoRefreshed(): page does not have focus');
2596 if(this.needsRecreation() === true) {
2597 if(this.debug === true)
2598 this.log('canBeAutoRefreshed(): needs re-creation.');
2603 // options valid only for autoRefresh()
2604 if(NETDATA.options.auto_refresher_stop_until === 0 || NETDATA.options.auto_refresher_stop_until < now) {
2605 if(NETDATA.globalPanAndZoom.isActive()) {
2606 if(NETDATA.globalPanAndZoom.shouldBeAutoRefreshed(this)) {
2607 if(this.debug === true)
2608 this.log('canBeAutoRefreshed(): global panning: I need an update.');
2613 if(this.debug === true)
2614 this.log('canBeAutoRefreshed(): global panning: I am already up to date.');
2620 if(this.selected === true) {
2621 if(this.debug === true)
2622 this.log('canBeAutoRefreshed(): I have a selection in place.');
2627 if(this.paused === true) {
2628 if(this.debug === true)
2629 this.log('canBeAutoRefreshed(): I am paused.');
2634 if(now - this.tm.last_autorefreshed >= this.data_update_every) {
2635 if(this.debug === true)
2636 this.log('canBeAutoRefreshed(): It is time to update me.');
2646 this.autoRefresh = function(callback) {
2647 if(this.canBeAutoRefreshed() === true) {
2648 this.updateChart(callback);
2651 if(typeof callback !== 'undefined')
2656 this._defaultsFromDownloadedChart = function(chart) {
2658 this.chart_url = chart.url;
2659 this.data_update_every = chart.update_every * 1000;
2660 this.data_points = Math.round(this.chartWidth() / this.chartPixelsPerPoint());
2661 this.tm.last_info_downloaded = new Date().getTime();
2663 if(this.title === null)
2664 this.title = chart.title;
2666 if(this.units === null)
2667 this.units = chart.units;
2670 // fetch the chart description from the netdata server
2671 this.getChart = function(callback) {
2672 this.chart = NETDATA.chartRegistry.get(this.host, this.id);
2674 this._defaultsFromDownloadedChart(this.chart);
2675 if(typeof callback === 'function') callback();
2678 this.chart_url = "/api/v1/chart?chart=" + this.id;
2680 if(this.debug === true)
2681 this.log('downloading ' + this.chart_url);
2684 url: this.host + this.chart_url,
2685 crossDomain: NETDATA.options.crossDomainAjax,
2689 .done(function(chart) {
2690 chart.url = that.chart_url;
2691 that._defaultsFromDownloadedChart(chart);
2692 NETDATA.chartRegistry.add(that.host, that.id, chart);
2695 NETDATA.error(404, that.chart_url);
2696 error('chart not found on url "' + that.chart_url + '"');
2698 .always(function() {
2699 if(typeof callback === 'function') callback();
2704 // ============================================================================================================
2710 NETDATA.resetAllCharts = function(state) {
2711 // first clear the global selection sync
2712 // to make sure no chart is in selected state
2713 state.globalSelectionSyncStop();
2715 // there are 2 possibilities here
2716 // a. state is the global Pan and Zoom master
2717 // b. state is not the global Pan and Zoom master
2719 if(NETDATA.globalPanAndZoom.isMaster(state) === false)
2722 // clear the global Pan and Zoom
2723 // this will also refresh the master
2724 // and unblock any charts currently mirroring the master
2725 NETDATA.globalPanAndZoom.clearMaster();
2727 // if we were not the master, reset our status too
2728 // this is required because most probably the mouse
2729 // is over this chart, blocking it from autorefreshing
2730 if(master === false && (state.paused === true || state.selected === true))
2734 // get or create a chart state, given a DOM element
2735 NETDATA.chartState = function(element) {
2736 var state = $(element).data('netdata-state-object') || null;
2737 if(state === null) {
2738 state = new chartState(element);
2739 $(element).data('netdata-state-object', state);
2744 // ----------------------------------------------------------------------------------------------------------------
2745 // Library functions
2747 // Load a script without jquery
2748 // This is used to load jquery - after it is loaded, we use jquery
2749 NETDATA._loadjQuery = function(callback) {
2750 if(typeof jQuery === 'undefined') {
2751 if(NETDATA.options.debug.main_loop === true)
2752 console.log('loading ' + NETDATA.jQuery);
2754 var script = document.createElement('script');
2755 script.type = 'text/javascript';
2756 script.async = true;
2757 script.src = NETDATA.jQuery;
2759 // script.onabort = onError;
2760 script.onerror = function(err, t) { NETDATA.error(101, NETDATA.jQuery); };
2761 if(typeof callback === "function")
2762 script.onload = callback;
2764 var s = document.getElementsByTagName('script')[0];
2765 s.parentNode.insertBefore(script, s);
2767 else if(typeof callback === "function")
2771 NETDATA._loadCSS = function(filename) {
2772 // don't use jQuery here
2773 // styles are loaded before jQuery
2774 // to eliminate showing an unstyled page to the user
2776 var fileref = document.createElement("link");
2777 fileref.setAttribute("rel", "stylesheet");
2778 fileref.setAttribute("type", "text/css");
2779 fileref.setAttribute("href", filename);
2781 if (typeof fileref !== 'undefined')
2782 document.getElementsByTagName("head")[0].appendChild(fileref);
2785 NETDATA.colorHex2Rgb = function(hex) {
2786 // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
2787 var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
2788 hex = hex.replace(shorthandRegex, function(m, r, g, b) {
2789 return r + r + g + g + b + b;
2792 var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
2794 r: parseInt(result[1], 16),
2795 g: parseInt(result[2], 16),
2796 b: parseInt(result[3], 16)
2800 NETDATA.colorLuminance = function(hex, lum) {
2801 // validate hex string
2802 hex = String(hex).replace(/[^0-9a-f]/gi, '');
2804 hex = hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2];
2808 // convert to decimal and change luminosity
2809 var rgb = "#", c, i;
2810 for (i = 0; i < 3; i++) {
2811 c = parseInt(hex.substr(i*2,2), 16);
2812 c = Math.round(Math.min(Math.max(0, c + (c * lum)), 255)).toString(16);
2813 rgb += ("00"+c).substr(c.length);
2819 NETDATA.guid = function() {
2821 return Math.floor((1 + Math.random()) * 0x10000)
2826 return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
2829 NETDATA.zeropad = function(x) {
2830 if(x > -10 && x < 10) return '0' + x.toString();
2831 else return x.toString();
2834 // user function to signal us the DOM has been
2836 NETDATA.updatedDom = function() {
2837 NETDATA.options.updated_dom = true;
2840 NETDATA.ready = function(callback) {
2841 NETDATA.options.pauseCallback = callback;
2844 NETDATA.pause = function(callback) {
2845 if(NETDATA.options.pause === true)
2848 NETDATA.options.pauseCallback = callback;
2851 NETDATA.unpause = function() {
2852 NETDATA.options.pauseCallback = null;
2853 NETDATA.options.updated_dom = true;
2854 NETDATA.options.pause = false;
2857 // ----------------------------------------------------------------------------------------------------------------
2859 // this is purely sequencial charts refresher
2860 // it is meant to be autonomous
2861 NETDATA.chartRefresherNoParallel = function(index) {
2862 if(NETDATA.options.debug.mail_loop === true)
2863 console.log('NETDATA.chartRefresherNoParallel(' + index + ')');
2865 if(NETDATA.options.updated_dom === true) {
2866 // the dom has been updated
2867 // get the dom parts again
2868 NETDATA.parseDom(NETDATA.chartRefresher);
2871 if(index >= NETDATA.options.targets.length) {
2872 if(NETDATA.options.debug.main_loop === true)
2873 console.log('waiting to restart main loop...');
2875 NETDATA.options.auto_refresher_fast_weight = 0;
2877 setTimeout(function() {
2878 NETDATA.chartRefresher();
2879 }, NETDATA.options.current.idle_between_loops);
2882 var state = NETDATA.options.targets[index];
2884 if(NETDATA.options.auto_refresher_fast_weight < NETDATA.options.current.fast_render_timeframe) {
2885 if(NETDATA.options.debug.main_loop === true)
2886 console.log('fast rendering...');
2888 state.autoRefresh(function() {
2889 NETDATA.chartRefresherNoParallel(++index);
2893 if(NETDATA.options.debug.main_loop === true) console.log('waiting for next refresh...');
2894 NETDATA.options.auto_refresher_fast_weight = 0;
2896 setTimeout(function() {
2897 state.autoRefresh(function() {
2898 NETDATA.chartRefresherNoParallel(++index);
2900 }, NETDATA.options.current.idle_between_charts);
2905 // this is part of the parallel refresher
2906 // its cause is to refresh sequencially all the charts
2907 // that depend on chart library initialization
2908 // it will call the parallel refresher back
2909 // as soon as it sees a chart that its chart library
2911 NETDATA.chartRefresher_unitialized = function() {
2912 if(NETDATA.options.updated_dom === true) {
2913 // the dom has been updated
2914 // get the dom parts again
2915 NETDATA.parseDom(NETDATA.chartRefresher);
2919 if(NETDATA.options.sequencial.length === 0)
2920 NETDATA.chartRefresher();
2922 var state = NETDATA.options.sequencial.pop();
2923 if(state.library.initialized === true)
2924 NETDATA.chartRefresher();
2926 state.autoRefresh(NETDATA.chartRefresher_unitialized);
2930 NETDATA.chartRefresherWaitTime = function() {
2931 return NETDATA.options.current.idle_parallel_loops;
2934 // the default refresher
2935 // it will create 2 sets of charts:
2936 // - the ones that can be refreshed in parallel
2937 // - the ones that depend on something else
2938 // the first set will be executed in parallel
2939 // the second will be given to NETDATA.chartRefresher_unitialized()
2940 NETDATA.chartRefresher = function() {
2941 if(NETDATA.options.pause === true) {
2942 // console.log('auto-refresher is paused');
2943 setTimeout(NETDATA.chartRefresher,
2944 NETDATA.chartRefresherWaitTime());
2948 if(typeof NETDATA.options.pauseCallback === 'function') {
2949 // console.log('auto-refresher is calling pauseCallback');
2950 NETDATA.options.pause = true;
2951 NETDATA.options.pauseCallback();
2952 NETDATA.chartRefresher();
2956 if(NETDATA.options.current.parallel_refresher === false) {
2957 NETDATA.chartRefresherNoParallel(0);
2961 if(NETDATA.options.updated_dom === true) {
2962 // the dom has been updated
2963 // get the dom parts again
2964 NETDATA.parseDom(NETDATA.chartRefresher);
2968 var parallel = new Array();
2969 var targets = NETDATA.options.targets;
2970 var len = targets.length;
2972 if(targets[len].isVisible() === false)
2975 var state = targets[len];
2976 if(state.library.initialized === false) {
2977 if(state.library.enabled === true) {
2978 state.library.initialize(NETDATA.chartRefresher);
2982 state.error('chart library "' + state.library_name + '" is not enabled.');
2986 parallel.unshift(state);
2989 if(parallel.length > 0) {
2990 var parallel_jobs = parallel.length;
2992 // this will execute the jobs in parallel
2993 $(parallel).each(function() {
2994 this.autoRefresh(function() {
2997 if(parallel_jobs === 0) {
2998 setTimeout(NETDATA.chartRefresher,
2999 NETDATA.chartRefresherWaitTime());
3005 setTimeout(NETDATA.chartRefresher,
3006 NETDATA.chartRefresherWaitTime());
3010 NETDATA.parseDom = function(callback) {
3011 NETDATA.options.last_page_scroll = new Date().getTime();
3012 NETDATA.options.updated_dom = false;
3014 var targets = $('div[data-netdata]'); //.filter(':visible');
3016 if(NETDATA.options.debug.main_loop === true)
3017 console.log('DOM updated - there are ' + targets.length + ' charts on page.');
3019 NETDATA.options.targets = new Array();
3020 var len = targets.length;
3022 // the initialization will take care of sizing
3023 // and the "loading..." message
3024 NETDATA.options.targets.push(NETDATA.chartState(targets[len]));
3027 if(typeof callback === 'function') callback();
3030 // this is the main function - where everything starts
3031 NETDATA.start = function() {
3032 // this should be called only once
3034 NETDATA.options.page_is_visible = true;
3036 $(window).blur(function() {
3037 if(NETDATA.options.current.stop_updates_when_focus_is_lost === true) {
3038 NETDATA.options.page_is_visible = false;
3039 if(NETDATA.options.debug.focus === true)
3040 console.log('Lost Focus!');
3044 $(window).focus(function() {
3045 if(NETDATA.options.current.stop_updates_when_focus_is_lost === true) {
3046 NETDATA.options.page_is_visible = true;
3047 if(NETDATA.options.debug.focus === true)
3048 console.log('Focus restored!');
3052 if(typeof document.hasFocus === 'function' && !document.hasFocus()) {
3053 if(NETDATA.options.current.stop_updates_when_focus_is_lost === true) {
3054 NETDATA.options.page_is_visible = false;
3055 if(NETDATA.options.debug.focus === true)
3056 console.log('Document has no focus!');
3060 // bootstrap tab switching
3061 $('a[data-toggle="tab"]').on('shown.bs.tab', NETDATA.onscroll);
3063 // bootstrap modal switching
3064 $('.modal').on('hidden.bs.modal', NETDATA.onscroll);
3065 $('.modal').on('shown.bs.modal', NETDATA.onscroll);
3067 NETDATA.parseDom(NETDATA.chartRefresher);
3070 // ----------------------------------------------------------------------------------------------------------------
3073 NETDATA.peityInitialize = function(callback) {
3074 if(typeof netdataNoPeitys === 'undefined' || !netdataNoPeitys) {
3076 url: NETDATA.peity_js,
3081 NETDATA.registerChartLibrary('peity', NETDATA.peity_js);
3084 NETDATA.chartLibraries.peity.enabled = false;
3085 NETDATA.error(100, NETDATA.peity_js);
3087 .always(function() {
3088 if(typeof callback === "function")
3093 NETDATA.chartLibraries.peity.enabled = false;
3094 if(typeof callback === "function")
3099 NETDATA.peityChartUpdate = function(state, data) {
3100 state.peity_instance.innerHTML = data.result;
3102 if(state.peity_options.stroke !== state.chartColors()[0]) {
3103 state.peity_options.stroke = state.chartColors()[0];
3104 if(state.chart.chart_type === 'line')
3105 state.peity_options.fill = '#FFF';
3107 state.peity_options.fill = NETDATA.colorLuminance(state.chartColors()[0], NETDATA.chartDefaults.fill_luminance);
3110 $(state.peity_instance).peity('line', state.peity_options);
3114 NETDATA.peityChartCreate = function(state, data) {
3115 state.peity_instance = document.createElement('div');
3116 state.element_chart.appendChild(state.peity_instance);
3118 var self = $(state.element);
3119 state.peity_options = {
3121 strokeWidth: self.data('peity-strokewidth') || 1,
3122 width: state.chartWidth(),
3123 height: state.chartHeight(),
3127 NETDATA.peityChartUpdate(state, data);
3131 // ----------------------------------------------------------------------------------------------------------------
3134 NETDATA.sparklineInitialize = function(callback) {
3135 if(typeof netdataNoSparklines === 'undefined' || !netdataNoSparklines) {
3137 url: NETDATA.sparkline_js,
3142 NETDATA.registerChartLibrary('sparkline', NETDATA.sparkline_js);
3145 NETDATA.chartLibraries.sparkline.enabled = false;
3146 NETDATA.error(100, NETDATA.sparkline_js);
3148 .always(function() {
3149 if(typeof callback === "function")
3154 NETDATA.chartLibraries.sparkline.enabled = false;
3155 if(typeof callback === "function")
3160 NETDATA.sparklineChartUpdate = function(state, data) {
3161 state.sparkline_options.width = state.chartWidth();
3162 state.sparkline_options.height = state.chartHeight();
3164 $(state.element_chart).sparkline(data.result, state.sparkline_options);
3168 NETDATA.sparklineChartCreate = function(state, data) {
3169 var self = $(state.element);
3170 var type = self.data('sparkline-type') || 'line';
3171 var lineColor = self.data('sparkline-linecolor') || state.chartColors()[0];
3172 var fillColor = self.data('sparkline-fillcolor') || (state.chart.chart_type === 'line')?'#FFF':NETDATA.colorLuminance(lineColor, NETDATA.chartDefaults.fill_luminance);
3173 var chartRangeMin = self.data('sparkline-chartrangemin') || undefined;
3174 var chartRangeMax = self.data('sparkline-chartrangemax') || undefined;
3175 var composite = self.data('sparkline-composite') || undefined;
3176 var enableTagOptions = self.data('sparkline-enabletagoptions') || undefined;
3177 var tagOptionPrefix = self.data('sparkline-tagoptionprefix') || undefined;
3178 var tagValuesAttribute = self.data('sparkline-tagvaluesattribute') || undefined;
3179 var disableHiddenCheck = self.data('sparkline-disablehiddencheck') || undefined;
3180 var defaultPixelsPerValue = self.data('sparkline-defaultpixelspervalue') || undefined;
3181 var spotColor = self.data('sparkline-spotcolor') || undefined;
3182 var minSpotColor = self.data('sparkline-minspotcolor') || undefined;
3183 var maxSpotColor = self.data('sparkline-maxspotcolor') || undefined;
3184 var spotRadius = self.data('sparkline-spotradius') || undefined;
3185 var valueSpots = self.data('sparkline-valuespots') || undefined;
3186 var highlightSpotColor = self.data('sparkline-highlightspotcolor') || undefined;
3187 var highlightLineColor = self.data('sparkline-highlightlinecolor') || undefined;
3188 var lineWidth = self.data('sparkline-linewidth') || undefined;
3189 var normalRangeMin = self.data('sparkline-normalrangemin') || undefined;
3190 var normalRangeMax = self.data('sparkline-normalrangemax') || undefined;
3191 var drawNormalOnTop = self.data('sparkline-drawnormalontop') || undefined;
3192 var xvalues = self.data('sparkline-xvalues') || undefined;
3193 var chartRangeClip = self.data('sparkline-chartrangeclip') || undefined;
3194 var xvalues = self.data('sparkline-xvalues') || undefined;
3195 var chartRangeMinX = self.data('sparkline-chartrangeminx') || undefined;
3196 var chartRangeMaxX = self.data('sparkline-chartrangemaxx') || undefined;
3197 var disableInteraction = self.data('sparkline-disableinteraction') || false;
3198 var disableTooltips = self.data('sparkline-disabletooltips') || false;
3199 var disableHighlight = self.data('sparkline-disablehighlight') || false;
3200 var highlightLighten = self.data('sparkline-highlightlighten') || 1.4;
3201 var highlightColor = self.data('sparkline-highlightcolor') || undefined;
3202 var tooltipContainer = self.data('sparkline-tooltipcontainer') || undefined;
3203 var tooltipClassname = self.data('sparkline-tooltipclassname') || undefined;
3204 var tooltipFormat = self.data('sparkline-tooltipformat') || undefined;
3205 var tooltipPrefix = self.data('sparkline-tooltipprefix') || undefined;
3206 var tooltipSuffix = self.data('sparkline-tooltipsuffix') || ' ' + state.units;
3207 var tooltipSkipNull = self.data('sparkline-tooltipskipnull') || true;
3208 var tooltipValueLookups = self.data('sparkline-tooltipvaluelookups') || undefined;
3209 var tooltipFormatFieldlist = self.data('sparkline-tooltipformatfieldlist') || undefined;
3210 var tooltipFormatFieldlistKey = self.data('sparkline-tooltipformatfieldlistkey') || undefined;
3211 var numberFormatter = self.data('sparkline-numberformatter') || function(n){ return n.toFixed(2); };
3212 var numberDigitGroupSep = self.data('sparkline-numberdigitgroupsep') || undefined;
3213 var numberDecimalMark = self.data('sparkline-numberdecimalmark') || undefined;
3214 var numberDigitGroupCount = self.data('sparkline-numberdigitgroupcount') || undefined;
3215 var animatedZooms = self.data('sparkline-animatedzooms') || false;
3217 state.sparkline_options = {
3219 lineColor: lineColor,
3220 fillColor: fillColor,
3221 chartRangeMin: chartRangeMin,
3222 chartRangeMax: chartRangeMax,
3223 composite: composite,
3224 enableTagOptions: enableTagOptions,
3225 tagOptionPrefix: tagOptionPrefix,
3226 tagValuesAttribute: tagValuesAttribute,
3227 disableHiddenCheck: disableHiddenCheck,
3228 defaultPixelsPerValue: defaultPixelsPerValue,
3229 spotColor: spotColor,
3230 minSpotColor: minSpotColor,
3231 maxSpotColor: maxSpotColor,
3232 spotRadius: spotRadius,
3233 valueSpots: valueSpots,
3234 highlightSpotColor: highlightSpotColor,
3235 highlightLineColor: highlightLineColor,
3236 lineWidth: lineWidth,
3237 normalRangeMin: normalRangeMin,
3238 normalRangeMax: normalRangeMax,
3239 drawNormalOnTop: drawNormalOnTop,
3241 chartRangeClip: chartRangeClip,
3242 chartRangeMinX: chartRangeMinX,
3243 chartRangeMaxX: chartRangeMaxX,
3244 disableInteraction: disableInteraction,
3245 disableTooltips: disableTooltips,
3246 disableHighlight: disableHighlight,
3247 highlightLighten: highlightLighten,
3248 highlightColor: highlightColor,
3249 tooltipContainer: tooltipContainer,
3250 tooltipClassname: tooltipClassname,
3251 tooltipChartTitle: state.title,
3252 tooltipFormat: tooltipFormat,
3253 tooltipPrefix: tooltipPrefix,
3254 tooltipSuffix: tooltipSuffix,
3255 tooltipSkipNull: tooltipSkipNull,
3256 tooltipValueLookups: tooltipValueLookups,
3257 tooltipFormatFieldlist: tooltipFormatFieldlist,
3258 tooltipFormatFieldlistKey: tooltipFormatFieldlistKey,
3259 numberFormatter: numberFormatter,
3260 numberDigitGroupSep: numberDigitGroupSep,
3261 numberDecimalMark: numberDecimalMark,
3262 numberDigitGroupCount: numberDigitGroupCount,
3263 animatedZooms: animatedZooms,
3264 width: state.chartWidth(),
3265 height: state.chartHeight()
3268 $(state.element_chart).sparkline(data.result, state.sparkline_options);
3272 // ----------------------------------------------------------------------------------------------------------------
3279 NETDATA.dygraphSetSelection = function(state, t) {
3280 if(typeof state.dygraph_instance !== 'undefined') {
3281 var r = state.calculateRowForTime(t);
3283 state.dygraph_instance.setSelection(r);
3285 state.dygraph_instance.clearSelection();
3286 state.legendShowUndefined();
3293 NETDATA.dygraphClearSelection = function(state, t) {
3294 if(typeof state.dygraph_instance !== 'undefined') {
3295 state.dygraph_instance.clearSelection();
3300 NETDATA.dygraphSmoothInitialize = function(callback) {
3302 url: NETDATA.dygraph_smooth_js,
3307 NETDATA.dygraph.smooth = true;
3308 smoothPlotter.smoothing = 0.3;
3311 NETDATA.dygraph.smooth = false;
3313 .always(function() {
3314 if(typeof callback === "function")
3319 NETDATA.dygraphInitialize = function(callback) {
3320 if(typeof netdataNoDygraphs === 'undefined' || !netdataNoDygraphs) {
3322 url: NETDATA.dygraph_js,
3327 NETDATA.registerChartLibrary('dygraph', NETDATA.dygraph_js);
3330 NETDATA.chartLibraries.dygraph.enabled = false;
3331 NETDATA.error(100, NETDATA.dygraph_js);
3333 .always(function() {
3334 if(NETDATA.chartLibraries.dygraph.enabled === true && NETDATA.options.current.smooth_plot === true)
3335 NETDATA.dygraphSmoothInitialize(callback);
3336 else if(typeof callback === "function")
3341 NETDATA.chartLibraries.dygraph.enabled = false;
3342 if(typeof callback === "function")
3347 NETDATA.dygraphChartUpdate = function(state, data) {
3348 var dygraph = state.dygraph_instance;
3350 if(typeof dygraph === 'undefined')
3351 return NETDATA.dygraphChartCreate(state, data);
3353 // when the chart is not visible, and hidden
3354 // if there is a window resize, dygraph detects
3355 // its element size as 0x0.
3356 // this will make it re-appear properly
3358 if(state.tm.last_unhidden > state.dygraph_last_rendered)
3362 file: data.result.data,
3363 colors: state.chartColors(),
3364 labels: data.result.labels,
3365 labelsDivWidth: state.chartWidth() - 70,
3366 visibility: state.dimensions_visibility.selected2BooleanArray(state.data.dimension_names)
3369 if(state.dygraph_force_zoom === true) {
3370 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3371 state.log('dygraphChartUpdate() forced zoom update');
3373 options.dateWindow = (state.requested_padding !== null)?[ state.view_after, state.view_before ]:null;
3374 options.valueRange = null;
3375 options.isZoomedIgnoreProgrammaticZoom = true;
3376 state.dygraph_force_zoom = false;
3378 else if(state.current.name !== 'auto') {
3379 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3380 state.log('dygraphChartUpdate() loose update');
3383 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3384 state.log('dygraphChartUpdate() strict update');
3386 options.dateWindow = (state.requested_padding !== null)?[ state.view_after, state.view_before ]:null;
3387 options.valueRange = null;
3388 options.isZoomedIgnoreProgrammaticZoom = true;
3391 if(state.dygraph_smooth_eligible === true) {
3392 if((NETDATA.options.current.smooth_plot === true && state.dygraph_options.plotter !== smoothPlotter)
3393 || (NETDATA.options.current.smooth_plot === false && state.dygraph_options.plotter === smoothPlotter)) {
3394 NETDATA.dygraphChartCreate(state, data);
3399 dygraph.updateOptions(options);
3401 state.dygraph_last_rendered = new Date().getTime();
3405 NETDATA.dygraphChartCreate = function(state, data) {
3406 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3407 state.log('dygraphChartCreate()');
3409 var self = $(state.element);
3411 var chart_type = state.chart.chart_type;
3412 if(chart_type === 'stacked' && data.dimensions === 1) chart_type = 'area';
3413 chart_type = self.data('dygraph-type') || chart_type;
3415 var smooth = (chart_type === 'line' && !NETDATA.chartLibraries.dygraph.isSparkline(state))?true:false;
3416 smooth = self.data('dygraph-smooth') || smooth;
3418 if(NETDATA.dygraph.smooth === false)
3421 var strokeWidth = (chart_type === 'stacked')?0.1:((smooth)?1.5:0.7)
3422 var highlightCircleSize = (NETDATA.chartLibraries.dygraph.isSparkline(state))?3:4;
3424 state.dygraph_options = {
3425 colors: self.data('dygraph-colors') || state.chartColors(),
3427 // leave a few pixels empty on the right of the chart
3428 rightGap: self.data('dygraph-rightgap') || 5,
3429 showRangeSelector: self.data('dygraph-showrangeselector') || false,
3430 showRoller: self.data('dygraph-showroller') || false,
3432 title: self.data('dygraph-title') || state.title,
3433 titleHeight: self.data('dygraph-titleheight') || 19,
3435 legend: self.data('dygraph-legend') || 'always', // 'onmouseover',
3436 labels: data.result.labels,
3437 labelsDiv: self.data('dygraph-labelsdiv') || state.element_legend_childs.hidden,
3438 labelsDivStyles: self.data('dygraph-labelsdivstyles') || { 'fontSize':'1px' },
3439 labelsDivWidth: self.data('dygraph-labelsdivwidth') || state.chartWidth() - 70,
3440 labelsSeparateLines: self.data('dygraph-labelsseparatelines') || true,
3441 labelsShowZeroValues: self.data('dygraph-labelsshowzerovalues') || true,
3444 showLabelsOnHighlight: self.data('dygraph-showlabelsonhighlight') || true,
3445 hideOverlayOnMouseOut: self.data('dygraph-hideoverlayonmouseout') || true,
3447 ylabel: state.units,
3448 yLabelWidth: self.data('dygraph-ylabelwidth') || 12,
3450 // the function to plot the chart
3453 // The width of the lines connecting data points. This can be used to increase the contrast or some graphs.
3454 strokeWidth: self.data('dygraph-strokewidth') || strokeWidth,
3455 strokePattern: self.data('dygraph-strokepattern') || undefined,
3457 // The size of the dot to draw on each point in pixels (see drawPoints). A dot is always drawn when a point is "isolated",
3458 // i.e. there is a missing point on either side of it. This also controls the size of those dots.
3459 drawPoints: self.data('dygraph-drawpoints') || false,
3461 // Draw points at the edges of gaps in the data. This improves visibility of small data segments or other data irregularities.
3462 drawGapEdgePoints: self.data('dygraph-drawgapedgepoints') || true,
3464 connectSeparatedPoints: self.data('dygraph-connectseparatedpoints') || false,
3465 pointSize: self.data('dygraph-pointsize') || 1,
3467 // enabling this makes the chart with little square lines
3468 stepPlot: self.data('dygraph-stepplot') || false,
3470 // Draw a border around graph lines to make crossing lines more easily distinguishable. Useful for graphs with many lines.
3471 strokeBorderColor: self.data('dygraph-strokebordercolor') || 'white',
3472 strokeBorderWidth: self.data('dygraph-strokeborderwidth') || (chart_type === 'stacked')?0.0:0.0,
3474 fillGraph: self.data('dygraph-fillgraph') || (chart_type === 'area' || chart_type === 'stacked')?true:false,
3475 fillAlpha: self.data('dygraph-fillalpha') || (chart_type === 'stacked')?NETDATA.options.current.color_fill_opacity_stacked:NETDATA.options.current.color_fill_opacity_area,
3476 stackedGraph: self.data('dygraph-stackedgraph') || (chart_type === 'stacked')?true:false,
3477 stackedGraphNaNFill: self.data('dygraph-stackedgraphnanfill') || 'none',
3479 drawAxis: self.data('dygraph-drawaxis') || true,
3480 axisLabelFontSize: self.data('dygraph-axislabelfontsize') || 10,
3481 axisLineColor: self.data('dygraph-axislinecolor') || '#CCC',
3482 axisLineWidth: self.data('dygraph-axislinewidth') || 0.3,
3484 drawGrid: self.data('dygraph-drawgrid') || true,
3485 drawXGrid: self.data('dygraph-drawxgrid') || undefined,
3486 drawYGrid: self.data('dygraph-drawygrid') || undefined,
3487 gridLinePattern: self.data('dygraph-gridlinepattern') || null,
3488 gridLineWidth: self.data('dygraph-gridlinewidth') || 0.3,
3489 gridLineColor: self.data('dygraph-gridlinecolor') || '#DDD',
3491 maxNumberWidth: self.data('dygraph-maxnumberwidth') || 8,
3492 sigFigs: self.data('dygraph-sigfigs') || null,
3493 digitsAfterDecimal: self.data('dygraph-digitsafterdecimal') || 2,
3494 valueFormatter: self.data('dygraph-valueformatter') || function(x){ return x.toFixed(2); },
3496 highlightCircleSize: self.data('dygraph-highlightcirclesize') || highlightCircleSize,
3497 highlightSeriesOpts: self.data('dygraph-highlightseriesopts') || null, // TOO SLOW: { strokeWidth: 1.5 },
3498 highlightSeriesBackgroundAlpha: self.data('dygraph-highlightseriesbackgroundalpha') || null, // TOO SLOW: (chart_type === 'stacked')?0.7:0.5,
3500 pointClickCallback: self.data('dygraph-pointclickcallback') || undefined,
3501 visibility: state.dimensions_visibility.selected2BooleanArray(state.data.dimension_names),
3505 ticker: Dygraph.dateTicker,
3506 axisLabelFormatter: function (d, gran) {
3507 return NETDATA.zeropad(d.getHours()) + ":" + NETDATA.zeropad(d.getMinutes()) + ":" + NETDATA.zeropad(d.getSeconds());
3509 valueFormatter: function (ms) {
3510 var d = new Date(ms);
3511 return d.toLocaleDateString() + ' ' + d.toLocaleTimeString();
3512 // return NETDATA.zeropad(d.getHours()) + ":" + NETDATA.zeropad(d.getMinutes()) + ":" + NETDATA.zeropad(d.getSeconds());
3517 valueFormatter: function (x) {
3518 // we format legends with the state object
3519 // no need to do anything here
3520 // return (Math.round(x*100) / 100).toLocaleString();
3521 // return state.legendFormatValue(x);
3526 legendFormatter: function(data) {
3527 var elements = state.element_legend_childs;
3529 // if the hidden div is not there
3530 // we are not managing the legend
3531 if(elements.hidden === null) return;
3533 if (typeof data.x !== 'undefined') {
3534 state.legendSetDate(data.x);
3535 var i = data.series.length;
3537 var series = data.series[i];
3538 if(!series.isVisible) continue;
3539 state.legendSetLabelValue(series.label, series.y);
3545 drawCallback: function(dygraph, is_initial) {
3546 if(state.current.name !== 'auto' && state.dygraph_user_action === true) {
3547 state.dygraph_user_action = false;
3549 var x_range = dygraph.xAxisRange();
3550 var after = Math.round(x_range[0]);
3551 var before = Math.round(x_range[1]);
3553 if(NETDATA.options.debug.dygraph === true)
3554 state.log('dygraphDrawCallback(dygraph, ' + is_initial + '): ' + (after / 1000).toString() + ' - ' + (before / 1000).toString());
3556 if(before <= state.netdata_last && after >= state.netdata_first)
3557 state.updateChartPanOrZoom(after, before);
3560 zoomCallback: function(minDate, maxDate, yRanges) {
3561 if(NETDATA.options.debug.dygraph === true)
3562 state.log('dygraphZoomCallback()');
3564 state.globalSelectionSyncStop();
3565 state.globalSelectionSyncDelay();
3566 state.setMode('zoom');
3568 // refresh it to the greatest possible zoom level
3569 state.dygraph_user_action = true;
3570 state.dygraph_force_zoom = true;
3571 state.updateChartPanOrZoom(minDate, maxDate);
3573 highlightCallback: function(event, x, points, row, seriesName) {
3574 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3575 state.log('dygraphHighlightCallback()');
3579 // there is a bug in dygraph when the chart is zoomed enough
3580 // the time it thinks is selected is wrong
3581 // here we calculate the time t based on the row number selected
3583 var t = state.data_after + row * state.data_update_every;
3584 // console.log('row = ' + row + ', x = ' + x + ', t = ' + t + ' ' + ((t === x)?'SAME':(Math.abs(x-t)<=state.data_update_every)?'SIMILAR':'DIFFERENT') + ', rows in db: ' + state.data_points + ' visible(x) = ' + state.timeIsVisible(x) + ' visible(t) = ' + state.timeIsVisible(t) + ' r(x) = ' + state.calculateRowForTime(x) + ' r(t) = ' + state.calculateRowForTime(t) + ' range: ' + state.data_after + ' - ' + state.data_before + ' real: ' + state.data.after + ' - ' + state.data.before + ' every: ' + state.data_update_every);
3586 state.globalSelectionSync(x);
3588 // fix legend zIndex using the internal structures of dygraph legend module
3589 // this works, but it is a hack!
3590 // state.dygraph_instance.plugins_[0].plugin.legend_div_.style.zIndex = 10000;
3592 unhighlightCallback: function(event) {
3593 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3594 state.log('dygraphUnhighlightCallback()');
3596 state.unpauseChart();
3597 state.globalSelectionSyncStop();
3599 interactionModel : {
3600 mousedown: function(event, dygraph, context) {
3601 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3602 state.log('interactionModel.mousedown()');
3604 state.dygraph_user_action = true;
3605 state.globalSelectionSyncStop();
3607 if(NETDATA.options.debug.dygraph === true)
3608 state.log('dygraphMouseDown()');
3610 // Right-click should not initiate a zoom.
3611 if(event.button && event.button === 2) return;
3613 context.initializeMouseDown(event, dygraph, context);
3615 if(event.button && event.button === 1) {
3616 if (event.altKey || event.shiftKey) {
3617 state.setMode('pan');
3618 state.globalSelectionSyncDelay();
3619 Dygraph.startPan(event, dygraph, context);
3622 state.setMode('zoom');
3623 state.globalSelectionSyncDelay();
3624 Dygraph.startZoom(event, dygraph, context);
3628 if (event.altKey || event.shiftKey) {
3629 state.setMode('zoom');
3630 state.globalSelectionSyncDelay();
3631 Dygraph.startZoom(event, dygraph, context);
3634 state.setMode('pan');
3635 state.globalSelectionSyncDelay();
3636 Dygraph.startPan(event, dygraph, context);
3640 mousemove: function(event, dygraph, context) {
3641 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3642 state.log('interactionModel.mousemove()');
3644 if(context.isPanning) {
3645 state.dygraph_user_action = true;
3646 state.globalSelectionSyncStop();
3647 state.globalSelectionSyncDelay();
3648 state.setMode('pan');
3649 Dygraph.movePan(event, dygraph, context);
3651 else if(context.isZooming) {
3652 state.dygraph_user_action = true;
3653 state.globalSelectionSyncStop();
3654 state.globalSelectionSyncDelay();
3655 state.setMode('zoom');
3656 Dygraph.moveZoom(event, dygraph, context);
3659 mouseup: function(event, dygraph, context) {
3660 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3661 state.log('interactionModel.mouseup()');
3663 if (context.isPanning) {
3664 state.dygraph_user_action = true;
3665 state.globalSelectionSyncDelay();
3666 Dygraph.endPan(event, dygraph, context);
3668 else if (context.isZooming) {
3669 state.dygraph_user_action = true;
3670 state.globalSelectionSyncDelay();
3671 Dygraph.endZoom(event, dygraph, context);
3674 click: function(event, dygraph, context) {
3675 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3676 state.log('interactionModel.click()');
3678 event.preventDefault();
3680 dblclick: function(event, dygraph, context) {
3681 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3682 state.log('interactionModel.dblclick()');
3683 NETDATA.resetAllCharts(state);
3685 mousewheel: function(event, dygraph, context) {
3686 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3687 state.log('interactionModel.mousewheel()');
3689 // Take the offset of a mouse event on the dygraph canvas and
3690 // convert it to a pair of percentages from the bottom left.
3691 // (Not top left, bottom is where the lower value is.)
3692 function offsetToPercentage(g, offsetX, offsetY) {
3693 // This is calculating the pixel offset of the leftmost date.
3694 var xOffset = g.toDomCoords(g.xAxisRange()[0], null)[0];
3695 var yar0 = g.yAxisRange(0);
3697 // This is calculating the pixel of the higest value. (Top pixel)
3698 var yOffset = g.toDomCoords(null, yar0[1])[1];
3700 // x y w and h are relative to the corner of the drawing area,
3701 // so that the upper corner of the drawing area is (0, 0).
3702 var x = offsetX - xOffset;
3703 var y = offsetY - yOffset;
3705 // This is computing the rightmost pixel, effectively defining the
3707 var w = g.toDomCoords(g.xAxisRange()[1], null)[0] - xOffset;
3709 // This is computing the lowest pixel, effectively defining the height.
3710 var h = g.toDomCoords(null, yar0[0])[1] - yOffset;
3712 // Percentage from the left.
3713 var xPct = w === 0 ? 0 : (x / w);
3714 // Percentage from the top.
3715 var yPct = h === 0 ? 0 : (y / h);
3717 // The (1-) part below changes it from "% distance down from the top"
3718 // to "% distance up from the bottom".
3719 return [xPct, (1-yPct)];
3722 // Adjusts [x, y] toward each other by zoomInPercentage%
3723 // Split it so the left/bottom axis gets xBias/yBias of that change and
3724 // tight/top gets (1-xBias)/(1-yBias) of that change.
3726 // If a bias is missing it splits it down the middle.
3727 function zoomRange(g, zoomInPercentage, xBias, yBias) {
3728 xBias = xBias || 0.5;
3729 yBias = yBias || 0.5;
3731 function adjustAxis(axis, zoomInPercentage, bias) {
3732 var delta = axis[1] - axis[0];
3733 var increment = delta * zoomInPercentage;
3734 var foo = [increment * bias, increment * (1-bias)];
3736 return [ axis[0] + foo[0], axis[1] - foo[1] ];
3739 var yAxes = g.yAxisRanges();
3741 for (var i = 0; i < yAxes.length; i++) {
3742 newYAxes[i] = adjustAxis(yAxes[i], zoomInPercentage, yBias);
3745 return adjustAxis(g.xAxisRange(), zoomInPercentage, xBias);
3748 if(event.altKey || event.shiftKey) {
3749 state.dygraph_user_action = true;
3751 state.globalSelectionSyncStop();
3752 state.globalSelectionSyncDelay();
3754 // http://dygraphs.com/gallery/interaction-api.js
3755 var normal = (event.detail) ? event.detail * -1 : event.wheelDelta / 40;
3756 var percentage = normal / 50;
3758 if (!(event.offsetX && event.offsetY)){
3759 event.offsetX = event.layerX - event.target.offsetLeft;
3760 event.offsetY = event.layerY - event.target.offsetTop;
3763 var percentages = offsetToPercentage(dygraph, event.offsetX, event.offsetY);
3764 var xPct = percentages[0];
3765 var yPct = percentages[1];
3767 var new_x_range = zoomRange(dygraph, percentage, xPct, yPct);
3769 var after = new_x_range[0];
3770 var before = new_x_range[1];
3772 var first = state.netdata_first + state.data_update_every;
3773 var last = state.netdata_last + state.data_update_every;
3776 after -= (before - last);
3783 state.setMode('zoom');
3784 if(state.updateChartPanOrZoom(after, before) === true)
3785 dygraph.updateOptions({ dateWindow: [ after, before ] });
3787 event.preventDefault();
3790 touchstart: function(event, dygraph, context) {
3791 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3792 state.log('interactionModel.touchstart()');
3794 state.dygraph_user_action = true;
3795 state.setMode('zoom');
3798 Dygraph.defaultInteractionModel.touchstart(event, dygraph, context);
3800 // we overwrite the touch directions at the end, to overwrite
3801 // the internal default of dygraphs
3802 context.touchDirections = { x: true, y: false };
3804 state.dygraph_last_touch_start = new Date().getTime();
3805 state.dygraph_last_touch_move = 0;
3807 if(typeof event.touches[0].pageX === 'number')
3808 state.dygraph_last_touch_page_x = event.touches[0].pageX;
3810 state.dygraph_last_touch_page_x = 0;
3812 touchmove: function(event, dygraph, context) {
3813 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3814 state.log('interactionModel.touchmove()');
3816 state.dygraph_user_action = true;
3817 Dygraph.defaultInteractionModel.touchmove(event, dygraph, context);
3819 state.dygraph_last_touch_move = new Date().getTime();
3821 touchend: function(event, dygraph, context) {
3822 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3823 state.log('interactionModel.touchend()');
3825 state.dygraph_user_action = true;
3826 Dygraph.defaultInteractionModel.touchend(event, dygraph, context);
3828 // if it didn't move, it is a selection
3829 if(state.dygraph_last_touch_move === 0 && state.dygraph_last_touch_page_x !== 0) {
3830 // internal api of dygraphs
3831 var pct = (state.dygraph_last_touch_page_x - (dygraph.plotter_.area.x + state.element.getBoundingClientRect().left)) / dygraph.plotter_.area.w;
3832 var t = Math.round(state.data_after + (state.data_before - state.data_after) * pct);
3833 if(NETDATA.dygraphSetSelection(state, t) === true)
3834 state.globalSelectionSync(t);
3837 // if it was double tap within double click time, reset the charts
3838 var now = new Date().getTime();
3839 if(typeof state.dygraph_last_touch_end !== 'undefined') {
3840 if(state.dygraph_last_touch_move === 0) {
3841 var dt = now - state.dygraph_last_touch_end;
3842 if(dt <= NETDATA.options.current.double_click_speed)
3843 NETDATA.resetAllCharts(state);
3847 // remember the timestamp of the last touch end
3848 state.dygraph_last_touch_end = now;
3853 if(NETDATA.chartLibraries.dygraph.isSparkline(state)) {
3854 state.dygraph_options.drawGrid = false;
3855 state.dygraph_options.drawAxis = false;
3856 state.dygraph_options.title = undefined;
3857 state.dygraph_options.units = undefined;
3858 state.dygraph_options.ylabel = undefined;
3859 state.dygraph_options.yLabelWidth = 0;
3860 state.dygraph_options.labelsDivWidth = 120;
3861 state.dygraph_options.labelsDivStyles.width = '120px';
3862 state.dygraph_options.labelsSeparateLines = true;
3863 state.dygraph_options.rightGap = 0;
3866 if(smooth === true) {
3867 state.dygraph_smooth_eligible = true;
3869 if(NETDATA.options.current.smooth_plot === true)
3870 state.dygraph_options.plotter = smoothPlotter;
3872 else state.dygraph_smooth_eligible = false;
3874 state.dygraph_instance = new Dygraph(state.element_chart,
3875 data.result.data, state.dygraph_options);
3877 state.dygraph_force_zoom = false;
3878 state.dygraph_user_action = false;
3879 state.dygraph_last_rendered = new Date().getTime();
3883 // ----------------------------------------------------------------------------------------------------------------
3886 NETDATA.morrisInitialize = function(callback) {
3887 if(typeof netdataNoMorris === 'undefined' || !netdataNoMorris) {
3889 // morris requires raphael
3890 if(!NETDATA.chartLibraries.raphael.initialized) {
3891 if(NETDATA.chartLibraries.raphael.enabled) {
3892 NETDATA.raphaelInitialize(function() {
3893 NETDATA.morrisInitialize(callback);
3897 NETDATA.chartLibraries.morris.enabled = false;
3898 if(typeof callback === "function")
3903 NETDATA._loadCSS(NETDATA.morris_css);
3906 url: NETDATA.morris_js,
3911 NETDATA.registerChartLibrary('morris', NETDATA.morris_js);
3914 NETDATA.chartLibraries.morris.enabled = false;
3915 NETDATA.error(100, NETDATA.morris_js);
3917 .always(function() {
3918 if(typeof callback === "function")
3924 NETDATA.chartLibraries.morris.enabled = false;
3925 if(typeof callback === "function")
3930 NETDATA.morrisChartUpdate = function(state, data) {
3931 state.morris_instance.setData(data.result.data);
3935 NETDATA.morrisChartCreate = function(state, data) {
3937 state.morris_options = {
3938 element: state.element_chart.id,
3939 data: data.result.data,
3941 ykeys: data.dimension_names,
3942 labels: data.dimension_names,
3948 continuousLine: false,
3949 behaveLikeLine: false
3952 if(state.chart.chart_type === 'line')
3953 state.morris_instance = new Morris.Line(state.morris_options);
3955 else if(state.chart.chart_type === 'area') {
3956 state.morris_options.behaveLikeLine = true;
3957 state.morris_instance = new Morris.Area(state.morris_options);
3960 state.morris_instance = new Morris.Area(state.morris_options);
3965 // ----------------------------------------------------------------------------------------------------------------
3968 NETDATA.raphaelInitialize = function(callback) {
3969 if(typeof netdataStopRaphael === 'undefined' || !netdataStopRaphael) {
3971 url: NETDATA.raphael_js,
3976 NETDATA.registerChartLibrary('raphael', NETDATA.raphael_js);
3979 NETDATA.chartLibraries.raphael.enabled = false;
3980 NETDATA.error(100, NETDATA.raphael_js);
3982 .always(function() {
3983 if(typeof callback === "function")
3988 NETDATA.chartLibraries.raphael.enabled = false;
3989 if(typeof callback === "function")
3994 NETDATA.raphaelChartUpdate = function(state, data) {
3995 $(state.element_chart).raphael(data.result, {
3996 width: state.chartWidth(),
3997 height: state.chartHeight()
4003 NETDATA.raphaelChartCreate = function(state, data) {
4004 $(state.element_chart).raphael(data.result, {
4005 width: state.chartWidth(),
4006 height: state.chartHeight()
4012 // ----------------------------------------------------------------------------------------------------------------
4015 NETDATA.c3Initialize = function(callback) {
4016 if(typeof netdataNoC3 === 'undefined' || !netdataNoC3) {
4019 if(!NETDATA.chartLibraries.d3.initialized) {
4020 if(NETDATA.chartLibraries.d3.enabled) {
4021 NETDATA.d3Initialize(function() {
4022 NETDATA.c3Initialize(callback);
4026 NETDATA.chartLibraries.c3.enabled = false;
4027 if(typeof callback === "function")
4032 NETDATA._loadCSS(NETDATA.c3_css);
4040 NETDATA.registerChartLibrary('c3', NETDATA.c3_js);
4043 NETDATA.chartLibraries.c3.enabled = false;
4044 NETDATA.error(100, NETDATA.c3_js);
4046 .always(function() {
4047 if(typeof callback === "function")
4053 NETDATA.chartLibraries.c3.enabled = false;
4054 if(typeof callback === "function")
4059 NETDATA.c3ChartUpdate = function(state, data) {
4060 state.c3_instance.destroy();
4061 return NETDATA.c3ChartCreate(state, data);
4063 //state.c3_instance.load({
4064 // rows: data.result,
4071 NETDATA.c3ChartCreate = function(state, data) {
4073 state.element_chart.id = 'c3-' + state.uuid;
4074 // console.log('id = ' + state.element_chart.id);
4076 state.c3_instance = c3.generate({
4077 bindto: '#' + state.element_chart.id,
4079 width: state.chartWidth(),
4080 height: state.chartHeight()
4083 pattern: state.chartColors()
4088 type: (state.chart.chart_type === 'line')?'spline':'area-spline'
4094 format: function(x) {
4095 return NETDATA.zeropad(x.getHours()) + ":" + NETDATA.zeropad(x.getMinutes()) + ":" + NETDATA.zeropad(x.getSeconds());
4122 // console.log(state.c3_instance);
4127 // ----------------------------------------------------------------------------------------------------------------
4130 NETDATA.d3Initialize = function(callback) {
4131 if(typeof netdataStopD3 === 'undefined' || !netdataStopD3) {
4138 NETDATA.registerChartLibrary('d3', NETDATA.d3_js);
4141 NETDATA.chartLibraries.d3.enabled = false;
4142 NETDATA.error(100, NETDATA.d3_js);
4144 .always(function() {
4145 if(typeof callback === "function")
4150 NETDATA.chartLibraries.d3.enabled = false;
4151 if(typeof callback === "function")
4156 NETDATA.d3ChartUpdate = function(state, data) {
4160 NETDATA.d3ChartCreate = function(state, data) {
4164 // ----------------------------------------------------------------------------------------------------------------
4167 NETDATA.googleInitialize = function(callback) {
4168 if(typeof netdataNoGoogleCharts === 'undefined' || !netdataNoGoogleCharts) {
4170 url: NETDATA.google_js,
4175 NETDATA.registerChartLibrary('google', NETDATA.google_js);
4176 google.load('visualization', '1.1', {
4177 'packages': ['corechart', 'controls'],
4178 'callback': callback
4182 NETDATA.chartLibraries.google.enabled = false;
4183 NETDATA.error(100, NETDATA.google_js);
4184 if(typeof callback === "function")
4189 NETDATA.chartLibraries.google.enabled = false;
4190 if(typeof callback === "function")
4195 NETDATA.googleChartUpdate = function(state, data) {
4196 var datatable = new google.visualization.DataTable(data.result);
4197 state.google_instance.draw(datatable, state.google_options);
4201 NETDATA.googleChartCreate = function(state, data) {
4202 var datatable = new google.visualization.DataTable(data.result);
4204 state.google_options = {
4205 colors: state.chartColors(),
4207 // do not set width, height - the chart resizes itself
4208 //width: state.chartWidth(),
4209 //height: state.chartHeight(),
4214 // title: "Time of Day",
4215 // format:'HH:mm:ss',
4216 viewWindowMode: 'maximized',
4228 viewWindowMode: 'pretty',
4243 focusTarget: 'category',
4250 titlePosition: 'out',
4261 curveType: 'function',
4266 switch(state.chart.chart_type) {
4268 state.google_options.vAxis.viewWindowMode = 'maximized';
4269 state.google_options.areaOpacity = NETDATA.options.current.color_fill_opacity_area;
4270 state.google_instance = new google.visualization.AreaChart(state.element_chart);
4274 state.google_options.isStacked = true;
4275 state.google_options.areaOpacity = NETDATA.options.current.color_fill_opacity_stacked;
4276 state.google_options.vAxis.viewWindowMode = 'maximized';
4277 state.google_options.vAxis.minValue = null;
4278 state.google_options.vAxis.maxValue = null;
4279 state.google_instance = new google.visualization.AreaChart(state.element_chart);
4284 state.google_options.lineWidth = 2;
4285 state.google_instance = new google.visualization.LineChart(state.element_chart);
4289 state.google_instance.draw(datatable, state.google_options);
4293 // ----------------------------------------------------------------------------------------------------------------
4295 NETDATA.percentFromValueMax = function(value, max) {
4296 if(value === null) value = 0;
4297 if(max < value) max = value;
4301 pcent = Math.round(value * 100 / max);
4302 if(pcent === 0 && value > 0) pcent = 1;
4308 // ----------------------------------------------------------------------------------------------------------------
4311 NETDATA.easypiechartInitialize = function(callback) {
4312 if(typeof netdataNoEasyPieChart === 'undefined' || !netdataNoEasyPieChart) {
4314 url: NETDATA.easypiechart_js,
4319 NETDATA.registerChartLibrary('easypiechart', NETDATA.easypiechart_js);
4322 NETDATA.error(100, NETDATA.easypiechart_js);
4324 .always(function() {
4325 if(typeof callback === "function")
4330 NETDATA.chartLibraries.easypiechart.enabled = false;
4331 if(typeof callback === "function")
4336 NETDATA.easypiechartClearSelection = function(state) {
4337 if(typeof state.easyPieChartEvent !== 'undefined') {
4338 if(state.easyPieChartEvent.timer !== null)
4339 clearTimeout(state.easyPieChartEvent.timer);
4341 state.easyPieChartEvent.timer = null;
4344 if(state.isAutoRefreshed() === true && state.data !== null) {
4345 NETDATA.easypiechartChartUpdate(state, state.data);
4348 state.easyPieChartLabel.innerHTML = state.legendFormatValue(null);
4349 state.easyPieChart_instance.update(0);
4351 state.easyPieChart_instance.enableAnimation();
4356 NETDATA.easypiechartSetSelection = function(state, t) {
4357 if(state.timeIsVisible(t) !== true)
4358 return NETDATA.easypiechartClearSelection(state);
4360 var slot = state.calculateRowForTime(t);
4361 if(slot < 0 || slot >= state.data.result.length)
4362 return NETDATA.easypiechartClearSelection(state);
4364 if(typeof state.easyPieChartEvent === 'undefined') {
4365 state.easyPieChartEvent = {
4372 var value = state.data.result[state.data.result.length - 1 - slot];
4373 var max = (state.easyPieChartMax === null)?state.data.max:state.easyPieChartMax;
4374 var pcent = NETDATA.percentFromValueMax(value, max);
4376 state.easyPieChartEvent.value = value;
4377 state.easyPieChartEvent.pcent = pcent;
4378 state.easyPieChartLabel.innerHTML = state.legendFormatValue(value);
4380 if(state.easyPieChartEvent.timer === null) {
4381 state.easyPieChart_instance.disableAnimation();
4383 state.easyPieChartEvent.timer = setTimeout(function() {
4384 state.easyPieChartEvent.timer = null;
4385 state.easyPieChart_instance.update(state.easyPieChartEvent.pcent);
4386 }, NETDATA.options.current.charts_selection_animation_delay);
4392 NETDATA.easypiechartChartUpdate = function(state, data) {
4393 var value, max, pcent;
4395 if(NETDATA.globalPanAndZoom.isActive() === true || state.isAutoRefreshed() === false) {
4401 value = data.result[0];
4402 max = (state.easyPieChartMax === null)?data.max:state.easyPieChartMax;
4403 pcent = NETDATA.percentFromValueMax(value, max);
4406 state.easyPieChartLabel.innerHTML = state.legendFormatValue(value);
4407 state.easyPieChart_instance.update(pcent);
4411 NETDATA.easypiechartChartCreate = function(state, data) {
4412 var self = $(state.element);
4413 var chart = $(state.element_chart);
4415 var value = data.result[0];
4416 var max = self.data('easypiechart-max-value') || null;
4417 var adjust = self.data('easypiechart-adjust') || null;
4421 state.easyPieChartMax = null;
4424 state.easyPieChartMax = max;
4426 var pcent = NETDATA.percentFromValueMax(value, max);
4428 chart.data('data-percent', pcent);
4432 case 'width': size = state.chartHeight(); break;
4433 case 'min': size = Math.min(state.chartWidth(), state.chartHeight()); break;
4434 case 'max': size = Math.max(state.chartWidth(), state.chartHeight()); break;
4436 default: size = state.chartWidth(); break;
4438 state.element.style.width = size + 'px';
4439 state.element.style.height = size + 'px';
4441 var stroke = Math.floor(size / 22);
4442 if(stroke < 3) stroke = 2;
4444 var valuefontsize = Math.floor((size * 2 / 3) / 5);
4445 var valuetop = Math.round((size - valuefontsize - (size / 40)) / 2);
4446 state.easyPieChartLabel = document.createElement('span');
4447 state.easyPieChartLabel.className = 'easyPieChartLabel';
4448 state.easyPieChartLabel.innerHTML = state.legendFormatValue(value);
4449 state.easyPieChartLabel.style.fontSize = valuefontsize + 'px';
4450 state.easyPieChartLabel.style.top = valuetop.toString() + 'px';
4451 state.element_chart.appendChild(state.easyPieChartLabel);
4453 var titlefontsize = Math.round(valuefontsize * 1.6 / 3);
4454 var titletop = Math.round(valuetop - (titlefontsize * 2) - (size / 40));
4455 state.easyPieChartTitle = document.createElement('span');
4456 state.easyPieChartTitle.className = 'easyPieChartTitle';
4457 state.easyPieChartTitle.innerHTML = state.title;
4458 state.easyPieChartTitle.style.fontSize = titlefontsize + 'px';
4459 state.easyPieChartTitle.style.lineHeight = titlefontsize + 'px';
4460 state.easyPieChartTitle.style.top = titletop.toString() + 'px';
4461 state.element_chart.appendChild(state.easyPieChartTitle);
4463 var unitfontsize = Math.round(titlefontsize * 0.9);
4464 var unittop = Math.round(valuetop + (valuefontsize + unitfontsize) + (size / 40));
4465 state.easyPieChartUnits = document.createElement('span');
4466 state.easyPieChartUnits.className = 'easyPieChartUnits';
4467 state.easyPieChartUnits.innerHTML = state.units;
4468 state.easyPieChartUnits.style.fontSize = unitfontsize + 'px';
4469 state.easyPieChartUnits.style.top = unittop.toString() + 'px';
4470 state.element_chart.appendChild(state.easyPieChartUnits);
4472 chart.easyPieChart({
4473 barColor: self.data('easypiechart-barcolor') || state.chartColors()[0], //'#ef1e25',
4474 trackColor: self.data('easypiechart-trackcolor') || '#f0f0f0',
4475 scaleColor: self.data('easypiechart-scalecolor') || '#dfe0e0',
4476 scaleLength: self.data('easypiechart-scalelength') || 5,
4477 lineCap: self.data('easypiechart-linecap') || 'round',
4478 lineWidth: self.data('easypiechart-linewidth') || stroke,
4479 trackWidth: self.data('easypiechart-trackwidth') || undefined,
4480 size: self.data('easypiechart-size') || size,
4481 rotate: self.data('easypiechart-rotate') || 0,
4482 animate: self.data('easypiechart-rotate') || {duration: 500, enabled: true},
4483 easing: self.data('easypiechart-easing') || undefined
4486 // when we just re-create the chart
4487 // do not animate the first update
4489 if(typeof state.easyPieChart_instance !== 'undefined')
4492 state.easyPieChart_instance = chart.data('easyPieChart');
4493 if(animate === false) state.easyPieChart_instance.disableAnimation();
4494 state.easyPieChart_instance.update(pcent);
4495 if(animate === false) state.easyPieChart_instance.enableAnimation();
4499 // ----------------------------------------------------------------------------------------------------------------
4502 NETDATA.gaugeInitialize = function(callback) {
4503 if(typeof netdataNoGauge === 'undefined' || !netdataNoGauge) {
4505 url: NETDATA.gauge_js,
4510 NETDATA.registerChartLibrary('gauge', NETDATA.gauge_js);
4513 NETDATA.error(100, NETDATA.gauge_js);
4515 .always(function() {
4516 if(typeof callback === "function")
4521 NETDATA.chartLibraries.gauge.enabled = false;
4522 if(typeof callback === "function")
4527 NETDATA.gaugeAnimation = function(state, status) {
4530 if(typeof status === 'boolean' && status === false)
4532 else if(typeof status === 'number')
4535 state.gauge_instance.animationSpeed = speed;
4536 state.___gaugeOld__.speed = speed;
4539 NETDATA.gaugeSet = function(state, value, min, max) {
4540 if(typeof value !== 'number') value = 0;
4541 if(typeof min !== 'number') min = 0;
4542 if(typeof max !== 'number') max = 0;
4543 if(value > max) max = value;
4544 if(value < min) min = value;
4553 // gauge.js has an issue if the needle
4554 // is smaller than min or larger than max
4555 // when we set the new values
4556 // the needle will go crazy
4558 // to prevent it, we always feed it
4559 // with a percentage, so that the needle
4560 // is always between min and max
4561 var pcent = (value - min) * 100 / (max - min);
4563 // these should never happen
4564 if(pcent < 0) pcent = 0;
4565 if(pcent > 100) pcent = 100;
4567 state.gauge_instance.set(pcent);
4569 state.___gaugeOld__.value = value;
4570 state.___gaugeOld__.min = min;
4571 state.___gaugeOld__.max = max;
4574 NETDATA.gaugeSetLabels = function(state, value, min, max) {
4575 if(state.___gaugeOld__.valueLabel !== value) {
4576 state.___gaugeOld__.valueLabel = value;
4577 state.gaugeChartLabel.innerHTML = state.legendFormatValue(value);
4579 if(state.___gaugeOld__.minLabel !== min) {
4580 state.___gaugeOld__.minLabel = min;
4581 state.gaugeChartMin.innerHTML = state.legendFormatValue(min);
4583 if(state.___gaugeOld__.maxLabel !== max) {
4584 state.___gaugeOld__.maxLabel = max;
4585 state.gaugeChartMax.innerHTML = state.legendFormatValue(max);
4589 NETDATA.gaugeClearSelection = function(state) {
4590 if(typeof state.gaugeEvent !== 'undefined') {
4591 if(state.gaugeEvent.timer !== null)
4592 clearTimeout(state.gaugeEvent.timer);
4594 state.gaugeEvent.timer = null;
4597 if(state.isAutoRefreshed() === true && state.data !== null) {
4598 NETDATA.gaugeChartUpdate(state, state.data);
4601 NETDATA.gaugeAnimation(state, false);
4602 NETDATA.gaugeSet(state, null, null, null);
4603 NETDATA.gaugeSetLabels(state, null, null, null);
4606 NETDATA.gaugeAnimation(state, true);
4610 NETDATA.gaugeSetSelection = function(state, t) {
4611 if(state.timeIsVisible(t) !== true)
4612 return NETDATA.gaugeClearSelection(state);
4614 var slot = state.calculateRowForTime(t);
4615 if(slot < 0 || slot >= state.data.result.length)
4616 return NETDATA.gaugeClearSelection(state);
4618 if(typeof state.gaugeEvent === 'undefined') {
4619 state.gaugeEvent = {
4627 var value = state.data.result[state.data.result.length - 1 - slot];
4628 var max = (state.gaugeMax === null)?state.data.max:state.gaugeMax;
4631 state.gaugeEvent.value = value;
4632 state.gaugeEvent.max = max;
4633 state.gaugeEvent.min = min;
4634 NETDATA.gaugeSetLabels(state, value, min, max);
4636 if(state.gaugeEvent.timer === null) {
4637 NETDATA.gaugeAnimation(state, false);
4639 state.gaugeEvent.timer = setTimeout(function() {
4640 state.gaugeEvent.timer = null;
4641 NETDATA.gaugeSet(state, state.gaugeEvent.value, state.gaugeEvent.min, state.gaugeEvent.max);
4642 }, NETDATA.options.current.charts_selection_animation_delay);
4648 NETDATA.gaugeChartUpdate = function(state, data) {
4649 var value, min, max;
4651 if(NETDATA.globalPanAndZoom.isActive() === true || state.isAutoRefreshed() === false) {
4655 NETDATA.gaugeSetLabels(state, null, null, null);
4658 value = data.result[0];
4660 max = (state.gaugeMax === null)?data.max:state.gaugeMax;
4661 if(value > max) max = value;
4662 NETDATA.gaugeSetLabels(state, value, min, max);
4665 NETDATA.gaugeSet(state, value, min, max);
4669 NETDATA.gaugeChartCreate = function(state, data) {
4670 var self = $(state.element);
4671 var chart = $(state.element_chart);
4673 var value = data.result[0];
4674 var max = self.data('gauge-max-value') || null;
4675 var adjust = self.data('gauge-adjust') || null;
4676 var pointerColor = self.data('gauge-pointer-color') || '#C0C0C0';
4677 var strokeColor = self.data('gauge-stroke-color') || '#F0F0F0';
4678 var startColor = self.data('gauge-start-color') || state.chartColors()[0];
4679 var stopColor = self.data('gauge-stop-color') || void 0;
4680 var generateGradient = self.data('gauge-generate-gradient') || false;
4684 state.gaugeMax = null;
4687 state.gaugeMax = max;
4689 var width = state.chartWidth(), height = state.chartHeight(); //, ratio = 1.5;
4691 // case 'width': width = height * ratio; break;
4693 // default: height = width / ratio; break;
4695 //state.element.style.width = width.toString() + 'px';
4696 //state.element.style.height = height.toString() + 'px';
4701 lines: 12, // The number of lines to draw
4702 angle: 0.15, // The length of each line
4703 lineWidth: 0.44, // 0.44 The line thickness
4705 length: 0.8, // 0.9 The radius of the inner circle
4706 strokeWidth: 0.035, // The rotation offset
4707 color: pointerColor // Fill color
4709 colorStart: startColor, // Colors
4710 colorStop: stopColor, // just experiment with them
4711 strokeColor: strokeColor, // to see which ones work best for you
4713 generateGradient: generateGradient,
4716 [0.0, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 0))],
4717 [0.1, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 1))],
4718 [0.2, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 2))],
4719 [0.3, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 3))],
4720 [0.4, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 4))],
4721 [0.5, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 5))],
4722 [0.6, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 6))],
4723 [0.7, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 7))],
4724 [0.8, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 8))],
4725 [0.9, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 9))],
4726 [1.0, NETDATA.colorLuminance(startColor, 0.0)]]
4729 state.gauge_canvas = document.createElement('canvas');
4730 state.gauge_canvas.id = 'gauge-' + state.uuid + '-canvas';
4731 state.gauge_canvas.className = 'gaugeChart';
4732 state.gauge_canvas.width = width;
4733 state.gauge_canvas.height = height;
4734 state.element_chart.appendChild(state.gauge_canvas);
4736 var valuefontsize = Math.floor(height / 6);
4737 var valuetop = Math.round((height - valuefontsize - (height / 6)) / 2);
4738 state.gaugeChartLabel = document.createElement('span');
4739 state.gaugeChartLabel.className = 'gaugeChartLabel';
4740 state.gaugeChartLabel.style.fontSize = valuefontsize + 'px';
4741 state.gaugeChartLabel.style.top = valuetop.toString() + 'px';
4742 state.element_chart.appendChild(state.gaugeChartLabel);
4744 var titlefontsize = Math.round(valuefontsize / 2);
4746 state.gaugeChartTitle = document.createElement('span');
4747 state.gaugeChartTitle.className = 'gaugeChartTitle';
4748 state.gaugeChartTitle.innerHTML = state.title;
4749 state.gaugeChartTitle.style.fontSize = titlefontsize + 'px';
4750 state.gaugeChartTitle.style.lineHeight = titlefontsize + 'px';
4751 state.gaugeChartTitle.style.top = titletop.toString() + 'px';
4752 state.element_chart.appendChild(state.gaugeChartTitle);
4754 var unitfontsize = Math.round(titlefontsize * 0.9);
4755 state.gaugeChartUnits = document.createElement('span');
4756 state.gaugeChartUnits.className = 'gaugeChartUnits';
4757 state.gaugeChartUnits.innerHTML = state.units;
4758 state.gaugeChartUnits.style.fontSize = unitfontsize + 'px';
4759 state.element_chart.appendChild(state.gaugeChartUnits);
4761 state.gaugeChartMin = document.createElement('span');
4762 state.gaugeChartMin.className = 'gaugeChartMin';
4763 state.gaugeChartMin.style.fontSize = Math.round(valuefontsize * 0.75).toString() + 'px';
4764 state.element_chart.appendChild(state.gaugeChartMin);
4766 state.gaugeChartMax = document.createElement('span');
4767 state.gaugeChartMax.className = 'gaugeChartMax';
4768 state.gaugeChartMax.style.fontSize = Math.round(valuefontsize * 0.75).toString() + 'px';
4769 state.element_chart.appendChild(state.gaugeChartMax);
4771 // when we just re-create the chart
4772 // do not animate the first update
4774 if(typeof state.gauge_instance !== 'undefined')
4777 state.gauge_instance = new Gauge(state.gauge_canvas).setOptions(options); // create sexy gauge!
4779 state.___gaugeOld__ = {
4788 // we will always feed a percentage
4789 state.gauge_instance.minValue = 0;
4790 state.gauge_instance.maxValue = 100;
4792 NETDATA.gaugeAnimation(state, animate);
4793 NETDATA.gaugeSet(state, value, 0, max);
4794 NETDATA.gaugeSetLabels(state, value, 0, max);
4795 NETDATA.gaugeAnimation(state, true);
4799 // ----------------------------------------------------------------------------------------------------------------
4800 // Charts Libraries Registration
4802 NETDATA.chartLibraries = {
4804 initialize: NETDATA.dygraphInitialize,
4805 create: NETDATA.dygraphChartCreate,
4806 update: NETDATA.dygraphChartUpdate,
4807 resize: function(state) {
4808 if(typeof state.dygraph_instance.resize === 'function')
4809 state.dygraph_instance.resize();
4811 setSelection: NETDATA.dygraphSetSelection,
4812 clearSelection: NETDATA.dygraphClearSelection,
4815 format: function(state) { return 'json'; },
4816 options: function(state) { return 'ms|flip'; },
4817 legend: function(state) {
4818 if(this.isSparkline(state) === false)
4819 return 'right-side';
4823 autoresize: function(state) { return true; },
4824 max_updates_to_recreate: function(state) { return 5000; },
4825 track_colors: function(state) { return true; },
4826 pixels_per_point: function(state) {
4827 if(this.isSparkline(state) === false)
4833 isSparkline: function(state) {
4834 if(typeof state.dygraph_sparkline === 'undefined') {
4835 var t = $(state.element).data('dygraph-theme');
4836 if(t === 'sparkline')
4837 state.dygraph_sparkline = true;
4839 state.dygraph_sparkline = false;
4841 return state.dygraph_sparkline;
4845 initialize: NETDATA.sparklineInitialize,
4846 create: NETDATA.sparklineChartCreate,
4847 update: NETDATA.sparklineChartUpdate,
4849 setSelection: undefined, // function(state, t) { return true; },
4850 clearSelection: undefined, // function(state) { return true; },
4853 format: function(state) { return 'array'; },
4854 options: function(state) { return 'flip|abs'; },
4855 legend: function(state) { return null; },
4856 autoresize: function(state) { return false; },
4857 max_updates_to_recreate: function(state) { return 5000; },
4858 track_colors: function(state) { return false; },
4859 pixels_per_point: function(state) { return 3; }
4862 initialize: NETDATA.peityInitialize,
4863 create: NETDATA.peityChartCreate,
4864 update: NETDATA.peityChartUpdate,
4866 setSelection: undefined, // function(state, t) { return true; },
4867 clearSelection: undefined, // function(state) { return true; },
4870 format: function(state) { return 'ssvcomma'; },
4871 options: function(state) { return 'null2zero|flip|abs'; },
4872 legend: function(state) { return null; },
4873 autoresize: function(state) { return false; },
4874 max_updates_to_recreate: function(state) { return 5000; },
4875 track_colors: function(state) { return false; },
4876 pixels_per_point: function(state) { return 3; }
4879 initialize: NETDATA.morrisInitialize,
4880 create: NETDATA.morrisChartCreate,
4881 update: NETDATA.morrisChartUpdate,
4883 setSelection: undefined, // function(state, t) { return true; },
4884 clearSelection: undefined, // function(state) { return true; },
4887 format: function(state) { return 'json'; },
4888 options: function(state) { return 'objectrows|ms'; },
4889 legend: function(state) { return null; },
4890 autoresize: function(state) { return false; },
4891 max_updates_to_recreate: function(state) { return 50; },
4892 track_colors: function(state) { return false; },
4893 pixels_per_point: function(state) { return 15; }
4896 initialize: NETDATA.googleInitialize,
4897 create: NETDATA.googleChartCreate,
4898 update: NETDATA.googleChartUpdate,
4900 setSelection: undefined, //function(state, t) { return true; },
4901 clearSelection: undefined, //function(state) { return true; },
4904 format: function(state) { return 'datatable'; },
4905 options: function(state) { return ''; },
4906 legend: function(state) { return null; },
4907 autoresize: function(state) { return false; },
4908 max_updates_to_recreate: function(state) { return 300; },
4909 track_colors: function(state) { return false; },
4910 pixels_per_point: function(state) { return 4; }
4913 initialize: NETDATA.raphaelInitialize,
4914 create: NETDATA.raphaelChartCreate,
4915 update: NETDATA.raphaelChartUpdate,
4917 setSelection: undefined, // function(state, t) { return true; },
4918 clearSelection: undefined, // function(state) { return true; },
4921 format: function(state) { return 'json'; },
4922 options: function(state) { return ''; },
4923 legend: function(state) { return null; },
4924 autoresize: function(state) { return false; },
4925 max_updates_to_recreate: function(state) { return 5000; },
4926 track_colors: function(state) { return false; },
4927 pixels_per_point: function(state) { return 3; }
4930 initialize: NETDATA.c3Initialize,
4931 create: NETDATA.c3ChartCreate,
4932 update: NETDATA.c3ChartUpdate,
4934 setSelection: undefined, // function(state, t) { return true; },
4935 clearSelection: undefined, // function(state) { return true; },
4938 format: function(state) { return 'csvjsonarray'; },
4939 options: function(state) { return 'milliseconds'; },
4940 legend: function(state) { return null; },
4941 autoresize: function(state) { return false; },
4942 max_updates_to_recreate: function(state) { return 5000; },
4943 track_colors: function(state) { return false; },
4944 pixels_per_point: function(state) { return 15; }
4947 initialize: NETDATA.d3Initialize,
4948 create: NETDATA.d3ChartCreate,
4949 update: NETDATA.d3ChartUpdate,
4951 setSelection: undefined, // function(state, t) { return true; },
4952 clearSelection: undefined, // function(state) { return true; },
4955 format: function(state) { return 'json'; },
4956 options: function(state) { return ''; },
4957 legend: function(state) { return null; },
4958 autoresize: function(state) { return false; },
4959 max_updates_to_recreate: function(state) { return 5000; },
4960 track_colors: function(state) { return false; },
4961 pixels_per_point: function(state) { return 3; }
4964 initialize: NETDATA.easypiechartInitialize,
4965 create: NETDATA.easypiechartChartCreate,
4966 update: NETDATA.easypiechartChartUpdate,
4968 setSelection: NETDATA.easypiechartSetSelection,
4969 clearSelection: NETDATA.easypiechartClearSelection,
4972 format: function(state) { return 'array'; },
4973 options: function(state) { return 'absolute'; },
4974 legend: function(state) { return null; },
4975 autoresize: function(state) { return false; },
4976 max_updates_to_recreate: function(state) { return 5000; },
4977 track_colors: function(state) { return true; },
4978 pixels_per_point: function(state) { return 3; },
4982 initialize: NETDATA.gaugeInitialize,
4983 create: NETDATA.gaugeChartCreate,
4984 update: NETDATA.gaugeChartUpdate,
4986 setSelection: NETDATA.gaugeSetSelection,
4987 clearSelection: NETDATA.gaugeClearSelection,
4990 format: function(state) { return 'array'; },
4991 options: function(state) { return 'absolute'; },
4992 legend: function(state) { return null; },
4993 autoresize: function(state) { return false; },
4994 max_updates_to_recreate: function(state) { return 5000; },
4995 track_colors: function(state) { return true; },
4996 pixels_per_point: function(state) { return 3; },
5001 NETDATA.registerChartLibrary = function(library, url) {
5002 if(NETDATA.options.debug.libraries === true)
5003 console.log("registering chart library: " + library);
5005 NETDATA.chartLibraries[library].url = url;
5006 NETDATA.chartLibraries[library].initialized = true;
5007 NETDATA.chartLibraries[library].enabled = true;
5010 // ----------------------------------------------------------------------------------------------------------------
5013 NETDATA.requiredJs = [
5015 url: NETDATA.serverDefault + 'lib/bootstrap.min.js',
5016 isAlreadyLoaded: function() {
5017 if(typeof $().emulateTransitionEnd == 'function')
5020 if(typeof netdataNoBootstrap !== 'undefined' && netdataNoBootstrap)
5028 url: NETDATA.serverDefault + 'lib/jquery.nanoscroller.min.js',
5029 isAlreadyLoaded: function() { return false; }
5032 url: NETDATA.serverDefault + 'lib/bootstrap-toggle.min.js',
5033 isAlreadyLoaded: function() { return false; }
5037 NETDATA.requiredCSS = [
5039 url: NETDATA.serverDefault + 'css/bootstrap.min.css',
5040 isAlreadyLoaded: function() {
5041 if(typeof netdataNoBootstrap !== 'undefined' && netdataNoBootstrap)
5048 url: NETDATA.serverDefault + 'css/font-awesome.min.css',
5049 isAlreadyLoaded: function() { return false; }
5052 url: NETDATA.dashboard_css,
5053 isAlreadyLoaded: function() { return false; }
5056 url: NETDATA.serverDefault + 'css/bootstrap-toggle.min.css',
5057 isAlreadyLoaded: function() { return false; }
5061 NETDATA.loadRequiredJs = function(index, callback) {
5062 if(index >= NETDATA.requiredJs.length) {
5063 if(typeof callback === 'function')
5068 if(NETDATA.requiredJs[index].isAlreadyLoaded()) {
5069 NETDATA.loadRequiredJs(++index, callback);
5073 if(NETDATA.options.debug.main_loop === true)
5074 console.log('loading ' + NETDATA.requiredJs[index].url);
5077 url: NETDATA.requiredJs[index].url,
5081 .success(function() {
5082 if(NETDATA.options.debug.main_loop === true)
5083 console.log('loaded ' + NETDATA.requiredJs[index].url);
5085 NETDATA.loadRequiredJs(++index, callback);
5088 alert('Cannot load required JS library: ' + NETDATA.requiredJs[index].url);
5092 NETDATA.loadRequiredCSS = function(index) {
5093 if(index >= NETDATA.requiredCSS.length)
5096 if(NETDATA.requiredCSS[index].isAlreadyLoaded()) {
5097 NETDATA.loadRequiredCSS(++index);
5101 if(NETDATA.options.debug.main_loop === true)
5102 console.log('loading ' + NETDATA.requiredCSS[index].url);
5104 NETDATA._loadCSS(NETDATA.requiredCSS[index].url);
5105 NETDATA.loadRequiredCSS(++index);
5108 NETDATA.errorReset();
5109 NETDATA.loadRequiredCSS(0);
5111 NETDATA._loadjQuery(function() {
5112 NETDATA.loadRequiredJs(0, function() {
5113 if(typeof netdataDontStart === 'undefined' || !netdataDontStart) {
5114 if(NETDATA.options.debug.main_loop === true)
5115 console.log('starting chart refresh thread');
5122 // window.NETDATA = NETDATA;
5123 // })(window, document);