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 // ============================================================================================================
976 var createDOM = function() {
977 if(that.enabled === false) return;
979 if(that.element_message !== null) that.element_message.innerHTML = '';
980 if(that.element_legend !== null) that.element_legend.innerHTML = '';
981 if(that.element_chart !== null) that.element_chart.innerHTML = '';
983 that.element.innerHTML = '';
985 that.element_message = document.createElement('div');
986 that.element_message.className = ' netdata-message hidden';
987 that.element.appendChild(that.element_message);
989 that.element_chart = document.createElement('div');
990 that.element_chart.id = that.library_name + '-' + that.uuid + '-chart';
991 that.element.appendChild(that.element_chart);
993 if(that.hasLegend() === true) {
994 that.element.className = "netdata-container-with-legend";
995 that.element_chart.className = 'netdata-chart-with-legend-right netdata-' + that.library_name + '-chart-with-legend-right';
997 that.element_legend = document.createElement('div');
998 that.element_legend.className = 'netdata-chart-legend netdata-' + that.library_name + '-legend';
999 that.element.appendChild(that.element_legend);
1002 that.element.className = "netdata-container";
1003 that.element_chart.className = ' netdata-chart netdata-' + that.library_name + '-chart';
1005 that.element_legend = null;
1007 that.element_legend_childs.series = null;
1009 if(typeof(that.width) === 'string')
1010 $(that.element).css('width', that.width);
1011 else if(typeof(that.width) === 'number')
1012 $(that.element).css('width', that.width + 'px');
1014 if(typeof(that.library.aspect_ratio) === 'undefined') {
1015 if(typeof(that.height) === 'string')
1016 $(that.element).css('height', that.height);
1017 else if(typeof(that.height) === 'number')
1018 $(that.element).css('height', that.height + 'px');
1021 var w = that.element.offsetWidth;
1022 if(w === null || w === 0) {
1023 // the div is hidden
1024 // this is resize the chart when next viewed
1025 that.tm.last_resized = 0;
1028 $(that.element).css('height', (that.element.offsetWidth * that.library.aspect_ratio / 100).toString() + 'px');
1031 if(NETDATA.chartDefaults.min_width !== null)
1032 $(that.element).css('min-width', NETDATA.chartDefaults.min_width);
1034 that.tm.last_dom_created = new Date().getTime();
1040 * initialize state viariables
1041 * destroy all (possibly) created state elements
1042 * create the basic DOM for a chart
1044 var init = function() {
1045 if(that.enabled === false) return;
1047 that.paused = false;
1048 that.selected = false;
1050 that.chart_created = false; // boolean - is the library.create() been called?
1051 that.updates_counter = 0; // numeric - the number of refreshes made so far
1052 that.updates_since_last_unhide = 0; // numeric - the number of refreshes made since the last time the chart was unhidden
1053 that.updates_since_last_creation = 0; // numeric - the number of refreshes made since the last time the chart was created
1056 last_initialized: 0, // milliseconds - the timestamp it was last initialized
1057 last_dom_created: 0, // milliseconds - the timestamp its DOM was last created
1058 last_mode_switch: 0, // milliseconds - the timestamp it switched modes
1060 last_info_downloaded: 0, // milliseconds - the timestamp we downloaded the chart
1061 last_updated: 0, // the timestamp the chart last updated with data
1062 pan_and_zoom_seq: 0, // the sequence number of the global synchronization
1064 // Used with NETDATA.globalPanAndZoom.seq
1065 last_visible_check: 0, // the time we last checked if it is visible
1066 last_resized: 0, // the time the chart was resized
1067 last_hidden: 0, // the time the chart was hidden
1068 last_unhidden: 0, // the time the chart was unhidden
1069 last_autorefreshed: 0 // the time the chart was last refreshed
1072 that.data = null; // the last data as downloaded from the netdata server
1073 that.data_url = 'invalid://'; // string - the last url used to update the chart
1074 that.data_points = 0; // number - the number of points returned from netdata
1075 that.data_after = 0; // milliseconds - the first timestamp of the data
1076 that.data_before = 0; // milliseconds - the last timestamp of the data
1077 that.data_update_every = 0; // milliseconds - the frequency to update the data
1079 that.tm.last_initialized = new Date().getTime();
1082 that.setMode('auto');
1085 var maxMessageFontSize = function() {
1086 // normally we want a font size, as tall as the element
1087 var h = that.element_message.clientHeight;
1089 // but give it some air, 20% let's say, or 5 pixels min
1090 var lost = Math.max(h * 0.2, 5);
1093 // center the text, verically
1094 var paddingTop = (lost - 5) / 2;
1096 // but check the width too
1097 // it should fit 10 characters in it
1098 var w = that.element_message.clientWidth / 10;
1100 paddingTop += (h - w) / 2;
1104 // and don't make it too huge
1105 // 5% of the screen size is good
1106 if(h > screen.height / 20) {
1107 paddingTop += (h - (screen.height / 20)) / 2;
1108 h = screen.height / 20;
1112 that.element_message.style.fontSize = h.toString() + 'px';
1113 that.element_message.style.paddingTop = paddingTop.toString() + 'px';
1116 var showMessage = function(msg) {
1117 that.element_message.className = 'netdata-message';
1118 that.element_message.innerHTML = msg;
1119 this.element_message.style.fontSize = 'x-small';
1120 that.element_message.style.paddingTop = '0px';
1121 that.___messageHidden___ = undefined;
1124 var showMessageIcon = function(icon) {
1125 that.element_message.innerHTML = icon;
1126 that.element_message.className = 'netdata-message icon';
1127 maxMessageFontSize();
1128 that.___messageHidden___ = undefined;
1131 var hideMessage = function() {
1132 if(typeof that.___messageHidden___ === 'undefined') {
1133 that.___messageHidden___ = true;
1134 that.element_message.className = 'netdata-message hidden';
1138 var showRendering = function() {
1140 if(that.chart !== null) {
1141 if(that.chart.chart_type === 'line')
1142 icon = '<i class="fa fa-line-chart"></i>';
1144 icon = '<i class="fa fa-area-chart"></i>';
1147 icon = '<i class="fa fa-area-chart"></i>';
1149 showMessageIcon(icon + ' netdata');
1152 var showLoading = function() {
1153 if(that.chart_created === false) {
1154 showMessageIcon('<i class="fa fa-refresh"></i> netdata');
1160 var isHidden = function() {
1161 if(typeof that.___chartIsHidden___ !== 'undefined')
1167 // hide the chart, when it is not visible - called from isVisible()
1168 var hideChart = function() {
1169 // hide it, if it is not already hidden
1170 if(isHidden() === true) return;
1172 if(that.chart_created === true) {
1173 // we should destroy it
1174 if(NETDATA.options.current.destroy_on_hide === true) {
1179 that.element_chart.style.display = 'none';
1180 if(that.element_legend !== null) that.element_legend.style.display = 'none';
1181 that.tm.last_hidden = new Date().getTime();
1185 that.___chartIsHidden___ = true;
1188 // unhide the chart, when it is visible - called from isVisible()
1189 var unhideChart = function() {
1190 if(isHidden() === false) return;
1192 that.___chartIsHidden___ = undefined;
1193 that.updates_since_last_unhide = 0;
1195 if(that.chart_created === false) {
1196 // we need to re-initialize it, to show our background
1197 // logo in bootstrap tabs, until the chart loads
1201 that.tm.last_unhidden = new Date().getTime();
1202 that.element_chart.style.display = '';
1203 if(that.element_legend !== null) that.element_legend.style.display = '';
1209 var canBeRendered = function() {
1210 if(isHidden() === true || that.isVisible(true) === false)
1216 // https://github.com/petkaantonov/bluebird/wiki/Optimization-killers
1217 var callChartLibraryUpdateSafely = function(data) {
1220 if(canBeRendered() === false)
1223 if(NETDATA.options.debug.chart_errors === true)
1224 status = that.library.update(that, data);
1227 status = that.library.update(that, data);
1234 if(status === false) {
1235 error('chart failed to be updated as ' + that.library_name);
1242 // https://github.com/petkaantonov/bluebird/wiki/Optimization-killers
1243 var callChartLibraryCreateSafely = function(data) {
1246 if(canBeRendered() === false)
1249 if(NETDATA.options.debug.chart_errors === true)
1250 status = that.library.create(that, data);
1253 status = that.library.create(that, data);
1260 if(status === false) {
1261 error('chart failed to be created as ' + that.library_name);
1265 that.chart_created = true;
1266 that.updates_since_last_creation = 0;
1270 // ----------------------------------------------------------------------------------------------------------------
1273 // resizeChart() - private
1274 // to be called just before the chart library to make sure that
1275 // a properly sized dom is available
1276 var resizeChart = function() {
1277 if(that.isVisible() === true && that.tm.last_resized < NETDATA.options.last_resized) {
1278 if(that.chart_created === false) return;
1280 if(that.needsRecreation()) {
1283 else if(typeof that.library.resize === 'function') {
1284 that.library.resize(that);
1286 if(that.element_legend_childs.nano !== null && that.element_legend_childs.nano_options !== null)
1287 $(that.element_legend_childs.nano).nanoScroller();
1289 maxMessageFontSize();
1292 that.tm.last_resized = new Date().getTime();
1296 // this is the actual chart resize algorithm
1298 // - resize the entire container
1299 // - update the internal states
1300 // - resize the chart as the div changes height
1301 // - update the scrollbar of the legend
1302 var resizeChartToHeight = function(h) {
1304 that.element.style.height = h;
1306 if(that.settings_id !== null)
1307 NETDATA.localStorageSet('chart_heights.' + that.settings_id, h);
1309 var now = new Date().getTime();
1310 NETDATA.options.last_page_scroll = now;
1311 NETDATA.options.auto_refresher_stop_until = now + NETDATA.options.current.stop_updates_while_resizing;
1314 that.tm.last_resized = 0;
1318 this.resizeHandler = function(e) {
1321 if(typeof this.event_resize === 'undefined'
1322 || this.event_resize.chart_original_w === 'undefined'
1323 || this.event_resize.chart_original_h === 'undefined')
1324 this.event_resize = {
1325 chart_original_w: this.element.clientWidth,
1326 chart_original_h: this.element.clientHeight,
1330 if(e.type === 'touchstart') {
1331 this.event_resize.mouse_start_x = e.touches.item(0).pageX;
1332 this.event_resize.mouse_start_y = e.touches.item(0).pageY;
1335 this.event_resize.mouse_start_x = e.clientX;
1336 this.event_resize.mouse_start_y = e.clientY;
1339 this.event_resize.chart_start_w = this.element.clientWidth;
1340 this.event_resize.chart_start_h = this.element.clientHeight;
1341 this.event_resize.chart_last_w = this.element.clientWidth;
1342 this.event_resize.chart_last_h = this.element.clientHeight;
1344 var now = new Date().getTime();
1345 if(now - this.event_resize.last <= NETDATA.options.current.double_click_speed) {
1346 // double click / double tap event
1348 // the optimal height of the chart
1349 // showing the entire legend
1350 var optimal = this.event_resize.chart_last_h
1351 + this.element_legend_childs.content.scrollHeight
1352 - this.element_legend_childs.content.clientHeight;
1354 // if we are not optimal, be optimal
1355 if(this.event_resize.chart_last_h != optimal)
1356 resizeChartToHeight(optimal.toString() + 'px');
1358 // else if we do not have the original height
1359 // reset to the original height
1360 else if(this.event_resize.chart_last_h != this.event_resize.chart_original_h)
1361 resizeChartToHeight(this.event_resize.chart_original_h.toString() + 'px');
1364 this.event_resize.last = now;
1366 // process movement event
1367 document.onmousemove =
1368 document.ontouchmove =
1369 this.element_legend_childs.resize_handler.onmousemove =
1370 this.element_legend_childs.resize_handler.ontouchmove =
1375 case 'mousemove': y = e.clientY; break;
1376 case 'touchmove': y = e.touches.item(e.touches - 1).pageY; break;
1380 var newH = that.event_resize.chart_start_h + y - that.event_resize.mouse_start_y;
1382 if(newH >= 70 && newH !== that.event_resize.chart_last_h) {
1383 resizeChartToHeight(newH.toString() + 'px');
1384 that.event_resize.chart_last_h = newH;
1389 // process end event
1390 document.onmouseup =
1391 document.ontouchend =
1392 this.element_legend_childs.resize_handler.onmouseup =
1393 this.element_legend_childs.resize_handler.ontouchend =
1395 // remove all the hooks
1396 document.onmouseup =
1397 document.onmousemove =
1398 document.ontouchmove =
1399 document.ontouchend =
1400 that.element_legend_childs.resize_handler.onmousemove =
1401 that.element_legend_childs.resize_handler.ontouchmove =
1402 that.element_legend_childs.resize_handler.onmouseout =
1403 that.element_legend_childs.resize_handler.onmouseup =
1404 that.element_legend_childs.resize_handler.ontouchend =
1407 // allow auto-refreshes
1408 NETDATA.options.auto_refresher_stop_until = 0;
1414 var noDataToShow = function() {
1415 showMessageIcon('<i class="fa fa-warning"></i> empty');
1416 that.legendUpdateDOM();
1417 that.tm.last_autorefreshed = new Date().getTime();
1418 // that.data_update_every = 30 * 1000;
1419 //that.element_chart.style.display = 'none';
1420 //if(that.element_legend !== null) that.element_legend.style.display = 'none';
1421 //that.___chartIsHidden___ = true;
1424 // ============================================================================================================
1427 this.error = function(msg) {
1431 this.setMode = function(m) {
1432 if(this.current !== null && this.current.name === m) return;
1435 this.current = this.auto;
1436 else if(m === 'pan')
1437 this.current = this.pan;
1438 else if(m === 'zoom')
1439 this.current = this.zoom;
1441 this.current = this.auto;
1443 this.current.force_update_at = 0;
1444 this.current.force_before_ms = null;
1445 this.current.force_after_ms = null;
1447 this.tm.last_mode_switch = new Date().getTime();
1450 // ----------------------------------------------------------------------------------------------------------------
1451 // global selection sync
1453 // prevent to global selection sync for some time
1454 this.globalSelectionSyncDelay = function(ms) {
1455 if(NETDATA.options.current.sync_selection === false)
1458 if(typeof ms === 'number')
1459 NETDATA.globalSelectionSync.dont_sync_before = new Date().getTime() + ms;
1461 NETDATA.globalSelectionSync.dont_sync_before = new Date().getTime() + NETDATA.options.current.sync_selection_delay;
1464 // can we globally apply selection sync?
1465 this.globalSelectionSyncAbility = function() {
1466 if(NETDATA.options.current.sync_selection === false)
1469 if(NETDATA.globalSelectionSync.dont_sync_before > new Date().getTime())
1475 this.globalSelectionSyncIsMaster = function() {
1476 if(NETDATA.globalSelectionSync.state === this)
1482 // this chart is the master of the global selection sync
1483 this.globalSelectionSyncBeMaster = function() {
1485 if(this.globalSelectionSyncIsMaster()) {
1486 if(this.debug === true)
1487 this.log('sync: I am the master already.');
1492 if(NETDATA.globalSelectionSync.state) {
1493 if(this.debug === true)
1494 this.log('sync: I am not the sync master. Resetting global sync.');
1496 this.globalSelectionSyncStop();
1499 // become the master
1500 if(this.debug === true)
1501 this.log('sync: becoming sync master.');
1503 this.selected = true;
1504 NETDATA.globalSelectionSync.state = this;
1506 // find the all slaves
1507 var targets = NETDATA.options.targets;
1508 var len = targets.length;
1513 if(this.debug === true)
1514 st.log('sync: not adding me to sync');
1516 else if(st.globalSelectionSyncIsEligible()) {
1517 if(this.debug === true)
1518 st.log('sync: adding to sync as slave');
1520 st.globalSelectionSyncBeSlave();
1524 // this.globalSelectionSyncDelay(100);
1527 // can the chart participate to the global selection sync as a slave?
1528 this.globalSelectionSyncIsEligible = function() {
1529 if(this.enabled === true
1530 && this.library !== null
1531 && typeof this.library.setSelection === 'function'
1532 && this.isVisible() === true
1533 && this.chart_created === true)
1539 // this chart becomes a slave of the global selection sync
1540 this.globalSelectionSyncBeSlave = function() {
1541 if(NETDATA.globalSelectionSync.state !== this)
1542 NETDATA.globalSelectionSync.slaves.push(this);
1545 // sync all the visible charts to the given time
1546 // this is to be called from the chart libraries
1547 this.globalSelectionSync = function(t) {
1548 if(this.globalSelectionSyncAbility() === false) {
1549 if(this.debug === true)
1550 this.log('sync: cannot sync (yet?).');
1555 if(this.globalSelectionSyncIsMaster() === false) {
1556 if(this.debug === true)
1557 this.log('sync: trying to be sync master.');
1559 this.globalSelectionSyncBeMaster();
1561 if(this.globalSelectionSyncAbility() === false) {
1562 if(this.debug === true)
1563 this.log('sync: cannot sync (yet?).');
1569 NETDATA.globalSelectionSync.last_t = t;
1570 $.each(NETDATA.globalSelectionSync.slaves, function(i, st) {
1575 // stop syncing all charts to the given time
1576 this.globalSelectionSyncStop = function() {
1577 if(NETDATA.globalSelectionSync.slaves.length) {
1578 if(this.debug === true)
1579 this.log('sync: cleaning up...');
1581 $.each(NETDATA.globalSelectionSync.slaves, function(i, st) {
1583 if(that.debug === true)
1584 st.log('sync: not adding me to sync stop');
1587 if(that.debug === true)
1588 st.log('sync: removed slave from sync');
1590 st.clearSelection();
1594 NETDATA.globalSelectionSync.last_t = 0;
1595 NETDATA.globalSelectionSync.slaves = [];
1596 NETDATA.globalSelectionSync.state = null;
1599 this.clearSelection();
1602 this.setSelection = function(t) {
1603 if(typeof this.library.setSelection === 'function') {
1604 if(this.library.setSelection(this, t) === true)
1605 this.selected = true;
1607 this.selected = false;
1609 else this.selected = true;
1611 if(this.selected === true && this.debug === true)
1612 this.log('selection set to ' + t.toString());
1614 return this.selected;
1617 this.clearSelection = function() {
1618 if(this.selected === true) {
1619 if(typeof this.library.clearSelection === 'function') {
1620 if(this.library.clearSelection(this) === true)
1621 this.selected = false;
1623 this.selected = true;
1625 else this.selected = false;
1627 if(this.selected === false && this.debug === true)
1628 this.log('selection cleared');
1633 return this.selected;
1636 // find if a timestamp (ms) is shown in the current chart
1637 this.timeIsVisible = function(t) {
1638 if(t >= this.data_after && t <= this.data_before)
1643 this.calculateRowForTime = function(t) {
1644 if(this.timeIsVisible(t) === false) return -1;
1645 return Math.floor((t - this.data_after) / this.data_update_every);
1648 // ----------------------------------------------------------------------------------------------------------------
1651 this.log = function(msg) {
1652 console.log(this.id + ' (' + this.library_name + ' ' + this.uuid + '): ' + msg);
1655 this.pauseChart = function() {
1656 if(this.paused === false) {
1657 if(this.debug === true)
1658 this.log('pauseChart()');
1664 this.unpauseChart = function() {
1665 if(this.paused === true) {
1666 if(this.debug === true)
1667 this.log('unpauseChart()');
1669 this.paused = false;
1673 this.resetChart = function(dont_clear_master, dont_update) {
1674 if(this.debug === true)
1675 this.log('resetChart(' + dont_clear_master + ', ' + dont_update + ') called');
1677 if(typeof dont_clear_master === 'undefined')
1678 dont_clear_master = false;
1680 if(typeof dont_update === 'undefined')
1681 dont_update = false;
1683 if(dont_clear_master !== true && NETDATA.globalPanAndZoom.isMaster(this) === true) {
1684 if(this.debug === true)
1685 this.log('resetChart() diverting to clearMaster().');
1686 // this will call us back with master === true
1687 NETDATA.globalPanAndZoom.clearMaster();
1691 this.clearSelection();
1693 this.tm.pan_and_zoom_seq = 0;
1695 this.setMode('auto');
1696 this.current.force_update_at = 0;
1697 this.current.force_before_ms = null;
1698 this.current.force_after_ms = null;
1699 this.tm.last_autorefreshed = 0;
1700 this.paused = false;
1701 this.selected = false;
1702 this.enabled = true;
1703 // this.debug = false;
1705 // do not update the chart here
1706 // or the chart will flip-flop when it is the master
1707 // of a selection sync and another chart becomes
1710 if(dont_update !== true && this.isVisible() === true) {
1715 this.updateChartPanOrZoom = function(after, before) {
1716 var logme = 'updateChartPanOrZoom(' + after + ', ' + before + '): ';
1719 if(this.debug === true)
1722 if(before < after) {
1723 this.log(logme + 'flipped parameters, rejecting it.');
1727 if(typeof this.fixed_min_duration === 'undefined')
1728 this.fixed_min_duration = Math.round((this.chartWidth() / 30) * this.chart.update_every * 1000);
1730 var min_duration = this.fixed_min_duration;
1731 var current_duration = Math.round(this.view_before - this.view_after);
1733 // round the numbers
1734 after = Math.round(after);
1735 before = Math.round(before);
1737 // align them to update_every
1738 // stretching them further away
1739 after -= after % this.data_update_every;
1740 before += this.data_update_every - (before % this.data_update_every);
1742 // the final wanted duration
1743 var wanted_duration = before - after;
1745 // to allow panning, accept just a point below our minimum
1746 if((current_duration - this.data_update_every) < min_duration)
1747 min_duration = current_duration - this.data_update_every;
1749 // we do it, but we adjust to minimum size and return false
1750 // when the wanted size is below the current and the minimum
1752 if(this.current === this.zoom && wanted_duration < current_duration && wanted_duration < min_duration) {
1753 if(this.debug === true)
1754 this.log(logme + 'too small: min_duration: ' + (min_duration / 1000).toString() + ', wanted: ' + (wanted_duration / 1000).toString());
1756 min_duration = this.fixed_min_duration;
1758 var dt = (min_duration - wanted_duration) / 2;
1764 var tolerance = this.data_update_every * 2;
1765 var movement = Math.abs(before - this.view_before);
1767 if(Math.abs(current_duration - wanted_duration) <= tolerance && movement <= tolerance) {
1768 if(this.debug === true)
1769 this.log(logme + 'REJECTING UPDATE: current duration: ' + (current_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);
1773 if(this.current.name === 'auto') {
1774 this.log(logme + 'caller called me with mode: ' + this.current.name);
1775 this.setMode('pan');
1778 if(this.debug === true)
1779 this.log(logme + 'ACCEPTING UPDATE: current duration: ' + (current_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);
1781 this.current.force_update_at = new Date().getTime() + NETDATA.options.current.pan_and_zoom_delay;
1782 this.current.force_after_ms = after;
1783 this.current.force_before_ms = before;
1784 NETDATA.globalPanAndZoom.setMaster(this, after, before);
1788 this.legendFormatValue = function(value) {
1789 if(value === null || value === 'undefined') return '-';
1790 if(typeof value !== 'number') return value;
1792 var abs = Math.abs(value);
1793 if(abs >= 1000) return (Math.round(value)).toLocaleString();
1794 if(abs >= 100 ) return (Math.round(value * 10) / 10).toLocaleString();
1795 if(abs >= 1 ) return (Math.round(value * 100) / 100).toLocaleString();
1796 if(abs >= 0.1 ) return (Math.round(value * 1000) / 1000).toLocaleString();
1797 return (Math.round(value * 10000) / 10000).toLocaleString();
1800 this.legendSetLabelValue = function(label, value) {
1801 var series = this.element_legend_childs.series[label];
1802 if(typeof series === 'undefined') return;
1803 if(series.value === null && series.user === null) return;
1805 // if the value has not changed, skip DOM update
1806 //if(series.last === value) return;
1809 if(typeof value === 'number') {
1810 var v = Math.abs(value);
1811 s = r = this.legendFormatValue(value);
1813 if(typeof series.last === 'number') {
1814 if(v > series.last) s += '<i class="fa fa-angle-up" style="width: 8px; text-align: center; overflow: hidden; vertical-align: middle;"></i>';
1815 else if(v < series.last) s += '<i class="fa fa-angle-down" style="width: 8px; text-align: center; overflow: hidden; vertical-align: middle;"></i>';
1816 else s += '<i class="fa fa-angle-left" style="width: 8px; text-align: center; overflow: hidden; vertical-align: middle;"></i>';
1818 else s += '<i class="fa fa-angle-right" style="width: 8px; text-align: center; overflow: hidden; vertical-align: middle;"></i>';
1823 series.last = value;
1826 if(series.value !== null) series.value.innerHTML = s;
1827 if(series.user !== null) series.user.innerHTML = r;
1830 this.legendSetDate = function(ms) {
1831 if(typeof ms !== 'number') {
1832 this.legendShowUndefined();
1836 var d = new Date(ms);
1838 if(this.element_legend_childs.title_date)
1839 this.element_legend_childs.title_date.innerHTML = d.toLocaleDateString();
1841 if(this.element_legend_childs.title_time)
1842 this.element_legend_childs.title_time.innerHTML = d.toLocaleTimeString();
1844 if(this.element_legend_childs.title_units)
1845 this.element_legend_childs.title_units.innerHTML = this.units;
1848 this.legendShowUndefined = function() {
1849 if(this.element_legend_childs.title_date)
1850 this.element_legend_childs.title_date.innerHTML = ' ';
1852 if(this.element_legend_childs.title_time)
1853 this.element_legend_childs.title_time.innerHTML = this.chart.name;
1855 if(this.element_legend_childs.title_units)
1856 this.element_legend_childs.title_units.innerHTML = ' ';
1858 if(this.data && this.element_legend_childs.series !== null) {
1859 var labels = this.data.dimension_names;
1860 var i = labels.length;
1862 var label = labels[i];
1864 if(typeof label === 'undefined') continue;
1865 if(typeof this.element_legend_childs.series[label] === 'undefined') continue;
1866 this.legendSetLabelValue(label, null);
1871 this.legendShowLatestValues = function() {
1872 if(this.chart === null) return;
1873 if(this.selected) return;
1875 if(this.data === null || this.element_legend_childs.series === null) {
1876 this.legendShowUndefined();
1880 var show_undefined = true;
1881 if(Math.abs(this.netdata_last - this.view_before) <= this.data_update_every)
1882 show_undefined = false;
1884 if(show_undefined) {
1885 this.legendShowUndefined();
1889 this.legendSetDate(this.view_before);
1891 var labels = this.data.dimension_names;
1892 var i = labels.length;
1894 var label = labels[i];
1896 if(typeof label === 'undefined') continue;
1897 if(typeof this.element_legend_childs.series[label] === 'undefined') continue;
1900 this.legendSetLabelValue(label, null);
1902 this.legendSetLabelValue(label, this.data.view_latest_values[i]);
1906 this.legendReset = function() {
1907 this.legendShowLatestValues();
1910 // this should be called just ONCE per dimension per chart
1911 this._chartDimensionColor = function(label) {
1912 if(this.colors === null) this.chartColors();
1914 if(typeof this.colors_assigned[label] === 'undefined') {
1915 if(this.colors_available.length === 0) {
1916 for(var i = 0, len = NETDATA.colors.length; i < len ; i++)
1917 this.colors_available.push(NETDATA.colors[i]);
1920 this.colors_assigned[label] = this.colors_available.shift();
1922 if(this.debug === true)
1923 this.log('label "' + label + '" got color "' + this.colors_assigned[label]);
1926 if(this.debug === true)
1927 this.log('label "' + label + '" already has color "' + this.colors_assigned[label] + '"');
1930 this.colors.push(this.colors_assigned[label]);
1931 return this.colors_assigned[label];
1934 this.chartColors = function() {
1935 if(this.colors !== null) return this.colors;
1937 this.colors = new Array();
1938 this.colors_available = new Array();
1940 var c = $(this.element).data('colors');
1941 // this.log('read colors: ' + c);
1942 if(typeof c !== 'undefined' && c !== null) {
1943 if(typeof c !== 'string') {
1944 this.log('invalid color given: ' + c + ' (give a space separated list of colors)');
1951 for(var i = 0, len = c.length; i < len ; i++) {
1953 this.colors_available.push(c[i]);
1954 // this.log('adding color: ' + c[i]);
1960 // push all the standard colors too
1961 for(var i = 0, len = NETDATA.colors.length; i < len ; i++)
1962 this.colors_available.push(NETDATA.colors[i]);
1967 this.legendUpdateDOM = function() {
1970 // check that the legend DOM is up to date for the downloaded dimensions
1971 if(typeof this.element_legend_childs.series !== 'object' || this.element_legend_childs.series === null) {
1972 // this.log('the legend does not have any series - requesting legend update');
1975 else if(this.data === null) {
1976 // this.log('the chart does not have any data - requesting legend update');
1979 else if(typeof this.element_legend_childs.series.labels_key === 'undefined') {
1983 var labels = this.data.dimension_names.toString();
1984 if(labels !== this.element_legend_childs.series.labels_key) {
1987 if(this.debug === true)
1988 this.log('NEW LABELS: "' + labels + '" NOT EQUAL OLD LABELS: "' + this.element_legend_childs.series.labels_key + '"');
1992 if(needed === false) {
1993 // make sure colors available
1996 // do we have to update the current values?
1997 // we do this, only when the visible chart is current
1998 if(Math.abs(this.netdata_last - this.view_before) <= this.data_update_every) {
1999 if(this.debug === true)
2000 this.log('chart is in latest position... updating values on legend...');
2002 //var labels = this.data.dimension_names;
2003 //var i = labels.length;
2005 // this.legendSetLabelValue(labels[i], this.data.latest_values[i]);
2009 if(this.colors === null) {
2010 // this is the first time we update the chart
2011 // let's assign colors to all dimensions
2012 if(this.library.track_colors() === true)
2013 for(var dim in this.chart.dimensions)
2014 this._chartDimensionColor(this.chart.dimensions[dim].name);
2016 // we will re-generate the colors for the chart
2017 // based on the selected dimensions
2020 if(this.debug === true)
2021 this.log('updating Legend DOM');
2023 // mark all dimensions as invalid
2024 this.dimensions_visibility.invalidateAll();
2026 var genLabel = function(state, parent, name, count) {
2027 var color = state._chartDimensionColor(name);
2029 var user_element = null;
2030 var user_id = self.data('show-value-of-' + name + '-at') || null;
2031 if(user_id !== null) {
2032 user_element = document.getElementById(user_id) || null;
2033 if(user_element === null)
2034 me.log('Cannot find element with id: ' + user_id);
2037 state.element_legend_childs.series[name] = {
2038 name: document.createElement('span'),
2039 value: document.createElement('span'),
2044 var label = state.element_legend_childs.series[name];
2046 // create the dimension visibility tracking for this label
2047 state.dimensions_visibility.dimensionAdd(name, label.name, label.value, color);
2049 var rgb = NETDATA.colorHex2Rgb(color);
2050 label.name.innerHTML = '<table class="netdata-legend-name-table-'
2051 + state.chart.chart_type
2052 + '" style="background-color: '
2053 + 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + NETDATA.options.current['color_fill_opacity_' + state.chart.chart_type] + ')'
2054 + '"><tr class="netdata-legend-name-tr"><td class="netdata-legend-name-td"></td></tr></table>'
2056 var text = document.createTextNode(' ' + name);
2057 label.name.appendChild(text);
2060 parent.appendChild(document.createElement('br'));
2062 parent.appendChild(label.name);
2063 parent.appendChild(label.value);
2066 var content = document.createElement('div');
2068 if(this.hasLegend()) {
2069 this.element_legend_childs = {
2071 resize_handler: document.createElement('div'),
2072 title_date: document.createElement('span'),
2073 title_time: document.createElement('span'),
2074 title_units: document.createElement('span'),
2075 nano: document.createElement('div'),
2077 paneClass: 'netdata-legend-series-pane',
2078 sliderClass: 'netdata-legend-series-slider',
2079 contentClass: 'netdata-legend-series-content',
2080 enabledClass: '__enabled',
2081 flashedClass: '__flashed',
2082 activeClass: '__active',
2084 alwaysVisible: true,
2090 this.element_legend.innerHTML = '';
2092 this.element_legend_childs.resize_handler.className += " netdata-legend-resize-handler";
2093 this.element_legend_childs.resize_handler.innerHTML = '<i class="fa fa-chevron-up"></i><i class="fa fa-chevron-down"></i>';
2094 this.element.appendChild(this.element_legend_childs.resize_handler);
2097 this.element_legend_childs.resize_handler.onmousedown =
2099 that.resizeHandler(e);
2103 this.element_legend_childs.resize_handler.addEventListener('touchstart', function(e) {
2104 that.resizeHandler(e);
2107 this.element_legend_childs.title_date.className += " netdata-legend-title-date";
2108 this.element_legend.appendChild(this.element_legend_childs.title_date);
2110 this.element_legend.appendChild(document.createElement('br'));
2112 this.element_legend_childs.title_time.className += " netdata-legend-title-time";
2113 this.element_legend.appendChild(this.element_legend_childs.title_time);
2115 this.element_legend.appendChild(document.createElement('br'));
2117 this.element_legend_childs.title_units.className += " netdata-legend-title-units";
2118 this.element_legend.appendChild(this.element_legend_childs.title_units);
2120 this.element_legend.appendChild(document.createElement('br'));
2122 this.element_legend_childs.nano.className = 'netdata-legend-series';
2123 this.element_legend.appendChild(this.element_legend_childs.nano);
2125 content.className = 'netdata-legend-series-content';
2126 this.element_legend_childs.nano.appendChild(content);
2129 this.element_legend_childs = {
2131 resize_handler: null,
2142 this.element_legend_childs.series.labels_key = this.data.dimension_names.toString();
2143 if(this.debug === true)
2144 this.log('labels from data: "' + this.element_legend_childs.series.labels_key + '"');
2146 for(var i = 0, len = this.data.dimension_names.length; i < len ;i++) {
2147 genLabel(this, content, this.data.dimension_names[i], i);
2151 var tmp = new Array();
2152 for(var dim in this.chart.dimensions) {
2153 tmp.push(this.chart.dimensions[dim].name);
2154 genLabel(this, content, this.chart.dimensions[dim].name, i);
2156 this.element_legend_childs.series.labels_key = tmp.toString();
2157 if(this.debug === true)
2158 this.log('labels from chart: "' + this.element_legend_childs.series.labels_key + '"');
2161 // create a hidden div to be used for hidding
2162 // the original legend of the chart library
2163 var el = document.createElement('div');
2164 if(this.element_legend !== null)
2165 this.element_legend.appendChild(el);
2166 el.style.display = 'none';
2168 this.element_legend_childs.hidden = document.createElement('div');
2169 el.appendChild(this.element_legend_childs.hidden);
2171 if(this.element_legend_childs.nano !== null && this.element_legend_childs.nano_options !== null)
2172 $(this.element_legend_childs.nano).nanoScroller(this.element_legend_childs.nano_options);
2174 this.legendShowLatestValues();
2177 this.hasLegend = function() {
2178 if(typeof this.___hasLegendCache___ !== 'undefined')
2179 return this.___hasLegendCache___;
2182 if(this.library && this.library.legend(this) === 'right-side') {
2183 var legend = $(this.element).data('legend') || 'yes';
2184 if(legend === 'yes') leg = true;
2187 this.___hasLegendCache___ = leg;
2191 this.legendWidth = function() {
2192 return (this.hasLegend())?140:0;
2195 this.legendHeight = function() {
2196 return $(this.element).height();
2199 this.chartWidth = function() {
2200 return $(this.element).width() - this.legendWidth();
2203 this.chartHeight = function() {
2204 return $(this.element).height();
2207 this.chartPixelsPerPoint = function() {
2208 // force an options provided detail
2209 var px = this.pixels_per_point;
2211 if(this.library && px < this.library.pixels_per_point(this))
2212 px = this.library.pixels_per_point(this);
2214 if(px < NETDATA.options.current.pixels_per_point)
2215 px = NETDATA.options.current.pixels_per_point;
2220 this.needsRecreation = function() {
2222 this.chart_created === true
2224 && this.library.autoresize() === false
2225 && this.tm.last_resized < NETDATA.options.last_resized
2229 this.chartURL = function() {
2230 var after, before, points_multiplier = 1;
2231 if(NETDATA.globalPanAndZoom.isActive() && NETDATA.globalPanAndZoom.isMaster(this) === false) {
2232 this.tm.pan_and_zoom_seq = NETDATA.globalPanAndZoom.seq;
2234 after = Math.round(NETDATA.globalPanAndZoom.force_after_ms / 1000);
2235 before = Math.round(NETDATA.globalPanAndZoom.force_before_ms / 1000);
2236 this.view_after = after * 1000;
2237 this.view_before = before * 1000;
2239 this.requested_padding = null;
2240 points_multiplier = 1;
2242 else if(this.current.force_before_ms !== null && this.current.force_after_ms !== null) {
2243 this.tm.pan_and_zoom_seq = 0;
2245 before = Math.round(this.current.force_before_ms / 1000);
2246 after = Math.round(this.current.force_after_ms / 1000);
2247 this.view_after = after * 1000;
2248 this.view_before = before * 1000;
2250 if(NETDATA.options.current.pan_and_zoom_data_padding === true) {
2251 this.requested_padding = Math.round((before - after) / 2);
2252 after -= this.requested_padding;
2253 before += this.requested_padding;
2254 this.requested_padding *= 1000;
2255 points_multiplier = 2;
2258 this.current.force_before_ms = null;
2259 this.current.force_after_ms = null;
2262 this.tm.pan_and_zoom_seq = 0;
2264 before = this.before;
2266 this.view_after = after * 1000;
2267 this.view_before = before * 1000;
2269 this.requested_padding = null;
2270 points_multiplier = 1;
2273 this.requested_after = after * 1000;
2274 this.requested_before = before * 1000;
2276 this.data_points = this.points || Math.round(this.chartWidth() / this.chartPixelsPerPoint());
2278 // build the data URL
2279 this.data_url = this.host + this.chart.data_url;
2280 this.data_url += "&format=" + this.library.format();
2281 this.data_url += "&points=" + (this.data_points * points_multiplier).toString();
2282 this.data_url += "&group=" + this.method;
2283 this.data_url += "&options=" + this.library.options(this);
2284 this.data_url += '|jsonwrap';
2286 if(NETDATA.options.current.eliminate_zero_dimensions === true)
2287 this.data_url += '|nonzero';
2289 if(this.append_options !== null)
2290 this.data_url += '|' + this.append_options.toString();
2293 this.data_url += "&after=" + after.toString();
2296 this.data_url += "&before=" + before.toString();
2299 this.data_url += "&dimensions=" + this.dimensions;
2301 if(NETDATA.options.debug.chart_data_url === true || this.debug === true)
2302 this.log('chartURL(): ' + this.data_url + ' WxH:' + this.chartWidth() + 'x' + this.chartHeight() + ' points: ' + this.data_points + ' library: ' + this.library_name);
2305 this.redrawChart = function() {
2306 if(this.data !== null)
2307 this.updateChartWithData(this.data);
2310 this.updateChartWithData = function(data) {
2311 if(this.debug === true)
2312 this.log('updateChartWithData() called.');
2314 // this may force the chart to be re-created
2318 this.updates_counter++;
2319 this.updates_since_last_unhide++;
2320 this.updates_since_last_creation++;
2322 var started = new Date().getTime();
2324 // if the result is JSON, find the latest update-every
2325 this.data_update_every = data.view_update_every * 1000;
2326 this.data_after = data.after * 1000;
2327 this.data_before = data.before * 1000;
2328 this.netdata_first = data.first_entry * 1000;
2329 this.netdata_last = data.last_entry * 1000;
2330 this.data_points = data.points;
2333 if(NETDATA.options.current.pan_and_zoom_data_padding === true && this.requested_padding !== null) {
2334 if(this.view_after < this.data_after) {
2335 // console.log('adusting view_after from ' + this.view_after + ' to ' + this.data_after);
2336 this.view_after = this.data_after;
2339 if(this.view_before > this.data_before) {
2340 // console.log('adusting view_before from ' + this.view_before + ' to ' + this.data_before);
2341 this.view_before = this.data_before;
2345 this.view_after = this.data_after;
2346 this.view_before = this.data_before;
2349 if(this.debug === true) {
2350 this.log('UPDATE No ' + this.updates_counter + ' COMPLETED');
2352 if(this.current.force_after_ms)
2353 this.log('STATUS: forced : ' + (this.current.force_after_ms / 1000).toString() + ' - ' + (this.current.force_before_ms / 1000).toString());
2355 this.log('STATUS: forced : unset');
2357 this.log('STATUS: requested : ' + (this.requested_after / 1000).toString() + ' - ' + (this.requested_before / 1000).toString());
2358 this.log('STATUS: downloaded: ' + (this.data_after / 1000).toString() + ' - ' + (this.data_before / 1000).toString());
2359 this.log('STATUS: rendered : ' + (this.view_after / 1000).toString() + ' - ' + (this.view_before / 1000).toString());
2360 this.log('STATUS: points : ' + (this.data_points).toString());
2363 if(this.data_points === 0) {
2368 if(this.updates_since_last_creation >= this.library.max_updates_to_recreate()) {
2369 if(this.debug === true)
2370 this.log('max updates of ' + this.updates_since_last_creation.toString() + ' reached. Forcing re-generation.');
2372 this.chart_created = false;
2375 // check and update the legend
2376 this.legendUpdateDOM();
2378 if(this.chart_created === true
2379 && typeof this.library.update === 'function') {
2381 if(this.debug === true)
2382 this.log('updating chart...');
2384 if(callChartLibraryUpdateSafely(data) === false)
2388 if(this.debug === true)
2389 this.log('creating chart...');
2391 if(callChartLibraryCreateSafely(data) === false)
2395 this.legendShowLatestValues();
2396 if(this.selected === true)
2397 NETDATA.globalSelectionSync.stop();
2399 // update the performance counters
2400 var now = new Date().getTime();
2401 this.tm.last_updated = now;
2403 // don't update last_autorefreshed if this chart is
2404 // forced to be updated with global PanAndZoom
2405 if(NETDATA.globalPanAndZoom.isActive())
2406 this.tm.last_autorefreshed = 0;
2408 if(NETDATA.options.current.parallel_refresher === true && NETDATA.options.current.concurrent_refreshes)
2409 this.tm.last_autorefreshed = Math.round(now / this.data_update_every) * this.data_update_every;
2411 this.tm.last_autorefreshed = now;
2414 this.refresh_dt_ms = now - started;
2415 NETDATA.options.auto_refresher_fast_weight += this.refresh_dt_ms;
2417 if(this.refresh_dt_element !== null)
2418 this.refresh_dt_element.innerHTML = this.refresh_dt_ms.toString();
2421 this.updateChart = function(callback) {
2422 if(this.debug === true)
2423 this.log('updateChart() called.');
2425 // due to late initialization of charts and libraries
2426 // we need to check this too
2427 if(this.enabled === false) {
2428 if(this.debug === true)
2429 this.log('I am not enabled');
2431 if(typeof callback === 'function') callback();
2435 if(canBeRendered() === false) {
2436 if(typeof callback === 'function') callback();
2440 if(this.chart === null) {
2441 this.getChart(function() { that.updateChart(callback); });
2445 if(this.library.initialized === false) {
2446 if(this.library.enabled === true) {
2447 this.library.initialize(function() { that.updateChart(callback); });
2451 error('chart library "' + this.library_name + '" is not available.');
2452 if(typeof callback === 'function') callback();
2457 this.clearSelection();
2460 if(this.debug === true)
2461 this.log('updating from ' + this.data_url);
2463 this.xhr = $.ajax( {
2465 crossDomain: NETDATA.options.crossDomainAjax,
2469 .success(function(data) {
2470 if(that.debug === true)
2471 that.log('data received. updating chart.');
2473 that.updateChartWithData(data);
2476 error('data download failed for url: ' + that.data_url);
2478 .always(function() {
2479 if(typeof callback === 'function') callback();
2485 this.isVisible = function(nocache) {
2486 if(typeof nocache === 'undefined')
2489 // this.log('last_visible_check: ' + this.tm.last_visible_check + ', last_page_scroll: ' + NETDATA.options.last_page_scroll);
2491 // caching - we do not evaluate the charts visibility
2492 // if the page has not been scrolled since the last check
2493 if(nocache === false && this.tm.last_visible_check > NETDATA.options.last_page_scroll)
2494 return this.___isVisible___;
2496 this.tm.last_visible_check = new Date().getTime();
2498 var wh = window.innerHeight;
2499 var x = this.element.getBoundingClientRect();
2503 if(x.width === 0 || x.height === 0) {
2505 this.___isVisible___ = false;
2506 return this.___isVisible___;
2509 if(x.top < 0 && -x.top > x.height) {
2510 // the chart is entirely above
2511 ret = -x.top - x.height;
2513 else if(x.top > wh) {
2514 // the chart is entirely below
2518 if(ret > tolerance) {
2519 // the chart is too far
2522 this.___isVisible___ = false;
2523 return this.___isVisible___;
2526 // the chart is inside or very close
2529 this.___isVisible___ = true;
2530 return this.___isVisible___;
2534 this.isAutoRefreshed = function() {
2535 return (this.current.autorefresh);
2538 this.canBeAutoRefreshed = function() {
2539 now = new Date().getTime();
2541 if(this.enabled === false) {
2542 if(this.debug === true)
2543 this.log('I am not enabled');
2548 if(this.library === null || this.library.enabled === false) {
2549 error('charting library "' + this.library_name + '" is not available');
2550 if(this.debug === true)
2551 this.log('My chart library ' + this.library_name + ' is not available');
2556 if(this.isVisible() === false) {
2557 if(NETDATA.options.debug.visibility === true || this.debug === true)
2558 this.log('I am not visible');
2563 if(this.current.force_update_at !== 0 && this.current.force_update_at < now) {
2564 if(this.debug === true)
2565 this.log('timed force update detected - allowing this update');
2567 this.current.force_update_at = 0;
2571 if(this.isAutoRefreshed() === true) {
2572 // allow the first update, even if the page is not visible
2573 if(this.updates_counter && this.updates_since_last_unhide && NETDATA.options.page_is_visible === false) {
2574 if(NETDATA.options.debug.focus === true || this.debug === true)
2575 this.log('canBeAutoRefreshed(): page does not have focus');
2580 if(this.needsRecreation() === true) {
2581 if(this.debug === true)
2582 this.log('canBeAutoRefreshed(): needs re-creation.');
2587 // options valid only for autoRefresh()
2588 if(NETDATA.options.auto_refresher_stop_until === 0 || NETDATA.options.auto_refresher_stop_until < now) {
2589 if(NETDATA.globalPanAndZoom.isActive()) {
2590 if(NETDATA.globalPanAndZoom.shouldBeAutoRefreshed(this)) {
2591 if(this.debug === true)
2592 this.log('canBeAutoRefreshed(): global panning: I need an update.');
2597 if(this.debug === true)
2598 this.log('canBeAutoRefreshed(): global panning: I am already up to date.');
2604 if(this.selected === true) {
2605 if(this.debug === true)
2606 this.log('canBeAutoRefreshed(): I have a selection in place.');
2611 if(this.paused === true) {
2612 if(this.debug === true)
2613 this.log('canBeAutoRefreshed(): I am paused.');
2618 if(now - this.tm.last_autorefreshed >= this.data_update_every) {
2619 if(this.debug === true)
2620 this.log('canBeAutoRefreshed(): It is time to update me.');
2630 this.autoRefresh = function(callback) {
2631 if(this.canBeAutoRefreshed() === true) {
2632 this.updateChart(callback);
2635 if(typeof callback !== 'undefined')
2640 this._defaultsFromDownloadedChart = function(chart) {
2642 this.chart_url = chart.url;
2643 this.data_update_every = chart.update_every * 1000;
2644 this.data_points = Math.round(this.chartWidth() / this.chartPixelsPerPoint());
2645 this.tm.last_info_downloaded = new Date().getTime();
2647 if(this.title === null)
2648 this.title = chart.title;
2650 if(this.units === null)
2651 this.units = chart.units;
2654 // fetch the chart description from the netdata server
2655 this.getChart = function(callback) {
2656 this.chart = NETDATA.chartRegistry.get(this.host, this.id);
2658 this._defaultsFromDownloadedChart(this.chart);
2659 if(typeof callback === 'function') callback();
2662 this.chart_url = "/api/v1/chart?chart=" + this.id;
2664 if(this.debug === true)
2665 this.log('downloading ' + this.chart_url);
2668 url: this.host + this.chart_url,
2669 crossDomain: NETDATA.options.crossDomainAjax,
2673 .done(function(chart) {
2674 chart.url = that.chart_url;
2675 that._defaultsFromDownloadedChart(chart);
2676 NETDATA.chartRegistry.add(that.host, that.id, chart);
2679 NETDATA.error(404, that.chart_url);
2680 error('chart not found on url "' + that.chart_url + '"');
2682 .always(function() {
2683 if(typeof callback === 'function') callback();
2688 // ============================================================================================================
2694 NETDATA.resetAllCharts = function(state) {
2695 // first clear the global selection sync
2696 // to make sure no chart is in selected state
2697 state.globalSelectionSyncStop();
2699 // there are 2 possibilities here
2700 // a. state is the global Pan and Zoom master
2701 // b. state is not the global Pan and Zoom master
2703 if(NETDATA.globalPanAndZoom.isMaster(state) === false)
2706 // clear the global Pan and Zoom
2707 // this will also refresh the master
2708 // and unblock any charts currently mirroring the master
2709 NETDATA.globalPanAndZoom.clearMaster();
2711 // if we were not the master, reset our status too
2712 // this is required because most probably the mouse
2713 // is over this chart, blocking it from autorefreshing
2714 if(master === false && (state.paused === true || state.selected === true))
2718 // get or create a chart state, given a DOM element
2719 NETDATA.chartState = function(element) {
2720 var state = $(element).data('netdata-state-object') || null;
2721 if(state === null) {
2722 state = new chartState(element);
2723 $(element).data('netdata-state-object', state);
2728 // ----------------------------------------------------------------------------------------------------------------
2729 // Library functions
2731 // Load a script without jquery
2732 // This is used to load jquery - after it is loaded, we use jquery
2733 NETDATA._loadjQuery = function(callback) {
2734 if(typeof jQuery === 'undefined') {
2735 if(NETDATA.options.debug.main_loop === true)
2736 console.log('loading ' + NETDATA.jQuery);
2738 var script = document.createElement('script');
2739 script.type = 'text/javascript';
2740 script.async = true;
2741 script.src = NETDATA.jQuery;
2743 // script.onabort = onError;
2744 script.onerror = function(err, t) { NETDATA.error(101, NETDATA.jQuery); };
2745 if(typeof callback === "function")
2746 script.onload = callback;
2748 var s = document.getElementsByTagName('script')[0];
2749 s.parentNode.insertBefore(script, s);
2751 else if(typeof callback === "function")
2755 NETDATA._loadCSS = function(filename) {
2756 // don't use jQuery here
2757 // styles are loaded before jQuery
2758 // to eliminate showing an unstyled page to the user
2760 var fileref = document.createElement("link");
2761 fileref.setAttribute("rel", "stylesheet");
2762 fileref.setAttribute("type", "text/css");
2763 fileref.setAttribute("href", filename);
2765 if (typeof fileref !== 'undefined')
2766 document.getElementsByTagName("head")[0].appendChild(fileref);
2769 NETDATA.colorHex2Rgb = function(hex) {
2770 // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
2771 var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
2772 hex = hex.replace(shorthandRegex, function(m, r, g, b) {
2773 return r + r + g + g + b + b;
2776 var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
2778 r: parseInt(result[1], 16),
2779 g: parseInt(result[2], 16),
2780 b: parseInt(result[3], 16)
2784 NETDATA.colorLuminance = function(hex, lum) {
2785 // validate hex string
2786 hex = String(hex).replace(/[^0-9a-f]/gi, '');
2788 hex = hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2];
2792 // convert to decimal and change luminosity
2793 var rgb = "#", c, i;
2794 for (i = 0; i < 3; i++) {
2795 c = parseInt(hex.substr(i*2,2), 16);
2796 c = Math.round(Math.min(Math.max(0, c + (c * lum)), 255)).toString(16);
2797 rgb += ("00"+c).substr(c.length);
2803 NETDATA.guid = function() {
2805 return Math.floor((1 + Math.random()) * 0x10000)
2810 return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
2813 NETDATA.zeropad = function(x) {
2814 if(x > -10 && x < 10) return '0' + x.toString();
2815 else return x.toString();
2818 // user function to signal us the DOM has been
2820 NETDATA.updatedDom = function() {
2821 NETDATA.options.updated_dom = true;
2824 NETDATA.ready = function(callback) {
2825 NETDATA.options.pauseCallback = callback;
2828 NETDATA.pause = function(callback) {
2829 if(NETDATA.options.pause === true)
2832 NETDATA.options.pauseCallback = callback;
2835 NETDATA.unpause = function() {
2836 NETDATA.options.pauseCallback = null;
2837 NETDATA.options.updated_dom = true;
2838 NETDATA.options.pause = false;
2841 // ----------------------------------------------------------------------------------------------------------------
2843 // this is purely sequencial charts refresher
2844 // it is meant to be autonomous
2845 NETDATA.chartRefresherNoParallel = function(index) {
2846 if(NETDATA.options.debug.mail_loop === true)
2847 console.log('NETDATA.chartRefresherNoParallel(' + index + ')');
2849 if(NETDATA.options.updated_dom === true) {
2850 // the dom has been updated
2851 // get the dom parts again
2852 NETDATA.parseDom(NETDATA.chartRefresher);
2855 if(index >= NETDATA.options.targets.length) {
2856 if(NETDATA.options.debug.main_loop === true)
2857 console.log('waiting to restart main loop...');
2859 NETDATA.options.auto_refresher_fast_weight = 0;
2861 setTimeout(function() {
2862 NETDATA.chartRefresher();
2863 }, NETDATA.options.current.idle_between_loops);
2866 var state = NETDATA.options.targets[index];
2868 if(NETDATA.options.auto_refresher_fast_weight < NETDATA.options.current.fast_render_timeframe) {
2869 if(NETDATA.options.debug.main_loop === true)
2870 console.log('fast rendering...');
2872 state.autoRefresh(function() {
2873 NETDATA.chartRefresherNoParallel(++index);
2877 if(NETDATA.options.debug.main_loop === true) console.log('waiting for next refresh...');
2878 NETDATA.options.auto_refresher_fast_weight = 0;
2880 setTimeout(function() {
2881 state.autoRefresh(function() {
2882 NETDATA.chartRefresherNoParallel(++index);
2884 }, NETDATA.options.current.idle_between_charts);
2889 // this is part of the parallel refresher
2890 // its cause is to refresh sequencially all the charts
2891 // that depend on chart library initialization
2892 // it will call the parallel refresher back
2893 // as soon as it sees a chart that its chart library
2895 NETDATA.chartRefresher_unitialized = function() {
2896 if(NETDATA.options.updated_dom === true) {
2897 // the dom has been updated
2898 // get the dom parts again
2899 NETDATA.parseDom(NETDATA.chartRefresher);
2903 if(NETDATA.options.sequencial.length === 0)
2904 NETDATA.chartRefresher();
2906 var state = NETDATA.options.sequencial.pop();
2907 if(state.library.initialized === true)
2908 NETDATA.chartRefresher();
2910 state.autoRefresh(NETDATA.chartRefresher_unitialized);
2914 NETDATA.chartRefresherWaitTime = function() {
2915 return NETDATA.options.current.idle_parallel_loops;
2918 // the default refresher
2919 // it will create 2 sets of charts:
2920 // - the ones that can be refreshed in parallel
2921 // - the ones that depend on something else
2922 // the first set will be executed in parallel
2923 // the second will be given to NETDATA.chartRefresher_unitialized()
2924 NETDATA.chartRefresher = function() {
2925 if(NETDATA.options.pause === true) {
2926 // console.log('auto-refresher is paused');
2927 setTimeout(NETDATA.chartRefresher,
2928 NETDATA.chartRefresherWaitTime());
2932 if(typeof NETDATA.options.pauseCallback === 'function') {
2933 // console.log('auto-refresher is calling pauseCallback');
2934 NETDATA.options.pause = true;
2935 NETDATA.options.pauseCallback();
2936 NETDATA.chartRefresher();
2940 if(NETDATA.options.current.parallel_refresher === false) {
2941 NETDATA.chartRefresherNoParallel(0);
2945 if(NETDATA.options.updated_dom === true) {
2946 // the dom has been updated
2947 // get the dom parts again
2948 NETDATA.parseDom(NETDATA.chartRefresher);
2952 var parallel = new Array();
2953 var targets = NETDATA.options.targets;
2954 var len = targets.length;
2956 if(targets[len].isVisible() === false)
2959 var state = targets[len];
2960 if(state.library.initialized === false) {
2961 if(state.library.enabled === true) {
2962 state.library.initialize(NETDATA.chartRefresher);
2966 state.error('chart library "' + state.library_name + '" is not enabled.');
2970 parallel.unshift(state);
2973 if(parallel.length > 0) {
2974 var parallel_jobs = parallel.length;
2976 // this will execute the jobs in parallel
2977 $(parallel).each(function() {
2978 this.autoRefresh(function() {
2981 if(parallel_jobs === 0) {
2982 setTimeout(NETDATA.chartRefresher,
2983 NETDATA.chartRefresherWaitTime());
2989 setTimeout(NETDATA.chartRefresher,
2990 NETDATA.chartRefresherWaitTime());
2994 NETDATA.parseDom = function(callback) {
2995 NETDATA.options.last_page_scroll = new Date().getTime();
2996 NETDATA.options.updated_dom = false;
2998 var targets = $('div[data-netdata]'); //.filter(':visible');
3000 if(NETDATA.options.debug.main_loop === true)
3001 console.log('DOM updated - there are ' + targets.length + ' charts on page.');
3003 NETDATA.options.targets = new Array();
3004 var len = targets.length;
3006 // the initialization will take care of sizing
3007 // and the "loading..." message
3008 NETDATA.options.targets.push(NETDATA.chartState(targets[len]));
3011 if(typeof callback === 'function') callback();
3014 // this is the main function - where everything starts
3015 NETDATA.start = function() {
3016 // this should be called only once
3018 NETDATA.options.page_is_visible = true;
3020 $(window).blur(function() {
3021 if(NETDATA.options.current.stop_updates_when_focus_is_lost === true) {
3022 NETDATA.options.page_is_visible = false;
3023 if(NETDATA.options.debug.focus === true)
3024 console.log('Lost Focus!');
3028 $(window).focus(function() {
3029 if(NETDATA.options.current.stop_updates_when_focus_is_lost === true) {
3030 NETDATA.options.page_is_visible = true;
3031 if(NETDATA.options.debug.focus === true)
3032 console.log('Focus restored!');
3036 if(typeof document.hasFocus === 'function' && !document.hasFocus()) {
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('Document has no focus!');
3044 // bootstrap tab switching
3045 $('a[data-toggle="tab"]').on('shown.bs.tab', NETDATA.onscroll);
3047 // bootstrap modal switching
3048 $('.modal').on('hidden.bs.modal', NETDATA.onscroll);
3049 $('.modal').on('shown.bs.modal', NETDATA.onscroll);
3051 NETDATA.parseDom(NETDATA.chartRefresher);
3054 // ----------------------------------------------------------------------------------------------------------------
3057 NETDATA.peityInitialize = function(callback) {
3058 if(typeof netdataNoPeitys === 'undefined' || !netdataNoPeitys) {
3060 url: NETDATA.peity_js,
3065 NETDATA.registerChartLibrary('peity', NETDATA.peity_js);
3068 NETDATA.chartLibraries.peity.enabled = false;
3069 NETDATA.error(100, NETDATA.peity_js);
3071 .always(function() {
3072 if(typeof callback === "function")
3077 NETDATA.chartLibraries.peity.enabled = false;
3078 if(typeof callback === "function")
3083 NETDATA.peityChartUpdate = function(state, data) {
3084 state.peity_instance.innerHTML = data.result;
3086 if(state.peity_options.stroke !== state.chartColors()[0]) {
3087 state.peity_options.stroke = state.chartColors()[0];
3088 if(state.chart.chart_type === 'line')
3089 state.peity_options.fill = '#FFF';
3091 state.peity_options.fill = NETDATA.colorLuminance(state.chartColors()[0], NETDATA.chartDefaults.fill_luminance);
3094 $(state.peity_instance).peity('line', state.peity_options);
3098 NETDATA.peityChartCreate = function(state, data) {
3099 state.peity_instance = document.createElement('div');
3100 state.element_chart.appendChild(state.peity_instance);
3102 var self = $(state.element);
3103 state.peity_options = {
3105 strokeWidth: self.data('peity-strokewidth') || 1,
3106 width: state.chartWidth(),
3107 height: state.chartHeight(),
3111 NETDATA.peityChartUpdate(state, data);
3115 // ----------------------------------------------------------------------------------------------------------------
3118 NETDATA.sparklineInitialize = function(callback) {
3119 if(typeof netdataNoSparklines === 'undefined' || !netdataNoSparklines) {
3121 url: NETDATA.sparkline_js,
3126 NETDATA.registerChartLibrary('sparkline', NETDATA.sparkline_js);
3129 NETDATA.chartLibraries.sparkline.enabled = false;
3130 NETDATA.error(100, NETDATA.sparkline_js);
3132 .always(function() {
3133 if(typeof callback === "function")
3138 NETDATA.chartLibraries.sparkline.enabled = false;
3139 if(typeof callback === "function")
3144 NETDATA.sparklineChartUpdate = function(state, data) {
3145 state.sparkline_options.width = state.chartWidth();
3146 state.sparkline_options.height = state.chartHeight();
3148 $(state.element_chart).sparkline(data.result, state.sparkline_options);
3152 NETDATA.sparklineChartCreate = function(state, data) {
3153 var self = $(state.element);
3154 var type = self.data('sparkline-type') || 'line';
3155 var lineColor = self.data('sparkline-linecolor') || state.chartColors()[0];
3156 var fillColor = self.data('sparkline-fillcolor') || (state.chart.chart_type === 'line')?'#FFF':NETDATA.colorLuminance(lineColor, NETDATA.chartDefaults.fill_luminance);
3157 var chartRangeMin = self.data('sparkline-chartrangemin') || undefined;
3158 var chartRangeMax = self.data('sparkline-chartrangemax') || undefined;
3159 var composite = self.data('sparkline-composite') || undefined;
3160 var enableTagOptions = self.data('sparkline-enabletagoptions') || undefined;
3161 var tagOptionPrefix = self.data('sparkline-tagoptionprefix') || undefined;
3162 var tagValuesAttribute = self.data('sparkline-tagvaluesattribute') || undefined;
3163 var disableHiddenCheck = self.data('sparkline-disablehiddencheck') || undefined;
3164 var defaultPixelsPerValue = self.data('sparkline-defaultpixelspervalue') || undefined;
3165 var spotColor = self.data('sparkline-spotcolor') || undefined;
3166 var minSpotColor = self.data('sparkline-minspotcolor') || undefined;
3167 var maxSpotColor = self.data('sparkline-maxspotcolor') || undefined;
3168 var spotRadius = self.data('sparkline-spotradius') || undefined;
3169 var valueSpots = self.data('sparkline-valuespots') || undefined;
3170 var highlightSpotColor = self.data('sparkline-highlightspotcolor') || undefined;
3171 var highlightLineColor = self.data('sparkline-highlightlinecolor') || undefined;
3172 var lineWidth = self.data('sparkline-linewidth') || undefined;
3173 var normalRangeMin = self.data('sparkline-normalrangemin') || undefined;
3174 var normalRangeMax = self.data('sparkline-normalrangemax') || undefined;
3175 var drawNormalOnTop = self.data('sparkline-drawnormalontop') || undefined;
3176 var xvalues = self.data('sparkline-xvalues') || undefined;
3177 var chartRangeClip = self.data('sparkline-chartrangeclip') || undefined;
3178 var xvalues = self.data('sparkline-xvalues') || undefined;
3179 var chartRangeMinX = self.data('sparkline-chartrangeminx') || undefined;
3180 var chartRangeMaxX = self.data('sparkline-chartrangemaxx') || undefined;
3181 var disableInteraction = self.data('sparkline-disableinteraction') || false;
3182 var disableTooltips = self.data('sparkline-disabletooltips') || false;
3183 var disableHighlight = self.data('sparkline-disablehighlight') || false;
3184 var highlightLighten = self.data('sparkline-highlightlighten') || 1.4;
3185 var highlightColor = self.data('sparkline-highlightcolor') || undefined;
3186 var tooltipContainer = self.data('sparkline-tooltipcontainer') || undefined;
3187 var tooltipClassname = self.data('sparkline-tooltipclassname') || undefined;
3188 var tooltipFormat = self.data('sparkline-tooltipformat') || undefined;
3189 var tooltipPrefix = self.data('sparkline-tooltipprefix') || undefined;
3190 var tooltipSuffix = self.data('sparkline-tooltipsuffix') || ' ' + state.units;
3191 var tooltipSkipNull = self.data('sparkline-tooltipskipnull') || true;
3192 var tooltipValueLookups = self.data('sparkline-tooltipvaluelookups') || undefined;
3193 var tooltipFormatFieldlist = self.data('sparkline-tooltipformatfieldlist') || undefined;
3194 var tooltipFormatFieldlistKey = self.data('sparkline-tooltipformatfieldlistkey') || undefined;
3195 var numberFormatter = self.data('sparkline-numberformatter') || function(n){ return n.toFixed(2); };
3196 var numberDigitGroupSep = self.data('sparkline-numberdigitgroupsep') || undefined;
3197 var numberDecimalMark = self.data('sparkline-numberdecimalmark') || undefined;
3198 var numberDigitGroupCount = self.data('sparkline-numberdigitgroupcount') || undefined;
3199 var animatedZooms = self.data('sparkline-animatedzooms') || false;
3201 state.sparkline_options = {
3203 lineColor: lineColor,
3204 fillColor: fillColor,
3205 chartRangeMin: chartRangeMin,
3206 chartRangeMax: chartRangeMax,
3207 composite: composite,
3208 enableTagOptions: enableTagOptions,
3209 tagOptionPrefix: tagOptionPrefix,
3210 tagValuesAttribute: tagValuesAttribute,
3211 disableHiddenCheck: disableHiddenCheck,
3212 defaultPixelsPerValue: defaultPixelsPerValue,
3213 spotColor: spotColor,
3214 minSpotColor: minSpotColor,
3215 maxSpotColor: maxSpotColor,
3216 spotRadius: spotRadius,
3217 valueSpots: valueSpots,
3218 highlightSpotColor: highlightSpotColor,
3219 highlightLineColor: highlightLineColor,
3220 lineWidth: lineWidth,
3221 normalRangeMin: normalRangeMin,
3222 normalRangeMax: normalRangeMax,
3223 drawNormalOnTop: drawNormalOnTop,
3225 chartRangeClip: chartRangeClip,
3226 chartRangeMinX: chartRangeMinX,
3227 chartRangeMaxX: chartRangeMaxX,
3228 disableInteraction: disableInteraction,
3229 disableTooltips: disableTooltips,
3230 disableHighlight: disableHighlight,
3231 highlightLighten: highlightLighten,
3232 highlightColor: highlightColor,
3233 tooltipContainer: tooltipContainer,
3234 tooltipClassname: tooltipClassname,
3235 tooltipChartTitle: state.title,
3236 tooltipFormat: tooltipFormat,
3237 tooltipPrefix: tooltipPrefix,
3238 tooltipSuffix: tooltipSuffix,
3239 tooltipSkipNull: tooltipSkipNull,
3240 tooltipValueLookups: tooltipValueLookups,
3241 tooltipFormatFieldlist: tooltipFormatFieldlist,
3242 tooltipFormatFieldlistKey: tooltipFormatFieldlistKey,
3243 numberFormatter: numberFormatter,
3244 numberDigitGroupSep: numberDigitGroupSep,
3245 numberDecimalMark: numberDecimalMark,
3246 numberDigitGroupCount: numberDigitGroupCount,
3247 animatedZooms: animatedZooms,
3248 width: state.chartWidth(),
3249 height: state.chartHeight()
3252 $(state.element_chart).sparkline(data.result, state.sparkline_options);
3256 // ----------------------------------------------------------------------------------------------------------------
3263 NETDATA.dygraphSetSelection = function(state, t) {
3264 if(typeof state.dygraph_instance !== 'undefined') {
3265 var r = state.calculateRowForTime(t);
3267 state.dygraph_instance.setSelection(r);
3269 state.dygraph_instance.clearSelection();
3270 state.legendShowUndefined();
3277 NETDATA.dygraphClearSelection = function(state, t) {
3278 if(typeof state.dygraph_instance !== 'undefined') {
3279 state.dygraph_instance.clearSelection();
3284 NETDATA.dygraphSmoothInitialize = function(callback) {
3286 url: NETDATA.dygraph_smooth_js,
3291 NETDATA.dygraph.smooth = true;
3292 smoothPlotter.smoothing = 0.3;
3295 NETDATA.dygraph.smooth = false;
3297 .always(function() {
3298 if(typeof callback === "function")
3303 NETDATA.dygraphInitialize = function(callback) {
3304 if(typeof netdataNoDygraphs === 'undefined' || !netdataNoDygraphs) {
3306 url: NETDATA.dygraph_js,
3311 NETDATA.registerChartLibrary('dygraph', NETDATA.dygraph_js);
3314 NETDATA.chartLibraries.dygraph.enabled = false;
3315 NETDATA.error(100, NETDATA.dygraph_js);
3317 .always(function() {
3318 if(NETDATA.chartLibraries.dygraph.enabled === true && NETDATA.options.current.smooth_plot === true)
3319 NETDATA.dygraphSmoothInitialize(callback);
3320 else if(typeof callback === "function")
3325 NETDATA.chartLibraries.dygraph.enabled = false;
3326 if(typeof callback === "function")
3331 NETDATA.dygraphChartUpdate = function(state, data) {
3332 var dygraph = state.dygraph_instance;
3334 if(typeof dygraph === 'undefined')
3335 return NETDATA.dygraphChartCreate(state, data);
3337 // when the chart is not visible, and hidden
3338 // if there is a window resize, dygraph detects
3339 // its element size as 0x0.
3340 // this will make it re-appear properly
3342 if(state.tm.last_unhidden > state.dygraph_last_rendered)
3346 file: data.result.data,
3347 colors: state.chartColors(),
3348 labels: data.result.labels,
3349 labelsDivWidth: state.chartWidth() - 70,
3350 visibility: state.dimensions_visibility.selected2BooleanArray(state.data.dimension_names)
3353 if(state.current.name !== 'auto') {
3354 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3355 state.log('dygraphChartUpdate() loose update');
3358 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3359 state.log('dygraphChartUpdate() strict update');
3361 options.dateWindow = null;
3362 options.valueRange = null;
3365 if(state.dygraph_smooth_eligible === true) {
3366 if((NETDATA.options.current.smooth_plot === true && state.dygraph_options.plotter !== smoothPlotter)
3367 || (NETDATA.options.current.smooth_plot === false && state.dygraph_options.plotter === smoothPlotter)) {
3368 NETDATA.dygraphChartCreate(state, data);
3373 dygraph.updateOptions(options);
3374 state.dygraph_last_rendered = new Date().getTime();
3378 NETDATA.dygraphChartCreate = function(state, data) {
3379 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3380 state.log('dygraphChartCreate()');
3382 var self = $(state.element);
3384 var chart_type = state.chart.chart_type;
3385 if(chart_type === 'stacked' && data.dimensions === 1) chart_type = 'area';
3386 chart_type = self.data('dygraph-type') || chart_type;
3388 var smooth = (chart_type === 'line' && !NETDATA.chartLibraries.dygraph.isSparkline(state))?true:false;
3389 smooth = self.data('dygraph-smooth') || smooth;
3391 if(NETDATA.dygraph.smooth === false)
3394 var strokeWidth = (chart_type === 'stacked')?0.1:((smooth)?1.5:0.7)
3395 var highlightCircleSize = (NETDATA.chartLibraries.dygraph.isSparkline(state))?3:4;
3397 state.dygraph_options = {
3398 colors: self.data('dygraph-colors') || state.chartColors(),
3400 // leave a few pixels empty on the right of the chart
3401 rightGap: self.data('dygraph-rightgap') || 5,
3402 showRangeSelector: self.data('dygraph-showrangeselector') || false,
3403 showRoller: self.data('dygraph-showroller') || false,
3405 title: self.data('dygraph-title') || state.title,
3406 titleHeight: self.data('dygraph-titleheight') || 19,
3408 legend: self.data('dygraph-legend') || 'always', // 'onmouseover',
3409 labels: data.result.labels,
3410 labelsDiv: self.data('dygraph-labelsdiv') || state.element_legend_childs.hidden,
3411 labelsDivStyles: self.data('dygraph-labelsdivstyles') || { 'fontSize':'1px' },
3412 labelsDivWidth: self.data('dygraph-labelsdivwidth') || state.chartWidth() - 70,
3413 labelsSeparateLines: self.data('dygraph-labelsseparatelines') || true,
3414 labelsShowZeroValues: self.data('dygraph-labelsshowzerovalues') || true,
3417 showLabelsOnHighlight: self.data('dygraph-showlabelsonhighlight') || true,
3418 hideOverlayOnMouseOut: self.data('dygraph-hideoverlayonmouseout') || true,
3420 ylabel: state.units,
3421 yLabelWidth: self.data('dygraph-ylabelwidth') || 12,
3423 // the function to plot the chart
3426 // The width of the lines connecting data points. This can be used to increase the contrast or some graphs.
3427 strokeWidth: self.data('dygraph-strokewidth') || strokeWidth,
3428 strokePattern: self.data('dygraph-strokepattern') || undefined,
3430 // The size of the dot to draw on each point in pixels (see drawPoints). A dot is always drawn when a point is "isolated",
3431 // i.e. there is a missing point on either side of it. This also controls the size of those dots.
3432 drawPoints: self.data('dygraph-drawpoints') || false,
3434 // Draw points at the edges of gaps in the data. This improves visibility of small data segments or other data irregularities.
3435 drawGapEdgePoints: self.data('dygraph-drawgapedgepoints') || true,
3437 connectSeparatedPoints: self.data('dygraph-connectseparatedpoints') || false,
3438 pointSize: self.data('dygraph-pointsize') || 1,
3440 // enabling this makes the chart with little square lines
3441 stepPlot: self.data('dygraph-stepplot') || false,
3443 // Draw a border around graph lines to make crossing lines more easily distinguishable. Useful for graphs with many lines.
3444 strokeBorderColor: self.data('dygraph-strokebordercolor') || 'white',
3445 strokeBorderWidth: self.data('dygraph-strokeborderwidth') || (chart_type === 'stacked')?0.0:0.0,
3447 fillGraph: self.data('dygraph-fillgraph') || (chart_type === 'area' || chart_type === 'stacked')?true:false,
3448 fillAlpha: self.data('dygraph-fillalpha') || (chart_type === 'stacked')?NETDATA.options.current.color_fill_opacity_stacked:NETDATA.options.current.color_fill_opacity_area,
3449 stackedGraph: self.data('dygraph-stackedgraph') || (chart_type === 'stacked')?true:false,
3450 stackedGraphNaNFill: self.data('dygraph-stackedgraphnanfill') || 'none',
3452 drawAxis: self.data('dygraph-drawaxis') || true,
3453 axisLabelFontSize: self.data('dygraph-axislabelfontsize') || 10,
3454 axisLineColor: self.data('dygraph-axislinecolor') || '#CCC',
3455 axisLineWidth: self.data('dygraph-axislinewidth') || 0.3,
3457 drawGrid: self.data('dygraph-drawgrid') || true,
3458 drawXGrid: self.data('dygraph-drawxgrid') || undefined,
3459 drawYGrid: self.data('dygraph-drawygrid') || undefined,
3460 gridLinePattern: self.data('dygraph-gridlinepattern') || null,
3461 gridLineWidth: self.data('dygraph-gridlinewidth') || 0.3,
3462 gridLineColor: self.data('dygraph-gridlinecolor') || '#DDD',
3464 maxNumberWidth: self.data('dygraph-maxnumberwidth') || 8,
3465 sigFigs: self.data('dygraph-sigfigs') || null,
3466 digitsAfterDecimal: self.data('dygraph-digitsafterdecimal') || 2,
3467 valueFormatter: self.data('dygraph-valueformatter') || function(x){ return x.toFixed(2); },
3469 highlightCircleSize: self.data('dygraph-highlightcirclesize') || highlightCircleSize,
3470 highlightSeriesOpts: self.data('dygraph-highlightseriesopts') || null, // TOO SLOW: { strokeWidth: 1.5 },
3471 highlightSeriesBackgroundAlpha: self.data('dygraph-highlightseriesbackgroundalpha') || null, // TOO SLOW: (chart_type === 'stacked')?0.7:0.5,
3473 pointClickCallback: self.data('dygraph-pointclickcallback') || undefined,
3474 visibility: state.dimensions_visibility.selected2BooleanArray(state.data.dimension_names),
3478 ticker: Dygraph.dateTicker,
3479 axisLabelFormatter: function (d, gran) {
3480 return NETDATA.zeropad(d.getHours()) + ":" + NETDATA.zeropad(d.getMinutes()) + ":" + NETDATA.zeropad(d.getSeconds());
3482 valueFormatter: function (ms) {
3483 var d = new Date(ms);
3484 return d.toLocaleDateString() + ' ' + d.toLocaleTimeString();
3485 // return NETDATA.zeropad(d.getHours()) + ":" + NETDATA.zeropad(d.getMinutes()) + ":" + NETDATA.zeropad(d.getSeconds());
3490 valueFormatter: function (x) {
3491 // we format legends with the state object
3492 // no need to do anything here
3493 // return (Math.round(x*100) / 100).toLocaleString();
3494 // return state.legendFormatValue(x);
3499 legendFormatter: function(data) {
3500 var elements = state.element_legend_childs;
3502 // if the hidden div is not there
3503 // we are not managing the legend
3504 if(elements.hidden === null) return;
3506 if (typeof data.x !== 'undefined') {
3507 state.legendSetDate(data.x);
3508 var i = data.series.length;
3510 var series = data.series[i];
3511 if(!series.isVisible) continue;
3512 state.legendSetLabelValue(series.label, series.y);
3518 drawCallback: function(dygraph, is_initial) {
3519 if(state.current.name !== 'auto') {
3520 if(NETDATA.options.debug.dygraph === true)
3521 state.log('dygraphDrawCallback()');
3523 var x_range = dygraph.xAxisRange();
3524 var after = Math.round(x_range[0]);
3525 var before = Math.round(x_range[1]);
3527 if(before <= state.netdata_last && after >= state.netdata_first)
3528 state.updateChartPanOrZoom(after, before);
3531 zoomCallback: function(minDate, maxDate, yRanges) {
3532 if(NETDATA.options.debug.dygraph === true)
3533 state.log('dygraphZoomCallback()');
3535 state.globalSelectionSyncStop();
3536 state.globalSelectionSyncDelay();
3538 if(state.updateChartPanOrZoom(minDate, maxDate) === false) {
3539 // we should not zoom that much
3540 state.dygraph_instance.updateOptions({
3546 highlightCallback: function(event, x, points, row, seriesName) {
3547 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3548 state.log('dygraphHighlightCallback()');
3552 // there is a bug in dygraph when the chart is zoomed enough
3553 // the time it thinks is selected is wrong
3554 // here we calculate the time t based on the row number selected
3556 var t = state.data_after + row * state.data_update_every;
3557 // 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);
3559 state.globalSelectionSync(x);
3561 // fix legend zIndex using the internal structures of dygraph legend module
3562 // this works, but it is a hack!
3563 // state.dygraph_instance.plugins_[0].plugin.legend_div_.style.zIndex = 10000;
3565 unhighlightCallback: function(event) {
3566 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3567 state.log('dygraphUnhighlightCallback()');
3569 state.unpauseChart();
3570 state.globalSelectionSyncStop();
3572 interactionModel : {
3573 mousedown: function(event, dygraph, context) {
3574 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3575 state.log('interactionModel.mousedown()');
3577 state.globalSelectionSyncStop();
3579 if(NETDATA.options.debug.dygraph === true)
3580 state.log('dygraphMouseDown()');
3582 // Right-click should not initiate a zoom.
3583 if(event.button && event.button === 2) return;
3585 context.initializeMouseDown(event, dygraph, context);
3587 if(event.button && event.button === 1) {
3588 if (event.altKey || event.shiftKey) {
3589 state.setMode('pan');
3590 state.globalSelectionSyncDelay();
3591 Dygraph.startPan(event, dygraph, context);
3594 state.setMode('zoom');
3595 state.globalSelectionSyncDelay();
3596 Dygraph.startZoom(event, dygraph, context);
3600 if (event.altKey || event.shiftKey) {
3601 state.setMode('zoom');
3602 state.globalSelectionSyncDelay();
3603 Dygraph.startZoom(event, dygraph, context);
3606 state.setMode('pan');
3607 state.globalSelectionSyncDelay();
3608 Dygraph.startPan(event, dygraph, context);
3612 mousemove: function(event, dygraph, context) {
3613 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3614 state.log('interactionModel.mousemove()');
3616 if(context.isPanning) {
3617 state.globalSelectionSyncStop();
3618 state.globalSelectionSyncDelay();
3619 state.setMode('pan');
3620 Dygraph.movePan(event, dygraph, context);
3622 else if(context.isZooming) {
3623 state.globalSelectionSyncStop();
3624 state.globalSelectionSyncDelay();
3625 state.setMode('zoom');
3626 Dygraph.moveZoom(event, dygraph, context);
3629 mouseup: function(event, dygraph, context) {
3630 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3631 state.log('interactionModel.mouseup()');
3633 if (context.isPanning) {
3634 state.globalSelectionSyncDelay();
3635 Dygraph.endPan(event, dygraph, context);
3637 else if (context.isZooming) {
3638 state.globalSelectionSyncDelay();
3639 Dygraph.endZoom(event, dygraph, context);
3642 click: function(event, dygraph, context) {
3643 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3644 state.log('interactionModel.click()');
3646 event.preventDefault();
3648 dblclick: function(event, dygraph, context) {
3649 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3650 state.log('interactionModel.dblclick()');
3651 NETDATA.resetAllCharts(state);
3653 mousewheel: function(event, dygraph, context) {
3654 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3655 state.log('interactionModel.mousewheel()');
3657 // Take the offset of a mouse event on the dygraph canvas and
3658 // convert it to a pair of percentages from the bottom left.
3659 // (Not top left, bottom is where the lower value is.)
3660 function offsetToPercentage(g, offsetX, offsetY) {
3661 // This is calculating the pixel offset of the leftmost date.
3662 var xOffset = g.toDomCoords(g.xAxisRange()[0], null)[0];
3663 var yar0 = g.yAxisRange(0);
3665 // This is calculating the pixel of the higest value. (Top pixel)
3666 var yOffset = g.toDomCoords(null, yar0[1])[1];
3668 // x y w and h are relative to the corner of the drawing area,
3669 // so that the upper corner of the drawing area is (0, 0).
3670 var x = offsetX - xOffset;
3671 var y = offsetY - yOffset;
3673 // This is computing the rightmost pixel, effectively defining the
3675 var w = g.toDomCoords(g.xAxisRange()[1], null)[0] - xOffset;
3677 // This is computing the lowest pixel, effectively defining the height.
3678 var h = g.toDomCoords(null, yar0[0])[1] - yOffset;
3680 // Percentage from the left.
3681 var xPct = w === 0 ? 0 : (x / w);
3682 // Percentage from the top.
3683 var yPct = h === 0 ? 0 : (y / h);
3685 // The (1-) part below changes it from "% distance down from the top"
3686 // to "% distance up from the bottom".
3687 return [xPct, (1-yPct)];
3690 // Adjusts [x, y] toward each other by zoomInPercentage%
3691 // Split it so the left/bottom axis gets xBias/yBias of that change and
3692 // tight/top gets (1-xBias)/(1-yBias) of that change.
3694 // If a bias is missing it splits it down the middle.
3695 function zoomRange(g, zoomInPercentage, xBias, yBias) {
3696 xBias = xBias || 0.5;
3697 yBias = yBias || 0.5;
3699 function adjustAxis(axis, zoomInPercentage, bias) {
3700 var delta = axis[1] - axis[0];
3701 var increment = delta * zoomInPercentage;
3702 var foo = [increment * bias, increment * (1-bias)];
3704 return [ axis[0] + foo[0], axis[1] - foo[1] ];
3707 var yAxes = g.yAxisRanges();
3709 for (var i = 0; i < yAxes.length; i++) {
3710 newYAxes[i] = adjustAxis(yAxes[i], zoomInPercentage, yBias);
3713 return adjustAxis(g.xAxisRange(), zoomInPercentage, xBias);
3716 if(event.altKey || event.shiftKey) {
3717 state.globalSelectionSyncStop();
3718 state.globalSelectionSyncDelay();
3720 // http://dygraphs.com/gallery/interaction-api.js
3721 var normal = (event.detail) ? event.detail * -1 : event.wheelDelta / 40;
3722 var percentage = normal / 50;
3724 if (!(event.offsetX && event.offsetY)){
3725 event.offsetX = event.layerX - event.target.offsetLeft;
3726 event.offsetY = event.layerY - event.target.offsetTop;
3729 var percentages = offsetToPercentage(dygraph, event.offsetX, event.offsetY);
3730 var xPct = percentages[0];
3731 var yPct = percentages[1];
3733 var new_x_range = zoomRange(dygraph, percentage, xPct, yPct);
3735 var after = new_x_range[0];
3736 var before = new_x_range[1];
3738 var first = state.netdata_first + state.data_update_every;
3739 var last = state.netdata_last + state.data_update_every;
3742 after -= (before - last);
3749 state.setMode('zoom');
3750 if(state.updateChartPanOrZoom(after, before) === true)
3751 dygraph.updateOptions({ dateWindow: [ after, before ] });
3753 event.preventDefault();
3756 touchstart: function(event, dygraph, context) {
3757 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3758 state.log('interactionModel.touchstart()');
3760 state.setMode('zoom');
3763 Dygraph.defaultInteractionModel.touchstart(event, dygraph, context);
3765 // we overwrite the touch directions at the end, to overwrite
3766 // the internal default of dygraphs
3767 context.touchDirections = { x: true, y: false };
3769 state.dygraph_last_touch_start = new Date().getTime();
3770 state.dygraph_last_touch_move = 0;
3772 if(typeof event.touches[0].pageX === 'number')
3773 state.dygraph_last_touch_page_x = event.touches[0].pageX;
3775 state.dygraph_last_touch_page_x = 0;
3777 touchmove: function(event, dygraph, context) {
3778 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3779 state.log('interactionModel.touchmove()');
3781 Dygraph.defaultInteractionModel.touchmove(event, dygraph, context);
3783 state.dygraph_last_touch_move = new Date().getTime();
3785 touchend: function(event, dygraph, context) {
3786 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3787 state.log('interactionModel.touchend()');
3789 Dygraph.defaultInteractionModel.touchend(event, dygraph, context);
3791 // if it didn't move, it is a selection
3792 if(state.dygraph_last_touch_move === 0 && state.dygraph_last_touch_page_x !== 0) {
3793 // internal api of dygraphs
3794 var pct = (state.dygraph_last_touch_page_x - (dygraph.plotter_.area.x + state.element.getBoundingClientRect().left)) / dygraph.plotter_.area.w;
3795 var t = Math.round(state.data_after + (state.data_before - state.data_after) * pct);
3796 if(NETDATA.dygraphSetSelection(state, t) === true)
3797 state.globalSelectionSync(t);
3800 // if it was double tap within double click time, reset the charts
3801 var now = new Date().getTime();
3802 if(typeof state.dygraph_last_touch_end !== 'undefined') {
3803 if(state.dygraph_last_touch_move === 0) {
3804 var dt = now - state.dygraph_last_touch_end;
3805 if(dt <= NETDATA.options.current.double_click_speed)
3806 NETDATA.resetAllCharts(state);
3810 // remember the timestamp of the last touch end
3811 state.dygraph_last_touch_end = now;
3816 if(NETDATA.chartLibraries.dygraph.isSparkline(state)) {
3817 state.dygraph_options.drawGrid = false;
3818 state.dygraph_options.drawAxis = false;
3819 state.dygraph_options.title = undefined;
3820 state.dygraph_options.units = undefined;
3821 state.dygraph_options.ylabel = undefined;
3822 state.dygraph_options.yLabelWidth = 0;
3823 state.dygraph_options.labelsDivWidth = 120;
3824 state.dygraph_options.labelsDivStyles.width = '120px';
3825 state.dygraph_options.labelsSeparateLines = true;
3826 state.dygraph_options.rightGap = 0;
3829 if(smooth === true) {
3830 state.dygraph_smooth_eligible = true;
3832 if(NETDATA.options.current.smooth_plot === true)
3833 state.dygraph_options.plotter = smoothPlotter;
3835 else state.dygraph_smooth_eligible = false;
3837 state.dygraph_instance = new Dygraph(state.element_chart,
3838 data.result.data, state.dygraph_options);
3840 state.dygraph_last_rendered = new Date().getTime();
3844 // ----------------------------------------------------------------------------------------------------------------
3847 NETDATA.morrisInitialize = function(callback) {
3848 if(typeof netdataNoMorris === 'undefined' || !netdataNoMorris) {
3850 // morris requires raphael
3851 if(!NETDATA.chartLibraries.raphael.initialized) {
3852 if(NETDATA.chartLibraries.raphael.enabled) {
3853 NETDATA.raphaelInitialize(function() {
3854 NETDATA.morrisInitialize(callback);
3858 NETDATA.chartLibraries.morris.enabled = false;
3859 if(typeof callback === "function")
3864 NETDATA._loadCSS(NETDATA.morris_css);
3867 url: NETDATA.morris_js,
3872 NETDATA.registerChartLibrary('morris', NETDATA.morris_js);
3875 NETDATA.chartLibraries.morris.enabled = false;
3876 NETDATA.error(100, NETDATA.morris_js);
3878 .always(function() {
3879 if(typeof callback === "function")
3885 NETDATA.chartLibraries.morris.enabled = false;
3886 if(typeof callback === "function")
3891 NETDATA.morrisChartUpdate = function(state, data) {
3892 state.morris_instance.setData(data.result.data);
3896 NETDATA.morrisChartCreate = function(state, data) {
3898 state.morris_options = {
3899 element: state.element_chart.id,
3900 data: data.result.data,
3902 ykeys: data.dimension_names,
3903 labels: data.dimension_names,
3909 continuousLine: false,
3910 behaveLikeLine: false
3913 if(state.chart.chart_type === 'line')
3914 state.morris_instance = new Morris.Line(state.morris_options);
3916 else if(state.chart.chart_type === 'area') {
3917 state.morris_options.behaveLikeLine = true;
3918 state.morris_instance = new Morris.Area(state.morris_options);
3921 state.morris_instance = new Morris.Area(state.morris_options);
3926 // ----------------------------------------------------------------------------------------------------------------
3929 NETDATA.raphaelInitialize = function(callback) {
3930 if(typeof netdataStopRaphael === 'undefined' || !netdataStopRaphael) {
3932 url: NETDATA.raphael_js,
3937 NETDATA.registerChartLibrary('raphael', NETDATA.raphael_js);
3940 NETDATA.chartLibraries.raphael.enabled = false;
3941 NETDATA.error(100, NETDATA.raphael_js);
3943 .always(function() {
3944 if(typeof callback === "function")
3949 NETDATA.chartLibraries.raphael.enabled = false;
3950 if(typeof callback === "function")
3955 NETDATA.raphaelChartUpdate = function(state, data) {
3956 $(state.element_chart).raphael(data.result, {
3957 width: state.chartWidth(),
3958 height: state.chartHeight()
3964 NETDATA.raphaelChartCreate = function(state, data) {
3965 $(state.element_chart).raphael(data.result, {
3966 width: state.chartWidth(),
3967 height: state.chartHeight()
3973 // ----------------------------------------------------------------------------------------------------------------
3976 NETDATA.c3Initialize = function(callback) {
3977 if(typeof netdataNoC3 === 'undefined' || !netdataNoC3) {
3980 if(!NETDATA.chartLibraries.d3.initialized) {
3981 if(NETDATA.chartLibraries.d3.enabled) {
3982 NETDATA.d3Initialize(function() {
3983 NETDATA.c3Initialize(callback);
3987 NETDATA.chartLibraries.c3.enabled = false;
3988 if(typeof callback === "function")
3993 NETDATA._loadCSS(NETDATA.c3_css);
4001 NETDATA.registerChartLibrary('c3', NETDATA.c3_js);
4004 NETDATA.chartLibraries.c3.enabled = false;
4005 NETDATA.error(100, NETDATA.c3_js);
4007 .always(function() {
4008 if(typeof callback === "function")
4014 NETDATA.chartLibraries.c3.enabled = false;
4015 if(typeof callback === "function")
4020 NETDATA.c3ChartUpdate = function(state, data) {
4021 state.c3_instance.destroy();
4022 return NETDATA.c3ChartCreate(state, data);
4024 //state.c3_instance.load({
4025 // rows: data.result,
4032 NETDATA.c3ChartCreate = function(state, data) {
4034 state.element_chart.id = 'c3-' + state.uuid;
4035 // console.log('id = ' + state.element_chart.id);
4037 state.c3_instance = c3.generate({
4038 bindto: '#' + state.element_chart.id,
4040 width: state.chartWidth(),
4041 height: state.chartHeight()
4044 pattern: state.chartColors()
4049 type: (state.chart.chart_type === 'line')?'spline':'area-spline'
4055 format: function(x) {
4056 return NETDATA.zeropad(x.getHours()) + ":" + NETDATA.zeropad(x.getMinutes()) + ":" + NETDATA.zeropad(x.getSeconds());
4083 // console.log(state.c3_instance);
4088 // ----------------------------------------------------------------------------------------------------------------
4091 NETDATA.d3Initialize = function(callback) {
4092 if(typeof netdataStopD3 === 'undefined' || !netdataStopD3) {
4099 NETDATA.registerChartLibrary('d3', NETDATA.d3_js);
4102 NETDATA.chartLibraries.d3.enabled = false;
4103 NETDATA.error(100, NETDATA.d3_js);
4105 .always(function() {
4106 if(typeof callback === "function")
4111 NETDATA.chartLibraries.d3.enabled = false;
4112 if(typeof callback === "function")
4117 NETDATA.d3ChartUpdate = function(state, data) {
4121 NETDATA.d3ChartCreate = function(state, data) {
4125 // ----------------------------------------------------------------------------------------------------------------
4128 NETDATA.googleInitialize = function(callback) {
4129 if(typeof netdataNoGoogleCharts === 'undefined' || !netdataNoGoogleCharts) {
4131 url: NETDATA.google_js,
4136 NETDATA.registerChartLibrary('google', NETDATA.google_js);
4137 google.load('visualization', '1.1', {
4138 'packages': ['corechart', 'controls'],
4139 'callback': callback
4143 NETDATA.chartLibraries.google.enabled = false;
4144 NETDATA.error(100, NETDATA.google_js);
4145 if(typeof callback === "function")
4150 NETDATA.chartLibraries.google.enabled = false;
4151 if(typeof callback === "function")
4156 NETDATA.googleChartUpdate = function(state, data) {
4157 var datatable = new google.visualization.DataTable(data.result);
4158 state.google_instance.draw(datatable, state.google_options);
4162 NETDATA.googleChartCreate = function(state, data) {
4163 var datatable = new google.visualization.DataTable(data.result);
4165 state.google_options = {
4166 colors: state.chartColors(),
4168 // do not set width, height - the chart resizes itself
4169 //width: state.chartWidth(),
4170 //height: state.chartHeight(),
4175 // title: "Time of Day",
4176 // format:'HH:mm:ss',
4177 viewWindowMode: 'maximized',
4189 viewWindowMode: 'pretty',
4204 focusTarget: 'category',
4211 titlePosition: 'out',
4222 curveType: 'function',
4227 switch(state.chart.chart_type) {
4229 state.google_options.vAxis.viewWindowMode = 'maximized';
4230 state.google_options.areaOpacity = NETDATA.options.current.color_fill_opacity_area;
4231 state.google_instance = new google.visualization.AreaChart(state.element_chart);
4235 state.google_options.isStacked = true;
4236 state.google_options.areaOpacity = NETDATA.options.current.color_fill_opacity_stacked;
4237 state.google_options.vAxis.viewWindowMode = 'maximized';
4238 state.google_options.vAxis.minValue = null;
4239 state.google_options.vAxis.maxValue = null;
4240 state.google_instance = new google.visualization.AreaChart(state.element_chart);
4245 state.google_options.lineWidth = 2;
4246 state.google_instance = new google.visualization.LineChart(state.element_chart);
4250 state.google_instance.draw(datatable, state.google_options);
4254 // ----------------------------------------------------------------------------------------------------------------
4256 NETDATA.percentFromValueMax = function(value, max) {
4257 if(value === null) value = 0;
4258 if(max < value) max = value;
4262 pcent = Math.round(value * 100 / max);
4263 if(pcent === 0 && value > 0) pcent = 1;
4269 // ----------------------------------------------------------------------------------------------------------------
4272 NETDATA.easypiechartInitialize = function(callback) {
4273 if(typeof netdataNoEasyPieChart === 'undefined' || !netdataNoEasyPieChart) {
4275 url: NETDATA.easypiechart_js,
4280 NETDATA.registerChartLibrary('easypiechart', NETDATA.easypiechart_js);
4283 NETDATA.error(100, NETDATA.easypiechart_js);
4285 .always(function() {
4286 if(typeof callback === "function")
4291 NETDATA.chartLibraries.easypiechart.enabled = false;
4292 if(typeof callback === "function")
4297 NETDATA.easypiechartClearSelection = function(state) {
4298 if(typeof state.easyPieChartEvent !== 'undefined') {
4299 if(state.easyPieChartEvent.timer !== null)
4300 clearTimeout(state.easyPieChartEvent.timer);
4302 state.easyPieChartEvent.timer = null;
4305 if(state.isAutoRefreshed() === true && state.data !== null) {
4306 NETDATA.easypiechartChartUpdate(state, state.data);
4309 state.easyPieChartLabel.innerHTML = state.legendFormatValue(null);
4310 state.easyPieChart_instance.update(0);
4312 state.easyPieChart_instance.enableAnimation();
4317 NETDATA.easypiechartSetSelection = function(state, t) {
4318 if(state.timeIsVisible(t) !== true)
4319 return NETDATA.easypiechartClearSelection(state);
4321 var slot = state.calculateRowForTime(t);
4322 if(slot < 0 || slot >= state.data.result.length)
4323 return NETDATA.easypiechartClearSelection(state);
4325 if(typeof state.easyPieChartEvent === 'undefined') {
4326 state.easyPieChartEvent = {
4333 var value = state.data.result[state.data.result.length - 1 - slot];
4334 var max = (state.easyPieChartMax === null)?state.data.max:state.easyPieChartMax;
4335 var pcent = NETDATA.percentFromValueMax(value, max);
4337 state.easyPieChartEvent.value = value;
4338 state.easyPieChartEvent.pcent = pcent;
4339 state.easyPieChartLabel.innerHTML = state.legendFormatValue(value);
4341 if(state.easyPieChartEvent.timer === null) {
4342 state.easyPieChart_instance.disableAnimation();
4344 state.easyPieChartEvent.timer = setTimeout(function() {
4345 state.easyPieChartEvent.timer = null;
4346 state.easyPieChart_instance.update(state.easyPieChartEvent.pcent);
4347 }, NETDATA.options.current.charts_selection_animation_delay);
4353 NETDATA.easypiechartChartUpdate = function(state, data) {
4354 var value, max, pcent;
4356 if(NETDATA.globalPanAndZoom.isActive() === true || state.isAutoRefreshed() === false) {
4362 value = data.result[0];
4363 max = (state.easyPieChartMax === null)?data.max:state.easyPieChartMax;
4364 pcent = NETDATA.percentFromValueMax(value, max);
4367 state.easyPieChartLabel.innerHTML = state.legendFormatValue(value);
4368 state.easyPieChart_instance.update(pcent);
4372 NETDATA.easypiechartChartCreate = function(state, data) {
4373 var self = $(state.element);
4374 var chart = $(state.element_chart);
4376 var value = data.result[0];
4377 var max = self.data('easypiechart-max-value') || null;
4378 var adjust = self.data('easypiechart-adjust') || null;
4382 state.easyPieChartMax = null;
4385 state.easyPieChartMax = max;
4387 var pcent = NETDATA.percentFromValueMax(value, max);
4389 chart.data('data-percent', pcent);
4393 case 'width': size = state.chartHeight(); break;
4394 case 'min': size = Math.min(state.chartWidth(), state.chartHeight()); break;
4395 case 'max': size = Math.max(state.chartWidth(), state.chartHeight()); break;
4397 default: size = state.chartWidth(); break;
4399 state.element.style.width = size + 'px';
4400 state.element.style.height = size + 'px';
4402 var stroke = Math.floor(size / 22);
4403 if(stroke < 3) stroke = 2;
4405 var valuefontsize = Math.floor((size * 2 / 3) / 5);
4406 var valuetop = Math.round((size - valuefontsize - (size / 40)) / 2);
4407 state.easyPieChartLabel = document.createElement('span');
4408 state.easyPieChartLabel.className = 'easyPieChartLabel';
4409 state.easyPieChartLabel.innerHTML = state.legendFormatValue(value);
4410 state.easyPieChartLabel.style.fontSize = valuefontsize + 'px';
4411 state.easyPieChartLabel.style.top = valuetop.toString() + 'px';
4412 state.element_chart.appendChild(state.easyPieChartLabel);
4414 var titlefontsize = Math.round(valuefontsize * 1.6 / 3);
4415 var titletop = Math.round(valuetop - (titlefontsize * 2) - (size / 40));
4416 state.easyPieChartTitle = document.createElement('span');
4417 state.easyPieChartTitle.className = 'easyPieChartTitle';
4418 state.easyPieChartTitle.innerHTML = state.title;
4419 state.easyPieChartTitle.style.fontSize = titlefontsize + 'px';
4420 state.easyPieChartTitle.style.lineHeight = titlefontsize + 'px';
4421 state.easyPieChartTitle.style.top = titletop.toString() + 'px';
4422 state.element_chart.appendChild(state.easyPieChartTitle);
4424 var unitfontsize = Math.round(titlefontsize * 0.9);
4425 var unittop = Math.round(valuetop + (valuefontsize + unitfontsize) + (size / 40));
4426 state.easyPieChartUnits = document.createElement('span');
4427 state.easyPieChartUnits.className = 'easyPieChartUnits';
4428 state.easyPieChartUnits.innerHTML = state.units;
4429 state.easyPieChartUnits.style.fontSize = unitfontsize + 'px';
4430 state.easyPieChartUnits.style.top = unittop.toString() + 'px';
4431 state.element_chart.appendChild(state.easyPieChartUnits);
4433 chart.easyPieChart({
4434 barColor: self.data('easypiechart-barcolor') || state.chartColors()[0], //'#ef1e25',
4435 trackColor: self.data('easypiechart-trackcolor') || '#f0f0f0',
4436 scaleColor: self.data('easypiechart-scalecolor') || '#dfe0e0',
4437 scaleLength: self.data('easypiechart-scalelength') || 5,
4438 lineCap: self.data('easypiechart-linecap') || 'round',
4439 lineWidth: self.data('easypiechart-linewidth') || stroke,
4440 trackWidth: self.data('easypiechart-trackwidth') || undefined,
4441 size: self.data('easypiechart-size') || size,
4442 rotate: self.data('easypiechart-rotate') || 0,
4443 animate: self.data('easypiechart-rotate') || {duration: 500, enabled: true},
4444 easing: self.data('easypiechart-easing') || undefined
4447 // when we just re-create the chart
4448 // do not animate the first update
4450 if(typeof state.easyPieChart_instance !== 'undefined')
4453 state.easyPieChart_instance = chart.data('easyPieChart');
4454 if(animate === false) state.easyPieChart_instance.disableAnimation();
4455 state.easyPieChart_instance.update(pcent);
4456 if(animate === false) state.easyPieChart_instance.enableAnimation();
4460 // ----------------------------------------------------------------------------------------------------------------
4463 NETDATA.gaugeInitialize = function(callback) {
4464 if(typeof netdataNoGauge === 'undefined' || !netdataNoGauge) {
4466 url: NETDATA.gauge_js,
4471 NETDATA.registerChartLibrary('gauge', NETDATA.gauge_js);
4474 NETDATA.error(100, NETDATA.gauge_js);
4476 .always(function() {
4477 if(typeof callback === "function")
4482 NETDATA.chartLibraries.gauge.enabled = false;
4483 if(typeof callback === "function")
4488 NETDATA.gaugeAnimation = function(state, status) {
4491 if(typeof status === 'boolean' && status === false)
4493 else if(typeof status === 'number')
4496 state.gauge_instance.animationSpeed = speed;
4497 state.___gaugeOld__.speed = speed;
4500 NETDATA.gaugeSet = function(state, value, min, max) {
4501 if(typeof value !== 'number') value = 0;
4502 if(typeof min !== 'number') min = 0;
4503 if(typeof max !== 'number') max = 0;
4504 if(value > max) max = value;
4505 if(value < min) min = value;
4514 // gauge.js has an issue if the needle
4515 // is smaller than min or larger than max
4516 // when we set the new values
4517 // the needle will go crazy
4519 // to prevent it, we always feed it
4520 // with a percentage, so that the needle
4521 // is always between min and max
4522 var pcent = (value - min) * 100 / (max - min);
4524 // these should never happen
4525 if(pcent < 0) pcent = 0;
4526 if(pcent > 100) pcent = 100;
4528 state.gauge_instance.set(pcent);
4530 state.___gaugeOld__.value = value;
4531 state.___gaugeOld__.min = min;
4532 state.___gaugeOld__.max = max;
4535 NETDATA.gaugeSetLabels = function(state, value, min, max) {
4536 if(state.___gaugeOld__.valueLabel !== value) {
4537 state.___gaugeOld__.valueLabel = value;
4538 state.gaugeChartLabel.innerHTML = state.legendFormatValue(value);
4540 if(state.___gaugeOld__.minLabel !== min) {
4541 state.___gaugeOld__.minLabel = min;
4542 state.gaugeChartMin.innerHTML = state.legendFormatValue(min);
4544 if(state.___gaugeOld__.maxLabel !== max) {
4545 state.___gaugeOld__.maxLabel = max;
4546 state.gaugeChartMax.innerHTML = state.legendFormatValue(max);
4550 NETDATA.gaugeClearSelection = function(state) {
4551 if(typeof state.gaugeEvent !== 'undefined') {
4552 if(state.gaugeEvent.timer !== null)
4553 clearTimeout(state.gaugeEvent.timer);
4555 state.gaugeEvent.timer = null;
4558 if(state.isAutoRefreshed() === true && state.data !== null) {
4559 NETDATA.gaugeChartUpdate(state, state.data);
4562 NETDATA.gaugeAnimation(state, false);
4563 NETDATA.gaugeSet(state, null, null, null);
4564 NETDATA.gaugeSetLabels(state, null, null, null);
4567 NETDATA.gaugeAnimation(state, true);
4571 NETDATA.gaugeSetSelection = function(state, t) {
4572 if(state.timeIsVisible(t) !== true)
4573 return NETDATA.gaugeClearSelection(state);
4575 var slot = state.calculateRowForTime(t);
4576 if(slot < 0 || slot >= state.data.result.length)
4577 return NETDATA.gaugeClearSelection(state);
4579 if(typeof state.gaugeEvent === 'undefined') {
4580 state.gaugeEvent = {
4588 var value = state.data.result[state.data.result.length - 1 - slot];
4589 var max = (state.gaugeMax === null)?state.data.max:state.gaugeMax;
4592 state.gaugeEvent.value = value;
4593 state.gaugeEvent.max = max;
4594 state.gaugeEvent.min = min;
4595 NETDATA.gaugeSetLabels(state, value, min, max);
4597 if(state.gaugeEvent.timer === null) {
4598 NETDATA.gaugeAnimation(state, false);
4600 state.gaugeEvent.timer = setTimeout(function() {
4601 state.gaugeEvent.timer = null;
4602 NETDATA.gaugeSet(state, state.gaugeEvent.value, state.gaugeEvent.min, state.gaugeEvent.max);
4603 }, NETDATA.options.current.charts_selection_animation_delay);
4609 NETDATA.gaugeChartUpdate = function(state, data) {
4610 var value, min, max;
4612 if(NETDATA.globalPanAndZoom.isActive() === true || state.isAutoRefreshed() === false) {
4616 NETDATA.gaugeSetLabels(state, null, null, null);
4619 value = data.result[0];
4621 max = (state.gaugeMax === null)?data.max:state.gaugeMax;
4622 if(value > max) max = value;
4623 NETDATA.gaugeSetLabels(state, value, min, max);
4626 NETDATA.gaugeSet(state, value, min, max);
4630 NETDATA.gaugeChartCreate = function(state, data) {
4631 var self = $(state.element);
4632 var chart = $(state.element_chart);
4634 var value = data.result[0];
4635 var max = self.data('gauge-max-value') || null;
4636 var adjust = self.data('gauge-adjust') || null;
4637 var pointerColor = self.data('gauge-pointer-color') || '#C0C0C0';
4638 var strokeColor = self.data('gauge-stroke-color') || '#F0F0F0';
4639 var startColor = self.data('gauge-start-color') || state.chartColors()[0];
4640 var stopColor = self.data('gauge-stop-color') || void 0;
4641 var generateGradient = self.data('gauge-generate-gradient') || false;
4645 state.gaugeMax = null;
4648 state.gaugeMax = max;
4650 var width = state.chartWidth(), height = state.chartHeight(); //, ratio = 1.5;
4652 // case 'width': width = height * ratio; break;
4654 // default: height = width / ratio; break;
4656 //state.element.style.width = width.toString() + 'px';
4657 //state.element.style.height = height.toString() + 'px';
4662 lines: 12, // The number of lines to draw
4663 angle: 0.15, // The length of each line
4664 lineWidth: 0.44, // 0.44 The line thickness
4666 length: 0.8, // 0.9 The radius of the inner circle
4667 strokeWidth: 0.035, // The rotation offset
4668 color: pointerColor // Fill color
4670 colorStart: startColor, // Colors
4671 colorStop: stopColor, // just experiment with them
4672 strokeColor: strokeColor, // to see which ones work best for you
4674 generateGradient: generateGradient,
4677 [0.0, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 0))],
4678 [0.1, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 1))],
4679 [0.2, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 2))],
4680 [0.3, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 3))],
4681 [0.4, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 4))],
4682 [0.5, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 5))],
4683 [0.6, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 6))],
4684 [0.7, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 7))],
4685 [0.8, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 8))],
4686 [0.9, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 9))],
4687 [1.0, NETDATA.colorLuminance(startColor, 0.0)]]
4690 state.gauge_canvas = document.createElement('canvas');
4691 state.gauge_canvas.id = 'gauge-' + state.uuid + '-canvas';
4692 state.gauge_canvas.className = 'gaugeChart';
4693 state.gauge_canvas.width = width;
4694 state.gauge_canvas.height = height;
4695 state.element_chart.appendChild(state.gauge_canvas);
4697 var valuefontsize = Math.floor(height / 6);
4698 var valuetop = Math.round((height - valuefontsize - (height / 6)) / 2);
4699 state.gaugeChartLabel = document.createElement('span');
4700 state.gaugeChartLabel.className = 'gaugeChartLabel';
4701 state.gaugeChartLabel.style.fontSize = valuefontsize + 'px';
4702 state.gaugeChartLabel.style.top = valuetop.toString() + 'px';
4703 state.element_chart.appendChild(state.gaugeChartLabel);
4705 var titlefontsize = Math.round(valuefontsize / 2);
4707 state.gaugeChartTitle = document.createElement('span');
4708 state.gaugeChartTitle.className = 'gaugeChartTitle';
4709 state.gaugeChartTitle.innerHTML = state.title;
4710 state.gaugeChartTitle.style.fontSize = titlefontsize + 'px';
4711 state.gaugeChartTitle.style.lineHeight = titlefontsize + 'px';
4712 state.gaugeChartTitle.style.top = titletop.toString() + 'px';
4713 state.element_chart.appendChild(state.gaugeChartTitle);
4715 var unitfontsize = Math.round(titlefontsize * 0.9);
4716 state.gaugeChartUnits = document.createElement('span');
4717 state.gaugeChartUnits.className = 'gaugeChartUnits';
4718 state.gaugeChartUnits.innerHTML = state.units;
4719 state.gaugeChartUnits.style.fontSize = unitfontsize + 'px';
4720 state.element_chart.appendChild(state.gaugeChartUnits);
4722 state.gaugeChartMin = document.createElement('span');
4723 state.gaugeChartMin.className = 'gaugeChartMin';
4724 state.gaugeChartMin.style.fontSize = Math.round(valuefontsize * 0.75).toString() + 'px';
4725 state.element_chart.appendChild(state.gaugeChartMin);
4727 state.gaugeChartMax = document.createElement('span');
4728 state.gaugeChartMax.className = 'gaugeChartMax';
4729 state.gaugeChartMax.style.fontSize = Math.round(valuefontsize * 0.75).toString() + 'px';
4730 state.element_chart.appendChild(state.gaugeChartMax);
4732 // when we just re-create the chart
4733 // do not animate the first update
4735 if(typeof state.gauge_instance !== 'undefined')
4738 state.gauge_instance = new Gauge(state.gauge_canvas).setOptions(options); // create sexy gauge!
4740 state.___gaugeOld__ = {
4749 // we will always feed a percentage
4750 state.gauge_instance.minValue = 0;
4751 state.gauge_instance.maxValue = 100;
4753 NETDATA.gaugeAnimation(state, animate);
4754 NETDATA.gaugeSet(state, value, 0, max);
4755 NETDATA.gaugeSetLabels(state, value, 0, max);
4756 NETDATA.gaugeAnimation(state, true);
4760 // ----------------------------------------------------------------------------------------------------------------
4761 // Charts Libraries Registration
4763 NETDATA.chartLibraries = {
4765 initialize: NETDATA.dygraphInitialize,
4766 create: NETDATA.dygraphChartCreate,
4767 update: NETDATA.dygraphChartUpdate,
4768 resize: function(state) {
4769 if(typeof state.dygraph_instance.resize === 'function')
4770 state.dygraph_instance.resize();
4772 setSelection: NETDATA.dygraphSetSelection,
4773 clearSelection: NETDATA.dygraphClearSelection,
4776 format: function(state) { return 'json'; },
4777 options: function(state) { return 'ms|flip'; },
4778 legend: function(state) {
4779 if(this.isSparkline(state) === false)
4780 return 'right-side';
4784 autoresize: function(state) { return true; },
4785 max_updates_to_recreate: function(state) { return 5000; },
4786 track_colors: function(state) { return true; },
4787 pixels_per_point: function(state) {
4788 if(this.isSparkline(state) === false)
4794 isSparkline: function(state) {
4795 if(typeof state.dygraph_sparkline === 'undefined') {
4796 var t = $(state.element).data('dygraph-theme');
4797 if(t === 'sparkline')
4798 state.dygraph_sparkline = true;
4800 state.dygraph_sparkline = false;
4802 return state.dygraph_sparkline;
4806 initialize: NETDATA.sparklineInitialize,
4807 create: NETDATA.sparklineChartCreate,
4808 update: NETDATA.sparklineChartUpdate,
4810 setSelection: undefined, // function(state, t) { return true; },
4811 clearSelection: undefined, // function(state) { return true; },
4814 format: function(state) { return 'array'; },
4815 options: function(state) { return 'flip|abs'; },
4816 legend: function(state) { return null; },
4817 autoresize: function(state) { return false; },
4818 max_updates_to_recreate: function(state) { return 5000; },
4819 track_colors: function(state) { return false; },
4820 pixels_per_point: function(state) { return 3; }
4823 initialize: NETDATA.peityInitialize,
4824 create: NETDATA.peityChartCreate,
4825 update: NETDATA.peityChartUpdate,
4827 setSelection: undefined, // function(state, t) { return true; },
4828 clearSelection: undefined, // function(state) { return true; },
4831 format: function(state) { return 'ssvcomma'; },
4832 options: function(state) { return 'null2zero|flip|abs'; },
4833 legend: function(state) { return null; },
4834 autoresize: function(state) { return false; },
4835 max_updates_to_recreate: function(state) { return 5000; },
4836 track_colors: function(state) { return false; },
4837 pixels_per_point: function(state) { return 3; }
4840 initialize: NETDATA.morrisInitialize,
4841 create: NETDATA.morrisChartCreate,
4842 update: NETDATA.morrisChartUpdate,
4844 setSelection: undefined, // function(state, t) { return true; },
4845 clearSelection: undefined, // function(state) { return true; },
4848 format: function(state) { return 'json'; },
4849 options: function(state) { return 'objectrows|ms'; },
4850 legend: function(state) { return null; },
4851 autoresize: function(state) { return false; },
4852 max_updates_to_recreate: function(state) { return 50; },
4853 track_colors: function(state) { return false; },
4854 pixels_per_point: function(state) { return 15; }
4857 initialize: NETDATA.googleInitialize,
4858 create: NETDATA.googleChartCreate,
4859 update: NETDATA.googleChartUpdate,
4861 setSelection: undefined, //function(state, t) { return true; },
4862 clearSelection: undefined, //function(state) { return true; },
4865 format: function(state) { return 'datatable'; },
4866 options: function(state) { return ''; },
4867 legend: function(state) { return null; },
4868 autoresize: function(state) { return false; },
4869 max_updates_to_recreate: function(state) { return 300; },
4870 track_colors: function(state) { return false; },
4871 pixels_per_point: function(state) { return 4; }
4874 initialize: NETDATA.raphaelInitialize,
4875 create: NETDATA.raphaelChartCreate,
4876 update: NETDATA.raphaelChartUpdate,
4878 setSelection: undefined, // function(state, t) { return true; },
4879 clearSelection: undefined, // function(state) { return true; },
4882 format: function(state) { return 'json'; },
4883 options: function(state) { return ''; },
4884 legend: function(state) { return null; },
4885 autoresize: function(state) { return false; },
4886 max_updates_to_recreate: function(state) { return 5000; },
4887 track_colors: function(state) { return false; },
4888 pixels_per_point: function(state) { return 3; }
4891 initialize: NETDATA.c3Initialize,
4892 create: NETDATA.c3ChartCreate,
4893 update: NETDATA.c3ChartUpdate,
4895 setSelection: undefined, // function(state, t) { return true; },
4896 clearSelection: undefined, // function(state) { return true; },
4899 format: function(state) { return 'csvjsonarray'; },
4900 options: function(state) { return 'milliseconds'; },
4901 legend: function(state) { return null; },
4902 autoresize: function(state) { return false; },
4903 max_updates_to_recreate: function(state) { return 5000; },
4904 track_colors: function(state) { return false; },
4905 pixels_per_point: function(state) { return 15; }
4908 initialize: NETDATA.d3Initialize,
4909 create: NETDATA.d3ChartCreate,
4910 update: NETDATA.d3ChartUpdate,
4912 setSelection: undefined, // function(state, t) { return true; },
4913 clearSelection: undefined, // function(state) { return true; },
4916 format: function(state) { return 'json'; },
4917 options: function(state) { return ''; },
4918 legend: function(state) { return null; },
4919 autoresize: function(state) { return false; },
4920 max_updates_to_recreate: function(state) { return 5000; },
4921 track_colors: function(state) { return false; },
4922 pixels_per_point: function(state) { return 3; }
4925 initialize: NETDATA.easypiechartInitialize,
4926 create: NETDATA.easypiechartChartCreate,
4927 update: NETDATA.easypiechartChartUpdate,
4929 setSelection: NETDATA.easypiechartSetSelection,
4930 clearSelection: NETDATA.easypiechartClearSelection,
4933 format: function(state) { return 'array'; },
4934 options: function(state) { return 'absolute'; },
4935 legend: function(state) { return null; },
4936 autoresize: function(state) { return false; },
4937 max_updates_to_recreate: function(state) { return 5000; },
4938 track_colors: function(state) { return true; },
4939 pixels_per_point: function(state) { return 3; },
4943 initialize: NETDATA.gaugeInitialize,
4944 create: NETDATA.gaugeChartCreate,
4945 update: NETDATA.gaugeChartUpdate,
4947 setSelection: NETDATA.gaugeSetSelection,
4948 clearSelection: NETDATA.gaugeClearSelection,
4951 format: function(state) { return 'array'; },
4952 options: function(state) { return 'absolute'; },
4953 legend: function(state) { return null; },
4954 autoresize: function(state) { return false; },
4955 max_updates_to_recreate: function(state) { return 5000; },
4956 track_colors: function(state) { return true; },
4957 pixels_per_point: function(state) { return 3; },
4962 NETDATA.registerChartLibrary = function(library, url) {
4963 if(NETDATA.options.debug.libraries === true)
4964 console.log("registering chart library: " + library);
4966 NETDATA.chartLibraries[library].url = url;
4967 NETDATA.chartLibraries[library].initialized = true;
4968 NETDATA.chartLibraries[library].enabled = true;
4971 // ----------------------------------------------------------------------------------------------------------------
4974 NETDATA.requiredJs = [
4976 url: NETDATA.serverDefault + 'lib/bootstrap.min.js',
4977 isAlreadyLoaded: function() {
4978 if(typeof $().emulateTransitionEnd == 'function')
4981 if(typeof netdataNoBootstrap !== 'undefined' && netdataNoBootstrap)
4989 url: NETDATA.serverDefault + 'lib/jquery.nanoscroller.min.js',
4990 isAlreadyLoaded: function() { return false; }
4993 url: NETDATA.serverDefault + 'lib/bootstrap-toggle.min.js',
4994 isAlreadyLoaded: function() { return false; }
4998 NETDATA.requiredCSS = [
5000 url: NETDATA.serverDefault + 'css/bootstrap.min.css',
5001 isAlreadyLoaded: function() {
5002 if(typeof netdataNoBootstrap !== 'undefined' && netdataNoBootstrap)
5009 url: NETDATA.serverDefault + 'css/font-awesome.min.css',
5010 isAlreadyLoaded: function() { return false; }
5013 url: NETDATA.dashboard_css,
5014 isAlreadyLoaded: function() { return false; }
5017 url: NETDATA.serverDefault + 'css/bootstrap-toggle.min.css',
5018 isAlreadyLoaded: function() { return false; }
5022 NETDATA.loadRequiredJs = function(index, callback) {
5023 if(index >= NETDATA.requiredJs.length) {
5024 if(typeof callback === 'function')
5029 if(NETDATA.requiredJs[index].isAlreadyLoaded()) {
5030 NETDATA.loadRequiredJs(++index, callback);
5034 if(NETDATA.options.debug.main_loop === true)
5035 console.log('loading ' + NETDATA.requiredJs[index].url);
5038 url: NETDATA.requiredJs[index].url,
5042 .success(function() {
5043 if(NETDATA.options.debug.main_loop === true)
5044 console.log('loaded ' + NETDATA.requiredJs[index].url);
5046 NETDATA.loadRequiredJs(++index, callback);
5049 alert('Cannot load required JS library: ' + NETDATA.requiredJs[index].url);
5053 NETDATA.loadRequiredCSS = function(index) {
5054 if(index >= NETDATA.requiredCSS.length)
5057 if(NETDATA.requiredCSS[index].isAlreadyLoaded()) {
5058 NETDATA.loadRequiredCSS(++index);
5062 if(NETDATA.options.debug.main_loop === true)
5063 console.log('loading ' + NETDATA.requiredCSS[index].url);
5065 NETDATA._loadCSS(NETDATA.requiredCSS[index].url);
5066 NETDATA.loadRequiredCSS(++index);
5069 NETDATA.errorReset();
5070 NETDATA.loadRequiredCSS(0);
5072 NETDATA._loadjQuery(function() {
5073 NETDATA.loadRequiredJs(0, function() {
5074 if(typeof netdataDontStart === 'undefined' || !netdataDontStart) {
5075 if(NETDATA.options.debug.main_loop === true)
5076 console.log('starting chart refresh thread');
5083 // window.NETDATA = NETDATA;
5084 // })(window, document);