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(scripts) {
33 var script = null, base = null;
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);
48 var link = document.createElement('a');
49 link.setAttribute('href', script);
51 if(!link.protocol || !link.hostname) return null;
54 if(base) base += "//";
55 base += link.hostname;
57 if(link.port) base += ":" + link.port;
63 if(typeof netdataServer !== 'undefined')
64 NETDATA.serverDefault = netdataServer;
66 NETDATA.serverDefault = NETDATA._scriptSource();
68 if(NETDATA.serverDefault === null)
69 NETDATA.serverDefault = '';
70 else if(NETDATA.serverDefault.slice(-1) !== '/')
71 NETDATA.serverDefault += '/';
73 // default URLs for all the external files we need
74 // make them RELATIVE so that the whole thing can also be
75 // installed under a web server
76 NETDATA.jQuery = NETDATA.serverDefault + 'lib/jquery-1.12.0.min.js';
77 NETDATA.peity_js = NETDATA.serverDefault + 'lib/jquery.peity.min.js';
78 NETDATA.sparkline_js = NETDATA.serverDefault + 'lib/jquery.sparkline.min.js';
79 NETDATA.easypiechart_js = NETDATA.serverDefault + 'lib/jquery.easypiechart.min.js';
80 NETDATA.gauge_js = NETDATA.serverDefault + 'lib/gauge.min.js';
81 NETDATA.dygraph_js = NETDATA.serverDefault + 'lib/dygraph-combined.js';
82 NETDATA.dygraph_smooth_js = NETDATA.serverDefault + 'lib/dygraph-smooth-plotter.js';
83 NETDATA.raphael_js = NETDATA.serverDefault + 'lib/raphael-min.js';
84 NETDATA.morris_js = NETDATA.serverDefault + 'lib/morris.min.js';
85 NETDATA.d3_js = NETDATA.serverDefault + 'lib/d3.min.js';
86 NETDATA.c3_js = NETDATA.serverDefault + 'lib/c3.min.js';
87 NETDATA.c3_css = NETDATA.serverDefault + 'css/c3.min.css';
88 NETDATA.morris_css = NETDATA.serverDefault + 'css/morris.css';
89 NETDATA.dashboard_css = NETDATA.serverDefault + 'dashboard.css';
90 NETDATA.google_js = 'https://www.google.com/jsapi';
92 // these are the colors Google Charts are using
93 // we have them here to attempt emulate their look and feel on the other chart libraries
94 // http://there4.io/2012/05/02/google-chart-color-list/
95 //NETDATA.colors = [ '#3366CC', '#DC3912', '#FF9900', '#109618', '#990099', '#3B3EAC', '#0099C6',
96 // '#DD4477', '#66AA00', '#B82E2E', '#316395', '#994499', '#22AA99', '#AAAA11',
97 // '#6633CC', '#E67300', '#8B0707', '#329262', '#5574A6', '#3B3EAC' ];
99 NETDATA.colors = [ '#3366CC', '#DC3912', '#109618', '#FF9900', '#990099', '#DD4477', '#3B3EAC',
100 '#66AA00', '#0099C6', '#B82E2E', '#AAAA11', '#5574A6', '#994499', '#22AA99',
101 '#6633CC', '#E67300', '#316395', '#8B0707', '#329262', '#3B3EAC' ];
102 // an alternative set
103 // http://www.mulinblog.com/a-color-palette-optimized-for-data-visualization/
104 // (blue) (red) (orange) (green) (pink) (brown) (purple) (yellow) (gray)
105 //NETDATA.colors = [ '#5DA5DA', '#F15854', '#FAA43A', '#60BD68', '#F17CB0', '#B2912F', '#B276B2', '#DECF3F', '#4D4D4D' ];
107 // ----------------------------------------------------------------------------------------------------------------
108 // the defaults for all charts
110 // if the user does not specify any of these, the following will be used
112 NETDATA.chartDefaults = {
113 host: NETDATA.serverDefault, // the server to get data from
114 width: '100%', // the chart width - can be null
115 height: '100%', // the chart height - can be null
116 min_width: null, // the chart minimum width - can be null
117 library: 'dygraph', // the graphing library to use
118 method: 'average', // the grouping method
119 before: 0, // panning
120 after: -600, // panning
121 pixels_per_point: 1, // the detail of the chart
122 fill_luminance: 0.8 // luminance of colors in solit areas
125 // ----------------------------------------------------------------------------------------------------------------
129 pauseCallback: null, // a callback when we are really paused
131 pause: false, // when enabled we don't auto-refresh the charts
133 targets: null, // an array of all the state objects that are
134 // currently active (independently of their
135 // viewport visibility)
137 updated_dom: true, // when true, the DOM has been updated with
138 // new elements we have to check.
140 auto_refresher_fast_weight: 0, // this is the current time in ms, spent
141 // rendering charts continiously.
142 // used with .current.fast_render_timeframe
144 page_is_visible: true, // when true, this page is visible
146 auto_refresher_stop_until: 0, // timestamp in ms - used internaly, to stop the
147 // auto-refresher for some time (when a chart is
148 // performing pan or zoom, we need to stop refreshing
149 // all other charts, to have the maximum speed for
150 // rendering the chart that is panned or zoomed).
151 // Used with .current.global_pan_sync_time
153 last_resized: new Date().getTime(), // the timestamp of the last resize request
155 crossDomainAjax: false, // enable this to request crossDomain AJAX
157 last_page_scroll: 0, // the timestamp the last time the page was scrolled
159 // the current profile
160 // we may have many...
162 pixels_per_point: 1, // the minimum pixels per point for all charts
163 // increase this to speed javascript up
164 // each chart library has its own limit too
165 // the max of this and the chart library is used
166 // the final is calculated every time, so a change
167 // here will have immediate effect on the next chart
170 idle_between_charts: 100, // ms - how much time to wait between chart updates
172 fast_render_timeframe: 200, // ms - render continously until this time of continious
173 // rendering has been reached
174 // this setting is used to make it render e.g. 10
175 // charts at once, sleep idle_between_charts time
176 // and continue for another 10 charts.
178 idle_between_loops: 500, // ms - if all charts have been updated, wait this
179 // time before starting again.
181 idle_parallel_loops: 100, // ms - the time between parallel refresher updates
183 idle_lost_focus: 500, // ms - when the window does not have focus, check
184 // if focus has been regained, every this time
186 global_pan_sync_time: 1000, // ms - when you pan or zoon a chart, the background
187 // autorefreshing of charts is paused for this amount
190 sync_selection_delay: 1500, // ms - when you pan or zoom a chart, wait this amount
191 // of time before setting up synchronized selections
194 sync_selection: true, // enable or disable selection sync
196 pan_and_zoom_delay: 50, // when panning or zooming, how ofter to update the chart
198 sync_pan_and_zoom: true, // enable or disable pan and zoom sync
200 pan_and_zoom_data_padding: true, // fetch more data for the master chart when panning or zooming
202 update_only_visible: true, // enable or disable visibility management
204 parallel_refresher: true, // enable parallel refresh of charts
206 concurrent_refreshes: true, // when parallel_refresher is enabled, sync also the charts
208 destroy_on_hide: false, // destroy charts when they are not visible
210 eliminate_zero_dimensions: true, // do not show dimensions with just zeros
212 stop_updates_when_focus_is_lost: true, // boolean - shall we stop auto-refreshes when document does not have user focus
213 stop_updates_while_resizing: 1000, // ms - time to stop auto-refreshes while resizing the charts
215 double_click_speed: 500, // ms - time between clicks / taps to detect double click/tap
217 smooth_plot: true, // enable smooth plot, where possible
219 color_fill_opacity_line: 1.0,
220 color_fill_opacity_area: 0.2,
221 color_fill_opacity_stacked: 0.8,
223 setOptionCallback: function() { ; }
231 chart_data_url: false,
232 chart_errors: false, // FIXME
241 // ----------------------------------------------------------------------------------------------------------------
242 // local storage options
244 NETDATA.localStorage = {
247 callback: {} // only used for resetting back to defaults
250 NETDATA.localStorageGet = function(key, def, callback) {
253 if(typeof NETDATA.localStorage.default[key.toString()] === 'undefined') {
254 NETDATA.localStorage.default[key.toString()] = def;
255 NETDATA.localStorage.callback[key.toString()] = callback;
258 if(typeof Storage !== "undefined" && typeof localStorage === 'object') {
260 // console.log('localStorage: loading "' + key.toString() + '"');
261 ret = localStorage.getItem(key.toString());
262 if(ret === null || ret === 'undefined') {
263 // console.log('localStorage: cannot load it, saving "' + key.toString() + '" with value "' + JSON.stringify(def) + '"');
264 localStorage.setItem(key.toString(), JSON.stringify(def));
268 // console.log('localStorage: got "' + key.toString() + '" with value "' + ret + '"');
269 ret = JSON.parse(ret);
270 // console.log('localStorage: loaded "' + key.toString() + '" as value ' + ret + ' of type ' + typeof(ret));
274 console.log('localStorage: failed to read "' + key.toString() + '", using default: "' + def.toString() + '"');
279 if(typeof ret === 'undefined' || ret === 'undefined') {
280 console.log('localStorage: LOADED UNDEFINED "' + key.toString() + '" as value ' + ret + ' of type ' + typeof(ret));
284 NETDATA.localStorage.current[key.toString()] = ret;
288 NETDATA.localStorageSet = function(key, value, callback) {
289 if(typeof value === 'undefined' || value === 'undefined') {
290 console.log('localStorage: ATTEMPT TO SET UNDEFINED "' + key.toString() + '" as value ' + value + ' of type ' + typeof(value));
293 if(typeof NETDATA.localStorage.default[key.toString()] === 'undefined') {
294 NETDATA.localStorage.default[key.toString()] = value;
295 NETDATA.localStorage.current[key.toString()] = value;
296 NETDATA.localStorage.callback[key.toString()] = callback;
299 if(typeof Storage !== "undefined" && typeof localStorage === 'object') {
300 // console.log('localStorage: saving "' + key.toString() + '" with value "' + JSON.stringify(value) + '"');
302 localStorage.setItem(key.toString(), JSON.stringify(value));
305 console.log('localStorage: failed to save "' + key.toString() + '" with value: "' + value.toString() + '"');
309 NETDATA.localStorage.current[key.toString()] = value;
313 NETDATA.localStorageGetRecursive = function(obj, prefix, callback) {
315 if(typeof obj[i] === 'object') {
316 //console.log('object ' + prefix + '.' + i.toString());
317 NETDATA.localStorageGetRecursive(obj[i], prefix + '.' + i.toString(), callback);
321 obj[i] = NETDATA.localStorageGet(prefix + '.' + i.toString(), obj[i], callback);
325 NETDATA.setOption = function(key, value) {
326 if(key.toString() === 'setOptionCallback') {
327 if(typeof NETDATA.options.current.setOptionCallback === 'function') {
328 NETDATA.options.current[key.toString()] = value;
329 NETDATA.options.current.setOptionCallback();
332 else if(NETDATA.options.current[key.toString()] !== value) {
333 var name = 'options.' + key.toString();
335 if(typeof NETDATA.localStorage.default[name.toString()] === 'undefined')
336 console.log('localStorage: setOption() on unsaved option: "' + name.toString() + '", value: ' + value);
338 //console.log(NETDATA.localStorage);
339 //console.log('setOption: setting "' + key.toString() + '" to "' + value + '" of type ' + typeof(value) + ' original type ' + typeof(NETDATA.options.current[key.toString()]));
340 //console.log(NETDATA.options);
341 NETDATA.options.current[key.toString()] = NETDATA.localStorageSet(name.toString(), value, null);
343 if(typeof NETDATA.options.current.setOptionCallback === 'function')
344 NETDATA.options.current.setOptionCallback();
350 NETDATA.getOption = function(key) {
351 return NETDATA.options.current[key.toString()];
354 // read settings from local storage
355 NETDATA.localStorageGetRecursive(NETDATA.options.current, 'options', null);
357 // always start with this option enabled.
358 NETDATA.setOption('stop_updates_when_focus_is_lost', true);
360 NETDATA.resetOptions = function() {
361 for(var i in NETDATA.localStorage.default) {
362 var a = i.split('.');
364 if(a[0] === 'options') {
365 if(a[1] === 'setOptionCallback') continue;
366 if(typeof NETDATA.localStorage.default[i] === 'undefined') continue;
367 if(NETDATA.options.current[i] === NETDATA.localStorage.default[i]) continue;
369 NETDATA.setOption(a[1], NETDATA.localStorage.default[i]);
371 else if(a[0] === 'chart_heights') {
372 if(typeof NETDATA.localStorage.callback[i] === 'function' && typeof NETDATA.localStorage.default[i] !== 'undefined') {
373 NETDATA.localStorage.callback[i](NETDATA.localStorage.default[i]);
379 // ----------------------------------------------------------------------------------------------------------------
381 if(NETDATA.options.debug.main_loop === true)
382 console.log('welcome to NETDATA');
384 NETDATA.onresize = function() {
385 NETDATA.options.last_resized = new Date().getTime();
389 NETDATA.onscroll = function() {
390 // console.log('onscroll');
392 NETDATA.options.last_page_scroll = new Date().getTime();
393 if(NETDATA.options.targets === null) return;
395 // when the user scrolls he sees that we have
396 // hidden all the not-visible charts
397 // using this little function we try to switch
398 // the charts back to visible quickly
399 var targets = NETDATA.options.targets;
400 var len = targets.length;
401 while(len--) targets[len].isVisible();
404 window.onresize = NETDATA.onresize;
405 window.onscroll = NETDATA.onscroll;
407 // ----------------------------------------------------------------------------------------------------------------
410 NETDATA.errorCodes = {
411 100: { message: "Cannot load chart library", alert: true },
412 101: { message: "Cannot load jQuery", alert: true },
413 402: { message: "Chart library not found", alert: false },
414 403: { message: "Chart library not enabled/is failed", alert: false },
415 404: { message: "Chart not found", alert: false }
417 NETDATA.errorLast = {
423 NETDATA.error = function(code, msg) {
424 NETDATA.errorLast.code = code;
425 NETDATA.errorLast.message = msg;
426 NETDATA.errorLast.datetime = new Date().getTime();
428 console.log("ERROR " + code + ": " + NETDATA.errorCodes[code].message + ": " + msg);
430 if(NETDATA.errorCodes[code].alert)
431 alert("ERROR " + code + ": " + NETDATA.errorCodes[code].message + ": " + msg);
434 NETDATA.errorReset = function() {
435 NETDATA.errorLast.code = 0;
436 NETDATA.errorLast.message = "You are doing fine!";
437 NETDATA.errorLast.datetime = 0;
440 // ----------------------------------------------------------------------------------------------------------------
443 // When multiple charts need the same chart, we avoid downloading it
444 // multiple times (and having it in browser memory multiple time)
445 // by using this registry.
447 // Every time we download a chart definition, we save it here with .add()
448 // Then we try to get it back with .get(). If that fails, we download it.
450 NETDATA.chartRegistry = {
453 fixid: function(id) {
454 return id.replace(/:/g, "_").replace(/\//g, "_");
457 add: function(host, id, data) {
458 host = this.fixid(host);
461 if(typeof this.charts[host] === 'undefined')
462 this.charts[host] = {};
464 //console.log('added ' + host + '/' + id);
465 this.charts[host][id] = data;
468 get: function(host, id) {
469 host = this.fixid(host);
472 if(typeof this.charts[host] === 'undefined')
475 if(typeof this.charts[host][id] === 'undefined')
478 //console.log('cached ' + host + '/' + id);
479 return this.charts[host][id];
482 downloadAll: function(host, callback) {
483 while(host.slice(-1) === '/')
484 host = host.substring(0, host.length - 1);
489 url: host + '/api/v1/charts',
490 crossDomain: NETDATA.options.crossDomainAjax,
494 .done(function(data) {
495 var h = NETDATA.chartRegistry.fixid(host);
496 //console.log('downloaded all charts from ' + host + ' (' + h + ')');
497 self.charts[h] = data.charts;
498 if(typeof callback === 'function')
502 if(typeof callback === 'function')
508 // ----------------------------------------------------------------------------------------------------------------
509 // Global Pan and Zoom on charts
511 // Using this structure are synchronize all the charts, so that
512 // when you pan or zoom one, all others are automatically refreshed
513 // to the same timespan.
515 NETDATA.globalPanAndZoom = {
516 seq: 0, // timestamp ms
517 // every time a chart is panned or zoomed
518 // we set the timestamp here
519 // then we use it as a sequence number
520 // to find if other charts are syncronized
523 master: null, // the master chart (state), to which all others
526 force_before_ms: null, // the timespan to sync all other charts
527 force_after_ms: null,
530 setMaster: function(state, after, before) {
531 if(NETDATA.options.current.sync_pan_and_zoom === false)
534 if(this.master !== null && this.master !== state)
535 this.master.resetChart(true, true);
537 var now = new Date().getTime();
540 this.force_after_ms = after;
541 this.force_before_ms = before;
542 NETDATA.options.auto_refresher_stop_until = now + NETDATA.options.current.global_pan_sync_time;
546 clearMaster: function() {
547 if(this.master !== null) {
548 var st = this.master;
555 this.force_after_ms = null;
556 this.force_before_ms = null;
557 NETDATA.options.auto_refresher_stop_until = 0;
560 // is the given state the master of the global
561 // pan and zoom sync?
562 isMaster: function(state) {
563 if(this.master === state) return true;
567 // are we currently have a global pan and zoom sync?
568 isActive: function() {
569 if(this.master !== null && this.force_before_ms !== null && this.force_after_ms !== null && this.seq !== 0) return true;
573 // check if a chart, other than the master
574 // needs to be refreshed, due to the global pan and zoom
575 shouldBeAutoRefreshed: function(state) {
576 if(this.master === null || this.seq === 0)
579 //if(state.needsRecreation())
582 if(state.tm.pan_and_zoom_seq === this.seq)
589 // ----------------------------------------------------------------------------------------------------------------
590 // dimensions selection
593 // move color assignment to dimensions, here
595 dimensionStatus = function(parent, label, name_div, value_div, color) {
596 this.enabled = false;
597 this.parent = parent;
599 this.name_div = null;
600 this.value_div = null;
603 if(parent.selected === parent.unselected)
604 this.selected = true;
606 this.selected = false;
608 this.setOptions(name_div, value_div, color);
611 dimensionStatus.prototype.invalidate = function() {
612 this.name_div = null;
613 this.value_div = null;
614 this.enabled = false;
617 dimensionStatus.prototype.setOptions = function(name_div, value_div, color) {
620 if(this.name_div != name_div) {
621 this.name_div = name_div;
622 this.name_div.title = this.label;
623 this.name_div.style.color = this.color;
624 if(this.selected === false)
625 this.name_div.className = 'netdata-legend-name not-selected';
627 this.name_div.className = 'netdata-legend-name selected';
630 if(this.value_div != value_div) {
631 this.value_div = value_div;
632 this.value_div.title = this.label;
633 this.value_div.style.color = this.color;
634 if(this.selected === false)
635 this.value_div.className = 'netdata-legend-value not-selected';
637 this.value_div.className = 'netdata-legend-value selected';
644 dimensionStatus.prototype.setHandler = function() {
645 if(this.enabled === false) return;
649 // this.name_div.onmousedown = this.value_div.onmousedown = function(e) {
650 this.name_div.onclick = this.value_div.onclick = function(e) {
652 if(ds.isSelected()) {
654 if(e.shiftKey === true || e.ctrlKey === true) {
655 // control or shift key is pressed -> unselect this (except is none will remain selected, in which case select all)
658 if(ds.parent.countSelected() === 0)
659 ds.parent.selectAll();
662 // no key is pressed -> select only this (except if it is the only selected already, in which case select all)
663 if(ds.parent.countSelected() === 1) {
664 ds.parent.selectAll();
667 ds.parent.selectNone();
673 // this is not selected
674 if(e.shiftKey === true || e.ctrlKey === true) {
675 // control or shift key is pressed -> select this too
679 // no key is pressed -> select only this
680 ds.parent.selectNone();
685 ds.parent.state.redrawChart();
689 dimensionStatus.prototype.select = function() {
690 if(this.enabled === false) return;
692 this.name_div.className = 'netdata-legend-name selected';
693 this.value_div.className = 'netdata-legend-value selected';
694 this.selected = true;
697 dimensionStatus.prototype.unselect = function() {
698 if(this.enabled === false) return;
700 this.name_div.className = 'netdata-legend-name not-selected';
701 this.value_div.className = 'netdata-legend-value hidden';
702 this.selected = false;
705 dimensionStatus.prototype.isSelected = function() {
706 return(this.enabled === true && this.selected === true);
709 // ----------------------------------------------------------------------------------------------------------------
711 dimensionsVisibility = function(state) {
714 this.dimensions = {};
715 this.selected_count = 0;
716 this.unselected_count = 0;
719 dimensionsVisibility.prototype.dimensionAdd = function(label, name_div, value_div, color) {
720 if(typeof this.dimensions[label] === 'undefined') {
722 this.dimensions[label] = new dimensionStatus(this, label, name_div, value_div, color);
725 this.dimensions[label].setOptions(name_div, value_div, color);
727 return this.dimensions[label];
730 dimensionsVisibility.prototype.dimensionGet = function(label) {
731 return this.dimensions[label];
734 dimensionsVisibility.prototype.invalidateAll = function() {
735 for(var d in this.dimensions)
736 this.dimensions[d].invalidate();
739 dimensionsVisibility.prototype.selectAll = function() {
740 for(var d in this.dimensions)
741 this.dimensions[d].select();
744 dimensionsVisibility.prototype.countSelected = function() {
746 for(var d in this.dimensions)
747 if(this.dimensions[d].isSelected()) i++;
752 dimensionsVisibility.prototype.selectNone = function() {
753 for(var d in this.dimensions)
754 this.dimensions[d].unselect();
757 dimensionsVisibility.prototype.selected2BooleanArray = function(array) {
758 var ret = new Array();
759 this.selected_count = 0;
760 this.unselected_count = 0;
762 for(var i = 0, len = array.length; i < len ; i++) {
763 var ds = this.dimensions[array[i]];
764 if(typeof ds === 'undefined') {
765 // console.log(array[i] + ' is not found');
770 if(ds.isSelected()) {
772 this.selected_count++;
776 this.unselected_count++;
780 if(this.selected_count === 0 && this.unselected_count !== 0) {
782 return this.selected2BooleanArray(array);
789 // ----------------------------------------------------------------------------------------------------------------
790 // global selection sync
792 NETDATA.globalSelectionSync = {
799 if(this.state !== null)
800 this.state.globalSelectionSyncStop();
804 if(this.state !== null) {
805 this.state.globalSelectionSyncDelay();
810 // ----------------------------------------------------------------------------------------------------------------
811 // Our state object, where all per-chart values are stored
813 chartState = function(element) {
814 var self = $(element);
815 this.element = element;
818 // all private functions should use 'that', instead of 'this'
822 * show an error instead of the chart
824 var error = function(msg) {
825 that.element.innerHTML = that.id + ': ' + msg;
826 that.enabled = false;
827 that.current = that.pan;
830 // GUID - a unique identifier for the chart
831 this.uuid = NETDATA.guid();
833 // string - the name of chart
834 this.id = self.data('netdata');
836 // string - the key for localStorage settings
837 this.settings_id = self.data('id') || null;
839 // the user given dimensions of the element
840 this.width = self.data('width') || NETDATA.chartDefaults.width;
841 this.height = self.data('height') || NETDATA.chartDefaults.height;
843 if(this.settings_id !== null) {
844 this.height = NETDATA.localStorageGet('chart_heights.' + this.settings_id, this.height, function(height) {
845 // this is the callback that will be called
846 // if and when the user resets all localStorage variables
849 resizeChartToHeight(height);
853 // string - the netdata server URL, without any path
854 this.host = self.data('host') || NETDATA.chartDefaults.host;
856 // make sure the host does not end with /
857 // all netdata API requests use absolute paths
858 while(this.host.slice(-1) === '/')
859 this.host = this.host.substring(0, this.host.length - 1);
861 // string - the grouping method requested by the user
862 this.method = self.data('method') || NETDATA.chartDefaults.method;
864 // the time-range requested by the user
865 this.after = self.data('after') || NETDATA.chartDefaults.after;
866 this.before = self.data('before') || NETDATA.chartDefaults.before;
868 // the pixels per point requested by the user
869 this.pixels_per_point = self.data('pixels-per-point') || 1;
870 this.points = self.data('points') || null;
872 // the dimensions requested by the user
873 this.dimensions = self.data('dimensions') || null;
875 // the chart library requested by the user
876 this.library_name = self.data('chart-library') || NETDATA.chartDefaults.library;
878 // object - the chart library used
883 this.colors_assigned = {};
884 this.colors_available = null;
886 // the element already created by the user
887 this.element_message = null;
889 // the element with the chart
890 this.element_chart = null;
892 // the element with the legend of the chart (if created by us)
893 this.element_legend = null;
894 this.element_legend_childs = {
904 this.chart_url = null; // string - the url to download chart info
905 this.chart = null; // object - the chart as downloaded from the server
907 this.title = self.data('title') || null; // the title of the chart
908 this.units = self.data('units') || null; // the units of the chart dimensions
909 this.append_options = self.data('append-options') || null; // the units of the chart dimensions
911 this.validated = false; // boolean - has the chart been validated?
912 this.enabled = true; // boolean - is the chart enabled for refresh?
913 this.paused = false; // boolean - is the chart paused for any reason?
914 this.selected = false; // boolean - is the chart shown a selection?
915 this.debug = false; // boolean - console.log() debug info about this chart
917 this.netdata_first = 0; // milliseconds - the first timestamp in netdata
918 this.netdata_last = 0; // milliseconds - the last timestamp in netdata
919 this.requested_after = null; // milliseconds - the timestamp of the request after param
920 this.requested_before = null; // milliseconds - the timestamp of the request before param
921 this.requested_padding = null;
923 this.view_before = 0;
928 force_update_at: 0, // the timestamp to force the update at
929 force_before_ms: null,
935 force_update_at: 0, // the timestamp to force the update at
936 force_before_ms: null,
942 force_update_at: 0, // the timestamp to force the update at
943 force_before_ms: null,
947 // this is a pointer to one of the sub-classes below
949 this.current = this.auto;
951 // check the requested library is available
952 // we don't initialize it here - it will be initialized when
953 // this chart will be first used
954 if(typeof NETDATA.chartLibraries[that.library_name] === 'undefined') {
955 NETDATA.error(402, that.library_name);
956 error('chart library "' + that.library_name + '" is not found');
959 else if(NETDATA.chartLibraries[that.library_name].enabled === false) {
960 NETDATA.error(403, that.library_name);
961 error('chart library "' + that.library_name + '" is not enabled');
965 that.library = NETDATA.chartLibraries[that.library_name];
967 // milliseconds - the time the last refresh took
968 this.refresh_dt_ms = 0;
970 // if we need to report the rendering speed
971 // find the element that needs to be updated
972 var refresh_dt_element_name = self.data('dt-element-name') || null; // string - the element to print refresh_dt_ms
974 if(refresh_dt_element_name !== null)
975 this.refresh_dt_element = document.getElementById(refresh_dt_element_name) || null;
977 this.refresh_dt_element = null;
979 this.dimensions_visibility = new dimensionsVisibility(this);
981 // ============================================================================================================
984 var createDOM = function() {
985 if(that.enabled === false) return;
987 if(that.element_message !== null) that.element_message.innerHTML = '';
988 if(that.element_legend !== null) that.element_legend.innerHTML = '';
989 if(that.element_chart !== null) that.element_chart.innerHTML = '';
991 that.element.innerHTML = '';
993 that.element_message = document.createElement('div');
994 that.element_message.className = ' netdata-message hidden';
995 that.element.appendChild(that.element_message);
997 that.element_chart = document.createElement('div');
998 that.element_chart.id = that.library_name + '-' + that.uuid + '-chart';
999 that.element.appendChild(that.element_chart);
1001 if(that.hasLegend() === true) {
1002 that.element.className = "netdata-container-with-legend";
1003 that.element_chart.className = 'netdata-chart-with-legend-right netdata-' + that.library_name + '-chart-with-legend-right';
1005 that.element_legend = document.createElement('div');
1006 that.element_legend.className = 'netdata-chart-legend netdata-' + that.library_name + '-legend';
1007 that.element.appendChild(that.element_legend);
1010 that.element.className = "netdata-container";
1011 that.element_chart.className = ' netdata-chart netdata-' + that.library_name + '-chart';
1013 that.element_legend = null;
1015 that.element_legend_childs.series = null;
1017 if(typeof(that.width) === 'string')
1018 $(that.element).css('width', that.width);
1019 else if(typeof(that.width) === 'number')
1020 $(that.element).css('width', that.width + 'px');
1022 if(typeof(that.library.aspect_ratio) === 'undefined') {
1023 if(typeof(that.height) === 'string')
1024 $(that.element).css('height', that.height);
1025 else if(typeof(that.height) === 'number')
1026 $(that.element).css('height', that.height + 'px');
1029 var w = that.element.offsetWidth;
1030 if(w === null || w === 0) {
1031 // the div is hidden
1032 // this is resize the chart when next viewed
1033 that.tm.last_resized = 0;
1036 $(that.element).css('height', (that.element.offsetWidth * that.library.aspect_ratio / 100).toString() + 'px');
1039 if(NETDATA.chartDefaults.min_width !== null)
1040 $(that.element).css('min-width', NETDATA.chartDefaults.min_width);
1042 that.tm.last_dom_created = new Date().getTime();
1048 * initialize state viariables
1049 * destroy all (possibly) created state elements
1050 * create the basic DOM for a chart
1052 var init = function() {
1053 if(that.enabled === false) return;
1055 that.paused = false;
1056 that.selected = false;
1058 that.chart_created = false; // boolean - is the library.create() been called?
1059 that.updates_counter = 0; // numeric - the number of refreshes made so far
1060 that.updates_since_last_unhide = 0; // numeric - the number of refreshes made since the last time the chart was unhidden
1061 that.updates_since_last_creation = 0; // numeric - the number of refreshes made since the last time the chart was created
1064 last_initialized: 0, // milliseconds - the timestamp it was last initialized
1065 last_dom_created: 0, // milliseconds - the timestamp its DOM was last created
1066 last_mode_switch: 0, // milliseconds - the timestamp it switched modes
1068 last_info_downloaded: 0, // milliseconds - the timestamp we downloaded the chart
1069 last_updated: 0, // the timestamp the chart last updated with data
1070 pan_and_zoom_seq: 0, // the sequence number of the global synchronization
1072 // Used with NETDATA.globalPanAndZoom.seq
1073 last_visible_check: 0, // the time we last checked if it is visible
1074 last_resized: 0, // the time the chart was resized
1075 last_hidden: 0, // the time the chart was hidden
1076 last_unhidden: 0, // the time the chart was unhidden
1077 last_autorefreshed: 0 // the time the chart was last refreshed
1080 that.data = null; // the last data as downloaded from the netdata server
1081 that.data_url = 'invalid://'; // string - the last url used to update the chart
1082 that.data_points = 0; // number - the number of points returned from netdata
1083 that.data_after = 0; // milliseconds - the first timestamp of the data
1084 that.data_before = 0; // milliseconds - the last timestamp of the data
1085 that.data_update_every = 0; // milliseconds - the frequency to update the data
1087 that.tm.last_initialized = new Date().getTime();
1090 that.setMode('auto');
1093 var maxMessageFontSize = function() {
1094 // normally we want a font size, as tall as the element
1095 var h = that.element_message.clientHeight;
1097 // but give it some air, 20% let's say, or 5 pixels min
1098 var lost = Math.max(h * 0.2, 5);
1101 // center the text, verically
1102 var paddingTop = (lost - 5) / 2;
1104 // but check the width too
1105 // it should fit 10 characters in it
1106 var w = that.element_message.clientWidth / 10;
1108 paddingTop += (h - w) / 2;
1112 // and don't make it too huge
1113 // 5% of the screen size is good
1114 if(h > screen.height / 20) {
1115 paddingTop += (h - (screen.height / 20)) / 2;
1116 h = screen.height / 20;
1120 that.element_message.style.fontSize = h.toString() + 'px';
1121 that.element_message.style.paddingTop = paddingTop.toString() + 'px';
1124 var showMessage = function(msg) {
1125 that.element_message.className = 'netdata-message';
1126 that.element_message.innerHTML = msg;
1127 this.element_message.style.fontSize = 'x-small';
1128 that.element_message.style.paddingTop = '0px';
1129 that.___messageHidden___ = undefined;
1132 var showMessageIcon = function(icon) {
1133 that.element_message.innerHTML = icon;
1134 that.element_message.className = 'netdata-message icon';
1135 maxMessageFontSize();
1136 that.___messageHidden___ = undefined;
1139 var hideMessage = function() {
1140 if(typeof that.___messageHidden___ === 'undefined') {
1141 that.___messageHidden___ = true;
1142 that.element_message.className = 'netdata-message hidden';
1146 var showRendering = function() {
1148 if(that.chart !== null) {
1149 if(that.chart.chart_type === 'line')
1150 icon = '<i class="fa fa-line-chart"></i>';
1152 icon = '<i class="fa fa-area-chart"></i>';
1155 icon = '<i class="fa fa-area-chart"></i>';
1157 showMessageIcon(icon + ' netdata');
1160 var showLoading = function() {
1161 if(that.chart_created === false) {
1162 showMessageIcon('<i class="fa fa-refresh"></i> netdata');
1168 var isHidden = function() {
1169 if(typeof that.___chartIsHidden___ !== 'undefined')
1175 // hide the chart, when it is not visible - called from isVisible()
1176 var hideChart = function() {
1177 // hide it, if it is not already hidden
1178 if(isHidden() === true) return;
1180 if(that.chart_created === true) {
1181 // we should destroy it
1182 if(NETDATA.options.current.destroy_on_hide === true) {
1187 that.element_chart.style.display = 'none';
1188 if(that.element_legend !== null) that.element_legend.style.display = 'none';
1189 that.tm.last_hidden = new Date().getTime();
1193 that.___chartIsHidden___ = true;
1196 // unhide the chart, when it is visible - called from isVisible()
1197 var unhideChart = function() {
1198 if(isHidden() === false) return;
1200 that.___chartIsHidden___ = undefined;
1201 that.updates_since_last_unhide = 0;
1203 if(that.chart_created === false) {
1204 // we need to re-initialize it, to show our background
1205 // logo in bootstrap tabs, until the chart loads
1209 that.tm.last_unhidden = new Date().getTime();
1210 that.element_chart.style.display = '';
1211 if(that.element_legend !== null) that.element_legend.style.display = '';
1217 var canBeRendered = function() {
1218 if(isHidden() === true || that.isVisible(true) === false)
1224 // https://github.com/petkaantonov/bluebird/wiki/Optimization-killers
1225 var callChartLibraryUpdateSafely = function(data) {
1228 if(canBeRendered() === false)
1231 if(NETDATA.options.debug.chart_errors === true)
1232 status = that.library.update(that, data);
1235 status = that.library.update(that, data);
1242 if(status === false) {
1243 error('chart failed to be updated as ' + that.library_name);
1250 // https://github.com/petkaantonov/bluebird/wiki/Optimization-killers
1251 var callChartLibraryCreateSafely = function(data) {
1254 if(canBeRendered() === false)
1257 if(NETDATA.options.debug.chart_errors === true)
1258 status = that.library.create(that, data);
1261 status = that.library.create(that, data);
1268 if(status === false) {
1269 error('chart failed to be created as ' + that.library_name);
1273 that.chart_created = true;
1274 that.updates_since_last_creation = 0;
1278 // ----------------------------------------------------------------------------------------------------------------
1281 // resizeChart() - private
1282 // to be called just before the chart library to make sure that
1283 // a properly sized dom is available
1284 var resizeChart = function() {
1285 if(that.isVisible() === true && that.tm.last_resized < NETDATA.options.last_resized) {
1286 if(that.chart_created === false) return;
1288 if(that.needsRecreation()) {
1291 else if(typeof that.library.resize === 'function') {
1292 that.library.resize(that);
1294 if(that.element_legend_childs.nano !== null && that.element_legend_childs.nano_options !== null)
1295 $(that.element_legend_childs.nano).nanoScroller();
1297 maxMessageFontSize();
1300 that.tm.last_resized = new Date().getTime();
1304 // this is the actual chart resize algorithm
1306 // - resize the entire container
1307 // - update the internal states
1308 // - resize the chart as the div changes height
1309 // - update the scrollbar of the legend
1310 var resizeChartToHeight = function(h) {
1312 that.element.style.height = h;
1314 if(that.settings_id !== null)
1315 NETDATA.localStorageSet('chart_heights.' + that.settings_id, h);
1317 var now = new Date().getTime();
1318 NETDATA.options.last_page_scroll = now;
1319 NETDATA.options.auto_refresher_stop_until = now + NETDATA.options.current.stop_updates_while_resizing;
1322 that.tm.last_resized = 0;
1326 this.resizeHandler = function(e) {
1329 if(typeof this.event_resize === 'undefined'
1330 || this.event_resize.chart_original_w === 'undefined'
1331 || this.event_resize.chart_original_h === 'undefined')
1332 this.event_resize = {
1333 chart_original_w: this.element.clientWidth,
1334 chart_original_h: this.element.clientHeight,
1338 if(e.type === 'touchstart') {
1339 this.event_resize.mouse_start_x = e.touches.item(0).pageX;
1340 this.event_resize.mouse_start_y = e.touches.item(0).pageY;
1343 this.event_resize.mouse_start_x = e.clientX;
1344 this.event_resize.mouse_start_y = e.clientY;
1347 this.event_resize.chart_start_w = this.element.clientWidth;
1348 this.event_resize.chart_start_h = this.element.clientHeight;
1349 this.event_resize.chart_last_w = this.element.clientWidth;
1350 this.event_resize.chart_last_h = this.element.clientHeight;
1352 var now = new Date().getTime();
1353 if(now - this.event_resize.last <= NETDATA.options.current.double_click_speed) {
1354 // double click / double tap event
1356 // the optimal height of the chart
1357 // showing the entire legend
1358 var optimal = this.event_resize.chart_last_h
1359 + this.element_legend_childs.content.scrollHeight
1360 - this.element_legend_childs.content.clientHeight;
1362 // if we are not optimal, be optimal
1363 if(this.event_resize.chart_last_h != optimal)
1364 resizeChartToHeight(optimal.toString() + 'px');
1366 // else if we do not have the original height
1367 // reset to the original height
1368 else if(this.event_resize.chart_last_h != this.event_resize.chart_original_h)
1369 resizeChartToHeight(this.event_resize.chart_original_h.toString() + 'px');
1372 this.event_resize.last = now;
1374 // process movement event
1375 document.onmousemove =
1376 document.ontouchmove =
1377 this.element_legend_childs.resize_handler.onmousemove =
1378 this.element_legend_childs.resize_handler.ontouchmove =
1383 case 'mousemove': y = e.clientY; break;
1384 case 'touchmove': y = e.touches.item(e.touches - 1).pageY; break;
1388 var newH = that.event_resize.chart_start_h + y - that.event_resize.mouse_start_y;
1390 if(newH >= 70 && newH !== that.event_resize.chart_last_h) {
1391 resizeChartToHeight(newH.toString() + 'px');
1392 that.event_resize.chart_last_h = newH;
1397 // process end event
1398 document.onmouseup =
1399 document.ontouchend =
1400 this.element_legend_childs.resize_handler.onmouseup =
1401 this.element_legend_childs.resize_handler.ontouchend =
1403 // remove all the hooks
1404 document.onmouseup =
1405 document.onmousemove =
1406 document.ontouchmove =
1407 document.ontouchend =
1408 that.element_legend_childs.resize_handler.onmousemove =
1409 that.element_legend_childs.resize_handler.ontouchmove =
1410 that.element_legend_childs.resize_handler.onmouseout =
1411 that.element_legend_childs.resize_handler.onmouseup =
1412 that.element_legend_childs.resize_handler.ontouchend =
1415 // allow auto-refreshes
1416 NETDATA.options.auto_refresher_stop_until = 0;
1422 var noDataToShow = function() {
1423 showMessageIcon('<i class="fa fa-warning"></i> empty');
1424 that.legendUpdateDOM();
1425 that.tm.last_autorefreshed = new Date().getTime();
1426 // that.data_update_every = 30 * 1000;
1427 //that.element_chart.style.display = 'none';
1428 //if(that.element_legend !== null) that.element_legend.style.display = 'none';
1429 //that.___chartIsHidden___ = true;
1432 // ============================================================================================================
1435 this.error = function(msg) {
1439 this.setMode = function(m) {
1440 if(this.current !== null && this.current.name === m) return;
1443 this.current = this.auto;
1444 else if(m === 'pan')
1445 this.current = this.pan;
1446 else if(m === 'zoom')
1447 this.current = this.zoom;
1449 this.current = this.auto;
1451 this.current.force_update_at = 0;
1452 this.current.force_before_ms = null;
1453 this.current.force_after_ms = null;
1455 this.tm.last_mode_switch = new Date().getTime();
1458 // ----------------------------------------------------------------------------------------------------------------
1459 // global selection sync
1461 // prevent to global selection sync for some time
1462 this.globalSelectionSyncDelay = function(ms) {
1463 if(NETDATA.options.current.sync_selection === false)
1466 if(typeof ms === 'number')
1467 NETDATA.globalSelectionSync.dont_sync_before = new Date().getTime() + ms;
1469 NETDATA.globalSelectionSync.dont_sync_before = new Date().getTime() + NETDATA.options.current.sync_selection_delay;
1472 // can we globally apply selection sync?
1473 this.globalSelectionSyncAbility = function() {
1474 if(NETDATA.options.current.sync_selection === false)
1477 if(NETDATA.globalSelectionSync.dont_sync_before > new Date().getTime())
1483 this.globalSelectionSyncIsMaster = function() {
1484 if(NETDATA.globalSelectionSync.state === this)
1490 // this chart is the master of the global selection sync
1491 this.globalSelectionSyncBeMaster = function() {
1493 if(this.globalSelectionSyncIsMaster()) {
1494 if(this.debug === true)
1495 this.log('sync: I am the master already.');
1500 if(NETDATA.globalSelectionSync.state) {
1501 if(this.debug === true)
1502 this.log('sync: I am not the sync master. Resetting global sync.');
1504 this.globalSelectionSyncStop();
1507 // become the master
1508 if(this.debug === true)
1509 this.log('sync: becoming sync master.');
1511 this.selected = true;
1512 NETDATA.globalSelectionSync.state = this;
1514 // find the all slaves
1515 var targets = NETDATA.options.targets;
1516 var len = targets.length;
1521 if(this.debug === true)
1522 st.log('sync: not adding me to sync');
1524 else if(st.globalSelectionSyncIsEligible()) {
1525 if(this.debug === true)
1526 st.log('sync: adding to sync as slave');
1528 st.globalSelectionSyncBeSlave();
1532 // this.globalSelectionSyncDelay(100);
1535 // can the chart participate to the global selection sync as a slave?
1536 this.globalSelectionSyncIsEligible = function() {
1537 if(this.enabled === true
1538 && this.library !== null
1539 && typeof this.library.setSelection === 'function'
1540 && this.isVisible() === true
1541 && this.chart_created === true)
1547 // this chart becomes a slave of the global selection sync
1548 this.globalSelectionSyncBeSlave = function() {
1549 if(NETDATA.globalSelectionSync.state !== this)
1550 NETDATA.globalSelectionSync.slaves.push(this);
1553 // sync all the visible charts to the given time
1554 // this is to be called from the chart libraries
1555 this.globalSelectionSync = function(t) {
1556 if(this.globalSelectionSyncAbility() === false) {
1557 if(this.debug === true)
1558 this.log('sync: cannot sync (yet?).');
1563 if(this.globalSelectionSyncIsMaster() === false) {
1564 if(this.debug === true)
1565 this.log('sync: trying to be sync master.');
1567 this.globalSelectionSyncBeMaster();
1569 if(this.globalSelectionSyncAbility() === false) {
1570 if(this.debug === true)
1571 this.log('sync: cannot sync (yet?).');
1577 NETDATA.globalSelectionSync.last_t = t;
1578 $.each(NETDATA.globalSelectionSync.slaves, function(i, st) {
1583 // stop syncing all charts to the given time
1584 this.globalSelectionSyncStop = function() {
1585 if(NETDATA.globalSelectionSync.slaves.length) {
1586 if(this.debug === true)
1587 this.log('sync: cleaning up...');
1589 $.each(NETDATA.globalSelectionSync.slaves, function(i, st) {
1591 if(that.debug === true)
1592 st.log('sync: not adding me to sync stop');
1595 if(that.debug === true)
1596 st.log('sync: removed slave from sync');
1598 st.clearSelection();
1602 NETDATA.globalSelectionSync.last_t = 0;
1603 NETDATA.globalSelectionSync.slaves = [];
1604 NETDATA.globalSelectionSync.state = null;
1607 this.clearSelection();
1610 this.setSelection = function(t) {
1611 if(typeof this.library.setSelection === 'function') {
1612 if(this.library.setSelection(this, t) === true)
1613 this.selected = true;
1615 this.selected = false;
1617 else this.selected = true;
1619 if(this.selected === true && this.debug === true)
1620 this.log('selection set to ' + t.toString());
1622 return this.selected;
1625 this.clearSelection = function() {
1626 if(this.selected === true) {
1627 if(typeof this.library.clearSelection === 'function') {
1628 if(this.library.clearSelection(this) === true)
1629 this.selected = false;
1631 this.selected = true;
1633 else this.selected = false;
1635 if(this.selected === false && this.debug === true)
1636 this.log('selection cleared');
1641 return this.selected;
1644 // find if a timestamp (ms) is shown in the current chart
1645 this.timeIsVisible = function(t) {
1646 if(t >= this.data_after && t <= this.data_before)
1651 this.calculateRowForTime = function(t) {
1652 if(this.timeIsVisible(t) === false) return -1;
1653 return Math.floor((t - this.data_after) / this.data_update_every);
1656 // ----------------------------------------------------------------------------------------------------------------
1659 this.log = function(msg) {
1660 console.log(this.id + ' (' + this.library_name + ' ' + this.uuid + '): ' + msg);
1663 this.pauseChart = function() {
1664 if(this.paused === false) {
1665 if(this.debug === true)
1666 this.log('pauseChart()');
1672 this.unpauseChart = function() {
1673 if(this.paused === true) {
1674 if(this.debug === true)
1675 this.log('unpauseChart()');
1677 this.paused = false;
1681 this.resetChart = function(dont_clear_master, dont_update) {
1682 if(this.debug === true)
1683 this.log('resetChart(' + dont_clear_master + ', ' + dont_update + ') called');
1685 if(typeof dont_clear_master === 'undefined')
1686 dont_clear_master = false;
1688 if(typeof dont_update === 'undefined')
1689 dont_update = false;
1691 if(dont_clear_master !== true && NETDATA.globalPanAndZoom.isMaster(this) === true) {
1692 if(this.debug === true)
1693 this.log('resetChart() diverting to clearMaster().');
1694 // this will call us back with master === true
1695 NETDATA.globalPanAndZoom.clearMaster();
1699 this.clearSelection();
1701 this.tm.pan_and_zoom_seq = 0;
1703 this.setMode('auto');
1704 this.current.force_update_at = 0;
1705 this.current.force_before_ms = null;
1706 this.current.force_after_ms = null;
1707 this.tm.last_autorefreshed = 0;
1708 this.paused = false;
1709 this.selected = false;
1710 this.enabled = true;
1711 // this.debug = false;
1713 // do not update the chart here
1714 // or the chart will flip-flop when it is the master
1715 // of a selection sync and another chart becomes
1718 if(dont_update !== true && this.isVisible() === true) {
1723 this.updateChartPanOrZoom = function(after, before) {
1724 var logme = 'updateChartPanOrZoom(' + after + ', ' + before + '): ';
1727 if(this.debug === true)
1730 if(before < after) {
1731 this.log(logme + 'flipped parameters, rejecting it.');
1735 if(typeof this.fixed_min_duration === 'undefined')
1736 this.fixed_min_duration = Math.round((this.chartWidth() / 30) * this.chart.update_every * 1000);
1738 var min_duration = this.fixed_min_duration;
1739 var current_duration = Math.round(this.view_before - this.view_after);
1741 // round the numbers
1742 after = Math.round(after);
1743 before = Math.round(before);
1745 // align them to update_every
1746 // stretching them further away
1747 after -= after % this.data_update_every;
1748 before += this.data_update_every - (before % this.data_update_every);
1750 // the final wanted duration
1751 var wanted_duration = before - after;
1753 // to allow panning, accept just a point below our minimum
1754 if((current_duration - this.data_update_every) < min_duration)
1755 min_duration = current_duration - this.data_update_every;
1757 // we do it, but we adjust to minimum size and return false
1758 // when the wanted size is below the current and the minimum
1760 if(this.current === this.zoom && wanted_duration < current_duration && wanted_duration < min_duration) {
1761 if(this.debug === true)
1762 this.log(logme + 'too small: min_duration: ' + (min_duration / 1000).toString() + ', wanted: ' + (wanted_duration / 1000).toString());
1764 min_duration = this.fixed_min_duration;
1766 var dt = (min_duration - wanted_duration) / 2;
1772 var tolerance = this.data_update_every * 2;
1773 var movement = Math.abs(before - this.view_before);
1775 if(Math.abs(current_duration - wanted_duration) <= tolerance && movement <= tolerance) {
1776 if(this.debug === true)
1777 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);
1781 if(this.current.name === 'auto') {
1782 this.log(logme + 'caller called me with mode: ' + this.current.name);
1783 this.setMode('pan');
1786 if(this.debug === true)
1787 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);
1789 this.current.force_update_at = new Date().getTime() + NETDATA.options.current.pan_and_zoom_delay;
1790 this.current.force_after_ms = after;
1791 this.current.force_before_ms = before;
1792 NETDATA.globalPanAndZoom.setMaster(this, after, before);
1796 this.legendFormatValue = function(value) {
1797 if(value === null || value === 'undefined') return '-';
1798 if(typeof value !== 'number') return value;
1800 var abs = Math.abs(value);
1801 if(abs >= 1000) return (Math.round(value)).toLocaleString();
1802 if(abs >= 100 ) return (Math.round(value * 10) / 10).toLocaleString();
1803 if(abs >= 1 ) return (Math.round(value * 100) / 100).toLocaleString();
1804 if(abs >= 0.1 ) return (Math.round(value * 1000) / 1000).toLocaleString();
1805 return (Math.round(value * 10000) / 10000).toLocaleString();
1808 this.legendSetLabelValue = function(label, value) {
1809 var series = this.element_legend_childs.series[label];
1810 if(typeof series === 'undefined') return;
1811 if(series.value === null && series.user === null) return;
1813 // if the value has not changed, skip DOM update
1814 //if(series.last === value) return;
1817 if(typeof value === 'number') {
1818 var v = Math.abs(value);
1819 s = r = this.legendFormatValue(value);
1821 if(typeof series.last === 'number') {
1822 if(v > series.last) s += '<i class="fa fa-angle-up" style="width: 8px; text-align: center; overflow: hidden; vertical-align: middle;"></i>';
1823 else if(v < series.last) s += '<i class="fa fa-angle-down" style="width: 8px; text-align: center; overflow: hidden; vertical-align: middle;"></i>';
1824 else s += '<i class="fa fa-angle-left" style="width: 8px; text-align: center; overflow: hidden; vertical-align: middle;"></i>';
1826 else s += '<i class="fa fa-angle-right" style="width: 8px; text-align: center; overflow: hidden; vertical-align: middle;"></i>';
1831 series.last = value;
1834 if(series.value !== null) series.value.innerHTML = s;
1835 if(series.user !== null) series.user.innerHTML = r;
1838 this.legendSetDate = function(ms) {
1839 if(typeof ms !== 'number') {
1840 this.legendShowUndefined();
1844 var d = new Date(ms);
1846 if(this.element_legend_childs.title_date)
1847 this.element_legend_childs.title_date.innerHTML = d.toLocaleDateString();
1849 if(this.element_legend_childs.title_time)
1850 this.element_legend_childs.title_time.innerHTML = d.toLocaleTimeString();
1852 if(this.element_legend_childs.title_units)
1853 this.element_legend_childs.title_units.innerHTML = this.units;
1856 this.legendShowUndefined = function() {
1857 if(this.element_legend_childs.title_date)
1858 this.element_legend_childs.title_date.innerHTML = ' ';
1860 if(this.element_legend_childs.title_time)
1861 this.element_legend_childs.title_time.innerHTML = this.chart.name;
1863 if(this.element_legend_childs.title_units)
1864 this.element_legend_childs.title_units.innerHTML = ' ';
1866 if(this.data && this.element_legend_childs.series !== null) {
1867 var labels = this.data.dimension_names;
1868 var i = labels.length;
1870 var label = labels[i];
1872 if(typeof label === 'undefined') continue;
1873 if(typeof this.element_legend_childs.series[label] === 'undefined') continue;
1874 this.legendSetLabelValue(label, null);
1879 this.legendShowLatestValues = function() {
1880 if(this.chart === null) return;
1881 if(this.selected) return;
1883 if(this.data === null || this.element_legend_childs.series === null) {
1884 this.legendShowUndefined();
1888 var show_undefined = true;
1889 if(Math.abs(this.data.last_entry - this.data.before) <= this.data.view_update_every)
1890 show_undefined = false;
1892 if(show_undefined) {
1893 this.legendShowUndefined();
1897 this.legendSetDate(this.data.before * 1000);
1899 var labels = this.data.dimension_names;
1900 var i = labels.length;
1902 var label = labels[i];
1904 if(typeof label === 'undefined') continue;
1905 if(typeof this.element_legend_childs.series[label] === 'undefined') continue;
1908 this.legendSetLabelValue(label, null);
1910 this.legendSetLabelValue(label, this.data.view_latest_values[i]);
1914 this.legendReset = function() {
1915 this.legendShowLatestValues();
1918 // this should be called just ONCE per dimension per chart
1919 this._chartDimensionColor = function(label) {
1920 if(this.colors === null) this.chartColors();
1922 if(typeof this.colors_assigned[label] === 'undefined') {
1923 if(this.colors_available.length === 0) {
1924 for(var i = 0, len = NETDATA.colors.length; i < len ; i++)
1925 this.colors_available.push(NETDATA.colors[i]);
1928 this.colors_assigned[label] = this.colors_available.shift();
1930 if(this.debug === true)
1931 this.log('label "' + label + '" got color "' + this.colors_assigned[label]);
1934 if(this.debug === true)
1935 this.log('label "' + label + '" already has color "' + this.colors_assigned[label] + '"');
1938 this.colors.push(this.colors_assigned[label]);
1939 return this.colors_assigned[label];
1942 this.chartColors = function() {
1943 if(this.colors !== null) return this.colors;
1945 this.colors = new Array();
1946 this.colors_available = new Array();
1947 // this.colors_assigned = {};
1949 var c = $(this.element).data('colors');
1950 if(typeof c !== 'undefined' && c !== null) {
1951 if(typeof c !== 'string') {
1952 this.log('invalid color given: ' + c + ' (give a space separated list of colors)');
1956 for(var i = 0, len = c.length; i < len ; i++)
1957 this.colors_available.push(c[i]);
1961 // push all the standard colors too
1962 for(var i = 0, len = NETDATA.colors.length; i < len ; i++)
1963 this.colors_available.push(NETDATA.colors[i]);
1968 this.legendUpdateDOM = function() {
1971 // check that the legend DOM is up to date for the downloaded dimensions
1972 if(typeof this.element_legend_childs.series !== 'object' || this.element_legend_childs.series === null) {
1973 // this.log('the legend does not have any series - requesting legend update');
1976 else if(this.data === null) {
1977 // this.log('the chart does not have any data - requesting legend update');
1980 else if(typeof this.element_legend_childs.series.labels_key === 'undefined') {
1984 var labels = this.data.dimension_names.toString();
1985 if(labels !== this.element_legend_childs.series.labels_key) {
1988 if(this.debug === true)
1989 this.log('NEW LABELS: "' + labels + '" NOT EQUAL OLD LABELS: "' + this.element_legend_childs.series.labels_key + '"');
1993 if(needed === false) {
1994 // make sure colors available
1997 // do we have to update the current values?
1998 // we do this, only when the visible chart is current
1999 if(Math.abs(this.data.last_entry - this.data.before) <= this.data.view_update_every) {
2000 if(this.debug === true)
2001 this.log('chart in running... updating values on legend...');
2003 //var labels = this.data.dimension_names;
2004 //var i = labels.length;
2006 // this.legendSetLabelValue(labels[i], this.data.latest_values[i]);
2010 if(this.colors === null) {
2011 // this is the first time we update the chart
2012 // let's assign colors to all dimensions
2013 if(this.library.track_colors() === true)
2014 for(var dim in this.chart.dimensions)
2015 this._chartDimensionColor(this.chart.dimensions[dim].name);
2017 // we will re-generate the colors for the chart
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.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 = this.host + "/api/v1/chart?chart=" + this.id;
2664 if(this.debug === true)
2665 this.log('downloading ' + this.chart_url);
2668 url: this.chart_url,
2669 crossDomain: NETDATA.options.crossDomainAjax,
2673 .done(function(chart) {
2674 chart.url = that.chart_url;
2675 chart.data_url = (that.host + chart.data_url);
2676 that._defaultsFromDownloadedChart(chart);
2677 NETDATA.chartRegistry.add(that.host, that.id, chart);
2680 NETDATA.error(404, that.chart_url);
2681 error('chart not found on url "' + that.chart_url + '"');
2683 .always(function() {
2684 if(typeof callback === 'function') callback();
2689 // ============================================================================================================
2695 NETDATA.resetAllCharts = function(state) {
2696 // first clear the global selection sync
2697 // to make sure no chart is in selected state
2698 state.globalSelectionSyncStop();
2700 // there are 2 possibilities here
2701 // a. state is the global Pan and Zoom master
2702 // b. state is not the global Pan and Zoom master
2704 if(NETDATA.globalPanAndZoom.isMaster(state) === false)
2707 // clear the global Pan and Zoom
2708 // this will also refresh the master
2709 // and unblock any charts currently mirroring the master
2710 NETDATA.globalPanAndZoom.clearMaster();
2712 // if we were not the master, reset our status too
2713 // this is required because most probably the mouse
2714 // is over this chart, blocking it from autorefreshing
2715 if(master === false && (state.paused === true || state.selected === true))
2719 // get or create a chart state, given a DOM element
2720 NETDATA.chartState = function(element) {
2721 var state = $(element).data('netdata-state-object') || null;
2722 if(state === null) {
2723 state = new chartState(element);
2724 $(element).data('netdata-state-object', state);
2729 // ----------------------------------------------------------------------------------------------------------------
2730 // Library functions
2732 // Load a script without jquery
2733 // This is used to load jquery - after it is loaded, we use jquery
2734 NETDATA._loadjQuery = function(callback) {
2735 if(typeof jQuery === 'undefined') {
2736 if(NETDATA.options.debug.main_loop === true)
2737 console.log('loading ' + NETDATA.jQuery);
2739 var script = document.createElement('script');
2740 script.type = 'text/javascript';
2741 script.async = true;
2742 script.src = NETDATA.jQuery;
2744 // script.onabort = onError;
2745 script.onerror = function(err, t) { NETDATA.error(101, NETDATA.jQuery); };
2746 if(typeof callback === "function")
2747 script.onload = callback;
2749 var s = document.getElementsByTagName('script')[0];
2750 s.parentNode.insertBefore(script, s);
2752 else if(typeof callback === "function")
2756 NETDATA._loadCSS = function(filename) {
2757 // don't use jQuery here
2758 // styles are loaded before jQuery
2759 // to eliminate showing an unstyled page to the user
2761 var fileref = document.createElement("link");
2762 fileref.setAttribute("rel", "stylesheet");
2763 fileref.setAttribute("type", "text/css");
2764 fileref.setAttribute("href", filename);
2766 if (typeof fileref !== 'undefined')
2767 document.getElementsByTagName("head")[0].appendChild(fileref);
2770 NETDATA.colorHex2Rgb = function(hex) {
2771 // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
2772 var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
2773 hex = hex.replace(shorthandRegex, function(m, r, g, b) {
2774 return r + r + g + g + b + b;
2777 var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
2779 r: parseInt(result[1], 16),
2780 g: parseInt(result[2], 16),
2781 b: parseInt(result[3], 16)
2785 NETDATA.colorLuminance = function(hex, lum) {
2786 // validate hex string
2787 hex = String(hex).replace(/[^0-9a-f]/gi, '');
2789 hex = hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2];
2793 // convert to decimal and change luminosity
2794 var rgb = "#", c, i;
2795 for (i = 0; i < 3; i++) {
2796 c = parseInt(hex.substr(i*2,2), 16);
2797 c = Math.round(Math.min(Math.max(0, c + (c * lum)), 255)).toString(16);
2798 rgb += ("00"+c).substr(c.length);
2804 NETDATA.guid = function() {
2806 return Math.floor((1 + Math.random()) * 0x10000)
2811 return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
2814 NETDATA.zeropad = function(x) {
2815 if(x > -10 && x < 10) return '0' + x.toString();
2816 else return x.toString();
2819 // user function to signal us the DOM has been
2821 NETDATA.updatedDom = function() {
2822 NETDATA.options.updated_dom = true;
2825 NETDATA.ready = function(callback) {
2826 NETDATA.options.pauseCallback = callback;
2829 NETDATA.pause = function(callback) {
2830 if(NETDATA.options.pause === true)
2833 NETDATA.options.pauseCallback = callback;
2836 NETDATA.unpause = function() {
2837 NETDATA.options.pauseCallback = null;
2838 NETDATA.options.updated_dom = true;
2839 NETDATA.options.pause = false;
2842 // ----------------------------------------------------------------------------------------------------------------
2844 // this is purely sequencial charts refresher
2845 // it is meant to be autonomous
2846 NETDATA.chartRefresherNoParallel = function(index) {
2847 if(NETDATA.options.debug.mail_loop === true)
2848 console.log('NETDATA.chartRefresherNoParallel(' + index + ')');
2850 if(NETDATA.options.updated_dom === true) {
2851 // the dom has been updated
2852 // get the dom parts again
2853 NETDATA.parseDom(NETDATA.chartRefresher);
2856 if(index >= NETDATA.options.targets.length) {
2857 if(NETDATA.options.debug.main_loop === true)
2858 console.log('waiting to restart main loop...');
2860 NETDATA.options.auto_refresher_fast_weight = 0;
2862 setTimeout(function() {
2863 NETDATA.chartRefresher();
2864 }, NETDATA.options.current.idle_between_loops);
2867 var state = NETDATA.options.targets[index];
2869 if(NETDATA.options.auto_refresher_fast_weight < NETDATA.options.current.fast_render_timeframe) {
2870 if(NETDATA.options.debug.main_loop === true)
2871 console.log('fast rendering...');
2873 state.autoRefresh(function() {
2874 NETDATA.chartRefresherNoParallel(++index);
2878 if(NETDATA.options.debug.main_loop === true) console.log('waiting for next refresh...');
2879 NETDATA.options.auto_refresher_fast_weight = 0;
2881 setTimeout(function() {
2882 state.autoRefresh(function() {
2883 NETDATA.chartRefresherNoParallel(++index);
2885 }, NETDATA.options.current.idle_between_charts);
2890 // this is part of the parallel refresher
2891 // its cause is to refresh sequencially all the charts
2892 // that depend on chart library initialization
2893 // it will call the parallel refresher back
2894 // as soon as it sees a chart that its chart library
2896 NETDATA.chartRefresher_unitialized = function() {
2897 if(NETDATA.options.updated_dom === true) {
2898 // the dom has been updated
2899 // get the dom parts again
2900 NETDATA.parseDom(NETDATA.chartRefresher);
2904 if(NETDATA.options.sequencial.length === 0)
2905 NETDATA.chartRefresher();
2907 var state = NETDATA.options.sequencial.pop();
2908 if(state.library.initialized === true)
2909 NETDATA.chartRefresher();
2911 state.autoRefresh(NETDATA.chartRefresher_unitialized);
2915 NETDATA.chartRefresherWaitTime = function() {
2916 return NETDATA.options.current.idle_parallel_loops;
2919 // the default refresher
2920 // it will create 2 sets of charts:
2921 // - the ones that can be refreshed in parallel
2922 // - the ones that depend on something else
2923 // the first set will be executed in parallel
2924 // the second will be given to NETDATA.chartRefresher_unitialized()
2925 NETDATA.chartRefresher = function() {
2926 if(NETDATA.options.pause === true) {
2927 // console.log('auto-refresher is paused');
2928 setTimeout(NETDATA.chartRefresher,
2929 NETDATA.chartRefresherWaitTime());
2933 if(typeof NETDATA.options.pauseCallback === 'function') {
2934 // console.log('auto-refresher is calling pauseCallback');
2935 NETDATA.options.pause = true;
2936 NETDATA.options.pauseCallback();
2937 NETDATA.chartRefresher();
2941 if(NETDATA.options.current.parallel_refresher === false) {
2942 NETDATA.chartRefresherNoParallel(0);
2946 if(NETDATA.options.updated_dom === true) {
2947 // the dom has been updated
2948 // get the dom parts again
2949 NETDATA.parseDom(NETDATA.chartRefresher);
2953 var parallel = new Array();
2954 var targets = NETDATA.options.targets;
2955 var len = targets.length;
2957 if(targets[len].isVisible() === false)
2960 var state = targets[len];
2961 if(state.library.initialized === false) {
2962 if(state.library.enabled === true) {
2963 state.library.initialize(NETDATA.chartRefresher);
2967 state.error('chart library "' + state.library_name + '" is not enabled.');
2971 parallel.unshift(state);
2974 if(parallel.length > 0) {
2975 var parallel_jobs = parallel.length;
2977 // this will execute the jobs in parallel
2978 $(parallel).each(function() {
2979 this.autoRefresh(function() {
2982 if(parallel_jobs === 0) {
2983 setTimeout(NETDATA.chartRefresher,
2984 NETDATA.chartRefresherWaitTime());
2990 setTimeout(NETDATA.chartRefresher,
2991 NETDATA.chartRefresherWaitTime());
2995 NETDATA.parseDom = function(callback) {
2996 NETDATA.options.last_page_scroll = new Date().getTime();
2997 NETDATA.options.updated_dom = false;
2999 var targets = $('div[data-netdata]'); //.filter(':visible');
3001 if(NETDATA.options.debug.main_loop === true)
3002 console.log('DOM updated - there are ' + targets.length + ' charts on page.');
3004 NETDATA.options.targets = new Array();
3005 var len = targets.length;
3007 // the initialization will take care of sizing
3008 // and the "loading..." message
3009 NETDATA.options.targets.push(NETDATA.chartState(targets[len]));
3012 if(typeof callback === 'function') callback();
3015 // this is the main function - where everything starts
3016 NETDATA.start = function() {
3017 // this should be called only once
3019 NETDATA.options.page_is_visible = true;
3021 $(window).blur(function() {
3022 if(NETDATA.options.current.stop_updates_when_focus_is_lost === true) {
3023 NETDATA.options.page_is_visible = false;
3024 if(NETDATA.options.debug.focus === true)
3025 console.log('Lost Focus!');
3029 $(window).focus(function() {
3030 if(NETDATA.options.current.stop_updates_when_focus_is_lost === true) {
3031 NETDATA.options.page_is_visible = true;
3032 if(NETDATA.options.debug.focus === true)
3033 console.log('Focus restored!');
3037 if(typeof document.hasFocus === 'function' && !document.hasFocus()) {
3038 if(NETDATA.options.current.stop_updates_when_focus_is_lost === true) {
3039 NETDATA.options.page_is_visible = false;
3040 if(NETDATA.options.debug.focus === true)
3041 console.log('Document has no focus!');
3045 // bootstrap tab switching
3046 $('a[data-toggle="tab"]').on('shown.bs.tab', NETDATA.onscroll);
3048 // bootstrap modal switching
3049 $('.modal').on('hidden.bs.modal', NETDATA.onscroll);
3050 $('.modal').on('shown.bs.modal', NETDATA.onscroll);
3052 NETDATA.parseDom(NETDATA.chartRefresher);
3055 // ----------------------------------------------------------------------------------------------------------------
3058 NETDATA.peityInitialize = function(callback) {
3059 if(typeof netdataNoPeitys === 'undefined' || !netdataNoPeitys) {
3061 url: NETDATA.peity_js,
3066 NETDATA.registerChartLibrary('peity', NETDATA.peity_js);
3069 NETDATA.chartLibraries.peity.enabled = false;
3070 NETDATA.error(100, NETDATA.peity_js);
3072 .always(function() {
3073 if(typeof callback === "function")
3078 NETDATA.chartLibraries.peity.enabled = false;
3079 if(typeof callback === "function")
3084 NETDATA.peityChartUpdate = function(state, data) {
3085 state.peity_instance.innerHTML = data.result;
3087 if(state.peity_options.stroke !== state.chartColors()[0]) {
3088 state.peity_options.stroke = state.chartColors()[0];
3089 if(state.chart.chart_type === 'line')
3090 state.peity_options.fill = '#FFF';
3092 state.peity_options.fill = NETDATA.colorLuminance(state.chartColors()[0], NETDATA.chartDefaults.fill_luminance);
3095 $(state.peity_instance).peity('line', state.peity_options);
3099 NETDATA.peityChartCreate = function(state, data) {
3100 state.peity_instance = document.createElement('div');
3101 state.element_chart.appendChild(state.peity_instance);
3103 var self = $(state.element);
3104 state.peity_options = {
3106 strokeWidth: self.data('peity-strokewidth') || 1,
3107 width: state.chartWidth(),
3108 height: state.chartHeight(),
3112 NETDATA.peityChartUpdate(state, data);
3116 // ----------------------------------------------------------------------------------------------------------------
3119 NETDATA.sparklineInitialize = function(callback) {
3120 if(typeof netdataNoSparklines === 'undefined' || !netdataNoSparklines) {
3122 url: NETDATA.sparkline_js,
3127 NETDATA.registerChartLibrary('sparkline', NETDATA.sparkline_js);
3130 NETDATA.chartLibraries.sparkline.enabled = false;
3131 NETDATA.error(100, NETDATA.sparkline_js);
3133 .always(function() {
3134 if(typeof callback === "function")
3139 NETDATA.chartLibraries.sparkline.enabled = false;
3140 if(typeof callback === "function")
3145 NETDATA.sparklineChartUpdate = function(state, data) {
3146 state.sparkline_options.width = state.chartWidth();
3147 state.sparkline_options.height = state.chartHeight();
3149 $(state.element_chart).sparkline(data.result, state.sparkline_options);
3153 NETDATA.sparklineChartCreate = function(state, data) {
3154 var self = $(state.element);
3155 var type = self.data('sparkline-type') || 'line';
3156 var lineColor = self.data('sparkline-linecolor') || state.chartColors()[0];
3157 var fillColor = self.data('sparkline-fillcolor') || (state.chart.chart_type === 'line')?'#FFF':NETDATA.colorLuminance(lineColor, NETDATA.chartDefaults.fill_luminance);
3158 var chartRangeMin = self.data('sparkline-chartrangemin') || undefined;
3159 var chartRangeMax = self.data('sparkline-chartrangemax') || undefined;
3160 var composite = self.data('sparkline-composite') || undefined;
3161 var enableTagOptions = self.data('sparkline-enabletagoptions') || undefined;
3162 var tagOptionPrefix = self.data('sparkline-tagoptionprefix') || undefined;
3163 var tagValuesAttribute = self.data('sparkline-tagvaluesattribute') || undefined;
3164 var disableHiddenCheck = self.data('sparkline-disablehiddencheck') || undefined;
3165 var defaultPixelsPerValue = self.data('sparkline-defaultpixelspervalue') || undefined;
3166 var spotColor = self.data('sparkline-spotcolor') || undefined;
3167 var minSpotColor = self.data('sparkline-minspotcolor') || undefined;
3168 var maxSpotColor = self.data('sparkline-maxspotcolor') || undefined;
3169 var spotRadius = self.data('sparkline-spotradius') || undefined;
3170 var valueSpots = self.data('sparkline-valuespots') || undefined;
3171 var highlightSpotColor = self.data('sparkline-highlightspotcolor') || undefined;
3172 var highlightLineColor = self.data('sparkline-highlightlinecolor') || undefined;
3173 var lineWidth = self.data('sparkline-linewidth') || undefined;
3174 var normalRangeMin = self.data('sparkline-normalrangemin') || undefined;
3175 var normalRangeMax = self.data('sparkline-normalrangemax') || undefined;
3176 var drawNormalOnTop = self.data('sparkline-drawnormalontop') || undefined;
3177 var xvalues = self.data('sparkline-xvalues') || undefined;
3178 var chartRangeClip = self.data('sparkline-chartrangeclip') || undefined;
3179 var xvalues = self.data('sparkline-xvalues') || undefined;
3180 var chartRangeMinX = self.data('sparkline-chartrangeminx') || undefined;
3181 var chartRangeMaxX = self.data('sparkline-chartrangemaxx') || undefined;
3182 var disableInteraction = self.data('sparkline-disableinteraction') || false;
3183 var disableTooltips = self.data('sparkline-disabletooltips') || false;
3184 var disableHighlight = self.data('sparkline-disablehighlight') || false;
3185 var highlightLighten = self.data('sparkline-highlightlighten') || 1.4;
3186 var highlightColor = self.data('sparkline-highlightcolor') || undefined;
3187 var tooltipContainer = self.data('sparkline-tooltipcontainer') || undefined;
3188 var tooltipClassname = self.data('sparkline-tooltipclassname') || undefined;
3189 var tooltipFormat = self.data('sparkline-tooltipformat') || undefined;
3190 var tooltipPrefix = self.data('sparkline-tooltipprefix') || undefined;
3191 var tooltipSuffix = self.data('sparkline-tooltipsuffix') || ' ' + state.units;
3192 var tooltipSkipNull = self.data('sparkline-tooltipskipnull') || true;
3193 var tooltipValueLookups = self.data('sparkline-tooltipvaluelookups') || undefined;
3194 var tooltipFormatFieldlist = self.data('sparkline-tooltipformatfieldlist') || undefined;
3195 var tooltipFormatFieldlistKey = self.data('sparkline-tooltipformatfieldlistkey') || undefined;
3196 var numberFormatter = self.data('sparkline-numberformatter') || function(n){ return n.toFixed(2); };
3197 var numberDigitGroupSep = self.data('sparkline-numberdigitgroupsep') || undefined;
3198 var numberDecimalMark = self.data('sparkline-numberdecimalmark') || undefined;
3199 var numberDigitGroupCount = self.data('sparkline-numberdigitgroupcount') || undefined;
3200 var animatedZooms = self.data('sparkline-animatedzooms') || false;
3202 state.sparkline_options = {
3204 lineColor: lineColor,
3205 fillColor: fillColor,
3206 chartRangeMin: chartRangeMin,
3207 chartRangeMax: chartRangeMax,
3208 composite: composite,
3209 enableTagOptions: enableTagOptions,
3210 tagOptionPrefix: tagOptionPrefix,
3211 tagValuesAttribute: tagValuesAttribute,
3212 disableHiddenCheck: disableHiddenCheck,
3213 defaultPixelsPerValue: defaultPixelsPerValue,
3214 spotColor: spotColor,
3215 minSpotColor: minSpotColor,
3216 maxSpotColor: maxSpotColor,
3217 spotRadius: spotRadius,
3218 valueSpots: valueSpots,
3219 highlightSpotColor: highlightSpotColor,
3220 highlightLineColor: highlightLineColor,
3221 lineWidth: lineWidth,
3222 normalRangeMin: normalRangeMin,
3223 normalRangeMax: normalRangeMax,
3224 drawNormalOnTop: drawNormalOnTop,
3226 chartRangeClip: chartRangeClip,
3227 chartRangeMinX: chartRangeMinX,
3228 chartRangeMaxX: chartRangeMaxX,
3229 disableInteraction: disableInteraction,
3230 disableTooltips: disableTooltips,
3231 disableHighlight: disableHighlight,
3232 highlightLighten: highlightLighten,
3233 highlightColor: highlightColor,
3234 tooltipContainer: tooltipContainer,
3235 tooltipClassname: tooltipClassname,
3236 tooltipChartTitle: state.title,
3237 tooltipFormat: tooltipFormat,
3238 tooltipPrefix: tooltipPrefix,
3239 tooltipSuffix: tooltipSuffix,
3240 tooltipSkipNull: tooltipSkipNull,
3241 tooltipValueLookups: tooltipValueLookups,
3242 tooltipFormatFieldlist: tooltipFormatFieldlist,
3243 tooltipFormatFieldlistKey: tooltipFormatFieldlistKey,
3244 numberFormatter: numberFormatter,
3245 numberDigitGroupSep: numberDigitGroupSep,
3246 numberDecimalMark: numberDecimalMark,
3247 numberDigitGroupCount: numberDigitGroupCount,
3248 animatedZooms: animatedZooms,
3249 width: state.chartWidth(),
3250 height: state.chartHeight()
3253 $(state.element_chart).sparkline(data.result, state.sparkline_options);
3257 // ----------------------------------------------------------------------------------------------------------------
3264 NETDATA.dygraphSetSelection = function(state, t) {
3265 if(typeof state.dygraph_instance !== 'undefined') {
3266 var r = state.calculateRowForTime(t);
3268 state.dygraph_instance.setSelection(r);
3270 state.dygraph_instance.clearSelection();
3271 state.legendShowUndefined();
3278 NETDATA.dygraphClearSelection = function(state, t) {
3279 if(typeof state.dygraph_instance !== 'undefined') {
3280 state.dygraph_instance.clearSelection();
3285 NETDATA.dygraphSmoothInitialize = function(callback) {
3287 url: NETDATA.dygraph_smooth_js,
3292 NETDATA.dygraph.smooth = true;
3293 smoothPlotter.smoothing = 0.3;
3296 NETDATA.dygraph.smooth = false;
3298 .always(function() {
3299 if(typeof callback === "function")
3304 NETDATA.dygraphInitialize = function(callback) {
3305 if(typeof netdataNoDygraphs === 'undefined' || !netdataNoDygraphs) {
3307 url: NETDATA.dygraph_js,
3312 NETDATA.registerChartLibrary('dygraph', NETDATA.dygraph_js);
3315 NETDATA.chartLibraries.dygraph.enabled = false;
3316 NETDATA.error(100, NETDATA.dygraph_js);
3318 .always(function() {
3319 if(NETDATA.chartLibraries.dygraph.enabled === true && NETDATA.options.current.smooth_plot === true)
3320 NETDATA.dygraphSmoothInitialize(callback);
3321 else if(typeof callback === "function")
3326 NETDATA.chartLibraries.dygraph.enabled = false;
3327 if(typeof callback === "function")
3332 NETDATA.dygraphChartUpdate = function(state, data) {
3333 var dygraph = state.dygraph_instance;
3335 if(typeof dygraph === 'undefined')
3336 return NETDATA.dygraphChartCreate(state, data);
3338 // when the chart is not visible, and hidden
3339 // if there is a window resize, dygraph detects
3340 // its element size as 0x0.
3341 // this will make it re-appear properly
3343 if(state.tm.last_unhidden > state.dygraph_last_rendered)
3347 file: data.result.data,
3348 colors: state.chartColors(),
3349 labels: data.result.labels,
3350 labelsDivWidth: state.chartWidth() - 70,
3351 visibility: state.dimensions_visibility.selected2BooleanArray(state.data.dimension_names)
3354 if(state.current.name !== 'auto') {
3355 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3356 state.log('dygraphChartUpdate() loose update');
3359 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3360 state.log('dygraphChartUpdate() strict update');
3362 options.dateWindow = null;
3363 options.valueRange = null;
3366 if(state.dygraph_smooth_eligible === true) {
3367 if((NETDATA.options.current.smooth_plot === true && state.dygraph_options.plotter !== smoothPlotter)
3368 || (NETDATA.options.current.smooth_plot === false && state.dygraph_options.plotter === smoothPlotter)) {
3369 NETDATA.dygraphChartCreate(state, data);
3374 dygraph.updateOptions(options);
3375 state.dygraph_last_rendered = new Date().getTime();
3379 NETDATA.dygraphChartCreate = function(state, data) {
3380 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3381 state.log('dygraphChartCreate()');
3383 var self = $(state.element);
3385 var chart_type = state.chart.chart_type;
3386 if(chart_type === 'stacked' && data.dimensions === 1) chart_type = 'area';
3387 chart_type = self.data('dygraph-type') || chart_type;
3389 var smooth = (chart_type === 'line' && !NETDATA.chartLibraries.dygraph.isSparkline(state))?true:false;
3390 smooth = self.data('dygraph-smooth') || smooth;
3392 if(NETDATA.dygraph.smooth === false)
3395 var strokeWidth = (chart_type === 'stacked')?0.1:((smooth)?1.5:0.7)
3396 var highlightCircleSize = (NETDATA.chartLibraries.dygraph.isSparkline(state))?3:4;
3398 state.dygraph_options = {
3399 colors: self.data('dygraph-colors') || state.chartColors(),
3401 // leave a few pixels empty on the right of the chart
3402 rightGap: self.data('dygraph-rightgap') || 5,
3403 showRangeSelector: self.data('dygraph-showrangeselector') || false,
3404 showRoller: self.data('dygraph-showroller') || false,
3406 title: self.data('dygraph-title') || state.title,
3407 titleHeight: self.data('dygraph-titleheight') || 19,
3409 legend: self.data('dygraph-legend') || 'always', // 'onmouseover',
3410 labels: data.result.labels,
3411 labelsDiv: self.data('dygraph-labelsdiv') || state.element_legend_childs.hidden,
3412 labelsDivStyles: self.data('dygraph-labelsdivstyles') || { 'fontSize':'1px' },
3413 labelsDivWidth: self.data('dygraph-labelsdivwidth') || state.chartWidth() - 70,
3414 labelsSeparateLines: self.data('dygraph-labelsseparatelines') || true,
3415 labelsShowZeroValues: self.data('dygraph-labelsshowzerovalues') || true,
3418 showLabelsOnHighlight: self.data('dygraph-showlabelsonhighlight') || true,
3419 hideOverlayOnMouseOut: self.data('dygraph-hideoverlayonmouseout') || true,
3421 ylabel: state.units,
3422 yLabelWidth: self.data('dygraph-ylabelwidth') || 12,
3424 // the function to plot the chart
3427 // The width of the lines connecting data points. This can be used to increase the contrast or some graphs.
3428 strokeWidth: self.data('dygraph-strokewidth') || strokeWidth,
3429 strokePattern: self.data('dygraph-strokepattern') || undefined,
3431 // The size of the dot to draw on each point in pixels (see drawPoints). A dot is always drawn when a point is "isolated",
3432 // i.e. there is a missing point on either side of it. This also controls the size of those dots.
3433 drawPoints: self.data('dygraph-drawpoints') || false,
3435 // Draw points at the edges of gaps in the data. This improves visibility of small data segments or other data irregularities.
3436 drawGapEdgePoints: self.data('dygraph-drawgapedgepoints') || true,
3438 connectSeparatedPoints: self.data('dygraph-connectseparatedpoints') || false,
3439 pointSize: self.data('dygraph-pointsize') || 1,
3441 // enabling this makes the chart with little square lines
3442 stepPlot: self.data('dygraph-stepplot') || false,
3444 // Draw a border around graph lines to make crossing lines more easily distinguishable. Useful for graphs with many lines.
3445 strokeBorderColor: self.data('dygraph-strokebordercolor') || 'white',
3446 strokeBorderWidth: self.data('dygraph-strokeborderwidth') || (chart_type === 'stacked')?0.0:0.0,
3448 fillGraph: self.data('dygraph-fillgraph') || (chart_type === 'area' || chart_type === 'stacked')?true:false,
3449 fillAlpha: self.data('dygraph-fillalpha') || (chart_type === 'stacked')?NETDATA.options.current.color_fill_opacity_stacked:NETDATA.options.current.color_fill_opacity_area,
3450 stackedGraph: self.data('dygraph-stackedgraph') || (chart_type === 'stacked')?true:false,
3451 stackedGraphNaNFill: self.data('dygraph-stackedgraphnanfill') || 'none',
3453 drawAxis: self.data('dygraph-drawaxis') || true,
3454 axisLabelFontSize: self.data('dygraph-axislabelfontsize') || 10,
3455 axisLineColor: self.data('dygraph-axislinecolor') || '#CCC',
3456 axisLineWidth: self.data('dygraph-axislinewidth') || 0.3,
3458 drawGrid: self.data('dygraph-drawgrid') || true,
3459 drawXGrid: self.data('dygraph-drawxgrid') || undefined,
3460 drawYGrid: self.data('dygraph-drawygrid') || undefined,
3461 gridLinePattern: self.data('dygraph-gridlinepattern') || null,
3462 gridLineWidth: self.data('dygraph-gridlinewidth') || 0.3,
3463 gridLineColor: self.data('dygraph-gridlinecolor') || '#DDD',
3465 maxNumberWidth: self.data('dygraph-maxnumberwidth') || 8,
3466 sigFigs: self.data('dygraph-sigfigs') || null,
3467 digitsAfterDecimal: self.data('dygraph-digitsafterdecimal') || 2,
3468 valueFormatter: self.data('dygraph-valueformatter') || function(x){ return x.toFixed(2); },
3470 highlightCircleSize: self.data('dygraph-highlightcirclesize') || highlightCircleSize,
3471 highlightSeriesOpts: self.data('dygraph-highlightseriesopts') || null, // TOO SLOW: { strokeWidth: 1.5 },
3472 highlightSeriesBackgroundAlpha: self.data('dygraph-highlightseriesbackgroundalpha') || null, // TOO SLOW: (chart_type === 'stacked')?0.7:0.5,
3474 pointClickCallback: self.data('dygraph-pointclickcallback') || undefined,
3475 visibility: state.dimensions_visibility.selected2BooleanArray(state.data.dimension_names),
3479 ticker: Dygraph.dateTicker,
3480 axisLabelFormatter: function (d, gran) {
3481 return NETDATA.zeropad(d.getHours()) + ":" + NETDATA.zeropad(d.getMinutes()) + ":" + NETDATA.zeropad(d.getSeconds());
3483 valueFormatter: function (ms) {
3484 var d = new Date(ms);
3485 return d.toLocaleDateString() + ' ' + d.toLocaleTimeString();
3486 // return NETDATA.zeropad(d.getHours()) + ":" + NETDATA.zeropad(d.getMinutes()) + ":" + NETDATA.zeropad(d.getSeconds());
3491 valueFormatter: function (x) {
3492 // we format legends with the state object
3493 // no need to do anything here
3494 // return (Math.round(x*100) / 100).toLocaleString();
3495 // return state.legendFormatValue(x);
3500 legendFormatter: function(data) {
3501 var elements = state.element_legend_childs;
3503 // if the hidden div is not there
3504 // we are not managing the legend
3505 if(elements.hidden === null) return;
3507 if (typeof data.x !== 'undefined') {
3508 state.legendSetDate(data.x);
3509 var i = data.series.length;
3511 var series = data.series[i];
3512 if(!series.isVisible) continue;
3513 state.legendSetLabelValue(series.label, series.y);
3519 drawCallback: function(dygraph, is_initial) {
3520 if(state.current.name !== 'auto') {
3521 if(NETDATA.options.debug.dygraph === true)
3522 state.log('dygraphDrawCallback()');
3524 var first = state.data.first_entry * 1000;
3525 var last = state.data.last_entry * 1000;
3527 var x_range = dygraph.xAxisRange();
3528 var after = Math.round(x_range[0]);
3529 var before = Math.round(x_range[1]);
3531 if(before <= last && after >= first)
3532 state.updateChartPanOrZoom(after, before);
3535 zoomCallback: function(minDate, maxDate, yRanges) {
3536 if(NETDATA.options.debug.dygraph === true)
3537 state.log('dygraphZoomCallback()');
3539 state.globalSelectionSyncStop();
3540 state.globalSelectionSyncDelay();
3542 if(state.updateChartPanOrZoom(minDate, maxDate) === false) {
3543 // we should not zoom that much
3544 state.dygraph_instance.updateOptions({
3550 highlightCallback: function(event, x, points, row, seriesName) {
3551 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3552 state.log('dygraphHighlightCallback()');
3556 // there is a bug in dygraph when the chart is zoomed enough
3557 // the time it thinks is selected is wrong
3558 // here we calculate the time t based on the row number selected
3560 var t = state.data_after + row * state.data_update_every;
3561 // 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);
3563 state.globalSelectionSync(x);
3565 // fix legend zIndex using the internal structures of dygraph legend module
3566 // this works, but it is a hack!
3567 // state.dygraph_instance.plugins_[0].plugin.legend_div_.style.zIndex = 10000;
3569 unhighlightCallback: function(event) {
3570 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3571 state.log('dygraphUnhighlightCallback()');
3573 state.unpauseChart();
3574 state.globalSelectionSyncStop();
3576 interactionModel : {
3577 mousedown: function(event, dygraph, context) {
3578 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3579 state.log('interactionModel.mousedown()');
3581 state.globalSelectionSyncStop();
3583 if(NETDATA.options.debug.dygraph === true)
3584 state.log('dygraphMouseDown()');
3586 // Right-click should not initiate a zoom.
3587 if(event.button && event.button === 2) return;
3589 context.initializeMouseDown(event, dygraph, context);
3591 if(event.button && event.button === 1) {
3592 if (event.altKey || event.shiftKey) {
3593 state.setMode('pan');
3594 state.globalSelectionSyncDelay();
3595 Dygraph.startPan(event, dygraph, context);
3598 state.setMode('zoom');
3599 state.globalSelectionSyncDelay();
3600 Dygraph.startZoom(event, dygraph, context);
3604 if (event.altKey || event.shiftKey) {
3605 state.setMode('zoom');
3606 state.globalSelectionSyncDelay();
3607 Dygraph.startZoom(event, dygraph, context);
3610 state.setMode('pan');
3611 state.globalSelectionSyncDelay();
3612 Dygraph.startPan(event, dygraph, context);
3616 mousemove: function(event, dygraph, context) {
3617 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3618 state.log('interactionModel.mousemove()');
3620 if(context.isPanning) {
3621 state.globalSelectionSyncStop();
3622 state.globalSelectionSyncDelay();
3623 state.setMode('pan');
3624 Dygraph.movePan(event, dygraph, context);
3626 else if(context.isZooming) {
3627 state.globalSelectionSyncStop();
3628 state.globalSelectionSyncDelay();
3629 state.setMode('zoom');
3630 Dygraph.moveZoom(event, dygraph, context);
3633 mouseup: function(event, dygraph, context) {
3634 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3635 state.log('interactionModel.mouseup()');
3637 if (context.isPanning) {
3638 state.globalSelectionSyncDelay();
3639 Dygraph.endPan(event, dygraph, context);
3641 else if (context.isZooming) {
3642 state.globalSelectionSyncDelay();
3643 Dygraph.endZoom(event, dygraph, context);
3646 click: function(event, dygraph, context) {
3647 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3648 state.log('interactionModel.click()');
3650 event.preventDefault();
3652 dblclick: function(event, dygraph, context) {
3653 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3654 state.log('interactionModel.dblclick()');
3655 NETDATA.resetAllCharts(state);
3657 mousewheel: function(event, dygraph, context) {
3658 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3659 state.log('interactionModel.mousewheel()');
3661 // Take the offset of a mouse event on the dygraph canvas and
3662 // convert it to a pair of percentages from the bottom left.
3663 // (Not top left, bottom is where the lower value is.)
3664 function offsetToPercentage(g, offsetX, offsetY) {
3665 // This is calculating the pixel offset of the leftmost date.
3666 var xOffset = g.toDomCoords(g.xAxisRange()[0], null)[0];
3667 var yar0 = g.yAxisRange(0);
3669 // This is calculating the pixel of the higest value. (Top pixel)
3670 var yOffset = g.toDomCoords(null, yar0[1])[1];
3672 // x y w and h are relative to the corner of the drawing area,
3673 // so that the upper corner of the drawing area is (0, 0).
3674 var x = offsetX - xOffset;
3675 var y = offsetY - yOffset;
3677 // This is computing the rightmost pixel, effectively defining the
3679 var w = g.toDomCoords(g.xAxisRange()[1], null)[0] - xOffset;
3681 // This is computing the lowest pixel, effectively defining the height.
3682 var h = g.toDomCoords(null, yar0[0])[1] - yOffset;
3684 // Percentage from the left.
3685 var xPct = w === 0 ? 0 : (x / w);
3686 // Percentage from the top.
3687 var yPct = h === 0 ? 0 : (y / h);
3689 // The (1-) part below changes it from "% distance down from the top"
3690 // to "% distance up from the bottom".
3691 return [xPct, (1-yPct)];
3694 // Adjusts [x, y] toward each other by zoomInPercentage%
3695 // Split it so the left/bottom axis gets xBias/yBias of that change and
3696 // tight/top gets (1-xBias)/(1-yBias) of that change.
3698 // If a bias is missing it splits it down the middle.
3699 function zoomRange(g, zoomInPercentage, xBias, yBias) {
3700 xBias = xBias || 0.5;
3701 yBias = yBias || 0.5;
3703 function adjustAxis(axis, zoomInPercentage, bias) {
3704 var delta = axis[1] - axis[0];
3705 var increment = delta * zoomInPercentage;
3706 var foo = [increment * bias, increment * (1-bias)];
3708 return [ axis[0] + foo[0], axis[1] - foo[1] ];
3711 var yAxes = g.yAxisRanges();
3713 for (var i = 0; i < yAxes.length; i++) {
3714 newYAxes[i] = adjustAxis(yAxes[i], zoomInPercentage, yBias);
3717 return adjustAxis(g.xAxisRange(), zoomInPercentage, xBias);
3720 if(event.altKey || event.shiftKey) {
3721 state.globalSelectionSyncStop();
3722 state.globalSelectionSyncDelay();
3724 // http://dygraphs.com/gallery/interaction-api.js
3725 var normal = (event.detail) ? event.detail * -1 : event.wheelDelta / 40;
3726 var percentage = normal / 50;
3728 if (!(event.offsetX && event.offsetY)){
3729 event.offsetX = event.layerX - event.target.offsetLeft;
3730 event.offsetY = event.layerY - event.target.offsetTop;
3733 var percentages = offsetToPercentage(dygraph, event.offsetX, event.offsetY);
3734 var xPct = percentages[0];
3735 var yPct = percentages[1];
3737 var new_x_range = zoomRange(dygraph, percentage, xPct, yPct);
3739 var after = new_x_range[0];
3740 var before = new_x_range[1];
3742 var first = (state.data.first_entry + state.data.view_update_every) * 1000;
3743 var last = (state.data.last_entry + state.data.view_update_every) * 1000;
3746 after -= (before - last);
3753 state.setMode('zoom');
3754 if(state.updateChartPanOrZoom(after, before) === true)
3755 dygraph.updateOptions({ dateWindow: [ after, before ] });
3757 event.preventDefault();
3760 touchstart: function(event, dygraph, context) {
3761 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3762 state.log('interactionModel.touchstart()');
3764 state.setMode('zoom');
3767 Dygraph.defaultInteractionModel.touchstart(event, dygraph, context);
3769 // we overwrite the touch directions at the end, to overwrite
3770 // the internal default of dygraphs
3771 context.touchDirections = { x: true, y: false };
3773 state.dygraph_last_touch_start = new Date().getTime();
3774 state.dygraph_last_touch_move = 0;
3776 if(typeof event.touches[0].pageX === 'number')
3777 state.dygraph_last_touch_page_x = event.touches[0].pageX;
3779 state.dygraph_last_touch_page_x = 0;
3781 touchmove: function(event, dygraph, context) {
3782 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3783 state.log('interactionModel.touchmove()');
3785 Dygraph.defaultInteractionModel.touchmove(event, dygraph, context);
3787 state.dygraph_last_touch_move = new Date().getTime();
3789 touchend: function(event, dygraph, context) {
3790 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3791 state.log('interactionModel.touchend()');
3793 Dygraph.defaultInteractionModel.touchend(event, dygraph, context);
3795 // if it didn't move, it is a selection
3796 if(state.dygraph_last_touch_move === 0 && state.dygraph_last_touch_page_x !== 0) {
3797 // internal api of dygraphs
3798 var pct = (state.dygraph_last_touch_page_x - (dygraph.plotter_.area.x + state.element.getBoundingClientRect().left)) / dygraph.plotter_.area.w;
3799 var t = Math.round(state.data_after + (state.data_before - state.data_after) * pct);
3800 if(NETDATA.dygraphSetSelection(state, t) === true)
3801 state.globalSelectionSync(t);
3804 // if it was double tap within double click time, reset the charts
3805 var now = new Date().getTime();
3806 if(typeof state.dygraph_last_touch_end !== 'undefined') {
3807 if(state.dygraph_last_touch_move === 0) {
3808 var dt = now - state.dygraph_last_touch_end;
3809 if(dt <= NETDATA.options.current.double_click_speed)
3810 NETDATA.resetAllCharts(state);
3814 // remember the timestamp of the last touch end
3815 state.dygraph_last_touch_end = now;
3820 if(NETDATA.chartLibraries.dygraph.isSparkline(state)) {
3821 state.dygraph_options.drawGrid = false;
3822 state.dygraph_options.drawAxis = false;
3823 state.dygraph_options.title = undefined;
3824 state.dygraph_options.units = undefined;
3825 state.dygraph_options.ylabel = undefined;
3826 state.dygraph_options.yLabelWidth = 0;
3827 state.dygraph_options.labelsDivWidth = 120;
3828 state.dygraph_options.labelsDivStyles.width = '120px';
3829 state.dygraph_options.labelsSeparateLines = true;
3830 state.dygraph_options.rightGap = 0;
3833 if(smooth === true) {
3834 state.dygraph_smooth_eligible = true;
3836 if(NETDATA.options.current.smooth_plot === true)
3837 state.dygraph_options.plotter = smoothPlotter;
3839 else state.dygraph_smooth_eligible = false;
3841 state.dygraph_instance = new Dygraph(state.element_chart,
3842 data.result.data, state.dygraph_options);
3844 state.dygraph_last_rendered = new Date().getTime();
3848 // ----------------------------------------------------------------------------------------------------------------
3851 NETDATA.morrisInitialize = function(callback) {
3852 if(typeof netdataNoMorris === 'undefined' || !netdataNoMorris) {
3854 // morris requires raphael
3855 if(!NETDATA.chartLibraries.raphael.initialized) {
3856 if(NETDATA.chartLibraries.raphael.enabled) {
3857 NETDATA.raphaelInitialize(function() {
3858 NETDATA.morrisInitialize(callback);
3862 NETDATA.chartLibraries.morris.enabled = false;
3863 if(typeof callback === "function")
3868 NETDATA._loadCSS(NETDATA.morris_css);
3871 url: NETDATA.morris_js,
3876 NETDATA.registerChartLibrary('morris', NETDATA.morris_js);
3879 NETDATA.chartLibraries.morris.enabled = false;
3880 NETDATA.error(100, NETDATA.morris_js);
3882 .always(function() {
3883 if(typeof callback === "function")
3889 NETDATA.chartLibraries.morris.enabled = false;
3890 if(typeof callback === "function")
3895 NETDATA.morrisChartUpdate = function(state, data) {
3896 state.morris_instance.setData(data.result.data);
3900 NETDATA.morrisChartCreate = function(state, data) {
3902 state.morris_options = {
3903 element: state.element_chart.id,
3904 data: data.result.data,
3906 ykeys: data.dimension_names,
3907 labels: data.dimension_names,
3913 continuousLine: false,
3914 behaveLikeLine: false
3917 if(state.chart.chart_type === 'line')
3918 state.morris_instance = new Morris.Line(state.morris_options);
3920 else if(state.chart.chart_type === 'area') {
3921 state.morris_options.behaveLikeLine = true;
3922 state.morris_instance = new Morris.Area(state.morris_options);
3925 state.morris_instance = new Morris.Area(state.morris_options);
3930 // ----------------------------------------------------------------------------------------------------------------
3933 NETDATA.raphaelInitialize = function(callback) {
3934 if(typeof netdataStopRaphael === 'undefined' || !netdataStopRaphael) {
3936 url: NETDATA.raphael_js,
3941 NETDATA.registerChartLibrary('raphael', NETDATA.raphael_js);
3944 NETDATA.chartLibraries.raphael.enabled = false;
3945 NETDATA.error(100, NETDATA.raphael_js);
3947 .always(function() {
3948 if(typeof callback === "function")
3953 NETDATA.chartLibraries.raphael.enabled = false;
3954 if(typeof callback === "function")
3959 NETDATA.raphaelChartUpdate = function(state, data) {
3960 $(state.element_chart).raphael(data.result, {
3961 width: state.chartWidth(),
3962 height: state.chartHeight()
3968 NETDATA.raphaelChartCreate = function(state, data) {
3969 $(state.element_chart).raphael(data.result, {
3970 width: state.chartWidth(),
3971 height: state.chartHeight()
3977 // ----------------------------------------------------------------------------------------------------------------
3980 NETDATA.c3Initialize = function(callback) {
3981 if(typeof netdataNoC3 === 'undefined' || !netdataNoC3) {
3984 if(!NETDATA.chartLibraries.d3.initialized) {
3985 if(NETDATA.chartLibraries.d3.enabled) {
3986 NETDATA.d3Initialize(function() {
3987 NETDATA.c3Initialize(callback);
3991 NETDATA.chartLibraries.c3.enabled = false;
3992 if(typeof callback === "function")
3997 NETDATA._loadCSS(NETDATA.c3_css);
4005 NETDATA.registerChartLibrary('c3', NETDATA.c3_js);
4008 NETDATA.chartLibraries.c3.enabled = false;
4009 NETDATA.error(100, NETDATA.c3_js);
4011 .always(function() {
4012 if(typeof callback === "function")
4018 NETDATA.chartLibraries.c3.enabled = false;
4019 if(typeof callback === "function")
4024 NETDATA.c3ChartUpdate = function(state, data) {
4025 state.c3_instance.destroy();
4026 return NETDATA.c3ChartCreate(state, data);
4028 //state.c3_instance.load({
4029 // rows: data.result,
4036 NETDATA.c3ChartCreate = function(state, data) {
4038 state.element_chart.id = 'c3-' + state.uuid;
4039 // console.log('id = ' + state.element_chart.id);
4041 state.c3_instance = c3.generate({
4042 bindto: '#' + state.element_chart.id,
4044 width: state.chartWidth(),
4045 height: state.chartHeight()
4048 pattern: state.chartColors()
4053 type: (state.chart.chart_type === 'line')?'spline':'area-spline'
4059 format: function(x) {
4060 return NETDATA.zeropad(x.getHours()) + ":" + NETDATA.zeropad(x.getMinutes()) + ":" + NETDATA.zeropad(x.getSeconds());
4087 // console.log(state.c3_instance);
4092 // ----------------------------------------------------------------------------------------------------------------
4095 NETDATA.d3Initialize = function(callback) {
4096 if(typeof netdataStopD3 === 'undefined' || !netdataStopD3) {
4103 NETDATA.registerChartLibrary('d3', NETDATA.d3_js);
4106 NETDATA.chartLibraries.d3.enabled = false;
4107 NETDATA.error(100, NETDATA.d3_js);
4109 .always(function() {
4110 if(typeof callback === "function")
4115 NETDATA.chartLibraries.d3.enabled = false;
4116 if(typeof callback === "function")
4121 NETDATA.d3ChartUpdate = function(state, data) {
4125 NETDATA.d3ChartCreate = function(state, data) {
4129 // ----------------------------------------------------------------------------------------------------------------
4132 NETDATA.googleInitialize = function(callback) {
4133 if(typeof netdataNoGoogleCharts === 'undefined' || !netdataNoGoogleCharts) {
4135 url: NETDATA.google_js,
4140 NETDATA.registerChartLibrary('google', NETDATA.google_js);
4141 google.load('visualization', '1.1', {
4142 'packages': ['corechart', 'controls'],
4143 'callback': callback
4147 NETDATA.chartLibraries.google.enabled = false;
4148 NETDATA.error(100, NETDATA.google_js);
4149 if(typeof callback === "function")
4154 NETDATA.chartLibraries.google.enabled = false;
4155 if(typeof callback === "function")
4160 NETDATA.googleChartUpdate = function(state, data) {
4161 var datatable = new google.visualization.DataTable(data.result);
4162 state.google_instance.draw(datatable, state.google_options);
4166 NETDATA.googleChartCreate = function(state, data) {
4167 var datatable = new google.visualization.DataTable(data.result);
4169 state.google_options = {
4170 colors: state.chartColors(),
4172 // do not set width, height - the chart resizes itself
4173 //width: state.chartWidth(),
4174 //height: state.chartHeight(),
4179 // title: "Time of Day",
4180 // format:'HH:mm:ss',
4181 viewWindowMode: 'maximized',
4193 viewWindowMode: 'pretty',
4208 focusTarget: 'category',
4215 titlePosition: 'out',
4226 curveType: 'function',
4231 switch(state.chart.chart_type) {
4233 state.google_options.vAxis.viewWindowMode = 'maximized';
4234 state.google_options.areaOpacity = NETDATA.options.current.color_fill_opacity_area;
4235 state.google_instance = new google.visualization.AreaChart(state.element_chart);
4239 state.google_options.isStacked = true;
4240 state.google_options.areaOpacity = NETDATA.options.current.color_fill_opacity_stacked;
4241 state.google_options.vAxis.viewWindowMode = 'maximized';
4242 state.google_options.vAxis.minValue = null;
4243 state.google_options.vAxis.maxValue = null;
4244 state.google_instance = new google.visualization.AreaChart(state.element_chart);
4249 state.google_options.lineWidth = 2;
4250 state.google_instance = new google.visualization.LineChart(state.element_chart);
4254 state.google_instance.draw(datatable, state.google_options);
4258 // ----------------------------------------------------------------------------------------------------------------
4260 NETDATA.percentFromValueMax = function(value, max) {
4261 if(value === null) value = 0;
4262 if(max < value) max = value;
4266 pcent = Math.round(value * 100 / max);
4267 if(pcent === 0 && value > 0) pcent = 1;
4273 // ----------------------------------------------------------------------------------------------------------------
4276 NETDATA.easypiechartInitialize = function(callback) {
4277 if(typeof netdataNoEasyPieChart === 'undefined' || !netdataNoEasyPieChart) {
4279 url: NETDATA.easypiechart_js,
4284 NETDATA.registerChartLibrary('easypiechart', NETDATA.easypiechart_js);
4287 NETDATA.error(100, NETDATA.easypiechart_js);
4289 .always(function() {
4290 if(typeof callback === "function")
4295 NETDATA.chartLibraries.easypiechart.enabled = false;
4296 if(typeof callback === "function")
4301 NETDATA.easypiechartClearSelection = function(state) {
4302 if(typeof state.easyPieChartEvent !== 'undefined') {
4303 if(state.easyPieChartEvent.timer !== null)
4304 clearTimeout(state.easyPieChartEvent.timer);
4306 state.easyPieChartEvent.timer = null;
4309 if(state.isAutoRefreshed() === true && state.data !== null) {
4310 NETDATA.easypiechartChartUpdate(state, state.data);
4313 state.easyPieChartLabel.innerHTML = state.legendFormatValue(null);
4314 state.easyPieChart_instance.update(0);
4316 state.easyPieChart_instance.enableAnimation();
4321 NETDATA.easypiechartSetSelection = function(state, t) {
4322 if(t < state.data_after || t > state.data_before)
4323 return NETDATA.easypiechartClearSelection(state);
4325 var slot = Math.floor(state.data.result.length - 1 - (t - state.data_after) / state.data_update_every);
4326 if(slot < 0 || slot >= state.data.result.length)
4327 return NETDATA.easypiechartClearSelection(state);
4329 if(typeof state.easyPieChartEvent === 'undefined') {
4330 state.easyPieChartEvent = {
4337 var value = state.data.result[slot];
4338 var max = (state.easyPieChartMax === null)?state.data.max:state.easyPieChartMax;
4339 var pcent = NETDATA.percentFromValueMax(value, max);
4341 state.easyPieChartEvent.value = value;
4342 state.easyPieChartEvent.pcent = pcent;
4343 state.easyPieChartLabel.innerHTML = state.legendFormatValue(value);
4345 if(state.easyPieChartEvent.timer === null) {
4346 state.easyPieChart_instance.disableAnimation();
4348 state.easyPieChartEvent.timer = setTimeout(function() {
4349 state.easyPieChartEvent.timer = null;
4350 state.easyPieChart_instance.update(state.easyPieChartEvent.pcent);
4357 NETDATA.easypiechartChartUpdate = function(state, data) {
4358 var value, max, pcent;
4360 if(NETDATA.globalPanAndZoom.isActive() === true || state.isAutoRefreshed() === false) {
4366 value = data.result[0];
4367 max = (state.easyPieChartMax === null)?data.max:state.easyPieChartMax;
4368 pcent = NETDATA.percentFromValueMax(value, max);
4371 state.easyPieChartLabel.innerHTML = state.legendFormatValue(value);
4372 state.easyPieChart_instance.update(pcent);
4376 NETDATA.easypiechartChartCreate = function(state, data) {
4377 var self = $(state.element);
4378 var chart = $(state.element_chart);
4380 var value = data.result[0];
4381 var max = self.data('easypiechart-max-value') || null;
4382 var adjust = self.data('easypiechart-adjust') || null;
4386 state.easyPieChartMax = null;
4389 state.easyPieChartMax = max;
4391 var pcent = NETDATA.percentFromValueMax(value, max);
4393 chart.data('data-percent', pcent);
4397 case 'width': size = state.chartHeight(); break;
4398 case 'min': size = Math.min(state.chartWidth(), state.chartHeight()); break;
4399 case 'max': size = Math.max(state.chartWidth(), state.chartHeight()); break;
4401 default: size = state.chartWidth(); break;
4403 state.element.style.width = size + 'px';
4404 state.element.style.height = size + 'px';
4406 var stroke = Math.floor(size / 22);
4407 if(stroke < 3) stroke = 2;
4409 var valuefontsize = Math.floor((size * 2 / 3) / 5);
4410 var valuetop = Math.round((size - valuefontsize - (size / 40)) / 2);
4411 state.easyPieChartLabel = document.createElement('span');
4412 state.easyPieChartLabel.className = 'easyPieChartLabel';
4413 state.easyPieChartLabel.innerHTML = state.legendFormatValue(value);
4414 state.easyPieChartLabel.style.fontSize = valuefontsize + 'px';
4415 state.easyPieChartLabel.style.top = valuetop.toString() + 'px';
4416 state.element_chart.appendChild(state.easyPieChartLabel);
4418 var titlefontsize = Math.round(valuefontsize * 1.6 / 3);
4419 var titletop = Math.round(valuetop - (titlefontsize * 2) - (size / 40));
4420 state.easyPieChartTitle = document.createElement('span');
4421 state.easyPieChartTitle.className = 'easyPieChartTitle';
4422 state.easyPieChartTitle.innerHTML = state.title;
4423 state.easyPieChartTitle.style.fontSize = titlefontsize + 'px';
4424 state.easyPieChartTitle.style.lineHeight = titlefontsize + 'px';
4425 state.easyPieChartTitle.style.top = titletop.toString() + 'px';
4426 state.element_chart.appendChild(state.easyPieChartTitle);
4428 var unitfontsize = Math.round(titlefontsize * 0.9);
4429 var unittop = Math.round(valuetop + (valuefontsize + unitfontsize) + (size / 40));
4430 state.easyPieChartUnits = document.createElement('span');
4431 state.easyPieChartUnits.className = 'easyPieChartUnits';
4432 state.easyPieChartUnits.innerHTML = state.units;
4433 state.easyPieChartUnits.style.fontSize = unitfontsize + 'px';
4434 state.easyPieChartUnits.style.top = unittop.toString() + 'px';
4435 state.element_chart.appendChild(state.easyPieChartUnits);
4437 chart.easyPieChart({
4438 barColor: self.data('easypiechart-barcolor') || state.chartColors()[0], //'#ef1e25',
4439 trackColor: self.data('easypiechart-trackcolor') || '#f0f0f0',
4440 scaleColor: self.data('easypiechart-scalecolor') || '#dfe0e0',
4441 scaleLength: self.data('easypiechart-scalelength') || 5,
4442 lineCap: self.data('easypiechart-linecap') || 'round',
4443 lineWidth: self.data('easypiechart-linewidth') || stroke,
4444 trackWidth: self.data('easypiechart-trackwidth') || undefined,
4445 size: self.data('easypiechart-size') || size,
4446 rotate: self.data('easypiechart-rotate') || 0,
4447 animate: self.data('easypiechart-rotate') || {duration: 500, enabled: true},
4448 easing: self.data('easypiechart-easing') || undefined
4451 // when we just re-create the chart
4452 // do not animate the first update
4454 if(typeof state.easyPieChart_instance !== 'undefined')
4457 state.easyPieChart_instance = chart.data('easyPieChart');
4458 if(animate === false) state.easyPieChart_instance.disableAnimation();
4459 state.easyPieChart_instance.update(pcent);
4460 if(animate === false) state.easyPieChart_instance.enableAnimation();
4464 // ----------------------------------------------------------------------------------------------------------------
4467 NETDATA.gaugeInitialize = function(callback) {
4468 if(typeof netdataNoGauge === 'undefined' || !netdataNoGauge) {
4470 url: NETDATA.gauge_js,
4475 NETDATA.registerChartLibrary('gauge', NETDATA.gauge_js);
4478 NETDATA.error(100, NETDATA.gauge_js);
4480 .always(function() {
4481 if(typeof callback === "function")
4486 NETDATA.chartLibraries.gauge.enabled = false;
4487 if(typeof callback === "function")
4492 NETDATA.gaugeAnimation = function(state, status) {
4495 if(typeof status === 'boolean' && status === false)
4497 else if(typeof status === 'number')
4500 state.gauge_instance.animationSpeed = speed;
4501 state.___gaugeOld__.speed = speed;
4504 NETDATA.gaugeSet = function(state, value, min, max) {
4505 if(typeof value !== 'number') value = 0;
4506 if(typeof min !== 'number') min = 0;
4507 if(typeof max !== 'number') max = 0;
4508 if(value > max) max = value;
4509 if(value < min) min = value;
4511 var dvalue = state.gauge_instance.displayedValue;
4513 if(dvalue >= min && dvalue <= max) {
4514 state.gauge_instance.minValue = min;
4515 state.gauge_instance.maxValue = max;
4516 state.gauge_instance.set(value);
4519 // the current display value of the gauge
4520 // is outside min-max.
4521 // we have to disable animation
4522 // otherwise, the gauge will go crazy
4523 var old_speed = state.___gaugeOld__.speed;
4524 NETDATA.gaugeAnimation(state, false);
4525 state.gauge_instance.minValue = min;
4526 state.gauge_instance.maxValue = max;
4527 state.gauge_instance.set(value);
4528 NETDATA.gaugeAnimation(state, old_speed);
4531 state.___gaugeOld__.value = value;
4532 state.___gaugeOld__.min = min;
4533 state.___gaugeOld__.max = max;
4536 NETDATA.gaugeSetLabels = function(state, value, min, max) {
4537 if(state.___gaugeOld__.valueLabel !== value) {
4538 state.___gaugeOld__.valueLabel = value;
4539 state.gaugeChartLabel.innerHTML = state.legendFormatValue(value);
4541 if(state.___gaugeOld__.minLabel !== min) {
4542 state.___gaugeOld__.minLabel = min;
4543 state.gaugeChartMin.innerHTML = state.legendFormatValue(min);
4545 if(state.___gaugeOld__.maxLabel !== max) {
4546 state.___gaugeOld__.maxLabel = max;
4547 state.gaugeChartMax.innerHTML = state.legendFormatValue(max);
4551 NETDATA.gaugeClearSelection = function(state) {
4552 if(typeof state.gaugeEvent !== 'undefined') {
4553 if(state.gaugeEvent.timer !== null)
4554 clearTimeout(state.gaugeEvent.timer);
4556 state.gaugeEvent.timer = null;
4559 if(state.isAutoRefreshed() === true && state.data !== null) {
4560 NETDATA.gaugeChartUpdate(state, state.data);
4563 NETDATA.gaugeAnimation(state, false);
4564 NETDATA.gaugeSet(state, null, null, null);
4565 NETDATA.gaugeSetLabels(state, null, null, null);
4568 NETDATA.gaugeAnimation(state, true);
4572 NETDATA.gaugeSetSelection = function(state, t) {
4573 if(t < state.data_after || t > state.data_before)
4574 return NETDATA.gaugeClearSelection(state);
4576 var slot = Math.floor(state.data.result.length - 1 - (t - state.data_after) / state.data_update_every);
4577 if(slot < 0 || slot >= state.data.result.length)
4578 return NETDATA.gaugeClearSelection(state);
4580 if(typeof state.gaugeEvent === 'undefined') {
4581 state.gaugeEvent = {
4589 var value = state.data.result[slot];
4590 var max = (state.gaugeMax === null)?state.data.max:state.gaugeMax;
4593 state.gaugeEvent.value = value;
4594 state.gaugeEvent.max = max;
4595 state.gaugeEvent.min = min;
4596 NETDATA.gaugeSetLabels(state, value, min, max);
4598 if(state.gaugeEvent.timer === null) {
4599 NETDATA.gaugeAnimation(state, false);
4601 state.gaugeEvent.timer = setTimeout(function() {
4602 state.gaugeEvent.timer = null;
4603 NETDATA.gaugeSet(state, state.gaugeEvent.value, state.gaugeEvent.min, state.gaugeEvent.max);
4610 NETDATA.gaugeChartUpdate = function(state, data) {
4611 var value, min, max;
4613 if(NETDATA.globalPanAndZoom.isActive() === true || state.isAutoRefreshed() === false) {
4617 NETDATA.gaugeSetLabels(state, null, null, null);
4620 value = data.result[0];
4622 max = (state.gaugeMax === null)?data.max:state.gaugeMax;
4623 if(value > max) max = value;
4624 NETDATA.gaugeSetLabels(state, value, min, max);
4627 NETDATA.gaugeSet(state, value, min, max);
4631 NETDATA.gaugeChartCreate = function(state, data) {
4632 var self = $(state.element);
4633 var chart = $(state.element_chart);
4635 var value = data.result[0];
4636 var max = self.data('gauge-max-value') || null;
4637 var adjust = self.data('gauge-adjust') || null;
4641 state.gaugeMax = null;
4644 state.gaugeMax = max;
4646 var width = state.chartWidth(), height = state.chartHeight(); //, ratio = 1.5;
4648 // case 'width': width = height * ratio; break;
4650 // default: height = width / ratio; break;
4652 //state.element.style.width = width.toString() + 'px';
4653 //state.element.style.height = height.toString() + 'px';
4658 lines: 12, // The number of lines to draw
4659 angle: 0.15, // The length of each line
4660 lineWidth: 0.44, // 0.44 The line thickness
4662 length: 0.8, // 0.9 The radius of the inner circle
4663 strokeWidth: 0.035, // The rotation offset
4664 color: '#C0C0C0' // Fill color
4666 colorStart: state.chartColors()[0], // Colors
4667 colorStop: void 0, // just experiment with them
4668 strokeColor: '#F0F0F0', // to see which ones work best for you
4670 generateGradient: false,
4673 [0.0, NETDATA.colorLuminance(state.chartColors()[0], (lum_d * 10) - (lum_d * 0))],
4674 [0.1, NETDATA.colorLuminance(state.chartColors()[0], (lum_d * 10) - (lum_d * 1))],
4675 [0.2, NETDATA.colorLuminance(state.chartColors()[0], (lum_d * 10) - (lum_d * 2))],
4676 [0.3, NETDATA.colorLuminance(state.chartColors()[0], (lum_d * 10) - (lum_d * 3))],
4677 [0.4, NETDATA.colorLuminance(state.chartColors()[0], (lum_d * 10) - (lum_d * 4))],
4678 [0.5, NETDATA.colorLuminance(state.chartColors()[0], (lum_d * 10) - (lum_d * 5))],
4679 [0.6, NETDATA.colorLuminance(state.chartColors()[0], (lum_d * 10) - (lum_d * 6))],
4680 [0.7, NETDATA.colorLuminance(state.chartColors()[0], (lum_d * 10) - (lum_d * 7))],
4681 [0.8, NETDATA.colorLuminance(state.chartColors()[0], (lum_d * 10) - (lum_d * 8))],
4682 [0.9, NETDATA.colorLuminance(state.chartColors()[0], (lum_d * 10) - (lum_d * 9))],
4683 [1.0, state.chartColors()[0]]]
4686 state.gauge_canvas = document.createElement('canvas');
4687 state.gauge_canvas.id = 'gauge-' + state.uuid + '-canvas';
4688 state.gauge_canvas.className = 'gaugeChart';
4689 state.gauge_canvas.width = width;
4690 state.gauge_canvas.height = height;
4691 state.element_chart.appendChild(state.gauge_canvas);
4693 var valuefontsize = Math.floor(height / 6);
4694 var valuetop = Math.round((height - valuefontsize - (height / 6)) / 2);
4695 state.gaugeChartLabel = document.createElement('span');
4696 state.gaugeChartLabel.className = 'gaugeChartLabel';
4697 state.gaugeChartLabel.style.fontSize = valuefontsize + 'px';
4698 state.gaugeChartLabel.style.top = valuetop.toString() + 'px';
4699 state.element_chart.appendChild(state.gaugeChartLabel);
4701 var titlefontsize = Math.round(valuefontsize / 2);
4703 state.gaugeChartTitle = document.createElement('span');
4704 state.gaugeChartTitle.className = 'gaugeChartTitle';
4705 state.gaugeChartTitle.innerHTML = state.title;
4706 state.gaugeChartTitle.style.fontSize = titlefontsize + 'px';
4707 state.gaugeChartTitle.style.lineHeight = titlefontsize + 'px';
4708 state.gaugeChartTitle.style.top = titletop.toString() + 'px';
4709 state.element_chart.appendChild(state.gaugeChartTitle);
4711 var unitfontsize = Math.round(titlefontsize * 0.9);
4712 state.gaugeChartUnits = document.createElement('span');
4713 state.gaugeChartUnits.className = 'gaugeChartUnits';
4714 state.gaugeChartUnits.innerHTML = state.units;
4715 state.gaugeChartUnits.style.fontSize = unitfontsize + 'px';
4716 state.element_chart.appendChild(state.gaugeChartUnits);
4718 state.gaugeChartMin = document.createElement('span');
4719 state.gaugeChartMin.className = 'gaugeChartMin';
4720 state.gaugeChartMin.style.fontSize = Math.round(valuefontsize * 0.75).toString() + 'px';
4721 state.element_chart.appendChild(state.gaugeChartMin);
4723 state.gaugeChartMax = document.createElement('span');
4724 state.gaugeChartMax.className = 'gaugeChartMax';
4725 state.gaugeChartMax.style.fontSize = Math.round(valuefontsize * 0.75).toString() + 'px';
4726 state.element_chart.appendChild(state.gaugeChartMax);
4728 // when we just re-create the chart
4729 // do not animate the first update
4731 if(typeof state.gauge_instance !== 'undefined')
4734 state.gauge_instance = new Gauge(state.gauge_canvas).setOptions(options); // create sexy gauge!
4736 state.___gaugeOld__ = {
4745 NETDATA.gaugeAnimation(state, animate);
4746 NETDATA.gaugeSet(state, value, 0, max);
4747 NETDATA.gaugeSetLabels(state, value, 0, max);
4748 NETDATA.gaugeAnimation(state, true);
4752 // ----------------------------------------------------------------------------------------------------------------
4753 // Charts Libraries Registration
4755 NETDATA.chartLibraries = {
4757 initialize: NETDATA.dygraphInitialize,
4758 create: NETDATA.dygraphChartCreate,
4759 update: NETDATA.dygraphChartUpdate,
4760 resize: function(state) {
4761 if(typeof state.dygraph_instance.resize === 'function')
4762 state.dygraph_instance.resize();
4764 setSelection: NETDATA.dygraphSetSelection,
4765 clearSelection: NETDATA.dygraphClearSelection,
4768 format: function(state) { return 'json'; },
4769 options: function(state) { return 'ms|flip'; },
4770 legend: function(state) {
4771 if(this.isSparkline(state) === false)
4772 return 'right-side';
4776 autoresize: function(state) { return true; },
4777 max_updates_to_recreate: function(state) { return 5000; },
4778 track_colors: function(state) { return true; },
4779 pixels_per_point: function(state) {
4780 if(this.isSparkline(state) === false)
4786 isSparkline: function(state) {
4787 if(typeof state.dygraph_sparkline === 'undefined') {
4788 var t = $(state.element).data('dygraph-theme');
4789 if(t === 'sparkline')
4790 state.dygraph_sparkline = true;
4792 state.dygraph_sparkline = false;
4794 return state.dygraph_sparkline;
4798 initialize: NETDATA.sparklineInitialize,
4799 create: NETDATA.sparklineChartCreate,
4800 update: NETDATA.sparklineChartUpdate,
4802 setSelection: undefined, // function(state, t) { return true; },
4803 clearSelection: undefined, // function(state) { return true; },
4806 format: function(state) { return 'array'; },
4807 options: function(state) { return 'flip|abs'; },
4808 legend: function(state) { return null; },
4809 autoresize: function(state) { return false; },
4810 max_updates_to_recreate: function(state) { return 5000; },
4811 track_colors: function(state) { return false; },
4812 pixels_per_point: function(state) { return 3; }
4815 initialize: NETDATA.peityInitialize,
4816 create: NETDATA.peityChartCreate,
4817 update: NETDATA.peityChartUpdate,
4819 setSelection: undefined, // function(state, t) { return true; },
4820 clearSelection: undefined, // function(state) { return true; },
4823 format: function(state) { return 'ssvcomma'; },
4824 options: function(state) { return 'null2zero|flip|abs'; },
4825 legend: function(state) { return null; },
4826 autoresize: function(state) { return false; },
4827 max_updates_to_recreate: function(state) { return 5000; },
4828 track_colors: function(state) { return false; },
4829 pixels_per_point: function(state) { return 3; }
4832 initialize: NETDATA.morrisInitialize,
4833 create: NETDATA.morrisChartCreate,
4834 update: NETDATA.morrisChartUpdate,
4836 setSelection: undefined, // function(state, t) { return true; },
4837 clearSelection: undefined, // function(state) { return true; },
4840 format: function(state) { return 'json'; },
4841 options: function(state) { return 'objectrows|ms'; },
4842 legend: function(state) { return null; },
4843 autoresize: function(state) { return false; },
4844 max_updates_to_recreate: function(state) { return 50; },
4845 track_colors: function(state) { return false; },
4846 pixels_per_point: function(state) { return 15; }
4849 initialize: NETDATA.googleInitialize,
4850 create: NETDATA.googleChartCreate,
4851 update: NETDATA.googleChartUpdate,
4853 setSelection: undefined, //function(state, t) { return true; },
4854 clearSelection: undefined, //function(state) { return true; },
4857 format: function(state) { return 'datatable'; },
4858 options: function(state) { return ''; },
4859 legend: function(state) { return null; },
4860 autoresize: function(state) { return false; },
4861 max_updates_to_recreate: function(state) { return 300; },
4862 track_colors: function(state) { return false; },
4863 pixels_per_point: function(state) { return 4; }
4866 initialize: NETDATA.raphaelInitialize,
4867 create: NETDATA.raphaelChartCreate,
4868 update: NETDATA.raphaelChartUpdate,
4870 setSelection: undefined, // function(state, t) { return true; },
4871 clearSelection: undefined, // function(state) { return true; },
4874 format: function(state) { return 'json'; },
4875 options: function(state) { return ''; },
4876 legend: function(state) { return null; },
4877 autoresize: function(state) { return false; },
4878 max_updates_to_recreate: function(state) { return 5000; },
4879 track_colors: function(state) { return false; },
4880 pixels_per_point: function(state) { return 3; }
4883 initialize: NETDATA.c3Initialize,
4884 create: NETDATA.c3ChartCreate,
4885 update: NETDATA.c3ChartUpdate,
4887 setSelection: undefined, // function(state, t) { return true; },
4888 clearSelection: undefined, // function(state) { return true; },
4891 format: function(state) { return 'csvjsonarray'; },
4892 options: function(state) { return 'milliseconds'; },
4893 legend: function(state) { return null; },
4894 autoresize: function(state) { return false; },
4895 max_updates_to_recreate: function(state) { return 5000; },
4896 track_colors: function(state) { return false; },
4897 pixels_per_point: function(state) { return 15; }
4900 initialize: NETDATA.d3Initialize,
4901 create: NETDATA.d3ChartCreate,
4902 update: NETDATA.d3ChartUpdate,
4904 setSelection: undefined, // function(state, t) { return true; },
4905 clearSelection: undefined, // function(state) { return true; },
4908 format: function(state) { return 'json'; },
4909 options: function(state) { return ''; },
4910 legend: function(state) { return null; },
4911 autoresize: function(state) { return false; },
4912 max_updates_to_recreate: function(state) { return 5000; },
4913 track_colors: function(state) { return false; },
4914 pixels_per_point: function(state) { return 3; }
4917 initialize: NETDATA.easypiechartInitialize,
4918 create: NETDATA.easypiechartChartCreate,
4919 update: NETDATA.easypiechartChartUpdate,
4921 setSelection: NETDATA.easypiechartSetSelection,
4922 clearSelection: NETDATA.easypiechartClearSelection,
4925 format: function(state) { return 'array'; },
4926 options: function(state) { return 'absolute'; },
4927 legend: function(state) { return null; },
4928 autoresize: function(state) { return false; },
4929 max_updates_to_recreate: function(state) { return 5000; },
4930 track_colors: function(state) { return false; },
4931 pixels_per_point: function(state) { return 3; },
4935 initialize: NETDATA.gaugeInitialize,
4936 create: NETDATA.gaugeChartCreate,
4937 update: NETDATA.gaugeChartUpdate,
4939 setSelection: NETDATA.gaugeSetSelection,
4940 clearSelection: NETDATA.gaugeClearSelection,
4943 format: function(state) { return 'array'; },
4944 options: function(state) { return 'absolute'; },
4945 legend: function(state) { return null; },
4946 autoresize: function(state) { return false; },
4947 max_updates_to_recreate: function(state) { return 5000; },
4948 track_colors: function(state) { return false; },
4949 pixels_per_point: function(state) { return 3; },
4954 NETDATA.registerChartLibrary = function(library, url) {
4955 if(NETDATA.options.debug.libraries === true)
4956 console.log("registering chart library: " + library);
4958 NETDATA.chartLibraries[library].url = url;
4959 NETDATA.chartLibraries[library].initialized = true;
4960 NETDATA.chartLibraries[library].enabled = true;
4963 // ----------------------------------------------------------------------------------------------------------------
4966 NETDATA.requiredJs = [
4968 url: NETDATA.serverDefault + 'lib/bootstrap.min.js',
4969 isAlreadyLoaded: function() {
4970 if(typeof $().emulateTransitionEnd == 'function')
4973 if(typeof netdataNoBootstrap !== 'undefined' && netdataNoBootstrap)
4981 url: NETDATA.serverDefault + 'lib/jquery.nanoscroller.min.js',
4982 isAlreadyLoaded: function() { return false; }
4985 url: NETDATA.serverDefault + 'lib/bootstrap-toggle.min.js',
4986 isAlreadyLoaded: function() { return false; }
4990 NETDATA.requiredCSS = [
4992 url: NETDATA.serverDefault + 'css/bootstrap.min.css',
4993 isAlreadyLoaded: function() {
4994 if(typeof netdataNoBootstrap !== 'undefined' && netdataNoBootstrap)
5001 url: NETDATA.serverDefault + 'css/font-awesome.min.css',
5002 isAlreadyLoaded: function() { return false; }
5005 url: NETDATA.dashboard_css,
5006 isAlreadyLoaded: function() { return false; }
5009 url: NETDATA.serverDefault + 'css/bootstrap-toggle.min.css',
5010 isAlreadyLoaded: function() { return false; }
5014 NETDATA.loadRequiredJs = function(index, callback) {
5015 if(index >= NETDATA.requiredJs.length) {
5016 if(typeof callback === 'function')
5021 if(NETDATA.requiredJs[index].isAlreadyLoaded()) {
5022 NETDATA.loadRequiredJs(++index, callback);
5026 if(NETDATA.options.debug.main_loop === true)
5027 console.log('loading ' + NETDATA.requiredJs[index].url);
5030 url: NETDATA.requiredJs[index].url,
5034 .success(function() {
5035 if(NETDATA.options.debug.main_loop === true)
5036 console.log('loaded ' + NETDATA.requiredJs[index].url);
5038 NETDATA.loadRequiredJs(++index, callback);
5041 alert('Cannot load required JS library: ' + NETDATA.requiredJs[index].url);
5045 NETDATA.loadRequiredCSS = function(index) {
5046 if(index >= NETDATA.requiredCSS.length)
5049 if(NETDATA.requiredCSS[index].isAlreadyLoaded()) {
5050 NETDATA.loadRequiredCSS(++index);
5054 if(NETDATA.options.debug.main_loop === true)
5055 console.log('loading ' + NETDATA.requiredCSS[index].url);
5057 NETDATA._loadCSS(NETDATA.requiredCSS[index].url);
5058 NETDATA.loadRequiredCSS(++index);
5061 NETDATA.errorReset();
5062 NETDATA.loadRequiredCSS(0);
5064 NETDATA._loadjQuery(function() {
5065 NETDATA.loadRequiredJs(0, function() {
5066 if(typeof netdataDontStart === 'undefined' || !netdataDontStart) {
5067 if(NETDATA.options.debug.main_loop === true)
5068 console.log('starting chart refresh thread');
5075 // window.NETDATA = NETDATA;
5076 // })(window, document);