1 // You can set the following variables before loading this script:
3 // var netdataNoDygraphs = true; // do not use dygraph
4 // var netdataNoSparklines = true; // do not use sparkline
5 // var netdataNoPeitys = true; // do not use peity
6 // var netdataNoGoogleCharts = true; // do not use google
7 // var netdataNoMorris = true; // do not use morris
8 // var netdataNoEasyPieChart = true; // do not use easy pie chart
9 // var netdataNoGauge = true; // do not use gauge.js
10 // var netdataNoD3 = true; // do not use D3
11 // var netdataNoC3 = true; // do not use C3
12 // var netdataNoBootstrap = true; // do not load bootstrap
13 // var netdataDontStart = true; // do not start the thread to process the charts
15 // You can also set the default netdata server, using the following.
16 // When this variable is not set, we assume the page is hosted on your
17 // netdata server already.
18 // var netdataServer = "http://yourhost:19999"; // set your NetData server
20 //(function(window, document, undefined) {
21 // fix IE issue with console
22 if(!window.console){ window.console = {log: function(){} }; }
25 var NETDATA = window.NETDATA || {};
27 // ----------------------------------------------------------------------------------------------------------------
28 // Detect the netdata server
30 // http://stackoverflow.com/questions/984510/what-is-my-script-src-url
31 // http://stackoverflow.com/questions/6941533/get-protocol-domain-and-port-from-url
32 NETDATA._scriptSource = function() {
35 if(typeof document.currentScript !== 'undefined') {
36 script = document.currentScript;
39 var all_scripts = document.getElementsByTagName('script');
40 script = all_scripts[all_scripts.length - 1];
43 if (typeof script.getAttribute.length !== 'undefined')
46 script = script.getAttribute('src', -1);
51 if(typeof netdataServer !== 'undefined')
52 NETDATA.serverDefault = netdataServer;
54 var s = NETDATA._scriptSource();
55 NETDATA.serverDefault = s.replace(/\/dashboard.js(\?.*)*$/g, "");
58 if(NETDATA.serverDefault === null)
59 NETDATA.serverDefault = '';
60 else if(NETDATA.serverDefault.slice(-1) !== '/')
61 NETDATA.serverDefault += '/';
63 // default URLs for all the external files we need
64 // make them RELATIVE so that the whole thing can also be
65 // installed under a web server
66 NETDATA.jQuery = NETDATA.serverDefault + 'lib/jquery-1.12.0.min.js';
67 NETDATA.peity_js = NETDATA.serverDefault + 'lib/jquery.peity.min.js';
68 NETDATA.sparkline_js = NETDATA.serverDefault + 'lib/jquery.sparkline.min.js';
69 NETDATA.easypiechart_js = NETDATA.serverDefault + 'lib/jquery.easypiechart.min.js';
70 NETDATA.gauge_js = NETDATA.serverDefault + 'lib/gauge.min.js';
71 NETDATA.dygraph_js = NETDATA.serverDefault + 'lib/dygraph-combined.js';
72 NETDATA.dygraph_smooth_js = NETDATA.serverDefault + 'lib/dygraph-smooth-plotter.js';
73 NETDATA.raphael_js = NETDATA.serverDefault + 'lib/raphael-min.js';
74 NETDATA.morris_js = NETDATA.serverDefault + 'lib/morris.min.js';
75 NETDATA.d3_js = NETDATA.serverDefault + 'lib/d3.min.js';
76 NETDATA.c3_js = NETDATA.serverDefault + 'lib/c3.min.js';
77 NETDATA.c3_css = NETDATA.serverDefault + 'css/c3.min.css';
78 NETDATA.morris_css = NETDATA.serverDefault + 'css/morris.css';
79 NETDATA.google_js = 'https://www.google.com/jsapi';
83 bootstrap_css: NETDATA.serverDefault + 'css/bootstrap.min.css',
84 dashboard_css: NETDATA.serverDefault + 'dashboard.css',
85 background: '#FFFFFF',
86 foreground: '#000000',
89 colors: [ '#3366CC', '#DC3912', '#109618', '#FF9900', '#990099', '#DD4477',
90 '#3B3EAC', '#66AA00', '#0099C6', '#B82E2E', '#AAAA11', '#5574A6',
91 '#994499', '#22AA99', '#6633CC', '#E67300', '#316395', '#8B0707',
92 '#329262', '#3B3EAC' ],
93 easypiechart_track: '#f0f0f0',
94 easypiechart_scale: '#dfe0e0',
95 gauge_pointer: '#C0C0C0',
96 gauge_stroke: '#F0F0F0',
100 bootstrap_css: NETDATA.serverDefault + 'css/bootstrap.slate.min.css',
101 dashboard_css: NETDATA.serverDefault + 'dashboard.slate.css',
102 background: '#272b30',
103 foreground: '#C8C8C8',
106 colors: [ '#66AA00', '#FE3912', '#3366CC', '#D66300', '#0099C6', '#DDDD00',
107 '#3B3EAC', '#EE9911', '#BB44CC', '#C83E3E', '#990099', '#CC7700',
108 '#22AA99', '#109618', '#6633CC', '#DD4477', '#316395', '#8B0707',
109 '#329262', '#3B3EFF' ],
110 easypiechart_track: '#373b40',
111 easypiechart_scale: '#373b40',
112 gauge_pointer: '#474b50',
113 gauge_stroke: '#373b40',
114 gauge_gradient: false
118 if(typeof netdataTheme !== 'undefined' && typeof NETDATA.themes[netdataTheme] !== 'undefined')
119 NETDATA.themes.current = NETDATA.themes[netdataTheme];
121 NETDATA.themes.current = NETDATA.themes.default;
123 NETDATA.colors = NETDATA.themes.current.colors;
125 // these are the colors Google Charts are using
126 // we have them here to attempt emulate their look and feel on the other chart libraries
127 // http://there4.io/2012/05/02/google-chart-color-list/
128 //NETDATA.colors = [ '#3366CC', '#DC3912', '#FF9900', '#109618', '#990099', '#3B3EAC', '#0099C6',
129 // '#DD4477', '#66AA00', '#B82E2E', '#316395', '#994499', '#22AA99', '#AAAA11',
130 // '#6633CC', '#E67300', '#8B0707', '#329262', '#5574A6', '#3B3EAC' ];
132 // an alternative set
133 // http://www.mulinblog.com/a-color-palette-optimized-for-data-visualization/
134 // (blue) (red) (orange) (green) (pink) (brown) (purple) (yellow) (gray)
135 //NETDATA.colors = [ '#5DA5DA', '#F15854', '#FAA43A', '#60BD68', '#F17CB0', '#B2912F', '#B276B2', '#DECF3F', '#4D4D4D' ];
137 // ----------------------------------------------------------------------------------------------------------------
138 // the defaults for all charts
140 // if the user does not specify any of these, the following will be used
142 NETDATA.chartDefaults = {
143 host: NETDATA.serverDefault, // the server to get data from
144 width: '100%', // the chart width - can be null
145 height: '100%', // the chart height - can be null
146 min_width: null, // the chart minimum width - can be null
147 library: 'dygraph', // the graphing library to use
148 method: 'average', // the grouping method
149 before: 0, // panning
150 after: -600, // panning
151 pixels_per_point: 1, // the detail of the chart
152 fill_luminance: 0.8 // luminance of colors in solit areas
155 // ----------------------------------------------------------------------------------------------------------------
159 pauseCallback: null, // a callback when we are really paused
161 pause: false, // when enabled we don't auto-refresh the charts
163 targets: null, // an array of all the state objects that are
164 // currently active (independently of their
165 // viewport visibility)
167 updated_dom: true, // when true, the DOM has been updated with
168 // new elements we have to check.
170 auto_refresher_fast_weight: 0, // this is the current time in ms, spent
171 // rendering charts continiously.
172 // used with .current.fast_render_timeframe
174 page_is_visible: true, // when true, this page is visible
176 auto_refresher_stop_until: 0, // timestamp in ms - used internaly, to stop the
177 // auto-refresher for some time (when a chart is
178 // performing pan or zoom, we need to stop refreshing
179 // all other charts, to have the maximum speed for
180 // rendering the chart that is panned or zoomed).
181 // Used with .current.global_pan_sync_time
183 last_resized: new Date().getTime(), // the timestamp of the last resize request
185 crossDomainAjax: false, // enable this to request crossDomain AJAX
187 last_page_scroll: 0, // the timestamp the last time the page was scrolled
189 // the current profile
190 // we may have many...
192 pixels_per_point: 1, // the minimum pixels per point for all charts
193 // increase this to speed javascript up
194 // each chart library has its own limit too
195 // the max of this and the chart library is used
196 // the final is calculated every time, so a change
197 // here will have immediate effect on the next chart
200 idle_between_charts: 100, // ms - how much time to wait between chart updates
202 fast_render_timeframe: 200, // ms - render continously until this time of continious
203 // rendering has been reached
204 // this setting is used to make it render e.g. 10
205 // charts at once, sleep idle_between_charts time
206 // and continue for another 10 charts.
208 idle_between_loops: 500, // ms - if all charts have been updated, wait this
209 // time before starting again.
211 idle_parallel_loops: 100, // ms - the time between parallel refresher updates
213 idle_lost_focus: 500, // ms - when the window does not have focus, check
214 // if focus has been regained, every this time
216 global_pan_sync_time: 1000, // ms - when you pan or zoon a chart, the background
217 // autorefreshing of charts is paused for this amount
220 sync_selection_delay: 1500, // ms - when you pan or zoom a chart, wait this amount
221 // of time before setting up synchronized selections
224 sync_selection: true, // enable or disable selection sync
226 pan_and_zoom_delay: 50, // when panning or zooming, how ofter to update the chart
228 sync_pan_and_zoom: true, // enable or disable pan and zoom sync
230 pan_and_zoom_data_padding: true, // fetch more data for the master chart when panning or zooming
232 update_only_visible: true, // enable or disable visibility management
234 parallel_refresher: true, // enable parallel refresh of charts
236 concurrent_refreshes: true, // when parallel_refresher is enabled, sync also the charts
238 destroy_on_hide: false, // destroy charts when they are not visible
240 eliminate_zero_dimensions: true, // do not show dimensions with just zeros
242 stop_updates_when_focus_is_lost: true, // boolean - shall we stop auto-refreshes when document does not have user focus
243 stop_updates_while_resizing: 1000, // ms - time to stop auto-refreshes while resizing the charts
245 double_click_speed: 500, // ms - time between clicks / taps to detect double click/tap
247 smooth_plot: true, // enable smooth plot, where possible
249 charts_selection_animation_delay: 50, // delay to animate charts when syncing selection
251 color_fill_opacity_line: 1.0,
252 color_fill_opacity_area: 0.2,
253 color_fill_opacity_stacked: 0.8,
255 setOptionCallback: function() { ; }
263 chart_data_url: false,
264 chart_errors: false, // FIXME
273 // ----------------------------------------------------------------------------------------------------------------
274 // local storage options
276 NETDATA.localStorage = {
279 callback: {} // only used for resetting back to defaults
282 NETDATA.localStorageGet = function(key, def, callback) {
285 if(typeof NETDATA.localStorage.default[key.toString()] === 'undefined') {
286 NETDATA.localStorage.default[key.toString()] = def;
287 NETDATA.localStorage.callback[key.toString()] = callback;
290 if(typeof Storage !== "undefined" && typeof localStorage === 'object') {
292 // console.log('localStorage: loading "' + key.toString() + '"');
293 ret = localStorage.getItem(key.toString());
294 if(ret === null || ret === 'undefined') {
295 // console.log('localStorage: cannot load it, saving "' + key.toString() + '" with value "' + JSON.stringify(def) + '"');
296 localStorage.setItem(key.toString(), JSON.stringify(def));
300 // console.log('localStorage: got "' + key.toString() + '" with value "' + ret + '"');
301 ret = JSON.parse(ret);
302 // console.log('localStorage: loaded "' + key.toString() + '" as value ' + ret + ' of type ' + typeof(ret));
306 console.log('localStorage: failed to read "' + key.toString() + '", using default: "' + def.toString() + '"');
311 if(typeof ret === 'undefined' || ret === 'undefined') {
312 console.log('localStorage: LOADED UNDEFINED "' + key.toString() + '" as value ' + ret + ' of type ' + typeof(ret));
316 NETDATA.localStorage.current[key.toString()] = ret;
320 NETDATA.localStorageSet = function(key, value, callback) {
321 if(typeof value === 'undefined' || value === 'undefined') {
322 console.log('localStorage: ATTEMPT TO SET UNDEFINED "' + key.toString() + '" as value ' + value + ' of type ' + typeof(value));
325 if(typeof NETDATA.localStorage.default[key.toString()] === 'undefined') {
326 NETDATA.localStorage.default[key.toString()] = value;
327 NETDATA.localStorage.current[key.toString()] = value;
328 NETDATA.localStorage.callback[key.toString()] = callback;
331 if(typeof Storage !== "undefined" && typeof localStorage === 'object') {
332 // console.log('localStorage: saving "' + key.toString() + '" with value "' + JSON.stringify(value) + '"');
334 localStorage.setItem(key.toString(), JSON.stringify(value));
337 console.log('localStorage: failed to save "' + key.toString() + '" with value: "' + value.toString() + '"');
341 NETDATA.localStorage.current[key.toString()] = value;
345 NETDATA.localStorageGetRecursive = function(obj, prefix, callback) {
347 if(typeof obj[i] === 'object') {
348 //console.log('object ' + prefix + '.' + i.toString());
349 NETDATA.localStorageGetRecursive(obj[i], prefix + '.' + i.toString(), callback);
353 obj[i] = NETDATA.localStorageGet(prefix + '.' + i.toString(), obj[i], callback);
357 NETDATA.setOption = function(key, value) {
358 if(key.toString() === 'setOptionCallback') {
359 if(typeof NETDATA.options.current.setOptionCallback === 'function') {
360 NETDATA.options.current[key.toString()] = value;
361 NETDATA.options.current.setOptionCallback();
364 else if(NETDATA.options.current[key.toString()] !== value) {
365 var name = 'options.' + key.toString();
367 if(typeof NETDATA.localStorage.default[name.toString()] === 'undefined')
368 console.log('localStorage: setOption() on unsaved option: "' + name.toString() + '", value: ' + value);
370 //console.log(NETDATA.localStorage);
371 //console.log('setOption: setting "' + key.toString() + '" to "' + value + '" of type ' + typeof(value) + ' original type ' + typeof(NETDATA.options.current[key.toString()]));
372 //console.log(NETDATA.options);
373 NETDATA.options.current[key.toString()] = NETDATA.localStorageSet(name.toString(), value, null);
375 if(typeof NETDATA.options.current.setOptionCallback === 'function')
376 NETDATA.options.current.setOptionCallback();
382 NETDATA.getOption = function(key) {
383 return NETDATA.options.current[key.toString()];
386 // read settings from local storage
387 NETDATA.localStorageGetRecursive(NETDATA.options.current, 'options', null);
389 // always start with this option enabled.
390 NETDATA.setOption('stop_updates_when_focus_is_lost', true);
392 NETDATA.resetOptions = function() {
393 for(var i in NETDATA.localStorage.default) {
394 var a = i.split('.');
396 if(a[0] === 'options') {
397 if(a[1] === 'setOptionCallback') continue;
398 if(typeof NETDATA.localStorage.default[i] === 'undefined') continue;
399 if(NETDATA.options.current[i] === NETDATA.localStorage.default[i]) continue;
401 NETDATA.setOption(a[1], NETDATA.localStorage.default[i]);
403 else if(a[0] === 'chart_heights') {
404 if(typeof NETDATA.localStorage.callback[i] === 'function' && typeof NETDATA.localStorage.default[i] !== 'undefined') {
405 NETDATA.localStorage.callback[i](NETDATA.localStorage.default[i]);
411 // ----------------------------------------------------------------------------------------------------------------
413 if(NETDATA.options.debug.main_loop === true)
414 console.log('welcome to NETDATA');
416 NETDATA.onresize = function() {
417 NETDATA.options.last_resized = new Date().getTime();
421 NETDATA.onscroll = function() {
422 // console.log('onscroll');
424 NETDATA.options.last_page_scroll = new Date().getTime();
425 if(NETDATA.options.targets === null) return;
427 // when the user scrolls he sees that we have
428 // hidden all the not-visible charts
429 // using this little function we try to switch
430 // the charts back to visible quickly
431 var targets = NETDATA.options.targets;
432 var len = targets.length;
433 while(len--) targets[len].isVisible();
436 window.onresize = NETDATA.onresize;
437 window.onscroll = NETDATA.onscroll;
439 // ----------------------------------------------------------------------------------------------------------------
442 NETDATA.errorCodes = {
443 100: { message: "Cannot load chart library", alert: true },
444 101: { message: "Cannot load jQuery", alert: true },
445 402: { message: "Chart library not found", alert: false },
446 403: { message: "Chart library not enabled/is failed", alert: false },
447 404: { message: "Chart not found", alert: false }
449 NETDATA.errorLast = {
455 NETDATA.error = function(code, msg) {
456 NETDATA.errorLast.code = code;
457 NETDATA.errorLast.message = msg;
458 NETDATA.errorLast.datetime = new Date().getTime();
460 console.log("ERROR " + code + ": " + NETDATA.errorCodes[code].message + ": " + msg);
462 if(NETDATA.errorCodes[code].alert)
463 alert("ERROR " + code + ": " + NETDATA.errorCodes[code].message + ": " + msg);
466 NETDATA.errorReset = function() {
467 NETDATA.errorLast.code = 0;
468 NETDATA.errorLast.message = "You are doing fine!";
469 NETDATA.errorLast.datetime = 0;
472 // ----------------------------------------------------------------------------------------------------------------
475 // When multiple charts need the same chart, we avoid downloading it
476 // multiple times (and having it in browser memory multiple time)
477 // by using this registry.
479 // Every time we download a chart definition, we save it here with .add()
480 // Then we try to get it back with .get(). If that fails, we download it.
482 NETDATA.chartRegistry = {
485 fixid: function(id) {
486 return id.replace(/:/g, "_").replace(/\//g, "_");
489 add: function(host, id, data) {
490 host = this.fixid(host);
493 if(typeof this.charts[host] === 'undefined')
494 this.charts[host] = {};
496 //console.log('added ' + host + '/' + id);
497 this.charts[host][id] = data;
500 get: function(host, id) {
501 host = this.fixid(host);
504 if(typeof this.charts[host] === 'undefined')
507 if(typeof this.charts[host][id] === 'undefined')
510 //console.log('cached ' + host + '/' + id);
511 return this.charts[host][id];
514 downloadAll: function(host, callback) {
515 while(host.slice(-1) === '/')
516 host = host.substring(0, host.length - 1);
521 url: host + '/api/v1/charts',
522 crossDomain: NETDATA.options.crossDomainAjax,
526 .done(function(data) {
527 var h = NETDATA.chartRegistry.fixid(host);
528 //console.log('downloaded all charts from ' + host + ' (' + h + ')');
529 self.charts[h] = data.charts;
530 if(typeof callback === 'function')
534 if(typeof callback === 'function')
540 // ----------------------------------------------------------------------------------------------------------------
541 // Global Pan and Zoom on charts
543 // Using this structure are synchronize all the charts, so that
544 // when you pan or zoom one, all others are automatically refreshed
545 // to the same timespan.
547 NETDATA.globalPanAndZoom = {
548 seq: 0, // timestamp ms
549 // every time a chart is panned or zoomed
550 // we set the timestamp here
551 // then we use it as a sequence number
552 // to find if other charts are syncronized
555 master: null, // the master chart (state), to which all others
558 force_before_ms: null, // the timespan to sync all other charts
559 force_after_ms: null,
562 setMaster: function(state, after, before) {
563 if(NETDATA.options.current.sync_pan_and_zoom === false)
566 if(this.master !== null && this.master !== state)
567 this.master.resetChart(true, true);
569 var now = new Date().getTime();
572 this.force_after_ms = after;
573 this.force_before_ms = before;
574 NETDATA.options.auto_refresher_stop_until = now + NETDATA.options.current.global_pan_sync_time;
578 clearMaster: function() {
579 if(this.master !== null) {
580 var st = this.master;
587 this.force_after_ms = null;
588 this.force_before_ms = null;
589 NETDATA.options.auto_refresher_stop_until = 0;
592 // is the given state the master of the global
593 // pan and zoom sync?
594 isMaster: function(state) {
595 if(this.master === state) return true;
599 // are we currently have a global pan and zoom sync?
600 isActive: function() {
601 if(this.master !== null && this.force_before_ms !== null && this.force_after_ms !== null && this.seq !== 0) return true;
605 // check if a chart, other than the master
606 // needs to be refreshed, due to the global pan and zoom
607 shouldBeAutoRefreshed: function(state) {
608 if(this.master === null || this.seq === 0)
611 //if(state.needsRecreation())
614 if(state.tm.pan_and_zoom_seq === this.seq)
621 // ----------------------------------------------------------------------------------------------------------------
622 // dimensions selection
625 // move color assignment to dimensions, here
627 dimensionStatus = function(parent, label, name_div, value_div, color) {
628 this.enabled = false;
629 this.parent = parent;
631 this.name_div = null;
632 this.value_div = null;
633 this.color = NETDATA.themes.current.foreground;
635 if(parent.selected === parent.unselected)
636 this.selected = true;
638 this.selected = false;
640 this.setOptions(name_div, value_div, color);
643 dimensionStatus.prototype.invalidate = function() {
644 this.name_div = null;
645 this.value_div = null;
646 this.enabled = false;
649 dimensionStatus.prototype.setOptions = function(name_div, value_div, color) {
652 if(this.name_div != name_div) {
653 this.name_div = name_div;
654 this.name_div.title = this.label;
655 this.name_div.style.color = this.color;
656 if(this.selected === false)
657 this.name_div.className = 'netdata-legend-name not-selected';
659 this.name_div.className = 'netdata-legend-name selected';
662 if(this.value_div != value_div) {
663 this.value_div = value_div;
664 this.value_div.title = this.label;
665 this.value_div.style.color = this.color;
666 if(this.selected === false)
667 this.value_div.className = 'netdata-legend-value not-selected';
669 this.value_div.className = 'netdata-legend-value selected';
676 dimensionStatus.prototype.setHandler = function() {
677 if(this.enabled === false) return;
681 // this.name_div.onmousedown = this.value_div.onmousedown = function(e) {
682 this.name_div.onclick = this.value_div.onclick = function(e) {
684 if(ds.isSelected()) {
686 if(e.shiftKey === true || e.ctrlKey === true) {
687 // control or shift key is pressed -> unselect this (except is none will remain selected, in which case select all)
690 if(ds.parent.countSelected() === 0)
691 ds.parent.selectAll();
694 // no key is pressed -> select only this (except if it is the only selected already, in which case select all)
695 if(ds.parent.countSelected() === 1) {
696 ds.parent.selectAll();
699 ds.parent.selectNone();
705 // this is not selected
706 if(e.shiftKey === true || e.ctrlKey === true) {
707 // control or shift key is pressed -> select this too
711 // no key is pressed -> select only this
712 ds.parent.selectNone();
717 ds.parent.state.redrawChart();
721 dimensionStatus.prototype.select = function() {
722 if(this.enabled === false) return;
724 this.name_div.className = 'netdata-legend-name selected';
725 this.value_div.className = 'netdata-legend-value selected';
726 this.selected = true;
729 dimensionStatus.prototype.unselect = function() {
730 if(this.enabled === false) return;
732 this.name_div.className = 'netdata-legend-name not-selected';
733 this.value_div.className = 'netdata-legend-value hidden';
734 this.selected = false;
737 dimensionStatus.prototype.isSelected = function() {
738 return(this.enabled === true && this.selected === true);
741 // ----------------------------------------------------------------------------------------------------------------
743 dimensionsVisibility = function(state) {
746 this.dimensions = {};
747 this.selected_count = 0;
748 this.unselected_count = 0;
751 dimensionsVisibility.prototype.dimensionAdd = function(label, name_div, value_div, color) {
752 if(typeof this.dimensions[label] === 'undefined') {
754 this.dimensions[label] = new dimensionStatus(this, label, name_div, value_div, color);
757 this.dimensions[label].setOptions(name_div, value_div, color);
759 return this.dimensions[label];
762 dimensionsVisibility.prototype.dimensionGet = function(label) {
763 return this.dimensions[label];
766 dimensionsVisibility.prototype.invalidateAll = function() {
767 for(var d in this.dimensions)
768 this.dimensions[d].invalidate();
771 dimensionsVisibility.prototype.selectAll = function() {
772 for(var d in this.dimensions)
773 this.dimensions[d].select();
776 dimensionsVisibility.prototype.countSelected = function() {
778 for(var d in this.dimensions)
779 if(this.dimensions[d].isSelected()) i++;
784 dimensionsVisibility.prototype.selectNone = function() {
785 for(var d in this.dimensions)
786 this.dimensions[d].unselect();
789 dimensionsVisibility.prototype.selected2BooleanArray = function(array) {
790 var ret = new Array();
791 this.selected_count = 0;
792 this.unselected_count = 0;
794 for(var i = 0, len = array.length; i < len ; i++) {
795 var ds = this.dimensions[array[i]];
796 if(typeof ds === 'undefined') {
797 // console.log(array[i] + ' is not found');
802 if(ds.isSelected()) {
804 this.selected_count++;
808 this.unselected_count++;
812 if(this.selected_count === 0 && this.unselected_count !== 0) {
814 return this.selected2BooleanArray(array);
821 // ----------------------------------------------------------------------------------------------------------------
822 // global selection sync
824 NETDATA.globalSelectionSync = {
831 if(this.state !== null)
832 this.state.globalSelectionSyncStop();
836 if(this.state !== null) {
837 this.state.globalSelectionSyncDelay();
842 // ----------------------------------------------------------------------------------------------------------------
843 // Our state object, where all per-chart values are stored
845 chartState = function(element) {
846 var self = $(element);
847 this.element = element;
850 // all private functions should use 'that', instead of 'this'
854 * show an error instead of the chart
856 var error = function(msg) {
857 that.element.innerHTML = that.id + ': ' + msg;
858 that.enabled = false;
859 that.current = that.pan;
862 // GUID - a unique identifier for the chart
863 this.uuid = NETDATA.guid();
865 // string - the name of chart
866 this.id = self.data('netdata');
868 // string - the key for localStorage settings
869 this.settings_id = self.data('id') || null;
871 // the user given dimensions of the element
872 this.width = self.data('width') || NETDATA.chartDefaults.width;
873 this.height = self.data('height') || NETDATA.chartDefaults.height;
875 if(this.settings_id !== null) {
876 this.height = NETDATA.localStorageGet('chart_heights.' + this.settings_id, this.height, function(height) {
877 // this is the callback that will be called
878 // if and when the user resets all localStorage variables
881 resizeChartToHeight(height);
885 // string - the netdata server URL, without any path
886 this.host = self.data('host') || NETDATA.chartDefaults.host;
888 // make sure the host does not end with /
889 // all netdata API requests use absolute paths
890 while(this.host.slice(-1) === '/')
891 this.host = this.host.substring(0, this.host.length - 1);
893 // string - the grouping method requested by the user
894 this.method = self.data('method') || NETDATA.chartDefaults.method;
896 // the time-range requested by the user
897 this.after = self.data('after') || NETDATA.chartDefaults.after;
898 this.before = self.data('before') || NETDATA.chartDefaults.before;
900 // the pixels per point requested by the user
901 this.pixels_per_point = self.data('pixels-per-point') || 1;
902 this.points = self.data('points') || null;
904 // the dimensions requested by the user
905 this.dimensions = self.data('dimensions') || null;
907 // the chart library requested by the user
908 this.library_name = self.data('chart-library') || NETDATA.chartDefaults.library;
910 // object - the chart library used
915 this.colors_assigned = {};
916 this.colors_available = null;
918 // the element already created by the user
919 this.element_message = null;
921 // the element with the chart
922 this.element_chart = null;
924 // the element with the legend of the chart (if created by us)
925 this.element_legend = null;
926 this.element_legend_childs = {
936 this.chart_url = null; // string - the url to download chart info
937 this.chart = null; // object - the chart as downloaded from the server
939 this.title = self.data('title') || null; // the title of the chart
940 this.units = self.data('units') || null; // the units of the chart dimensions
941 this.append_options = self.data('append-options') || null; // the units of the chart dimensions
943 this.validated = false; // boolean - has the chart been validated?
944 this.enabled = true; // boolean - is the chart enabled for refresh?
945 this.paused = false; // boolean - is the chart paused for any reason?
946 this.selected = false; // boolean - is the chart shown a selection?
947 this.debug = false; // boolean - console.log() debug info about this chart
949 this.netdata_first = 0; // milliseconds - the first timestamp in netdata
950 this.netdata_last = 0; // milliseconds - the last timestamp in netdata
951 this.requested_after = null; // milliseconds - the timestamp of the request after param
952 this.requested_before = null; // milliseconds - the timestamp of the request before param
953 this.requested_padding = null;
955 this.view_before = 0;
960 force_update_at: 0, // the timestamp to force the update at
961 force_before_ms: null,
967 force_update_at: 0, // the timestamp to force the update at
968 force_before_ms: null,
974 force_update_at: 0, // the timestamp to force the update at
975 force_before_ms: null,
979 // this is a pointer to one of the sub-classes below
981 this.current = this.auto;
983 // check the requested library is available
984 // we don't initialize it here - it will be initialized when
985 // this chart will be first used
986 if(typeof NETDATA.chartLibraries[that.library_name] === 'undefined') {
987 NETDATA.error(402, that.library_name);
988 error('chart library "' + that.library_name + '" is not found');
991 else if(NETDATA.chartLibraries[that.library_name].enabled === false) {
992 NETDATA.error(403, that.library_name);
993 error('chart library "' + that.library_name + '" is not enabled');
997 that.library = NETDATA.chartLibraries[that.library_name];
999 // milliseconds - the time the last refresh took
1000 this.refresh_dt_ms = 0;
1002 // if we need to report the rendering speed
1003 // find the element that needs to be updated
1004 var refresh_dt_element_name = self.data('dt-element-name') || null; // string - the element to print refresh_dt_ms
1006 if(refresh_dt_element_name !== null)
1007 this.refresh_dt_element = document.getElementById(refresh_dt_element_name) || null;
1009 this.refresh_dt_element = null;
1011 this.dimensions_visibility = new dimensionsVisibility(this);
1013 this._updating = false;
1015 // ============================================================================================================
1016 // PRIVATE FUNCTIONS
1018 var createDOM = function() {
1019 if(that.enabled === false) return;
1021 if(that.element_message !== null) that.element_message.innerHTML = '';
1022 if(that.element_legend !== null) that.element_legend.innerHTML = '';
1023 if(that.element_chart !== null) that.element_chart.innerHTML = '';
1025 that.element.innerHTML = '';
1027 that.element_message = document.createElement('div');
1028 that.element_message.className = ' netdata-message hidden';
1029 that.element.appendChild(that.element_message);
1031 that.element_chart = document.createElement('div');
1032 that.element_chart.id = that.library_name + '-' + that.uuid + '-chart';
1033 that.element.appendChild(that.element_chart);
1035 if(that.hasLegend() === true) {
1036 that.element.className = "netdata-container-with-legend";
1037 that.element_chart.className = 'netdata-chart-with-legend-right netdata-' + that.library_name + '-chart-with-legend-right';
1039 that.element_legend = document.createElement('div');
1040 that.element_legend.className = 'netdata-chart-legend netdata-' + that.library_name + '-legend';
1041 that.element.appendChild(that.element_legend);
1044 that.element.className = "netdata-container";
1045 that.element_chart.className = ' netdata-chart netdata-' + that.library_name + '-chart';
1047 that.element_legend = null;
1049 that.element_legend_childs.series = null;
1051 if(typeof(that.width) === 'string')
1052 $(that.element).css('width', that.width);
1053 else if(typeof(that.width) === 'number')
1054 $(that.element).css('width', that.width + 'px');
1056 if(typeof(that.library.aspect_ratio) === 'undefined') {
1057 if(typeof(that.height) === 'string')
1058 $(that.element).css('height', that.height);
1059 else if(typeof(that.height) === 'number')
1060 $(that.element).css('height', that.height + 'px');
1063 var w = that.element.offsetWidth;
1064 if(w === null || w === 0) {
1065 // the div is hidden
1066 // this is resize the chart when next viewed
1067 that.tm.last_resized = 0;
1070 $(that.element).css('height', (that.element.offsetWidth * that.library.aspect_ratio / 100).toString() + 'px');
1073 if(NETDATA.chartDefaults.min_width !== null)
1074 $(that.element).css('min-width', NETDATA.chartDefaults.min_width);
1076 that.tm.last_dom_created = new Date().getTime();
1082 * initialize state viariables
1083 * destroy all (possibly) created state elements
1084 * create the basic DOM for a chart
1086 var init = function() {
1087 if(that.enabled === false) return;
1089 that.paused = false;
1090 that.selected = false;
1092 that.chart_created = false; // boolean - is the library.create() been called?
1093 that.updates_counter = 0; // numeric - the number of refreshes made so far
1094 that.updates_since_last_unhide = 0; // numeric - the number of refreshes made since the last time the chart was unhidden
1095 that.updates_since_last_creation = 0; // numeric - the number of refreshes made since the last time the chart was created
1098 last_initialized: 0, // milliseconds - the timestamp it was last initialized
1099 last_dom_created: 0, // milliseconds - the timestamp its DOM was last created
1100 last_mode_switch: 0, // milliseconds - the timestamp it switched modes
1102 last_info_downloaded: 0, // milliseconds - the timestamp we downloaded the chart
1103 last_updated: 0, // the timestamp the chart last updated with data
1104 pan_and_zoom_seq: 0, // the sequence number of the global synchronization
1106 // Used with NETDATA.globalPanAndZoom.seq
1107 last_visible_check: 0, // the time we last checked if it is visible
1108 last_resized: 0, // the time the chart was resized
1109 last_hidden: 0, // the time the chart was hidden
1110 last_unhidden: 0, // the time the chart was unhidden
1111 last_autorefreshed: 0 // the time the chart was last refreshed
1114 that.data = null; // the last data as downloaded from the netdata server
1115 that.data_url = 'invalid://'; // string - the last url used to update the chart
1116 that.data_points = 0; // number - the number of points returned from netdata
1117 that.data_after = 0; // milliseconds - the first timestamp of the data
1118 that.data_before = 0; // milliseconds - the last timestamp of the data
1119 that.data_update_every = 0; // milliseconds - the frequency to update the data
1121 that.tm.last_initialized = new Date().getTime();
1124 that.setMode('auto');
1127 var maxMessageFontSize = function() {
1128 // normally we want a font size, as tall as the element
1129 var h = that.element_message.clientHeight;
1131 // but give it some air, 20% let's say, or 5 pixels min
1132 var lost = Math.max(h * 0.2, 5);
1135 // center the text, verically
1136 var paddingTop = (lost - 5) / 2;
1138 // but check the width too
1139 // it should fit 10 characters in it
1140 var w = that.element_message.clientWidth / 10;
1142 paddingTop += (h - w) / 2;
1146 // and don't make it too huge
1147 // 5% of the screen size is good
1148 if(h > screen.height / 20) {
1149 paddingTop += (h - (screen.height / 20)) / 2;
1150 h = screen.height / 20;
1154 that.element_message.style.fontSize = h.toString() + 'px';
1155 that.element_message.style.paddingTop = paddingTop.toString() + 'px';
1158 var showMessage = function(msg) {
1159 that.element_message.className = 'netdata-message';
1160 that.element_message.innerHTML = msg;
1161 this.element_message.style.fontSize = 'x-small';
1162 that.element_message.style.paddingTop = '0px';
1163 that.___messageHidden___ = undefined;
1166 var showMessageIcon = function(icon) {
1167 that.element_message.innerHTML = icon;
1168 that.element_message.className = 'netdata-message icon';
1169 maxMessageFontSize();
1170 that.___messageHidden___ = undefined;
1173 var hideMessage = function() {
1174 if(typeof that.___messageHidden___ === 'undefined') {
1175 that.___messageHidden___ = true;
1176 that.element_message.className = 'netdata-message hidden';
1180 var showRendering = function() {
1182 if(that.chart !== null) {
1183 if(that.chart.chart_type === 'line')
1184 icon = '<i class="fa fa-line-chart"></i>';
1186 icon = '<i class="fa fa-area-chart"></i>';
1189 icon = '<i class="fa fa-area-chart"></i>';
1191 showMessageIcon(icon + ' netdata');
1194 var showLoading = function() {
1195 if(that.chart_created === false) {
1196 showMessageIcon('<i class="fa fa-refresh"></i> netdata');
1202 var isHidden = function() {
1203 if(typeof that.___chartIsHidden___ !== 'undefined')
1209 // hide the chart, when it is not visible - called from isVisible()
1210 var hideChart = function() {
1211 // hide it, if it is not already hidden
1212 if(isHidden() === true) return;
1214 if(that.chart_created === true) {
1215 // we should destroy it
1216 if(NETDATA.options.current.destroy_on_hide === true) {
1221 that.element_chart.style.display = 'none';
1222 if(that.element_legend !== null) that.element_legend.style.display = 'none';
1223 that.tm.last_hidden = new Date().getTime();
1227 that.___chartIsHidden___ = true;
1230 // unhide the chart, when it is visible - called from isVisible()
1231 var unhideChart = function() {
1232 if(isHidden() === false) return;
1234 that.___chartIsHidden___ = undefined;
1235 that.updates_since_last_unhide = 0;
1237 if(that.chart_created === false) {
1238 // we need to re-initialize it, to show our background
1239 // logo in bootstrap tabs, until the chart loads
1243 that.tm.last_unhidden = new Date().getTime();
1244 that.element_chart.style.display = '';
1245 if(that.element_legend !== null) that.element_legend.style.display = '';
1251 var canBeRendered = function() {
1252 if(isHidden() === true || that.isVisible(true) === false)
1258 // https://github.com/petkaantonov/bluebird/wiki/Optimization-killers
1259 var callChartLibraryUpdateSafely = function(data) {
1262 if(canBeRendered() === false)
1265 if(NETDATA.options.debug.chart_errors === true)
1266 status = that.library.update(that, data);
1269 status = that.library.update(that, data);
1276 if(status === false) {
1277 error('chart failed to be updated as ' + that.library_name);
1284 // https://github.com/petkaantonov/bluebird/wiki/Optimization-killers
1285 var callChartLibraryCreateSafely = function(data) {
1288 if(canBeRendered() === false)
1291 if(NETDATA.options.debug.chart_errors === true)
1292 status = that.library.create(that, data);
1295 status = that.library.create(that, data);
1302 if(status === false) {
1303 error('chart failed to be created as ' + that.library_name);
1307 that.chart_created = true;
1308 that.updates_since_last_creation = 0;
1312 // ----------------------------------------------------------------------------------------------------------------
1315 // resizeChart() - private
1316 // to be called just before the chart library to make sure that
1317 // a properly sized dom is available
1318 var resizeChart = function() {
1319 if(that.isVisible() === true && that.tm.last_resized < NETDATA.options.last_resized) {
1320 if(that.chart_created === false) return;
1322 if(that.needsRecreation()) {
1325 else if(typeof that.library.resize === 'function') {
1326 that.library.resize(that);
1328 if(that.element_legend_childs.nano !== null && that.element_legend_childs.nano_options !== null)
1329 $(that.element_legend_childs.nano).nanoScroller();
1331 maxMessageFontSize();
1334 that.tm.last_resized = new Date().getTime();
1338 // this is the actual chart resize algorithm
1340 // - resize the entire container
1341 // - update the internal states
1342 // - resize the chart as the div changes height
1343 // - update the scrollbar of the legend
1344 var resizeChartToHeight = function(h) {
1346 that.element.style.height = h;
1348 if(that.settings_id !== null)
1349 NETDATA.localStorageSet('chart_heights.' + that.settings_id, h);
1351 var now = new Date().getTime();
1352 NETDATA.options.last_page_scroll = now;
1353 NETDATA.options.auto_refresher_stop_until = now + NETDATA.options.current.stop_updates_while_resizing;
1356 that.tm.last_resized = 0;
1360 this.resizeHandler = function(e) {
1363 if(typeof this.event_resize === 'undefined'
1364 || this.event_resize.chart_original_w === 'undefined'
1365 || this.event_resize.chart_original_h === 'undefined')
1366 this.event_resize = {
1367 chart_original_w: this.element.clientWidth,
1368 chart_original_h: this.element.clientHeight,
1372 if(e.type === 'touchstart') {
1373 this.event_resize.mouse_start_x = e.touches.item(0).pageX;
1374 this.event_resize.mouse_start_y = e.touches.item(0).pageY;
1377 this.event_resize.mouse_start_x = e.clientX;
1378 this.event_resize.mouse_start_y = e.clientY;
1381 this.event_resize.chart_start_w = this.element.clientWidth;
1382 this.event_resize.chart_start_h = this.element.clientHeight;
1383 this.event_resize.chart_last_w = this.element.clientWidth;
1384 this.event_resize.chart_last_h = this.element.clientHeight;
1386 var now = new Date().getTime();
1387 if(now - this.event_resize.last <= NETDATA.options.current.double_click_speed) {
1388 // double click / double tap event
1390 // the optimal height of the chart
1391 // showing the entire legend
1392 var optimal = this.event_resize.chart_last_h
1393 + this.element_legend_childs.content.scrollHeight
1394 - this.element_legend_childs.content.clientHeight;
1396 // if we are not optimal, be optimal
1397 if(this.event_resize.chart_last_h != optimal)
1398 resizeChartToHeight(optimal.toString() + 'px');
1400 // else if we do not have the original height
1401 // reset to the original height
1402 else if(this.event_resize.chart_last_h != this.event_resize.chart_original_h)
1403 resizeChartToHeight(this.event_resize.chart_original_h.toString() + 'px');
1406 this.event_resize.last = now;
1408 // process movement event
1409 document.onmousemove =
1410 document.ontouchmove =
1411 this.element_legend_childs.resize_handler.onmousemove =
1412 this.element_legend_childs.resize_handler.ontouchmove =
1417 case 'mousemove': y = e.clientY; break;
1418 case 'touchmove': y = e.touches.item(e.touches - 1).pageY; break;
1422 var newH = that.event_resize.chart_start_h + y - that.event_resize.mouse_start_y;
1424 if(newH >= 70 && newH !== that.event_resize.chart_last_h) {
1425 resizeChartToHeight(newH.toString() + 'px');
1426 that.event_resize.chart_last_h = newH;
1431 // process end event
1432 document.onmouseup =
1433 document.ontouchend =
1434 this.element_legend_childs.resize_handler.onmouseup =
1435 this.element_legend_childs.resize_handler.ontouchend =
1437 // remove all the hooks
1438 document.onmouseup =
1439 document.onmousemove =
1440 document.ontouchmove =
1441 document.ontouchend =
1442 that.element_legend_childs.resize_handler.onmousemove =
1443 that.element_legend_childs.resize_handler.ontouchmove =
1444 that.element_legend_childs.resize_handler.onmouseout =
1445 that.element_legend_childs.resize_handler.onmouseup =
1446 that.element_legend_childs.resize_handler.ontouchend =
1449 // allow auto-refreshes
1450 NETDATA.options.auto_refresher_stop_until = 0;
1456 var noDataToShow = function() {
1457 showMessageIcon('<i class="fa fa-warning"></i> empty');
1458 that.legendUpdateDOM();
1459 that.tm.last_autorefreshed = new Date().getTime();
1460 // that.data_update_every = 30 * 1000;
1461 //that.element_chart.style.display = 'none';
1462 //if(that.element_legend !== null) that.element_legend.style.display = 'none';
1463 //that.___chartIsHidden___ = true;
1466 // ============================================================================================================
1469 this.error = function(msg) {
1473 this.setMode = function(m) {
1474 if(this.current !== null && this.current.name === m) return;
1477 this.current = this.auto;
1478 else if(m === 'pan')
1479 this.current = this.pan;
1480 else if(m === 'zoom')
1481 this.current = this.zoom;
1483 this.current = this.auto;
1485 this.current.force_update_at = 0;
1486 this.current.force_before_ms = null;
1487 this.current.force_after_ms = null;
1489 this.tm.last_mode_switch = new Date().getTime();
1492 // ----------------------------------------------------------------------------------------------------------------
1493 // global selection sync
1495 // prevent to global selection sync for some time
1496 this.globalSelectionSyncDelay = function(ms) {
1497 if(NETDATA.options.current.sync_selection === false)
1500 if(typeof ms === 'number')
1501 NETDATA.globalSelectionSync.dont_sync_before = new Date().getTime() + ms;
1503 NETDATA.globalSelectionSync.dont_sync_before = new Date().getTime() + NETDATA.options.current.sync_selection_delay;
1506 // can we globally apply selection sync?
1507 this.globalSelectionSyncAbility = function() {
1508 if(NETDATA.options.current.sync_selection === false)
1511 if(NETDATA.globalSelectionSync.dont_sync_before > new Date().getTime())
1517 this.globalSelectionSyncIsMaster = function() {
1518 if(NETDATA.globalSelectionSync.state === this)
1524 // this chart is the master of the global selection sync
1525 this.globalSelectionSyncBeMaster = function() {
1527 if(this.globalSelectionSyncIsMaster()) {
1528 if(this.debug === true)
1529 this.log('sync: I am the master already.');
1534 if(NETDATA.globalSelectionSync.state) {
1535 if(this.debug === true)
1536 this.log('sync: I am not the sync master. Resetting global sync.');
1538 this.globalSelectionSyncStop();
1541 // become the master
1542 if(this.debug === true)
1543 this.log('sync: becoming sync master.');
1545 this.selected = true;
1546 NETDATA.globalSelectionSync.state = this;
1548 // find the all slaves
1549 var targets = NETDATA.options.targets;
1550 var len = targets.length;
1555 if(this.debug === true)
1556 st.log('sync: not adding me to sync');
1558 else if(st.globalSelectionSyncIsEligible()) {
1559 if(this.debug === true)
1560 st.log('sync: adding to sync as slave');
1562 st.globalSelectionSyncBeSlave();
1566 // this.globalSelectionSyncDelay(100);
1569 // can the chart participate to the global selection sync as a slave?
1570 this.globalSelectionSyncIsEligible = function() {
1571 if(this.enabled === true
1572 && this.library !== null
1573 && typeof this.library.setSelection === 'function'
1574 && this.isVisible() === true
1575 && this.chart_created === true)
1581 // this chart becomes a slave of the global selection sync
1582 this.globalSelectionSyncBeSlave = function() {
1583 if(NETDATA.globalSelectionSync.state !== this)
1584 NETDATA.globalSelectionSync.slaves.push(this);
1587 // sync all the visible charts to the given time
1588 // this is to be called from the chart libraries
1589 this.globalSelectionSync = function(t) {
1590 if(this.globalSelectionSyncAbility() === false) {
1591 if(this.debug === true)
1592 this.log('sync: cannot sync (yet?).');
1597 if(this.globalSelectionSyncIsMaster() === false) {
1598 if(this.debug === true)
1599 this.log('sync: trying to be sync master.');
1601 this.globalSelectionSyncBeMaster();
1603 if(this.globalSelectionSyncAbility() === false) {
1604 if(this.debug === true)
1605 this.log('sync: cannot sync (yet?).');
1611 NETDATA.globalSelectionSync.last_t = t;
1612 $.each(NETDATA.globalSelectionSync.slaves, function(i, st) {
1617 // stop syncing all charts to the given time
1618 this.globalSelectionSyncStop = function() {
1619 if(NETDATA.globalSelectionSync.slaves.length) {
1620 if(this.debug === true)
1621 this.log('sync: cleaning up...');
1623 $.each(NETDATA.globalSelectionSync.slaves, function(i, st) {
1625 if(that.debug === true)
1626 st.log('sync: not adding me to sync stop');
1629 if(that.debug === true)
1630 st.log('sync: removed slave from sync');
1632 st.clearSelection();
1636 NETDATA.globalSelectionSync.last_t = 0;
1637 NETDATA.globalSelectionSync.slaves = [];
1638 NETDATA.globalSelectionSync.state = null;
1641 this.clearSelection();
1644 this.setSelection = function(t) {
1645 if(typeof this.library.setSelection === 'function') {
1646 if(this.library.setSelection(this, t) === true)
1647 this.selected = true;
1649 this.selected = false;
1651 else this.selected = true;
1653 if(this.selected === true && this.debug === true)
1654 this.log('selection set to ' + t.toString());
1656 return this.selected;
1659 this.clearSelection = function() {
1660 if(this.selected === true) {
1661 if(typeof this.library.clearSelection === 'function') {
1662 if(this.library.clearSelection(this) === true)
1663 this.selected = false;
1665 this.selected = true;
1667 else this.selected = false;
1669 if(this.selected === false && this.debug === true)
1670 this.log('selection cleared');
1675 return this.selected;
1678 // find if a timestamp (ms) is shown in the current chart
1679 this.timeIsVisible = function(t) {
1680 if(t >= this.data_after && t <= this.data_before)
1685 this.calculateRowForTime = function(t) {
1686 if(this.timeIsVisible(t) === false) return -1;
1687 return Math.floor((t - this.data_after) / this.data_update_every);
1690 // ----------------------------------------------------------------------------------------------------------------
1693 this.log = function(msg) {
1694 console.log(this.id + ' (' + this.library_name + ' ' + this.uuid + '): ' + msg);
1697 this.pauseChart = function() {
1698 if(this.paused === false) {
1699 if(this.debug === true)
1700 this.log('pauseChart()');
1706 this.unpauseChart = function() {
1707 if(this.paused === true) {
1708 if(this.debug === true)
1709 this.log('unpauseChart()');
1711 this.paused = false;
1715 this.resetChart = function(dont_clear_master, dont_update) {
1716 if(this.debug === true)
1717 this.log('resetChart(' + dont_clear_master + ', ' + dont_update + ') called');
1719 if(typeof dont_clear_master === 'undefined')
1720 dont_clear_master = false;
1722 if(typeof dont_update === 'undefined')
1723 dont_update = false;
1725 if(dont_clear_master !== true && NETDATA.globalPanAndZoom.isMaster(this) === true) {
1726 if(this.debug === true)
1727 this.log('resetChart() diverting to clearMaster().');
1728 // this will call us back with master === true
1729 NETDATA.globalPanAndZoom.clearMaster();
1733 this.clearSelection();
1735 this.tm.pan_and_zoom_seq = 0;
1737 this.setMode('auto');
1738 this.current.force_update_at = 0;
1739 this.current.force_before_ms = null;
1740 this.current.force_after_ms = null;
1741 this.tm.last_autorefreshed = 0;
1742 this.paused = false;
1743 this.selected = false;
1744 this.enabled = true;
1745 // this.debug = false;
1747 // do not update the chart here
1748 // or the chart will flip-flop when it is the master
1749 // of a selection sync and another chart becomes
1752 if(dont_update !== true && this.isVisible() === true) {
1757 this.updateChartPanOrZoom = function(after, before) {
1758 var logme = 'updateChartPanOrZoom(' + after + ', ' + before + '): ';
1761 if(this.debug === true)
1764 if(before < after) {
1765 this.log(logme + 'flipped parameters, rejecting it.');
1769 if(typeof this.fixed_min_duration === 'undefined')
1770 this.fixed_min_duration = Math.round((this.chartWidth() / 30) * this.chart.update_every * 1000);
1772 var min_duration = this.fixed_min_duration;
1773 var current_duration = Math.round(this.view_before - this.view_after);
1775 // round the numbers
1776 after = Math.round(after);
1777 before = Math.round(before);
1779 // align them to update_every
1780 // stretching them further away
1781 after -= after % this.data_update_every;
1782 before += this.data_update_every - (before % this.data_update_every);
1784 // the final wanted duration
1785 var wanted_duration = before - after;
1787 // to allow panning, accept just a point below our minimum
1788 if((current_duration - this.data_update_every) < min_duration)
1789 min_duration = current_duration - this.data_update_every;
1791 // we do it, but we adjust to minimum size and return false
1792 // when the wanted size is below the current and the minimum
1794 if(wanted_duration < current_duration && wanted_duration < min_duration) {
1795 if(this.debug === true)
1796 this.log(logme + 'too small: min_duration: ' + (min_duration / 1000).toString() + ', wanted: ' + (wanted_duration / 1000).toString());
1798 min_duration = this.fixed_min_duration;
1800 var dt = (min_duration - wanted_duration) / 2;
1803 wanted_duration = before - after;
1807 var tolerance = this.data_update_every * 2;
1808 var movement = Math.abs(before - this.view_before);
1810 if(Math.abs(current_duration - wanted_duration) <= tolerance && movement <= tolerance && ret === true) {
1811 if(this.debug === true)
1812 this.log(logme + 'REJECTING UPDATE: current/min duration: ' + (current_duration / 1000).toString() + '/' + (this.fixed_min_duration / 1000).toString() + ', wanted duration: ' + (wanted_duration / 1000).toString() + ', duration diff: ' + (Math.round(Math.abs(current_duration - wanted_duration) / 1000)).toString() + ', movement: ' + (movement / 1000).toString() + ', tolerance: ' + (tolerance / 1000).toString() + ', returning: ' + false);
1816 if(this.current.name === 'auto') {
1817 this.log(logme + 'caller called me with mode: ' + this.current.name);
1818 this.setMode('pan');
1821 if(this.debug === true)
1822 this.log(logme + 'ACCEPTING UPDATE: current/min duration: ' + (current_duration / 1000).toString() + '/' + (this.fixed_min_duration / 1000).toString() + ', wanted duration: ' + (wanted_duration / 1000).toString() + ', duration diff: ' + (Math.round(Math.abs(current_duration - wanted_duration) / 1000)).toString() + ', movement: ' + (movement / 1000).toString() + ', tolerance: ' + (tolerance / 1000).toString() + ', returning: ' + ret);
1824 this.current.force_update_at = new Date().getTime() + NETDATA.options.current.pan_and_zoom_delay;
1825 this.current.force_after_ms = after;
1826 this.current.force_before_ms = before;
1827 NETDATA.globalPanAndZoom.setMaster(this, after, before);
1831 this.legendFormatValue = function(value) {
1832 if(value === null || value === 'undefined') return '-';
1833 if(typeof value !== 'number') return value;
1835 var abs = Math.abs(value);
1836 if(abs >= 1000) return (Math.round(value)).toLocaleString();
1837 if(abs >= 100 ) return (Math.round(value * 10) / 10).toLocaleString();
1838 if(abs >= 1 ) return (Math.round(value * 100) / 100).toLocaleString();
1839 if(abs >= 0.1 ) return (Math.round(value * 1000) / 1000).toLocaleString();
1840 return (Math.round(value * 10000) / 10000).toLocaleString();
1843 this.legendSetLabelValue = function(label, value) {
1844 var series = this.element_legend_childs.series[label];
1845 if(typeof series === 'undefined') return;
1846 if(series.value === null && series.user === null) return;
1848 // if the value has not changed, skip DOM update
1849 //if(series.last === value) return;
1852 if(typeof value === 'number') {
1853 var v = Math.abs(value);
1854 s = r = this.legendFormatValue(value);
1856 if(typeof series.last === 'number') {
1857 if(v > series.last) s += '<i class="fa fa-angle-up" style="width: 8px; text-align: center; overflow: hidden; vertical-align: middle;"></i>';
1858 else if(v < series.last) s += '<i class="fa fa-angle-down" style="width: 8px; text-align: center; overflow: hidden; vertical-align: middle;"></i>';
1859 else s += '<i class="fa fa-angle-left" style="width: 8px; text-align: center; overflow: hidden; vertical-align: middle;"></i>';
1861 else s += '<i class="fa fa-angle-right" style="width: 8px; text-align: center; overflow: hidden; vertical-align: middle;"></i>';
1866 series.last = value;
1869 if(series.value !== null) series.value.innerHTML = s;
1870 if(series.user !== null) series.user.innerHTML = r;
1873 this.legendSetDate = function(ms) {
1874 if(typeof ms !== 'number') {
1875 this.legendShowUndefined();
1879 var d = new Date(ms);
1881 if(this.element_legend_childs.title_date)
1882 this.element_legend_childs.title_date.innerHTML = d.toLocaleDateString();
1884 if(this.element_legend_childs.title_time)
1885 this.element_legend_childs.title_time.innerHTML = d.toLocaleTimeString();
1887 if(this.element_legend_childs.title_units)
1888 this.element_legend_childs.title_units.innerHTML = this.units;
1891 this.legendShowUndefined = function() {
1892 if(this.element_legend_childs.title_date)
1893 this.element_legend_childs.title_date.innerHTML = ' ';
1895 if(this.element_legend_childs.title_time)
1896 this.element_legend_childs.title_time.innerHTML = this.chart.name;
1898 if(this.element_legend_childs.title_units)
1899 this.element_legend_childs.title_units.innerHTML = ' ';
1901 if(this.data && this.element_legend_childs.series !== null) {
1902 var labels = this.data.dimension_names;
1903 var i = labels.length;
1905 var label = labels[i];
1907 if(typeof label === 'undefined') continue;
1908 if(typeof this.element_legend_childs.series[label] === 'undefined') continue;
1909 this.legendSetLabelValue(label, null);
1914 this.legendShowLatestValues = function() {
1915 if(this.chart === null) return;
1916 if(this.selected) return;
1918 if(this.data === null || this.element_legend_childs.series === null) {
1919 this.legendShowUndefined();
1923 var show_undefined = true;
1924 if(Math.abs(this.netdata_last - this.view_before) <= this.data_update_every)
1925 show_undefined = false;
1927 if(show_undefined) {
1928 this.legendShowUndefined();
1932 this.legendSetDate(this.view_before);
1934 var labels = this.data.dimension_names;
1935 var i = labels.length;
1937 var label = labels[i];
1939 if(typeof label === 'undefined') continue;
1940 if(typeof this.element_legend_childs.series[label] === 'undefined') continue;
1943 this.legendSetLabelValue(label, null);
1945 this.legendSetLabelValue(label, this.data.view_latest_values[i]);
1949 this.legendReset = function() {
1950 this.legendShowLatestValues();
1953 // this should be called just ONCE per dimension per chart
1954 this._chartDimensionColor = function(label) {
1955 if(this.colors === null) this.chartColors();
1957 if(typeof this.colors_assigned[label] === 'undefined') {
1958 if(this.colors_available.length === 0) {
1959 for(var i = 0, len = NETDATA.themes.current.colors.length; i < len ; i++)
1960 this.colors_available.push(NETDATA.themes.current.colors[i]);
1963 this.colors_assigned[label] = this.colors_available.shift();
1965 if(this.debug === true)
1966 this.log('label "' + label + '" got color "' + this.colors_assigned[label]);
1969 if(this.debug === true)
1970 this.log('label "' + label + '" already has color "' + this.colors_assigned[label] + '"');
1973 this.colors.push(this.colors_assigned[label]);
1974 return this.colors_assigned[label];
1977 this.chartColors = function() {
1978 if(this.colors !== null) return this.colors;
1980 this.colors = new Array();
1981 this.colors_available = new Array();
1983 var c = $(this.element).data('colors');
1984 // this.log('read colors: ' + c);
1985 if(typeof c !== 'undefined' && c !== null) {
1986 if(typeof c !== 'string') {
1987 this.log('invalid color given: ' + c + ' (give a space separated list of colors)');
1994 for(var i = 0, len = c.length; i < len ; i++) {
1996 this.colors_available.push(c[i]);
1997 // this.log('adding color: ' + c[i]);
2003 // push all the standard colors too
2004 for(var i = 0, len = NETDATA.themes.current.colors.length; i < len ; i++)
2005 this.colors_available.push(NETDATA.themes.current.colors[i]);
2010 this.legendUpdateDOM = function() {
2013 // check that the legend DOM is up to date for the downloaded dimensions
2014 if(typeof this.element_legend_childs.series !== 'object' || this.element_legend_childs.series === null) {
2015 // this.log('the legend does not have any series - requesting legend update');
2018 else if(this.data === null) {
2019 // this.log('the chart does not have any data - requesting legend update');
2022 else if(typeof this.element_legend_childs.series.labels_key === 'undefined') {
2026 var labels = this.data.dimension_names.toString();
2027 if(labels !== this.element_legend_childs.series.labels_key) {
2030 if(this.debug === true)
2031 this.log('NEW LABELS: "' + labels + '" NOT EQUAL OLD LABELS: "' + this.element_legend_childs.series.labels_key + '"');
2035 if(needed === false) {
2036 // make sure colors available
2039 // do we have to update the current values?
2040 // we do this, only when the visible chart is current
2041 if(Math.abs(this.netdata_last - this.view_before) <= this.data_update_every) {
2042 if(this.debug === true)
2043 this.log('chart is in latest position... updating values on legend...');
2045 //var labels = this.data.dimension_names;
2046 //var i = labels.length;
2048 // this.legendSetLabelValue(labels[i], this.data.latest_values[i]);
2052 if(this.colors === null) {
2053 // this is the first time we update the chart
2054 // let's assign colors to all dimensions
2055 if(this.library.track_colors() === true)
2056 for(var dim in this.chart.dimensions)
2057 this._chartDimensionColor(this.chart.dimensions[dim].name);
2059 // we will re-generate the colors for the chart
2060 // based on the selected dimensions
2063 if(this.debug === true)
2064 this.log('updating Legend DOM');
2066 // mark all dimensions as invalid
2067 this.dimensions_visibility.invalidateAll();
2069 var genLabel = function(state, parent, name, count) {
2070 var color = state._chartDimensionColor(name);
2072 var user_element = null;
2073 var user_id = self.data('show-value-of-' + name + '-at') || null;
2074 if(user_id !== null) {
2075 user_element = document.getElementById(user_id) || null;
2076 if(user_element === null)
2077 me.log('Cannot find element with id: ' + user_id);
2080 state.element_legend_childs.series[name] = {
2081 name: document.createElement('span'),
2082 value: document.createElement('span'),
2087 var label = state.element_legend_childs.series[name];
2089 // create the dimension visibility tracking for this label
2090 state.dimensions_visibility.dimensionAdd(name, label.name, label.value, color);
2092 var rgb = NETDATA.colorHex2Rgb(color);
2093 label.name.innerHTML = '<table class="netdata-legend-name-table-'
2094 + state.chart.chart_type
2095 + '" style="background-color: '
2096 + 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + NETDATA.options.current['color_fill_opacity_' + state.chart.chart_type] + ')'
2097 + '"><tr class="netdata-legend-name-tr"><td class="netdata-legend-name-td"></td></tr></table>'
2099 var text = document.createTextNode(' ' + name);
2100 label.name.appendChild(text);
2103 parent.appendChild(document.createElement('br'));
2105 parent.appendChild(label.name);
2106 parent.appendChild(label.value);
2109 var content = document.createElement('div');
2111 if(this.hasLegend()) {
2112 this.element_legend_childs = {
2114 resize_handler: document.createElement('div'),
2115 title_date: document.createElement('span'),
2116 title_time: document.createElement('span'),
2117 title_units: document.createElement('span'),
2118 nano: document.createElement('div'),
2120 paneClass: 'netdata-legend-series-pane',
2121 sliderClass: 'netdata-legend-series-slider',
2122 contentClass: 'netdata-legend-series-content',
2123 enabledClass: '__enabled',
2124 flashedClass: '__flashed',
2125 activeClass: '__active',
2127 alwaysVisible: true,
2133 this.element_legend.innerHTML = '';
2135 this.element_legend_childs.resize_handler.className += " netdata-legend-resize-handler";
2136 this.element_legend_childs.resize_handler.innerHTML = '<i class="fa fa-chevron-up"></i><i class="fa fa-chevron-down"></i>';
2137 this.element.appendChild(this.element_legend_childs.resize_handler);
2140 this.element_legend_childs.resize_handler.onmousedown =
2142 that.resizeHandler(e);
2146 this.element_legend_childs.resize_handler.addEventListener('touchstart', function(e) {
2147 that.resizeHandler(e);
2150 this.element_legend_childs.title_date.className += " netdata-legend-title-date";
2151 this.element_legend.appendChild(this.element_legend_childs.title_date);
2153 this.element_legend.appendChild(document.createElement('br'));
2155 this.element_legend_childs.title_time.className += " netdata-legend-title-time";
2156 this.element_legend.appendChild(this.element_legend_childs.title_time);
2158 this.element_legend.appendChild(document.createElement('br'));
2160 this.element_legend_childs.title_units.className += " netdata-legend-title-units";
2161 this.element_legend.appendChild(this.element_legend_childs.title_units);
2163 this.element_legend.appendChild(document.createElement('br'));
2165 this.element_legend_childs.nano.className = 'netdata-legend-series';
2166 this.element_legend.appendChild(this.element_legend_childs.nano);
2168 content.className = 'netdata-legend-series-content';
2169 this.element_legend_childs.nano.appendChild(content);
2172 this.element_legend_childs = {
2174 resize_handler: null,
2185 this.element_legend_childs.series.labels_key = this.data.dimension_names.toString();
2186 if(this.debug === true)
2187 this.log('labels from data: "' + this.element_legend_childs.series.labels_key + '"');
2189 for(var i = 0, len = this.data.dimension_names.length; i < len ;i++) {
2190 genLabel(this, content, this.data.dimension_names[i], i);
2194 var tmp = new Array();
2195 for(var dim in this.chart.dimensions) {
2196 tmp.push(this.chart.dimensions[dim].name);
2197 genLabel(this, content, this.chart.dimensions[dim].name, i);
2199 this.element_legend_childs.series.labels_key = tmp.toString();
2200 if(this.debug === true)
2201 this.log('labels from chart: "' + this.element_legend_childs.series.labels_key + '"');
2204 // create a hidden div to be used for hidding
2205 // the original legend of the chart library
2206 var el = document.createElement('div');
2207 if(this.element_legend !== null)
2208 this.element_legend.appendChild(el);
2209 el.style.display = 'none';
2211 this.element_legend_childs.hidden = document.createElement('div');
2212 el.appendChild(this.element_legend_childs.hidden);
2214 if(this.element_legend_childs.nano !== null && this.element_legend_childs.nano_options !== null)
2215 $(this.element_legend_childs.nano).nanoScroller(this.element_legend_childs.nano_options);
2217 this.legendShowLatestValues();
2220 this.hasLegend = function() {
2221 if(typeof this.___hasLegendCache___ !== 'undefined')
2222 return this.___hasLegendCache___;
2225 if(this.library && this.library.legend(this) === 'right-side') {
2226 var legend = $(this.element).data('legend') || 'yes';
2227 if(legend === 'yes') leg = true;
2230 this.___hasLegendCache___ = leg;
2234 this.legendWidth = function() {
2235 return (this.hasLegend())?140:0;
2238 this.legendHeight = function() {
2239 return $(this.element).height();
2242 this.chartWidth = function() {
2243 return $(this.element).width() - this.legendWidth();
2246 this.chartHeight = function() {
2247 return $(this.element).height();
2250 this.chartPixelsPerPoint = function() {
2251 // force an options provided detail
2252 var px = this.pixels_per_point;
2254 if(this.library && px < this.library.pixels_per_point(this))
2255 px = this.library.pixels_per_point(this);
2257 if(px < NETDATA.options.current.pixels_per_point)
2258 px = NETDATA.options.current.pixels_per_point;
2263 this.needsRecreation = function() {
2265 this.chart_created === true
2267 && this.library.autoresize() === false
2268 && this.tm.last_resized < NETDATA.options.last_resized
2272 this.chartURL = function() {
2273 var after, before, points_multiplier = 1;
2274 if(NETDATA.globalPanAndZoom.isActive() && NETDATA.globalPanAndZoom.isMaster(this) === false) {
2275 this.tm.pan_and_zoom_seq = NETDATA.globalPanAndZoom.seq;
2277 after = Math.round(NETDATA.globalPanAndZoom.force_after_ms / 1000);
2278 before = Math.round(NETDATA.globalPanAndZoom.force_before_ms / 1000);
2279 this.view_after = after * 1000;
2280 this.view_before = before * 1000;
2282 this.requested_padding = null;
2283 points_multiplier = 1;
2285 else if(this.current.force_before_ms !== null && this.current.force_after_ms !== null) {
2286 this.tm.pan_and_zoom_seq = 0;
2288 before = Math.round(this.current.force_before_ms / 1000);
2289 after = Math.round(this.current.force_after_ms / 1000);
2290 this.view_after = after * 1000;
2291 this.view_before = before * 1000;
2293 if(NETDATA.options.current.pan_and_zoom_data_padding === true) {
2294 this.requested_padding = Math.round((before - after) / 2);
2295 after -= this.requested_padding;
2296 before += this.requested_padding;
2297 this.requested_padding *= 1000;
2298 points_multiplier = 2;
2301 this.current.force_before_ms = null;
2302 this.current.force_after_ms = null;
2305 this.tm.pan_and_zoom_seq = 0;
2307 before = this.before;
2309 this.view_after = after * 1000;
2310 this.view_before = before * 1000;
2312 this.requested_padding = null;
2313 points_multiplier = 1;
2316 this.requested_after = after * 1000;
2317 this.requested_before = before * 1000;
2319 this.data_points = this.points || Math.round(this.chartWidth() / this.chartPixelsPerPoint());
2321 // build the data URL
2322 this.data_url = this.host + this.chart.data_url;
2323 this.data_url += "&format=" + this.library.format();
2324 this.data_url += "&points=" + (this.data_points * points_multiplier).toString();
2325 this.data_url += "&group=" + this.method;
2326 this.data_url += "&options=" + this.library.options(this);
2327 this.data_url += '|jsonwrap';
2329 if(NETDATA.options.current.eliminate_zero_dimensions === true)
2330 this.data_url += '|nonzero';
2332 if(this.append_options !== null)
2333 this.data_url += '|' + this.append_options.toString();
2336 this.data_url += "&after=" + after.toString();
2339 this.data_url += "&before=" + before.toString();
2342 this.data_url += "&dimensions=" + this.dimensions;
2344 if(NETDATA.options.debug.chart_data_url === true || this.debug === true)
2345 this.log('chartURL(): ' + this.data_url + ' WxH:' + this.chartWidth() + 'x' + this.chartHeight() + ' points: ' + this.data_points + ' library: ' + this.library_name);
2348 this.redrawChart = function() {
2349 if(this.data !== null)
2350 this.updateChartWithData(this.data);
2353 this.updateChartWithData = function(data) {
2354 if(this.debug === true)
2355 this.log('updateChartWithData() called.');
2357 this._updating = false;
2359 // this may force the chart to be re-created
2363 this.updates_counter++;
2364 this.updates_since_last_unhide++;
2365 this.updates_since_last_creation++;
2367 var started = new Date().getTime();
2369 // if the result is JSON, find the latest update-every
2370 this.data_update_every = data.view_update_every * 1000;
2371 this.data_after = data.after * 1000;
2372 this.data_before = data.before * 1000;
2373 this.netdata_first = data.first_entry * 1000;
2374 this.netdata_last = data.last_entry * 1000;
2375 this.data_points = data.points;
2378 if(NETDATA.options.current.pan_and_zoom_data_padding === true && this.requested_padding !== null) {
2379 if(this.view_after < this.data_after) {
2380 // console.log('adusting view_after from ' + this.view_after + ' to ' + this.data_after);
2381 this.view_after = this.data_after;
2384 if(this.view_before > this.data_before) {
2385 // console.log('adusting view_before from ' + this.view_before + ' to ' + this.data_before);
2386 this.view_before = this.data_before;
2390 this.view_after = this.data_after;
2391 this.view_before = this.data_before;
2394 if(this.debug === true) {
2395 this.log('UPDATE No ' + this.updates_counter + ' COMPLETED');
2397 if(this.current.force_after_ms)
2398 this.log('STATUS: forced : ' + (this.current.force_after_ms / 1000).toString() + ' - ' + (this.current.force_before_ms / 1000).toString());
2400 this.log('STATUS: forced : unset');
2402 this.log('STATUS: requested : ' + (this.requested_after / 1000).toString() + ' - ' + (this.requested_before / 1000).toString());
2403 this.log('STATUS: downloaded: ' + (this.data_after / 1000).toString() + ' - ' + (this.data_before / 1000).toString());
2404 this.log('STATUS: rendered : ' + (this.view_after / 1000).toString() + ' - ' + (this.view_before / 1000).toString());
2405 this.log('STATUS: points : ' + (this.data_points).toString());
2408 if(this.data_points === 0) {
2413 if(this.updates_since_last_creation >= this.library.max_updates_to_recreate()) {
2414 if(this.debug === true)
2415 this.log('max updates of ' + this.updates_since_last_creation.toString() + ' reached. Forcing re-generation.');
2417 this.chart_created = false;
2420 // check and update the legend
2421 this.legendUpdateDOM();
2423 if(this.chart_created === true
2424 && typeof this.library.update === 'function') {
2426 if(this.debug === true)
2427 this.log('updating chart...');
2429 if(callChartLibraryUpdateSafely(data) === false)
2433 if(this.debug === true)
2434 this.log('creating chart...');
2436 if(callChartLibraryCreateSafely(data) === false)
2440 this.legendShowLatestValues();
2441 if(this.selected === true)
2442 NETDATA.globalSelectionSync.stop();
2444 // update the performance counters
2445 var now = new Date().getTime();
2446 this.tm.last_updated = now;
2448 // don't update last_autorefreshed if this chart is
2449 // forced to be updated with global PanAndZoom
2450 if(NETDATA.globalPanAndZoom.isActive())
2451 this.tm.last_autorefreshed = 0;
2453 if(NETDATA.options.current.parallel_refresher === true && NETDATA.options.current.concurrent_refreshes)
2454 this.tm.last_autorefreshed = Math.round(now / this.data_update_every) * this.data_update_every;
2456 this.tm.last_autorefreshed = now;
2459 this.refresh_dt_ms = now - started;
2460 NETDATA.options.auto_refresher_fast_weight += this.refresh_dt_ms;
2462 if(this.refresh_dt_element !== null)
2463 this.refresh_dt_element.innerHTML = this.refresh_dt_ms.toString();
2466 this.updateChart = function(callback) {
2467 if(this.debug === true)
2468 this.log('updateChart() called.');
2470 if(this._updating === true) {
2471 if(this.debug === true)
2472 this.log('I am already updating...');
2474 if(typeof callback === 'function') callback();
2478 // due to late initialization of charts and libraries
2479 // we need to check this too
2480 if(this.enabled === false) {
2481 if(this.debug === true)
2482 this.log('I am not enabled');
2484 if(typeof callback === 'function') callback();
2488 if(canBeRendered() === false) {
2489 if(typeof callback === 'function') callback();
2493 if(this.chart === null) {
2494 this.getChart(function() { that.updateChart(callback); });
2498 if(this.library.initialized === false) {
2499 if(this.library.enabled === true) {
2500 this.library.initialize(function() { that.updateChart(callback); });
2504 error('chart library "' + this.library_name + '" is not available.');
2505 if(typeof callback === 'function') callback();
2510 this.clearSelection();
2513 if(this.debug === true)
2514 this.log('updating from ' + this.data_url);
2516 this._updating = true;
2518 this.xhr = $.ajax( {
2520 crossDomain: NETDATA.options.crossDomainAjax,
2524 .success(function(data) {
2525 if(that.debug === true)
2526 that.log('data received. updating chart.');
2528 that.updateChartWithData(data);
2531 error('data download failed for url: ' + that.data_url);
2533 .always(function() {
2534 this._updating = false;
2535 if(typeof callback === 'function') callback();
2541 this.isVisible = function(nocache) {
2542 if(typeof nocache === 'undefined')
2545 // this.log('last_visible_check: ' + this.tm.last_visible_check + ', last_page_scroll: ' + NETDATA.options.last_page_scroll);
2547 // caching - we do not evaluate the charts visibility
2548 // if the page has not been scrolled since the last check
2549 if(nocache === false && this.tm.last_visible_check > NETDATA.options.last_page_scroll)
2550 return this.___isVisible___;
2552 this.tm.last_visible_check = new Date().getTime();
2554 var wh = window.innerHeight;
2555 var x = this.element.getBoundingClientRect();
2559 if(x.width === 0 || x.height === 0) {
2561 this.___isVisible___ = false;
2562 return this.___isVisible___;
2565 if(x.top < 0 && -x.top > x.height) {
2566 // the chart is entirely above
2567 ret = -x.top - x.height;
2569 else if(x.top > wh) {
2570 // the chart is entirely below
2574 if(ret > tolerance) {
2575 // the chart is too far
2578 this.___isVisible___ = false;
2579 return this.___isVisible___;
2582 // the chart is inside or very close
2585 this.___isVisible___ = true;
2586 return this.___isVisible___;
2590 this.isAutoRefreshed = function() {
2591 return (this.current.autorefresh);
2594 this.canBeAutoRefreshed = function() {
2595 now = new Date().getTime();
2597 if(this.enabled === false) {
2598 if(this.debug === true)
2599 this.log('I am not enabled');
2604 if(this.library === null || this.library.enabled === false) {
2605 error('charting library "' + this.library_name + '" is not available');
2606 if(this.debug === true)
2607 this.log('My chart library ' + this.library_name + ' is not available');
2612 if(this.isVisible() === false) {
2613 if(NETDATA.options.debug.visibility === true || this.debug === true)
2614 this.log('I am not visible');
2619 if(this.current.force_update_at !== 0 && this.current.force_update_at < now) {
2620 if(this.debug === true)
2621 this.log('timed force update detected - allowing this update');
2623 this.current.force_update_at = 0;
2627 if(this.isAutoRefreshed() === true) {
2628 // allow the first update, even if the page is not visible
2629 if(this.updates_counter && this.updates_since_last_unhide && NETDATA.options.page_is_visible === false) {
2630 if(NETDATA.options.debug.focus === true || this.debug === true)
2631 this.log('canBeAutoRefreshed(): page does not have focus');
2636 if(this.needsRecreation() === true) {
2637 if(this.debug === true)
2638 this.log('canBeAutoRefreshed(): needs re-creation.');
2643 // options valid only for autoRefresh()
2644 if(NETDATA.options.auto_refresher_stop_until === 0 || NETDATA.options.auto_refresher_stop_until < now) {
2645 if(NETDATA.globalPanAndZoom.isActive()) {
2646 if(NETDATA.globalPanAndZoom.shouldBeAutoRefreshed(this)) {
2647 if(this.debug === true)
2648 this.log('canBeAutoRefreshed(): global panning: I need an update.');
2653 if(this.debug === true)
2654 this.log('canBeAutoRefreshed(): global panning: I am already up to date.');
2660 if(this.selected === true) {
2661 if(this.debug === true)
2662 this.log('canBeAutoRefreshed(): I have a selection in place.');
2667 if(this.paused === true) {
2668 if(this.debug === true)
2669 this.log('canBeAutoRefreshed(): I am paused.');
2674 if(now - this.tm.last_autorefreshed >= this.data_update_every) {
2675 if(this.debug === true)
2676 this.log('canBeAutoRefreshed(): It is time to update me.');
2686 this.autoRefresh = function(callback) {
2687 if(this.canBeAutoRefreshed() === true) {
2688 this.updateChart(callback);
2691 if(typeof callback !== 'undefined')
2696 this._defaultsFromDownloadedChart = function(chart) {
2698 this.chart_url = chart.url;
2699 this.data_update_every = chart.update_every * 1000;
2700 this.data_points = Math.round(this.chartWidth() / this.chartPixelsPerPoint());
2701 this.tm.last_info_downloaded = new Date().getTime();
2703 if(this.title === null)
2704 this.title = chart.title;
2706 if(this.units === null)
2707 this.units = chart.units;
2710 // fetch the chart description from the netdata server
2711 this.getChart = function(callback) {
2712 this.chart = NETDATA.chartRegistry.get(this.host, this.id);
2714 this._defaultsFromDownloadedChart(this.chart);
2715 if(typeof callback === 'function') callback();
2718 this.chart_url = "/api/v1/chart?chart=" + this.id;
2720 if(this.debug === true)
2721 this.log('downloading ' + this.chart_url);
2724 url: this.host + this.chart_url,
2725 crossDomain: NETDATA.options.crossDomainAjax,
2729 .done(function(chart) {
2730 chart.url = that.chart_url;
2731 that._defaultsFromDownloadedChart(chart);
2732 NETDATA.chartRegistry.add(that.host, that.id, chart);
2735 NETDATA.error(404, that.chart_url);
2736 error('chart not found on url "' + that.chart_url + '"');
2738 .always(function() {
2739 if(typeof callback === 'function') callback();
2744 // ============================================================================================================
2750 NETDATA.resetAllCharts = function(state) {
2751 // first clear the global selection sync
2752 // to make sure no chart is in selected state
2753 state.globalSelectionSyncStop();
2755 // there are 2 possibilities here
2756 // a. state is the global Pan and Zoom master
2757 // b. state is not the global Pan and Zoom master
2759 if(NETDATA.globalPanAndZoom.isMaster(state) === false)
2762 // clear the global Pan and Zoom
2763 // this will also refresh the master
2764 // and unblock any charts currently mirroring the master
2765 NETDATA.globalPanAndZoom.clearMaster();
2767 // if we were not the master, reset our status too
2768 // this is required because most probably the mouse
2769 // is over this chart, blocking it from autorefreshing
2770 if(master === false && (state.paused === true || state.selected === true))
2774 // get or create a chart state, given a DOM element
2775 NETDATA.chartState = function(element) {
2776 var state = $(element).data('netdata-state-object') || null;
2777 if(state === null) {
2778 state = new chartState(element);
2779 $(element).data('netdata-state-object', state);
2784 // ----------------------------------------------------------------------------------------------------------------
2785 // Library functions
2787 // Load a script without jquery
2788 // This is used to load jquery - after it is loaded, we use jquery
2789 NETDATA._loadjQuery = function(callback) {
2790 if(typeof jQuery === 'undefined') {
2791 if(NETDATA.options.debug.main_loop === true)
2792 console.log('loading ' + NETDATA.jQuery);
2794 var script = document.createElement('script');
2795 script.type = 'text/javascript';
2796 script.async = true;
2797 script.src = NETDATA.jQuery;
2799 // script.onabort = onError;
2800 script.onerror = function(err, t) { NETDATA.error(101, NETDATA.jQuery); };
2801 if(typeof callback === "function")
2802 script.onload = callback;
2804 var s = document.getElementsByTagName('script')[0];
2805 s.parentNode.insertBefore(script, s);
2807 else if(typeof callback === "function")
2811 NETDATA._loadCSS = function(filename) {
2812 // don't use jQuery here
2813 // styles are loaded before jQuery
2814 // to eliminate showing an unstyled page to the user
2816 var fileref = document.createElement("link");
2817 fileref.setAttribute("rel", "stylesheet");
2818 fileref.setAttribute("type", "text/css");
2819 fileref.setAttribute("href", filename);
2821 if (typeof fileref !== 'undefined')
2822 document.getElementsByTagName("head")[0].appendChild(fileref);
2825 NETDATA.colorHex2Rgb = function(hex) {
2826 // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
2827 var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
2828 hex = hex.replace(shorthandRegex, function(m, r, g, b) {
2829 return r + r + g + g + b + b;
2832 var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
2834 r: parseInt(result[1], 16),
2835 g: parseInt(result[2], 16),
2836 b: parseInt(result[3], 16)
2840 NETDATA.colorLuminance = function(hex, lum) {
2841 // validate hex string
2842 hex = String(hex).replace(/[^0-9a-f]/gi, '');
2844 hex = hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2];
2848 // convert to decimal and change luminosity
2849 var rgb = "#", c, i;
2850 for (i = 0; i < 3; i++) {
2851 c = parseInt(hex.substr(i*2,2), 16);
2852 c = Math.round(Math.min(Math.max(0, c + (c * lum)), 255)).toString(16);
2853 rgb += ("00"+c).substr(c.length);
2859 NETDATA.guid = function() {
2861 return Math.floor((1 + Math.random()) * 0x10000)
2866 return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
2869 NETDATA.zeropad = function(x) {
2870 if(x > -10 && x < 10) return '0' + x.toString();
2871 else return x.toString();
2874 // user function to signal us the DOM has been
2876 NETDATA.updatedDom = function() {
2877 NETDATA.options.updated_dom = true;
2880 NETDATA.ready = function(callback) {
2881 NETDATA.options.pauseCallback = callback;
2884 NETDATA.pause = function(callback) {
2885 if(NETDATA.options.pause === true)
2888 NETDATA.options.pauseCallback = callback;
2891 NETDATA.unpause = function() {
2892 NETDATA.options.pauseCallback = null;
2893 NETDATA.options.updated_dom = true;
2894 NETDATA.options.pause = false;
2897 // ----------------------------------------------------------------------------------------------------------------
2899 // this is purely sequencial charts refresher
2900 // it is meant to be autonomous
2901 NETDATA.chartRefresherNoParallel = function(index) {
2902 if(NETDATA.options.debug.mail_loop === true)
2903 console.log('NETDATA.chartRefresherNoParallel(' + index + ')');
2905 if(NETDATA.options.updated_dom === true) {
2906 // the dom has been updated
2907 // get the dom parts again
2908 NETDATA.parseDom(NETDATA.chartRefresher);
2911 if(index >= NETDATA.options.targets.length) {
2912 if(NETDATA.options.debug.main_loop === true)
2913 console.log('waiting to restart main loop...');
2915 NETDATA.options.auto_refresher_fast_weight = 0;
2917 setTimeout(function() {
2918 NETDATA.chartRefresher();
2919 }, NETDATA.options.current.idle_between_loops);
2922 var state = NETDATA.options.targets[index];
2924 if(NETDATA.options.auto_refresher_fast_weight < NETDATA.options.current.fast_render_timeframe) {
2925 if(NETDATA.options.debug.main_loop === true)
2926 console.log('fast rendering...');
2928 state.autoRefresh(function() {
2929 NETDATA.chartRefresherNoParallel(++index);
2933 if(NETDATA.options.debug.main_loop === true) console.log('waiting for next refresh...');
2934 NETDATA.options.auto_refresher_fast_weight = 0;
2936 setTimeout(function() {
2937 state.autoRefresh(function() {
2938 NETDATA.chartRefresherNoParallel(++index);
2940 }, NETDATA.options.current.idle_between_charts);
2945 // this is part of the parallel refresher
2946 // its cause is to refresh sequencially all the charts
2947 // that depend on chart library initialization
2948 // it will call the parallel refresher back
2949 // as soon as it sees a chart that its chart library
2951 NETDATA.chartRefresher_unitialized = function() {
2952 if(NETDATA.options.updated_dom === true) {
2953 // the dom has been updated
2954 // get the dom parts again
2955 NETDATA.parseDom(NETDATA.chartRefresher);
2959 if(NETDATA.options.sequencial.length === 0)
2960 NETDATA.chartRefresher();
2962 var state = NETDATA.options.sequencial.pop();
2963 if(state.library.initialized === true)
2964 NETDATA.chartRefresher();
2966 state.autoRefresh(NETDATA.chartRefresher_unitialized);
2970 NETDATA.chartRefresherWaitTime = function() {
2971 return NETDATA.options.current.idle_parallel_loops;
2974 // the default refresher
2975 // it will create 2 sets of charts:
2976 // - the ones that can be refreshed in parallel
2977 // - the ones that depend on something else
2978 // the first set will be executed in parallel
2979 // the second will be given to NETDATA.chartRefresher_unitialized()
2980 NETDATA.chartRefresher = function() {
2981 if(NETDATA.options.pause === true) {
2982 // console.log('auto-refresher is paused');
2983 setTimeout(NETDATA.chartRefresher,
2984 NETDATA.chartRefresherWaitTime());
2988 if(typeof NETDATA.options.pauseCallback === 'function') {
2989 // console.log('auto-refresher is calling pauseCallback');
2990 NETDATA.options.pause = true;
2991 NETDATA.options.pauseCallback();
2992 NETDATA.chartRefresher();
2996 if(NETDATA.options.current.parallel_refresher === false) {
2997 NETDATA.chartRefresherNoParallel(0);
3001 if(NETDATA.options.updated_dom === true) {
3002 // the dom has been updated
3003 // get the dom parts again
3004 NETDATA.parseDom(NETDATA.chartRefresher);
3008 var parallel = new Array();
3009 var targets = NETDATA.options.targets;
3010 var len = targets.length;
3012 if(targets[len].isVisible() === false)
3015 var state = targets[len];
3016 if(state.library.initialized === false) {
3017 if(state.library.enabled === true) {
3018 state.library.initialize(NETDATA.chartRefresher);
3022 state.error('chart library "' + state.library_name + '" is not enabled.');
3026 parallel.unshift(state);
3029 if(parallel.length > 0) {
3030 var parallel_jobs = parallel.length;
3032 // this will execute the jobs in parallel
3033 $(parallel).each(function() {
3034 this.autoRefresh(function() {
3037 if(parallel_jobs === 0) {
3038 setTimeout(NETDATA.chartRefresher,
3039 NETDATA.chartRefresherWaitTime());
3045 setTimeout(NETDATA.chartRefresher,
3046 NETDATA.chartRefresherWaitTime());
3050 NETDATA.parseDom = function(callback) {
3051 NETDATA.options.last_page_scroll = new Date().getTime();
3052 NETDATA.options.updated_dom = false;
3054 var targets = $('div[data-netdata]'); //.filter(':visible');
3056 if(NETDATA.options.debug.main_loop === true)
3057 console.log('DOM updated - there are ' + targets.length + ' charts on page.');
3059 NETDATA.options.targets = new Array();
3060 var len = targets.length;
3062 // the initialization will take care of sizing
3063 // and the "loading..." message
3064 NETDATA.options.targets.push(NETDATA.chartState(targets[len]));
3067 if(typeof callback === 'function') callback();
3070 // this is the main function - where everything starts
3071 NETDATA.start = function() {
3072 // this should be called only once
3074 NETDATA.options.page_is_visible = true;
3076 $(window).blur(function() {
3077 if(NETDATA.options.current.stop_updates_when_focus_is_lost === true) {
3078 NETDATA.options.page_is_visible = false;
3079 if(NETDATA.options.debug.focus === true)
3080 console.log('Lost Focus!');
3084 $(window).focus(function() {
3085 if(NETDATA.options.current.stop_updates_when_focus_is_lost === true) {
3086 NETDATA.options.page_is_visible = true;
3087 if(NETDATA.options.debug.focus === true)
3088 console.log('Focus restored!');
3092 if(typeof document.hasFocus === 'function' && !document.hasFocus()) {
3093 if(NETDATA.options.current.stop_updates_when_focus_is_lost === true) {
3094 NETDATA.options.page_is_visible = false;
3095 if(NETDATA.options.debug.focus === true)
3096 console.log('Document has no focus!');
3100 // bootstrap tab switching
3101 $('a[data-toggle="tab"]').on('shown.bs.tab', NETDATA.onscroll);
3103 // bootstrap modal switching
3104 $('.modal').on('hidden.bs.modal', NETDATA.onscroll);
3105 $('.modal').on('shown.bs.modal', NETDATA.onscroll);
3107 NETDATA.parseDom(NETDATA.chartRefresher);
3110 // ----------------------------------------------------------------------------------------------------------------
3113 NETDATA.peityInitialize = function(callback) {
3114 if(typeof netdataNoPeitys === 'undefined' || !netdataNoPeitys) {
3116 url: NETDATA.peity_js,
3121 NETDATA.registerChartLibrary('peity', NETDATA.peity_js);
3124 NETDATA.chartLibraries.peity.enabled = false;
3125 NETDATA.error(100, NETDATA.peity_js);
3127 .always(function() {
3128 if(typeof callback === "function")
3133 NETDATA.chartLibraries.peity.enabled = false;
3134 if(typeof callback === "function")
3139 NETDATA.peityChartUpdate = function(state, data) {
3140 state.peity_instance.innerHTML = data.result;
3142 if(state.peity_options.stroke !== state.chartColors()[0]) {
3143 state.peity_options.stroke = state.chartColors()[0];
3144 if(state.chart.chart_type === 'line')
3145 state.peity_options.fill = NETDATA.themes.current.background;
3147 state.peity_options.fill = NETDATA.colorLuminance(state.chartColors()[0], NETDATA.chartDefaults.fill_luminance);
3150 $(state.peity_instance).peity('line', state.peity_options);
3154 NETDATA.peityChartCreate = function(state, data) {
3155 state.peity_instance = document.createElement('div');
3156 state.element_chart.appendChild(state.peity_instance);
3158 var self = $(state.element);
3159 state.peity_options = {
3160 stroke: NETDATA.themes.current.foreground,
3161 strokeWidth: self.data('peity-strokewidth') || 1,
3162 width: state.chartWidth(),
3163 height: state.chartHeight(),
3164 fill: NETDATA.themes.current.foreground
3167 NETDATA.peityChartUpdate(state, data);
3171 // ----------------------------------------------------------------------------------------------------------------
3174 NETDATA.sparklineInitialize = function(callback) {
3175 if(typeof netdataNoSparklines === 'undefined' || !netdataNoSparklines) {
3177 url: NETDATA.sparkline_js,
3182 NETDATA.registerChartLibrary('sparkline', NETDATA.sparkline_js);
3185 NETDATA.chartLibraries.sparkline.enabled = false;
3186 NETDATA.error(100, NETDATA.sparkline_js);
3188 .always(function() {
3189 if(typeof callback === "function")
3194 NETDATA.chartLibraries.sparkline.enabled = false;
3195 if(typeof callback === "function")
3200 NETDATA.sparklineChartUpdate = function(state, data) {
3201 state.sparkline_options.width = state.chartWidth();
3202 state.sparkline_options.height = state.chartHeight();
3204 $(state.element_chart).sparkline(data.result, state.sparkline_options);
3208 NETDATA.sparklineChartCreate = function(state, data) {
3209 var self = $(state.element);
3210 var type = self.data('sparkline-type') || 'line';
3211 var lineColor = self.data('sparkline-linecolor') || state.chartColors()[0];
3212 var fillColor = self.data('sparkline-fillcolor') || (state.chart.chart_type === 'line')?NETDATA.themes.current.background:NETDATA.colorLuminance(lineColor, NETDATA.chartDefaults.fill_luminance);
3213 var chartRangeMin = self.data('sparkline-chartrangemin') || undefined;
3214 var chartRangeMax = self.data('sparkline-chartrangemax') || undefined;
3215 var composite = self.data('sparkline-composite') || undefined;
3216 var enableTagOptions = self.data('sparkline-enabletagoptions') || undefined;
3217 var tagOptionPrefix = self.data('sparkline-tagoptionprefix') || undefined;
3218 var tagValuesAttribute = self.data('sparkline-tagvaluesattribute') || undefined;
3219 var disableHiddenCheck = self.data('sparkline-disablehiddencheck') || undefined;
3220 var defaultPixelsPerValue = self.data('sparkline-defaultpixelspervalue') || undefined;
3221 var spotColor = self.data('sparkline-spotcolor') || undefined;
3222 var minSpotColor = self.data('sparkline-minspotcolor') || undefined;
3223 var maxSpotColor = self.data('sparkline-maxspotcolor') || undefined;
3224 var spotRadius = self.data('sparkline-spotradius') || undefined;
3225 var valueSpots = self.data('sparkline-valuespots') || undefined;
3226 var highlightSpotColor = self.data('sparkline-highlightspotcolor') || undefined;
3227 var highlightLineColor = self.data('sparkline-highlightlinecolor') || undefined;
3228 var lineWidth = self.data('sparkline-linewidth') || undefined;
3229 var normalRangeMin = self.data('sparkline-normalrangemin') || undefined;
3230 var normalRangeMax = self.data('sparkline-normalrangemax') || undefined;
3231 var drawNormalOnTop = self.data('sparkline-drawnormalontop') || undefined;
3232 var xvalues = self.data('sparkline-xvalues') || undefined;
3233 var chartRangeClip = self.data('sparkline-chartrangeclip') || undefined;
3234 var xvalues = self.data('sparkline-xvalues') || undefined;
3235 var chartRangeMinX = self.data('sparkline-chartrangeminx') || undefined;
3236 var chartRangeMaxX = self.data('sparkline-chartrangemaxx') || undefined;
3237 var disableInteraction = self.data('sparkline-disableinteraction') || false;
3238 var disableTooltips = self.data('sparkline-disabletooltips') || false;
3239 var disableHighlight = self.data('sparkline-disablehighlight') || false;
3240 var highlightLighten = self.data('sparkline-highlightlighten') || 1.4;
3241 var highlightColor = self.data('sparkline-highlightcolor') || undefined;
3242 var tooltipContainer = self.data('sparkline-tooltipcontainer') || undefined;
3243 var tooltipClassname = self.data('sparkline-tooltipclassname') || undefined;
3244 var tooltipFormat = self.data('sparkline-tooltipformat') || undefined;
3245 var tooltipPrefix = self.data('sparkline-tooltipprefix') || undefined;
3246 var tooltipSuffix = self.data('sparkline-tooltipsuffix') || ' ' + state.units;
3247 var tooltipSkipNull = self.data('sparkline-tooltipskipnull') || true;
3248 var tooltipValueLookups = self.data('sparkline-tooltipvaluelookups') || undefined;
3249 var tooltipFormatFieldlist = self.data('sparkline-tooltipformatfieldlist') || undefined;
3250 var tooltipFormatFieldlistKey = self.data('sparkline-tooltipformatfieldlistkey') || undefined;
3251 var numberFormatter = self.data('sparkline-numberformatter') || function(n){ return n.toFixed(2); };
3252 var numberDigitGroupSep = self.data('sparkline-numberdigitgroupsep') || undefined;
3253 var numberDecimalMark = self.data('sparkline-numberdecimalmark') || undefined;
3254 var numberDigitGroupCount = self.data('sparkline-numberdigitgroupcount') || undefined;
3255 var animatedZooms = self.data('sparkline-animatedzooms') || false;
3257 state.sparkline_options = {
3259 lineColor: lineColor,
3260 fillColor: fillColor,
3261 chartRangeMin: chartRangeMin,
3262 chartRangeMax: chartRangeMax,
3263 composite: composite,
3264 enableTagOptions: enableTagOptions,
3265 tagOptionPrefix: tagOptionPrefix,
3266 tagValuesAttribute: tagValuesAttribute,
3267 disableHiddenCheck: disableHiddenCheck,
3268 defaultPixelsPerValue: defaultPixelsPerValue,
3269 spotColor: spotColor,
3270 minSpotColor: minSpotColor,
3271 maxSpotColor: maxSpotColor,
3272 spotRadius: spotRadius,
3273 valueSpots: valueSpots,
3274 highlightSpotColor: highlightSpotColor,
3275 highlightLineColor: highlightLineColor,
3276 lineWidth: lineWidth,
3277 normalRangeMin: normalRangeMin,
3278 normalRangeMax: normalRangeMax,
3279 drawNormalOnTop: drawNormalOnTop,
3281 chartRangeClip: chartRangeClip,
3282 chartRangeMinX: chartRangeMinX,
3283 chartRangeMaxX: chartRangeMaxX,
3284 disableInteraction: disableInteraction,
3285 disableTooltips: disableTooltips,
3286 disableHighlight: disableHighlight,
3287 highlightLighten: highlightLighten,
3288 highlightColor: highlightColor,
3289 tooltipContainer: tooltipContainer,
3290 tooltipClassname: tooltipClassname,
3291 tooltipChartTitle: state.title,
3292 tooltipFormat: tooltipFormat,
3293 tooltipPrefix: tooltipPrefix,
3294 tooltipSuffix: tooltipSuffix,
3295 tooltipSkipNull: tooltipSkipNull,
3296 tooltipValueLookups: tooltipValueLookups,
3297 tooltipFormatFieldlist: tooltipFormatFieldlist,
3298 tooltipFormatFieldlistKey: tooltipFormatFieldlistKey,
3299 numberFormatter: numberFormatter,
3300 numberDigitGroupSep: numberDigitGroupSep,
3301 numberDecimalMark: numberDecimalMark,
3302 numberDigitGroupCount: numberDigitGroupCount,
3303 animatedZooms: animatedZooms,
3304 width: state.chartWidth(),
3305 height: state.chartHeight()
3308 $(state.element_chart).sparkline(data.result, state.sparkline_options);
3312 // ----------------------------------------------------------------------------------------------------------------
3319 NETDATA.dygraphSetSelection = function(state, t) {
3320 if(typeof state.dygraph_instance !== 'undefined') {
3321 var r = state.calculateRowForTime(t);
3323 state.dygraph_instance.setSelection(r);
3325 state.dygraph_instance.clearSelection();
3326 state.legendShowUndefined();
3333 NETDATA.dygraphClearSelection = function(state, t) {
3334 if(typeof state.dygraph_instance !== 'undefined') {
3335 state.dygraph_instance.clearSelection();
3340 NETDATA.dygraphSmoothInitialize = function(callback) {
3342 url: NETDATA.dygraph_smooth_js,
3347 NETDATA.dygraph.smooth = true;
3348 smoothPlotter.smoothing = 0.3;
3351 NETDATA.dygraph.smooth = false;
3353 .always(function() {
3354 if(typeof callback === "function")
3359 NETDATA.dygraphInitialize = function(callback) {
3360 if(typeof netdataNoDygraphs === 'undefined' || !netdataNoDygraphs) {
3362 url: NETDATA.dygraph_js,
3367 NETDATA.registerChartLibrary('dygraph', NETDATA.dygraph_js);
3370 NETDATA.chartLibraries.dygraph.enabled = false;
3371 NETDATA.error(100, NETDATA.dygraph_js);
3373 .always(function() {
3374 if(NETDATA.chartLibraries.dygraph.enabled === true && NETDATA.options.current.smooth_plot === true)
3375 NETDATA.dygraphSmoothInitialize(callback);
3376 else if(typeof callback === "function")
3381 NETDATA.chartLibraries.dygraph.enabled = false;
3382 if(typeof callback === "function")
3387 NETDATA.dygraphChartUpdate = function(state, data) {
3388 var dygraph = state.dygraph_instance;
3390 if(typeof dygraph === 'undefined')
3391 return NETDATA.dygraphChartCreate(state, data);
3393 // when the chart is not visible, and hidden
3394 // if there is a window resize, dygraph detects
3395 // its element size as 0x0.
3396 // this will make it re-appear properly
3398 if(state.tm.last_unhidden > state.dygraph_last_rendered)
3402 file: data.result.data,
3403 colors: state.chartColors(),
3404 labels: data.result.labels,
3405 labelsDivWidth: state.chartWidth() - 70,
3406 visibility: state.dimensions_visibility.selected2BooleanArray(state.data.dimension_names)
3409 if(state.dygraph_force_zoom === true) {
3410 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3411 state.log('dygraphChartUpdate() forced zoom update');
3413 options.dateWindow = (state.requested_padding !== null)?[ state.view_after, state.view_before ]:null;
3414 options.valueRange = null;
3415 options.isZoomedIgnoreProgrammaticZoom = true;
3416 state.dygraph_force_zoom = false;
3418 else if(state.current.name !== 'auto') {
3419 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3420 state.log('dygraphChartUpdate() loose update');
3423 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3424 state.log('dygraphChartUpdate() strict update');
3426 options.dateWindow = (state.requested_padding !== null)?[ state.view_after, state.view_before ]:null;
3427 options.valueRange = null;
3428 options.isZoomedIgnoreProgrammaticZoom = true;
3431 if(state.dygraph_smooth_eligible === true) {
3432 if((NETDATA.options.current.smooth_plot === true && state.dygraph_options.plotter !== smoothPlotter)
3433 || (NETDATA.options.current.smooth_plot === false && state.dygraph_options.plotter === smoothPlotter)) {
3434 NETDATA.dygraphChartCreate(state, data);
3439 dygraph.updateOptions(options);
3441 state.dygraph_last_rendered = new Date().getTime();
3445 NETDATA.dygraphChartCreate = function(state, data) {
3446 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3447 state.log('dygraphChartCreate()');
3449 var self = $(state.element);
3451 var chart_type = state.chart.chart_type;
3452 if(chart_type === 'stacked' && data.dimensions === 1) chart_type = 'area';
3453 chart_type = self.data('dygraph-type') || chart_type;
3455 var smooth = (chart_type === 'line' && !NETDATA.chartLibraries.dygraph.isSparkline(state))?true:false;
3456 smooth = self.data('dygraph-smooth') || smooth;
3458 if(NETDATA.dygraph.smooth === false)
3461 var strokeWidth = (chart_type === 'stacked')?0.1:((smooth)?1.5:0.7)
3462 var highlightCircleSize = (NETDATA.chartLibraries.dygraph.isSparkline(state))?3:4;
3464 state.dygraph_options = {
3465 colors: self.data('dygraph-colors') || state.chartColors(),
3467 // leave a few pixels empty on the right of the chart
3468 rightGap: self.data('dygraph-rightgap') || 5,
3469 showRangeSelector: self.data('dygraph-showrangeselector') || false,
3470 showRoller: self.data('dygraph-showroller') || false,
3472 title: self.data('dygraph-title') || state.title,
3473 titleHeight: self.data('dygraph-titleheight') || 19,
3475 legend: self.data('dygraph-legend') || 'always', // 'onmouseover',
3476 labels: data.result.labels,
3477 labelsDiv: self.data('dygraph-labelsdiv') || state.element_legend_childs.hidden,
3478 labelsDivStyles: self.data('dygraph-labelsdivstyles') || { 'fontSize':'1px' },
3479 labelsDivWidth: self.data('dygraph-labelsdivwidth') || state.chartWidth() - 70,
3480 labelsSeparateLines: self.data('dygraph-labelsseparatelines') || true,
3481 labelsShowZeroValues: self.data('dygraph-labelsshowzerovalues') || true,
3484 showLabelsOnHighlight: self.data('dygraph-showlabelsonhighlight') || true,
3485 hideOverlayOnMouseOut: self.data('dygraph-hideoverlayonmouseout') || true,
3487 ylabel: state.units,
3488 yLabelWidth: self.data('dygraph-ylabelwidth') || 12,
3490 // the function to plot the chart
3493 // The width of the lines connecting data points. This can be used to increase the contrast or some graphs.
3494 strokeWidth: self.data('dygraph-strokewidth') || strokeWidth,
3495 strokePattern: self.data('dygraph-strokepattern') || undefined,
3497 // The size of the dot to draw on each point in pixels (see drawPoints). A dot is always drawn when a point is "isolated",
3498 // i.e. there is a missing point on either side of it. This also controls the size of those dots.
3499 drawPoints: self.data('dygraph-drawpoints') || false,
3501 // Draw points at the edges of gaps in the data. This improves visibility of small data segments or other data irregularities.
3502 drawGapEdgePoints: self.data('dygraph-drawgapedgepoints') || true,
3504 connectSeparatedPoints: self.data('dygraph-connectseparatedpoints') || false,
3505 pointSize: self.data('dygraph-pointsize') || 1,
3507 // enabling this makes the chart with little square lines
3508 stepPlot: self.data('dygraph-stepplot') || false,
3510 // Draw a border around graph lines to make crossing lines more easily distinguishable. Useful for graphs with many lines.
3511 strokeBorderColor: self.data('dygraph-strokebordercolor') || NETDATA.themes.current.background,
3512 strokeBorderWidth: self.data('dygraph-strokeborderwidth') || (chart_type === 'stacked')?0.0:0.0,
3514 fillGraph: self.data('dygraph-fillgraph') || (chart_type === 'area' || chart_type === 'stacked')?true:false,
3515 fillAlpha: self.data('dygraph-fillalpha') || (chart_type === 'stacked')?NETDATA.options.current.color_fill_opacity_stacked:NETDATA.options.current.color_fill_opacity_area,
3516 stackedGraph: self.data('dygraph-stackedgraph') || (chart_type === 'stacked')?true:false,
3517 stackedGraphNaNFill: self.data('dygraph-stackedgraphnanfill') || 'none',
3519 drawAxis: self.data('dygraph-drawaxis') || true,
3520 axisLabelFontSize: self.data('dygraph-axislabelfontsize') || 10,
3521 axisLineColor: self.data('dygraph-axislinecolor') || NETDATA.themes.current.axis,
3522 axisLineWidth: self.data('dygraph-axislinewidth') || 0.3,
3524 drawGrid: self.data('dygraph-drawgrid') || true,
3525 drawXGrid: self.data('dygraph-drawxgrid') || undefined,
3526 drawYGrid: self.data('dygraph-drawygrid') || undefined,
3527 gridLinePattern: self.data('dygraph-gridlinepattern') || null,
3528 gridLineWidth: self.data('dygraph-gridlinewidth') || 0.3,
3529 gridLineColor: self.data('dygraph-gridlinecolor') || NETDATA.themes.current.grid,
3531 maxNumberWidth: self.data('dygraph-maxnumberwidth') || 8,
3532 sigFigs: self.data('dygraph-sigfigs') || null,
3533 digitsAfterDecimal: self.data('dygraph-digitsafterdecimal') || 2,
3534 valueFormatter: self.data('dygraph-valueformatter') || function(x){ return x.toFixed(2); },
3536 highlightCircleSize: self.data('dygraph-highlightcirclesize') || highlightCircleSize,
3537 highlightSeriesOpts: self.data('dygraph-highlightseriesopts') || null, // TOO SLOW: { strokeWidth: 1.5 },
3538 highlightSeriesBackgroundAlpha: self.data('dygraph-highlightseriesbackgroundalpha') || null, // TOO SLOW: (chart_type === 'stacked')?0.7:0.5,
3540 pointClickCallback: self.data('dygraph-pointclickcallback') || undefined,
3541 visibility: state.dimensions_visibility.selected2BooleanArray(state.data.dimension_names),
3545 ticker: Dygraph.dateTicker,
3546 axisLabelFormatter: function (d, gran) {
3547 return NETDATA.zeropad(d.getHours()) + ":" + NETDATA.zeropad(d.getMinutes()) + ":" + NETDATA.zeropad(d.getSeconds());
3549 valueFormatter: function (ms) {
3550 var d = new Date(ms);
3551 return d.toLocaleDateString() + ' ' + d.toLocaleTimeString();
3552 // return NETDATA.zeropad(d.getHours()) + ":" + NETDATA.zeropad(d.getMinutes()) + ":" + NETDATA.zeropad(d.getSeconds());
3557 valueFormatter: function (x) {
3558 // we format legends with the state object
3559 // no need to do anything here
3560 // return (Math.round(x*100) / 100).toLocaleString();
3561 // return state.legendFormatValue(x);
3566 legendFormatter: function(data) {
3567 var elements = state.element_legend_childs;
3569 // if the hidden div is not there
3570 // we are not managing the legend
3571 if(elements.hidden === null) return;
3573 if (typeof data.x !== 'undefined') {
3574 state.legendSetDate(data.x);
3575 var i = data.series.length;
3577 var series = data.series[i];
3578 if(!series.isVisible) continue;
3579 state.legendSetLabelValue(series.label, series.y);
3585 drawCallback: function(dygraph, is_initial) {
3586 if(state.current.name !== 'auto' && state.dygraph_user_action === true) {
3587 state.dygraph_user_action = false;
3589 var x_range = dygraph.xAxisRange();
3590 var after = Math.round(x_range[0]);
3591 var before = Math.round(x_range[1]);
3593 if(NETDATA.options.debug.dygraph === true)
3594 state.log('dygraphDrawCallback(dygraph, ' + is_initial + '): ' + (after / 1000).toString() + ' - ' + (before / 1000).toString());
3596 if(before <= state.netdata_last && after >= state.netdata_first)
3597 state.updateChartPanOrZoom(after, before);
3600 zoomCallback: function(minDate, maxDate, yRanges) {
3601 if(NETDATA.options.debug.dygraph === true)
3602 state.log('dygraphZoomCallback()');
3604 state.globalSelectionSyncStop();
3605 state.globalSelectionSyncDelay();
3606 state.setMode('zoom');
3608 // refresh it to the greatest possible zoom level
3609 state.dygraph_user_action = true;
3610 state.dygraph_force_zoom = true;
3611 state.updateChartPanOrZoom(minDate, maxDate);
3613 highlightCallback: function(event, x, points, row, seriesName) {
3614 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3615 state.log('dygraphHighlightCallback()');
3619 // there is a bug in dygraph when the chart is zoomed enough
3620 // the time it thinks is selected is wrong
3621 // here we calculate the time t based on the row number selected
3623 var t = state.data_after + row * state.data_update_every;
3624 // 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);
3626 state.globalSelectionSync(x);
3628 // fix legend zIndex using the internal structures of dygraph legend module
3629 // this works, but it is a hack!
3630 // state.dygraph_instance.plugins_[0].plugin.legend_div_.style.zIndex = 10000;
3632 unhighlightCallback: function(event) {
3633 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3634 state.log('dygraphUnhighlightCallback()');
3636 state.unpauseChart();
3637 state.globalSelectionSyncStop();
3639 interactionModel : {
3640 mousedown: function(event, dygraph, context) {
3641 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3642 state.log('interactionModel.mousedown()');
3644 state.dygraph_user_action = true;
3645 state.globalSelectionSyncStop();
3647 if(NETDATA.options.debug.dygraph === true)
3648 state.log('dygraphMouseDown()');
3650 // Right-click should not initiate a zoom.
3651 if(event.button && event.button === 2) return;
3653 context.initializeMouseDown(event, dygraph, context);
3655 if(event.button && event.button === 1) {
3656 if (event.altKey || event.shiftKey) {
3657 state.setMode('pan');
3658 state.globalSelectionSyncDelay();
3659 Dygraph.startPan(event, dygraph, context);
3662 state.setMode('zoom');
3663 state.globalSelectionSyncDelay();
3664 Dygraph.startZoom(event, dygraph, context);
3668 if (event.altKey || event.shiftKey) {
3669 state.setMode('zoom');
3670 state.globalSelectionSyncDelay();
3671 Dygraph.startZoom(event, dygraph, context);
3674 state.setMode('pan');
3675 state.globalSelectionSyncDelay();
3676 Dygraph.startPan(event, dygraph, context);
3680 mousemove: function(event, dygraph, context) {
3681 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3682 state.log('interactionModel.mousemove()');
3684 if(context.isPanning) {
3685 state.dygraph_user_action = true;
3686 state.globalSelectionSyncStop();
3687 state.globalSelectionSyncDelay();
3688 state.setMode('pan');
3689 Dygraph.movePan(event, dygraph, context);
3691 else if(context.isZooming) {
3692 state.dygraph_user_action = true;
3693 state.globalSelectionSyncStop();
3694 state.globalSelectionSyncDelay();
3695 state.setMode('zoom');
3696 Dygraph.moveZoom(event, dygraph, context);
3699 mouseup: function(event, dygraph, context) {
3700 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3701 state.log('interactionModel.mouseup()');
3703 if (context.isPanning) {
3704 state.dygraph_user_action = true;
3705 state.globalSelectionSyncDelay();
3706 Dygraph.endPan(event, dygraph, context);
3708 else if (context.isZooming) {
3709 state.dygraph_user_action = true;
3710 state.globalSelectionSyncDelay();
3711 Dygraph.endZoom(event, dygraph, context);
3714 click: function(event, dygraph, context) {
3715 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3716 state.log('interactionModel.click()');
3718 event.preventDefault();
3720 dblclick: function(event, dygraph, context) {
3721 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3722 state.log('interactionModel.dblclick()');
3723 NETDATA.resetAllCharts(state);
3725 mousewheel: function(event, dygraph, context) {
3726 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3727 state.log('interactionModel.mousewheel()');
3729 // Take the offset of a mouse event on the dygraph canvas and
3730 // convert it to a pair of percentages from the bottom left.
3731 // (Not top left, bottom is where the lower value is.)
3732 function offsetToPercentage(g, offsetX, offsetY) {
3733 // This is calculating the pixel offset of the leftmost date.
3734 var xOffset = g.toDomCoords(g.xAxisRange()[0], null)[0];
3735 var yar0 = g.yAxisRange(0);
3737 // This is calculating the pixel of the higest value. (Top pixel)
3738 var yOffset = g.toDomCoords(null, yar0[1])[1];
3740 // x y w and h are relative to the corner of the drawing area,
3741 // so that the upper corner of the drawing area is (0, 0).
3742 var x = offsetX - xOffset;
3743 var y = offsetY - yOffset;
3745 // This is computing the rightmost pixel, effectively defining the
3747 var w = g.toDomCoords(g.xAxisRange()[1], null)[0] - xOffset;
3749 // This is computing the lowest pixel, effectively defining the height.
3750 var h = g.toDomCoords(null, yar0[0])[1] - yOffset;
3752 // Percentage from the left.
3753 var xPct = w === 0 ? 0 : (x / w);
3754 // Percentage from the top.
3755 var yPct = h === 0 ? 0 : (y / h);
3757 // The (1-) part below changes it from "% distance down from the top"
3758 // to "% distance up from the bottom".
3759 return [xPct, (1-yPct)];
3762 // Adjusts [x, y] toward each other by zoomInPercentage%
3763 // Split it so the left/bottom axis gets xBias/yBias of that change and
3764 // tight/top gets (1-xBias)/(1-yBias) of that change.
3766 // If a bias is missing it splits it down the middle.
3767 function zoomRange(g, zoomInPercentage, xBias, yBias) {
3768 xBias = xBias || 0.5;
3769 yBias = yBias || 0.5;
3771 function adjustAxis(axis, zoomInPercentage, bias) {
3772 var delta = axis[1] - axis[0];
3773 var increment = delta * zoomInPercentage;
3774 var foo = [increment * bias, increment * (1-bias)];
3776 return [ axis[0] + foo[0], axis[1] - foo[1] ];
3779 var yAxes = g.yAxisRanges();
3781 for (var i = 0; i < yAxes.length; i++) {
3782 newYAxes[i] = adjustAxis(yAxes[i], zoomInPercentage, yBias);
3785 return adjustAxis(g.xAxisRange(), zoomInPercentage, xBias);
3788 if(event.altKey || event.shiftKey) {
3789 state.dygraph_user_action = true;
3791 state.globalSelectionSyncStop();
3792 state.globalSelectionSyncDelay();
3794 // http://dygraphs.com/gallery/interaction-api.js
3795 var normal = (event.detail) ? event.detail * -1 : event.wheelDelta / 40;
3796 var percentage = normal / 50;
3798 if (!(event.offsetX && event.offsetY)){
3799 event.offsetX = event.layerX - event.target.offsetLeft;
3800 event.offsetY = event.layerY - event.target.offsetTop;
3803 var percentages = offsetToPercentage(dygraph, event.offsetX, event.offsetY);
3804 var xPct = percentages[0];
3805 var yPct = percentages[1];
3807 var new_x_range = zoomRange(dygraph, percentage, xPct, yPct);
3809 var after = new_x_range[0];
3810 var before = new_x_range[1];
3812 var first = state.netdata_first + state.data_update_every;
3813 var last = state.netdata_last + state.data_update_every;
3816 after -= (before - last);
3823 state.setMode('zoom');
3824 if(state.updateChartPanOrZoom(after, before) === true)
3825 dygraph.updateOptions({ dateWindow: [ after, before ] });
3827 event.preventDefault();
3830 touchstart: function(event, dygraph, context) {
3831 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3832 state.log('interactionModel.touchstart()');
3834 state.dygraph_user_action = true;
3835 state.setMode('zoom');
3838 Dygraph.defaultInteractionModel.touchstart(event, dygraph, context);
3840 // we overwrite the touch directions at the end, to overwrite
3841 // the internal default of dygraphs
3842 context.touchDirections = { x: true, y: false };
3844 state.dygraph_last_touch_start = new Date().getTime();
3845 state.dygraph_last_touch_move = 0;
3847 if(typeof event.touches[0].pageX === 'number')
3848 state.dygraph_last_touch_page_x = event.touches[0].pageX;
3850 state.dygraph_last_touch_page_x = 0;
3852 touchmove: function(event, dygraph, context) {
3853 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3854 state.log('interactionModel.touchmove()');
3856 state.dygraph_user_action = true;
3857 Dygraph.defaultInteractionModel.touchmove(event, dygraph, context);
3859 state.dygraph_last_touch_move = new Date().getTime();
3861 touchend: function(event, dygraph, context) {
3862 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3863 state.log('interactionModel.touchend()');
3865 state.dygraph_user_action = true;
3866 Dygraph.defaultInteractionModel.touchend(event, dygraph, context);
3868 // if it didn't move, it is a selection
3869 if(state.dygraph_last_touch_move === 0 && state.dygraph_last_touch_page_x !== 0) {
3870 // internal api of dygraphs
3871 var pct = (state.dygraph_last_touch_page_x - (dygraph.plotter_.area.x + state.element.getBoundingClientRect().left)) / dygraph.plotter_.area.w;
3872 var t = Math.round(state.data_after + (state.data_before - state.data_after) * pct);
3873 if(NETDATA.dygraphSetSelection(state, t) === true)
3874 state.globalSelectionSync(t);
3877 // if it was double tap within double click time, reset the charts
3878 var now = new Date().getTime();
3879 if(typeof state.dygraph_last_touch_end !== 'undefined') {
3880 if(state.dygraph_last_touch_move === 0) {
3881 var dt = now - state.dygraph_last_touch_end;
3882 if(dt <= NETDATA.options.current.double_click_speed)
3883 NETDATA.resetAllCharts(state);
3887 // remember the timestamp of the last touch end
3888 state.dygraph_last_touch_end = now;
3893 if(NETDATA.chartLibraries.dygraph.isSparkline(state)) {
3894 state.dygraph_options.drawGrid = false;
3895 state.dygraph_options.drawAxis = false;
3896 state.dygraph_options.title = undefined;
3897 state.dygraph_options.units = undefined;
3898 state.dygraph_options.ylabel = undefined;
3899 state.dygraph_options.yLabelWidth = 0;
3900 state.dygraph_options.labelsDivWidth = 120;
3901 state.dygraph_options.labelsDivStyles.width = '120px';
3902 state.dygraph_options.labelsSeparateLines = true;
3903 state.dygraph_options.rightGap = 0;
3906 if(smooth === true) {
3907 state.dygraph_smooth_eligible = true;
3909 if(NETDATA.options.current.smooth_plot === true)
3910 state.dygraph_options.plotter = smoothPlotter;
3912 else state.dygraph_smooth_eligible = false;
3914 state.dygraph_instance = new Dygraph(state.element_chart,
3915 data.result.data, state.dygraph_options);
3917 state.dygraph_force_zoom = false;
3918 state.dygraph_user_action = false;
3919 state.dygraph_last_rendered = new Date().getTime();
3923 // ----------------------------------------------------------------------------------------------------------------
3926 NETDATA.morrisInitialize = function(callback) {
3927 if(typeof netdataNoMorris === 'undefined' || !netdataNoMorris) {
3929 // morris requires raphael
3930 if(!NETDATA.chartLibraries.raphael.initialized) {
3931 if(NETDATA.chartLibraries.raphael.enabled) {
3932 NETDATA.raphaelInitialize(function() {
3933 NETDATA.morrisInitialize(callback);
3937 NETDATA.chartLibraries.morris.enabled = false;
3938 if(typeof callback === "function")
3943 NETDATA._loadCSS(NETDATA.morris_css);
3946 url: NETDATA.morris_js,
3951 NETDATA.registerChartLibrary('morris', NETDATA.morris_js);
3954 NETDATA.chartLibraries.morris.enabled = false;
3955 NETDATA.error(100, NETDATA.morris_js);
3957 .always(function() {
3958 if(typeof callback === "function")
3964 NETDATA.chartLibraries.morris.enabled = false;
3965 if(typeof callback === "function")
3970 NETDATA.morrisChartUpdate = function(state, data) {
3971 state.morris_instance.setData(data.result.data);
3975 NETDATA.morrisChartCreate = function(state, data) {
3977 state.morris_options = {
3978 element: state.element_chart.id,
3979 data: data.result.data,
3981 ykeys: data.dimension_names,
3982 labels: data.dimension_names,
3988 continuousLine: false,
3989 behaveLikeLine: false
3992 if(state.chart.chart_type === 'line')
3993 state.morris_instance = new Morris.Line(state.morris_options);
3995 else if(state.chart.chart_type === 'area') {
3996 state.morris_options.behaveLikeLine = true;
3997 state.morris_instance = new Morris.Area(state.morris_options);
4000 state.morris_instance = new Morris.Area(state.morris_options);
4005 // ----------------------------------------------------------------------------------------------------------------
4008 NETDATA.raphaelInitialize = function(callback) {
4009 if(typeof netdataStopRaphael === 'undefined' || !netdataStopRaphael) {
4011 url: NETDATA.raphael_js,
4016 NETDATA.registerChartLibrary('raphael', NETDATA.raphael_js);
4019 NETDATA.chartLibraries.raphael.enabled = false;
4020 NETDATA.error(100, NETDATA.raphael_js);
4022 .always(function() {
4023 if(typeof callback === "function")
4028 NETDATA.chartLibraries.raphael.enabled = false;
4029 if(typeof callback === "function")
4034 NETDATA.raphaelChartUpdate = function(state, data) {
4035 $(state.element_chart).raphael(data.result, {
4036 width: state.chartWidth(),
4037 height: state.chartHeight()
4043 NETDATA.raphaelChartCreate = function(state, data) {
4044 $(state.element_chart).raphael(data.result, {
4045 width: state.chartWidth(),
4046 height: state.chartHeight()
4052 // ----------------------------------------------------------------------------------------------------------------
4055 NETDATA.c3Initialize = function(callback) {
4056 if(typeof netdataNoC3 === 'undefined' || !netdataNoC3) {
4059 if(!NETDATA.chartLibraries.d3.initialized) {
4060 if(NETDATA.chartLibraries.d3.enabled) {
4061 NETDATA.d3Initialize(function() {
4062 NETDATA.c3Initialize(callback);
4066 NETDATA.chartLibraries.c3.enabled = false;
4067 if(typeof callback === "function")
4072 NETDATA._loadCSS(NETDATA.c3_css);
4080 NETDATA.registerChartLibrary('c3', NETDATA.c3_js);
4083 NETDATA.chartLibraries.c3.enabled = false;
4084 NETDATA.error(100, NETDATA.c3_js);
4086 .always(function() {
4087 if(typeof callback === "function")
4093 NETDATA.chartLibraries.c3.enabled = false;
4094 if(typeof callback === "function")
4099 NETDATA.c3ChartUpdate = function(state, data) {
4100 state.c3_instance.destroy();
4101 return NETDATA.c3ChartCreate(state, data);
4103 //state.c3_instance.load({
4104 // rows: data.result,
4111 NETDATA.c3ChartCreate = function(state, data) {
4113 state.element_chart.id = 'c3-' + state.uuid;
4114 // console.log('id = ' + state.element_chart.id);
4116 state.c3_instance = c3.generate({
4117 bindto: '#' + state.element_chart.id,
4119 width: state.chartWidth(),
4120 height: state.chartHeight()
4123 pattern: state.chartColors()
4128 type: (state.chart.chart_type === 'line')?'spline':'area-spline'
4134 format: function(x) {
4135 return NETDATA.zeropad(x.getHours()) + ":" + NETDATA.zeropad(x.getMinutes()) + ":" + NETDATA.zeropad(x.getSeconds());
4162 // console.log(state.c3_instance);
4167 // ----------------------------------------------------------------------------------------------------------------
4170 NETDATA.d3Initialize = function(callback) {
4171 if(typeof netdataStopD3 === 'undefined' || !netdataStopD3) {
4178 NETDATA.registerChartLibrary('d3', NETDATA.d3_js);
4181 NETDATA.chartLibraries.d3.enabled = false;
4182 NETDATA.error(100, NETDATA.d3_js);
4184 .always(function() {
4185 if(typeof callback === "function")
4190 NETDATA.chartLibraries.d3.enabled = false;
4191 if(typeof callback === "function")
4196 NETDATA.d3ChartUpdate = function(state, data) {
4200 NETDATA.d3ChartCreate = function(state, data) {
4204 // ----------------------------------------------------------------------------------------------------------------
4207 NETDATA.googleInitialize = function(callback) {
4208 if(typeof netdataNoGoogleCharts === 'undefined' || !netdataNoGoogleCharts) {
4210 url: NETDATA.google_js,
4215 NETDATA.registerChartLibrary('google', NETDATA.google_js);
4216 google.load('visualization', '1.1', {
4217 'packages': ['corechart', 'controls'],
4218 'callback': callback
4222 NETDATA.chartLibraries.google.enabled = false;
4223 NETDATA.error(100, NETDATA.google_js);
4224 if(typeof callback === "function")
4229 NETDATA.chartLibraries.google.enabled = false;
4230 if(typeof callback === "function")
4235 NETDATA.googleChartUpdate = function(state, data) {
4236 var datatable = new google.visualization.DataTable(data.result);
4237 state.google_instance.draw(datatable, state.google_options);
4241 NETDATA.googleChartCreate = function(state, data) {
4242 var datatable = new google.visualization.DataTable(data.result);
4244 state.google_options = {
4245 colors: state.chartColors(),
4247 // do not set width, height - the chart resizes itself
4248 //width: state.chartWidth(),
4249 //height: state.chartHeight(),
4254 // title: "Time of Day",
4255 // format:'HH:mm:ss',
4256 viewWindowMode: 'maximized',
4268 viewWindowMode: 'pretty',
4283 focusTarget: 'category',
4290 titlePosition: 'out',
4301 curveType: 'function',
4306 switch(state.chart.chart_type) {
4308 state.google_options.vAxis.viewWindowMode = 'maximized';
4309 state.google_options.areaOpacity = NETDATA.options.current.color_fill_opacity_area;
4310 state.google_instance = new google.visualization.AreaChart(state.element_chart);
4314 state.google_options.isStacked = true;
4315 state.google_options.areaOpacity = NETDATA.options.current.color_fill_opacity_stacked;
4316 state.google_options.vAxis.viewWindowMode = 'maximized';
4317 state.google_options.vAxis.minValue = null;
4318 state.google_options.vAxis.maxValue = null;
4319 state.google_instance = new google.visualization.AreaChart(state.element_chart);
4324 state.google_options.lineWidth = 2;
4325 state.google_instance = new google.visualization.LineChart(state.element_chart);
4329 state.google_instance.draw(datatable, state.google_options);
4333 // ----------------------------------------------------------------------------------------------------------------
4335 NETDATA.percentFromValueMax = function(value, max) {
4336 if(value === null) value = 0;
4337 if(max < value) max = value;
4341 pcent = Math.round(value * 100 / max);
4342 if(pcent === 0 && value > 0) pcent = 1;
4348 // ----------------------------------------------------------------------------------------------------------------
4351 NETDATA.easypiechartInitialize = function(callback) {
4352 if(typeof netdataNoEasyPieChart === 'undefined' || !netdataNoEasyPieChart) {
4354 url: NETDATA.easypiechart_js,
4359 NETDATA.registerChartLibrary('easypiechart', NETDATA.easypiechart_js);
4362 NETDATA.chartLibraries.easypiechart.enabled = false;
4363 NETDATA.error(100, NETDATA.easypiechart_js);
4365 .always(function() {
4366 if(typeof callback === "function")
4371 NETDATA.chartLibraries.easypiechart.enabled = false;
4372 if(typeof callback === "function")
4377 NETDATA.easypiechartClearSelection = function(state) {
4378 if(typeof state.easyPieChartEvent !== 'undefined') {
4379 if(state.easyPieChartEvent.timer !== null)
4380 clearTimeout(state.easyPieChartEvent.timer);
4382 state.easyPieChartEvent.timer = null;
4385 if(state.isAutoRefreshed() === true && state.data !== null) {
4386 NETDATA.easypiechartChartUpdate(state, state.data);
4389 state.easyPieChartLabel.innerHTML = state.legendFormatValue(null);
4390 state.easyPieChart_instance.update(0);
4392 state.easyPieChart_instance.enableAnimation();
4397 NETDATA.easypiechartSetSelection = function(state, t) {
4398 if(state.timeIsVisible(t) !== true)
4399 return NETDATA.easypiechartClearSelection(state);
4401 var slot = state.calculateRowForTime(t);
4402 if(slot < 0 || slot >= state.data.result.length)
4403 return NETDATA.easypiechartClearSelection(state);
4405 if(typeof state.easyPieChartEvent === 'undefined') {
4406 state.easyPieChartEvent = {
4413 var value = state.data.result[state.data.result.length - 1 - slot];
4414 var max = (state.easyPieChartMax === null)?state.data.max:state.easyPieChartMax;
4415 var pcent = NETDATA.percentFromValueMax(value, max);
4417 state.easyPieChartEvent.value = value;
4418 state.easyPieChartEvent.pcent = pcent;
4419 state.easyPieChartLabel.innerHTML = state.legendFormatValue(value);
4421 if(state.easyPieChartEvent.timer === null) {
4422 state.easyPieChart_instance.disableAnimation();
4424 state.easyPieChartEvent.timer = setTimeout(function() {
4425 state.easyPieChartEvent.timer = null;
4426 state.easyPieChart_instance.update(state.easyPieChartEvent.pcent);
4427 }, NETDATA.options.current.charts_selection_animation_delay);
4433 NETDATA.easypiechartChartUpdate = function(state, data) {
4434 var value, max, pcent;
4436 if(NETDATA.globalPanAndZoom.isActive() === true || state.isAutoRefreshed() === false) {
4442 value = data.result[0];
4443 max = (state.easyPieChartMax === null)?data.max:state.easyPieChartMax;
4444 pcent = NETDATA.percentFromValueMax(value, max);
4447 state.easyPieChartLabel.innerHTML = state.legendFormatValue(value);
4448 state.easyPieChart_instance.update(pcent);
4452 NETDATA.easypiechartChartCreate = function(state, data) {
4453 var self = $(state.element);
4454 var chart = $(state.element_chart);
4456 var value = data.result[0];
4457 var max = self.data('easypiechart-max-value') || null;
4458 var adjust = self.data('easypiechart-adjust') || null;
4462 state.easyPieChartMax = null;
4465 state.easyPieChartMax = max;
4467 var pcent = NETDATA.percentFromValueMax(value, max);
4469 chart.data('data-percent', pcent);
4473 case 'width': size = state.chartHeight(); break;
4474 case 'min': size = Math.min(state.chartWidth(), state.chartHeight()); break;
4475 case 'max': size = Math.max(state.chartWidth(), state.chartHeight()); break;
4477 default: size = state.chartWidth(); break;
4479 state.element.style.width = size + 'px';
4480 state.element.style.height = size + 'px';
4482 var stroke = Math.floor(size / 22);
4483 if(stroke < 3) stroke = 2;
4485 var valuefontsize = Math.floor((size * 2 / 3) / 5);
4486 var valuetop = Math.round((size - valuefontsize - (size / 40)) / 2);
4487 state.easyPieChartLabel = document.createElement('span');
4488 state.easyPieChartLabel.className = 'easyPieChartLabel';
4489 state.easyPieChartLabel.innerHTML = state.legendFormatValue(value);
4490 state.easyPieChartLabel.style.fontSize = valuefontsize + 'px';
4491 state.easyPieChartLabel.style.top = valuetop.toString() + 'px';
4492 state.element_chart.appendChild(state.easyPieChartLabel);
4494 var titlefontsize = Math.round(valuefontsize * 1.6 / 3);
4495 var titletop = Math.round(valuetop - (titlefontsize * 2) - (size / 40));
4496 state.easyPieChartTitle = document.createElement('span');
4497 state.easyPieChartTitle.className = 'easyPieChartTitle';
4498 state.easyPieChartTitle.innerHTML = state.title;
4499 state.easyPieChartTitle.style.fontSize = titlefontsize + 'px';
4500 state.easyPieChartTitle.style.lineHeight = titlefontsize + 'px';
4501 state.easyPieChartTitle.style.top = titletop.toString() + 'px';
4502 state.element_chart.appendChild(state.easyPieChartTitle);
4504 var unitfontsize = Math.round(titlefontsize * 0.9);
4505 var unittop = Math.round(valuetop + (valuefontsize + unitfontsize) + (size / 40));
4506 state.easyPieChartUnits = document.createElement('span');
4507 state.easyPieChartUnits.className = 'easyPieChartUnits';
4508 state.easyPieChartUnits.innerHTML = state.units;
4509 state.easyPieChartUnits.style.fontSize = unitfontsize + 'px';
4510 state.easyPieChartUnits.style.top = unittop.toString() + 'px';
4511 state.element_chart.appendChild(state.easyPieChartUnits);
4513 chart.easyPieChart({
4514 barColor: self.data('easypiechart-barcolor') || state.chartColors()[0], //'#ef1e25',
4515 trackColor: self.data('easypiechart-trackcolor') || NETDATA.themes.current.easypiechart_track,
4516 scaleColor: self.data('easypiechart-scalecolor') || NETDATA.themes.current.easypiechart_scale,
4517 scaleLength: self.data('easypiechart-scalelength') || 5,
4518 lineCap: self.data('easypiechart-linecap') || 'round',
4519 lineWidth: self.data('easypiechart-linewidth') || stroke,
4520 trackWidth: self.data('easypiechart-trackwidth') || undefined,
4521 size: self.data('easypiechart-size') || size,
4522 rotate: self.data('easypiechart-rotate') || 0,
4523 animate: self.data('easypiechart-rotate') || {duration: 500, enabled: true},
4524 easing: self.data('easypiechart-easing') || undefined
4527 // when we just re-create the chart
4528 // do not animate the first update
4530 if(typeof state.easyPieChart_instance !== 'undefined')
4533 state.easyPieChart_instance = chart.data('easyPieChart');
4534 if(animate === false) state.easyPieChart_instance.disableAnimation();
4535 state.easyPieChart_instance.update(pcent);
4536 if(animate === false) state.easyPieChart_instance.enableAnimation();
4540 // ----------------------------------------------------------------------------------------------------------------
4543 NETDATA.gaugeInitialize = function(callback) {
4544 if(typeof netdataNoGauge === 'undefined' || !netdataNoGauge) {
4546 url: NETDATA.gauge_js,
4551 NETDATA.registerChartLibrary('gauge', NETDATA.gauge_js);
4554 NETDATA.chartLibraries.gauge.enabled = false;
4555 NETDATA.error(100, NETDATA.gauge_js);
4557 .always(function() {
4558 if(typeof callback === "function")
4563 NETDATA.chartLibraries.gauge.enabled = false;
4564 if(typeof callback === "function")
4569 NETDATA.gaugeAnimation = function(state, status) {
4572 if(typeof status === 'boolean' && status === false)
4574 else if(typeof status === 'number')
4577 state.gauge_instance.animationSpeed = speed;
4578 state.___gaugeOld__.speed = speed;
4581 NETDATA.gaugeSet = function(state, value, min, max) {
4582 if(typeof value !== 'number') value = 0;
4583 if(typeof min !== 'number') min = 0;
4584 if(typeof max !== 'number') max = 0;
4585 if(value > max) max = value;
4586 if(value < min) min = value;
4595 // gauge.js has an issue if the needle
4596 // is smaller than min or larger than max
4597 // when we set the new values
4598 // the needle will go crazy
4600 // to prevent it, we always feed it
4601 // with a percentage, so that the needle
4602 // is always between min and max
4603 var pcent = (value - min) * 100 / (max - min);
4605 // these should never happen
4606 if(pcent < 0) pcent = 0;
4607 if(pcent > 100) pcent = 100;
4609 state.gauge_instance.set(pcent);
4611 state.___gaugeOld__.value = value;
4612 state.___gaugeOld__.min = min;
4613 state.___gaugeOld__.max = max;
4616 NETDATA.gaugeSetLabels = function(state, value, min, max) {
4617 if(state.___gaugeOld__.valueLabel !== value) {
4618 state.___gaugeOld__.valueLabel = value;
4619 state.gaugeChartLabel.innerHTML = state.legendFormatValue(value);
4621 if(state.___gaugeOld__.minLabel !== min) {
4622 state.___gaugeOld__.minLabel = min;
4623 state.gaugeChartMin.innerHTML = state.legendFormatValue(min);
4625 if(state.___gaugeOld__.maxLabel !== max) {
4626 state.___gaugeOld__.maxLabel = max;
4627 state.gaugeChartMax.innerHTML = state.legendFormatValue(max);
4631 NETDATA.gaugeClearSelection = function(state) {
4632 if(typeof state.gaugeEvent !== 'undefined') {
4633 if(state.gaugeEvent.timer !== null)
4634 clearTimeout(state.gaugeEvent.timer);
4636 state.gaugeEvent.timer = null;
4639 if(state.isAutoRefreshed() === true && state.data !== null) {
4640 NETDATA.gaugeChartUpdate(state, state.data);
4643 NETDATA.gaugeAnimation(state, false);
4644 NETDATA.gaugeSet(state, null, null, null);
4645 NETDATA.gaugeSetLabels(state, null, null, null);
4648 NETDATA.gaugeAnimation(state, true);
4652 NETDATA.gaugeSetSelection = function(state, t) {
4653 if(state.timeIsVisible(t) !== true)
4654 return NETDATA.gaugeClearSelection(state);
4656 var slot = state.calculateRowForTime(t);
4657 if(slot < 0 || slot >= state.data.result.length)
4658 return NETDATA.gaugeClearSelection(state);
4660 if(typeof state.gaugeEvent === 'undefined') {
4661 state.gaugeEvent = {
4669 var value = state.data.result[state.data.result.length - 1 - slot];
4670 var max = (state.gaugeMax === null)?state.data.max:state.gaugeMax;
4673 state.gaugeEvent.value = value;
4674 state.gaugeEvent.max = max;
4675 state.gaugeEvent.min = min;
4676 NETDATA.gaugeSetLabels(state, value, min, max);
4678 if(state.gaugeEvent.timer === null) {
4679 NETDATA.gaugeAnimation(state, false);
4681 state.gaugeEvent.timer = setTimeout(function() {
4682 state.gaugeEvent.timer = null;
4683 NETDATA.gaugeSet(state, state.gaugeEvent.value, state.gaugeEvent.min, state.gaugeEvent.max);
4684 }, NETDATA.options.current.charts_selection_animation_delay);
4690 NETDATA.gaugeChartUpdate = function(state, data) {
4691 var value, min, max;
4693 if(NETDATA.globalPanAndZoom.isActive() === true || state.isAutoRefreshed() === false) {
4697 NETDATA.gaugeSetLabels(state, null, null, null);
4700 value = data.result[0];
4702 max = (state.gaugeMax === null)?data.max:state.gaugeMax;
4703 if(value > max) max = value;
4704 NETDATA.gaugeSetLabels(state, value, min, max);
4707 NETDATA.gaugeSet(state, value, min, max);
4711 NETDATA.gaugeChartCreate = function(state, data) {
4712 var self = $(state.element);
4713 var chart = $(state.element_chart);
4715 var value = data.result[0];
4716 var max = self.data('gauge-max-value') || null;
4717 var adjust = self.data('gauge-adjust') || null;
4718 var pointerColor = self.data('gauge-pointer-color') || NETDATA.themes.current.gauge_pointer;
4719 var strokeColor = self.data('gauge-stroke-color') || NETDATA.themes.current.gauge_stroke;
4720 var startColor = self.data('gauge-start-color') || state.chartColors()[0];
4721 var stopColor = self.data('gauge-stop-color') || void 0;
4722 var generateGradient = self.data('gauge-generate-gradient') || false;
4726 state.gaugeMax = null;
4729 state.gaugeMax = max;
4731 var width = state.chartWidth(), height = state.chartHeight(); //, ratio = 1.5;
4733 // case 'width': width = height * ratio; break;
4735 // default: height = width / ratio; break;
4737 //state.element.style.width = width.toString() + 'px';
4738 //state.element.style.height = height.toString() + 'px';
4743 lines: 12, // The number of lines to draw
4744 angle: 0.15, // The length of each line
4745 lineWidth: 0.44, // 0.44 The line thickness
4747 length: 0.8, // 0.9 The radius of the inner circle
4748 strokeWidth: 0.035, // The rotation offset
4749 color: pointerColor // Fill color
4751 colorStart: startColor, // Colors
4752 colorStop: stopColor, // just experiment with them
4753 strokeColor: strokeColor, // to see which ones work best for you
4755 generateGradient: generateGradient,
4759 if(generateGradient === false && NETDATA.themes.current.gauge_gradient === true) {
4760 options.percentColors = [
4761 [0.0, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 0))],
4762 [0.1, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 1))],
4763 [0.2, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 2))],
4764 [0.3, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 3))],
4765 [0.4, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 4))],
4766 [0.5, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 5))],
4767 [0.6, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 6))],
4768 [0.7, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 7))],
4769 [0.8, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 8))],
4770 [0.9, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 9))],
4771 [1.0, NETDATA.colorLuminance(startColor, 0.0)]];
4774 state.gauge_canvas = document.createElement('canvas');
4775 state.gauge_canvas.id = 'gauge-' + state.uuid + '-canvas';
4776 state.gauge_canvas.className = 'gaugeChart';
4777 state.gauge_canvas.width = width;
4778 state.gauge_canvas.height = height;
4779 state.element_chart.appendChild(state.gauge_canvas);
4781 var valuefontsize = Math.floor(height / 6);
4782 var valuetop = Math.round((height - valuefontsize - (height / 6)) / 2);
4783 state.gaugeChartLabel = document.createElement('span');
4784 state.gaugeChartLabel.className = 'gaugeChartLabel';
4785 state.gaugeChartLabel.style.fontSize = valuefontsize + 'px';
4786 state.gaugeChartLabel.style.top = valuetop.toString() + 'px';
4787 state.element_chart.appendChild(state.gaugeChartLabel);
4789 var titlefontsize = Math.round(valuefontsize / 2);
4791 state.gaugeChartTitle = document.createElement('span');
4792 state.gaugeChartTitle.className = 'gaugeChartTitle';
4793 state.gaugeChartTitle.innerHTML = state.title;
4794 state.gaugeChartTitle.style.fontSize = titlefontsize + 'px';
4795 state.gaugeChartTitle.style.lineHeight = titlefontsize + 'px';
4796 state.gaugeChartTitle.style.top = titletop.toString() + 'px';
4797 state.element_chart.appendChild(state.gaugeChartTitle);
4799 var unitfontsize = Math.round(titlefontsize * 0.9);
4800 state.gaugeChartUnits = document.createElement('span');
4801 state.gaugeChartUnits.className = 'gaugeChartUnits';
4802 state.gaugeChartUnits.innerHTML = state.units;
4803 state.gaugeChartUnits.style.fontSize = unitfontsize + 'px';
4804 state.element_chart.appendChild(state.gaugeChartUnits);
4806 state.gaugeChartMin = document.createElement('span');
4807 state.gaugeChartMin.className = 'gaugeChartMin';
4808 state.gaugeChartMin.style.fontSize = Math.round(valuefontsize * 0.75).toString() + 'px';
4809 state.element_chart.appendChild(state.gaugeChartMin);
4811 state.gaugeChartMax = document.createElement('span');
4812 state.gaugeChartMax.className = 'gaugeChartMax';
4813 state.gaugeChartMax.style.fontSize = Math.round(valuefontsize * 0.75).toString() + 'px';
4814 state.element_chart.appendChild(state.gaugeChartMax);
4816 // when we just re-create the chart
4817 // do not animate the first update
4819 if(typeof state.gauge_instance !== 'undefined')
4822 state.gauge_instance = new Gauge(state.gauge_canvas).setOptions(options); // create sexy gauge!
4824 state.___gaugeOld__ = {
4833 // we will always feed a percentage
4834 state.gauge_instance.minValue = 0;
4835 state.gauge_instance.maxValue = 100;
4837 NETDATA.gaugeAnimation(state, animate);
4838 NETDATA.gaugeSet(state, value, 0, max);
4839 NETDATA.gaugeSetLabels(state, value, 0, max);
4840 NETDATA.gaugeAnimation(state, true);
4844 // ----------------------------------------------------------------------------------------------------------------
4845 // Charts Libraries Registration
4847 NETDATA.chartLibraries = {
4849 initialize: NETDATA.dygraphInitialize,
4850 create: NETDATA.dygraphChartCreate,
4851 update: NETDATA.dygraphChartUpdate,
4852 resize: function(state) {
4853 if(typeof state.dygraph_instance.resize === 'function')
4854 state.dygraph_instance.resize();
4856 setSelection: NETDATA.dygraphSetSelection,
4857 clearSelection: NETDATA.dygraphClearSelection,
4860 format: function(state) { return 'json'; },
4861 options: function(state) { return 'ms|flip'; },
4862 legend: function(state) {
4863 if(this.isSparkline(state) === false)
4864 return 'right-side';
4868 autoresize: function(state) { return true; },
4869 max_updates_to_recreate: function(state) { return 5000; },
4870 track_colors: function(state) { return true; },
4871 pixels_per_point: function(state) {
4872 if(this.isSparkline(state) === false)
4878 isSparkline: function(state) {
4879 if(typeof state.dygraph_sparkline === 'undefined') {
4880 var t = $(state.element).data('dygraph-theme');
4881 if(t === 'sparkline')
4882 state.dygraph_sparkline = true;
4884 state.dygraph_sparkline = false;
4886 return state.dygraph_sparkline;
4890 initialize: NETDATA.sparklineInitialize,
4891 create: NETDATA.sparklineChartCreate,
4892 update: NETDATA.sparklineChartUpdate,
4894 setSelection: undefined, // function(state, t) { return true; },
4895 clearSelection: undefined, // function(state) { return true; },
4898 format: function(state) { return 'array'; },
4899 options: function(state) { return 'flip|abs'; },
4900 legend: function(state) { return null; },
4901 autoresize: function(state) { return false; },
4902 max_updates_to_recreate: function(state) { return 5000; },
4903 track_colors: function(state) { return false; },
4904 pixels_per_point: function(state) { return 3; }
4907 initialize: NETDATA.peityInitialize,
4908 create: NETDATA.peityChartCreate,
4909 update: NETDATA.peityChartUpdate,
4911 setSelection: undefined, // function(state, t) { return true; },
4912 clearSelection: undefined, // function(state) { return true; },
4915 format: function(state) { return 'ssvcomma'; },
4916 options: function(state) { return 'null2zero|flip|abs'; },
4917 legend: function(state) { return null; },
4918 autoresize: function(state) { return false; },
4919 max_updates_to_recreate: function(state) { return 5000; },
4920 track_colors: function(state) { return false; },
4921 pixels_per_point: function(state) { return 3; }
4924 initialize: NETDATA.morrisInitialize,
4925 create: NETDATA.morrisChartCreate,
4926 update: NETDATA.morrisChartUpdate,
4928 setSelection: undefined, // function(state, t) { return true; },
4929 clearSelection: undefined, // function(state) { return true; },
4932 format: function(state) { return 'json'; },
4933 options: function(state) { return 'objectrows|ms'; },
4934 legend: function(state) { return null; },
4935 autoresize: function(state) { return false; },
4936 max_updates_to_recreate: function(state) { return 50; },
4937 track_colors: function(state) { return false; },
4938 pixels_per_point: function(state) { return 15; }
4941 initialize: NETDATA.googleInitialize,
4942 create: NETDATA.googleChartCreate,
4943 update: NETDATA.googleChartUpdate,
4945 setSelection: undefined, //function(state, t) { return true; },
4946 clearSelection: undefined, //function(state) { return true; },
4949 format: function(state) { return 'datatable'; },
4950 options: function(state) { return ''; },
4951 legend: function(state) { return null; },
4952 autoresize: function(state) { return false; },
4953 max_updates_to_recreate: function(state) { return 300; },
4954 track_colors: function(state) { return false; },
4955 pixels_per_point: function(state) { return 4; }
4958 initialize: NETDATA.raphaelInitialize,
4959 create: NETDATA.raphaelChartCreate,
4960 update: NETDATA.raphaelChartUpdate,
4962 setSelection: undefined, // function(state, t) { return true; },
4963 clearSelection: undefined, // function(state) { return true; },
4966 format: function(state) { return 'json'; },
4967 options: function(state) { return ''; },
4968 legend: function(state) { return null; },
4969 autoresize: function(state) { return false; },
4970 max_updates_to_recreate: function(state) { return 5000; },
4971 track_colors: function(state) { return false; },
4972 pixels_per_point: function(state) { return 3; }
4975 initialize: NETDATA.c3Initialize,
4976 create: NETDATA.c3ChartCreate,
4977 update: NETDATA.c3ChartUpdate,
4979 setSelection: undefined, // function(state, t) { return true; },
4980 clearSelection: undefined, // function(state) { return true; },
4983 format: function(state) { return 'csvjsonarray'; },
4984 options: function(state) { return 'milliseconds'; },
4985 legend: function(state) { return null; },
4986 autoresize: function(state) { return false; },
4987 max_updates_to_recreate: function(state) { return 5000; },
4988 track_colors: function(state) { return false; },
4989 pixels_per_point: function(state) { return 15; }
4992 initialize: NETDATA.d3Initialize,
4993 create: NETDATA.d3ChartCreate,
4994 update: NETDATA.d3ChartUpdate,
4996 setSelection: undefined, // function(state, t) { return true; },
4997 clearSelection: undefined, // function(state) { return true; },
5000 format: function(state) { return 'json'; },
5001 options: function(state) { return ''; },
5002 legend: function(state) { return null; },
5003 autoresize: function(state) { return false; },
5004 max_updates_to_recreate: function(state) { return 5000; },
5005 track_colors: function(state) { return false; },
5006 pixels_per_point: function(state) { return 3; }
5009 initialize: NETDATA.easypiechartInitialize,
5010 create: NETDATA.easypiechartChartCreate,
5011 update: NETDATA.easypiechartChartUpdate,
5013 setSelection: NETDATA.easypiechartSetSelection,
5014 clearSelection: NETDATA.easypiechartClearSelection,
5017 format: function(state) { return 'array'; },
5018 options: function(state) { return 'absolute'; },
5019 legend: function(state) { return null; },
5020 autoresize: function(state) { return false; },
5021 max_updates_to_recreate: function(state) { return 5000; },
5022 track_colors: function(state) { return true; },
5023 pixels_per_point: function(state) { return 3; },
5027 initialize: NETDATA.gaugeInitialize,
5028 create: NETDATA.gaugeChartCreate,
5029 update: NETDATA.gaugeChartUpdate,
5031 setSelection: NETDATA.gaugeSetSelection,
5032 clearSelection: NETDATA.gaugeClearSelection,
5035 format: function(state) { return 'array'; },
5036 options: function(state) { return 'absolute'; },
5037 legend: function(state) { return null; },
5038 autoresize: function(state) { return false; },
5039 max_updates_to_recreate: function(state) { return 5000; },
5040 track_colors: function(state) { return true; },
5041 pixels_per_point: function(state) { return 3; },
5046 NETDATA.registerChartLibrary = function(library, url) {
5047 if(NETDATA.options.debug.libraries === true)
5048 console.log("registering chart library: " + library);
5050 NETDATA.chartLibraries[library].url = url;
5051 NETDATA.chartLibraries[library].initialized = true;
5052 NETDATA.chartLibraries[library].enabled = true;
5055 // ----------------------------------------------------------------------------------------------------------------
5058 NETDATA.requiredJs = [
5060 url: NETDATA.serverDefault + 'lib/bootstrap.min.js',
5061 isAlreadyLoaded: function() {
5062 if(typeof $().emulateTransitionEnd == 'function')
5065 if(typeof netdataNoBootstrap !== 'undefined' && netdataNoBootstrap)
5073 url: NETDATA.serverDefault + 'lib/jquery.nanoscroller.min.js',
5074 isAlreadyLoaded: function() { return false; }
5077 url: NETDATA.serverDefault + 'lib/bootstrap-toggle.min.js',
5078 isAlreadyLoaded: function() { return false; }
5082 NETDATA.requiredCSS = [
5084 url: NETDATA.themes.current.bootstrap_css,
5085 isAlreadyLoaded: function() {
5086 if(typeof netdataNoBootstrap !== 'undefined' && netdataNoBootstrap)
5093 url: NETDATA.serverDefault + 'css/font-awesome.min.css',
5094 isAlreadyLoaded: function() { return false; }
5097 url: NETDATA.themes.current.dashboard_css,
5098 isAlreadyLoaded: function() { return false; }
5101 url: NETDATA.serverDefault + 'css/bootstrap-toggle.min.css',
5102 isAlreadyLoaded: function() { return false; }
5106 NETDATA.loadRequiredJs = function(index, callback) {
5107 if(index >= NETDATA.requiredJs.length) {
5108 if(typeof callback === 'function')
5113 if(NETDATA.requiredJs[index].isAlreadyLoaded()) {
5114 NETDATA.loadRequiredJs(++index, callback);
5118 if(NETDATA.options.debug.main_loop === true)
5119 console.log('loading ' + NETDATA.requiredJs[index].url);
5122 url: NETDATA.requiredJs[index].url,
5126 .success(function() {
5127 if(NETDATA.options.debug.main_loop === true)
5128 console.log('loaded ' + NETDATA.requiredJs[index].url);
5130 NETDATA.loadRequiredJs(++index, callback);
5133 alert('Cannot load required JS library: ' + NETDATA.requiredJs[index].url);
5137 NETDATA.loadRequiredCSS = function(index) {
5138 if(index >= NETDATA.requiredCSS.length)
5141 if(NETDATA.requiredCSS[index].isAlreadyLoaded()) {
5142 NETDATA.loadRequiredCSS(++index);
5146 if(NETDATA.options.debug.main_loop === true)
5147 console.log('loading ' + NETDATA.requiredCSS[index].url);
5149 NETDATA._loadCSS(NETDATA.requiredCSS[index].url);
5150 NETDATA.loadRequiredCSS(++index);
5153 NETDATA.errorReset();
5154 NETDATA.loadRequiredCSS(0);
5156 NETDATA._loadjQuery(function() {
5157 NETDATA.loadRequiredJs(0, function() {
5158 if(typeof netdataDontStart === 'undefined' || !netdataDontStart) {
5159 if(NETDATA.options.debug.main_loop === true)
5160 console.log('starting chart refresh thread');
5167 // window.NETDATA = NETDATA;
5168 // })(window, document);