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 netdataNoBootstrap = true; // do not load bootstrap
10 // var netdataDontStart = true; // do not start the thread to process the charts
12 // You can also set the default netdata server, using the following.
13 // When this variable is not set, we assume the page is hosted on your
14 // netdata server already.
15 // var netdataServer = "http://yourhost:19999"; // set your NetData server
17 //(function(window, document, undefined) {
18 // fix IE issue with console
19 if(!window.console){ window.console = {log: function(){} }; }
22 var NETDATA = window.NETDATA || {};
24 // ----------------------------------------------------------------------------------------------------------------
25 // Detect the netdata server
27 // http://stackoverflow.com/questions/984510/what-is-my-script-src-url
28 // http://stackoverflow.com/questions/6941533/get-protocol-domain-and-port-from-url
29 NETDATA._scriptSource = function(scripts) {
30 var script = null, base = null;
32 if(typeof document.currentScript !== 'undefined') {
33 script = document.currentScript;
36 var all_scripts = document.getElementsByTagName('script');
37 script = all_scripts[all_scripts.length - 1];
40 if (typeof script.getAttribute.length !== 'undefined')
43 script = script.getAttribute('src', -1);
45 var link = document.createElement('a');
46 link.setAttribute('href', script);
48 if(!link.protocol || !link.hostname) return null;
51 if(base) base += "//";
52 base += link.hostname;
54 if(link.port) base += ":" + link.port;
60 if(typeof netdataServer !== 'undefined')
61 NETDATA.serverDefault = netdataServer;
63 NETDATA.serverDefault = NETDATA._scriptSource();
65 if(NETDATA.serverDefault === null)
66 NETDATA.serverDefault = '';
67 else if(NETDATA.serverDefault.slice(-1) !== '/')
68 NETDATA.serverDefault += '/';
70 // default URLs for all the external files we need
71 // make them RELATIVE so that the whole thing can also be
72 // installed under a web server
73 NETDATA.jQuery = NETDATA.serverDefault + 'lib/jquery-1.11.3.min.js';
74 NETDATA.peity_js = NETDATA.serverDefault + 'lib/jquery.peity.min.js';
75 NETDATA.sparkline_js = NETDATA.serverDefault + 'lib/jquery.sparkline.min.js';
76 NETDATA.easypiechart_js = NETDATA.serverDefault + 'lib/jquery.easypiechart.min.js';
77 NETDATA.dygraph_js = NETDATA.serverDefault + 'lib/dygraph-combined.js';
78 NETDATA.dygraph_smooth_js = NETDATA.serverDefault + 'lib/dygraph-smooth-plotter.js';
79 NETDATA.raphael_js = NETDATA.serverDefault + 'lib/raphael-min.js';
80 NETDATA.morris_js = NETDATA.serverDefault + 'lib/morris.min.js';
81 NETDATA.morris_css = NETDATA.serverDefault + 'css/morris.css';
82 NETDATA.dashboard_css = NETDATA.serverDefault + 'dashboard.css';
83 NETDATA.google_js = 'https://www.google.com/jsapi';
85 // these are the colors Google Charts are using
86 // we have them here to attempt emulate their look and feel on the other chart libraries
87 // http://there4.io/2012/05/02/google-chart-color-list/
88 //NETDATA.colors = [ '#3366CC', '#DC3912', '#FF9900', '#109618', '#990099', '#3B3EAC', '#0099C6',
89 // '#DD4477', '#66AA00', '#B82E2E', '#316395', '#994499', '#22AA99', '#AAAA11',
90 // '#6633CC', '#E67300', '#8B0707', '#329262', '#5574A6', '#3B3EAC' ];
92 NETDATA.colors = [ '#3366CC', '#DC3912', '#109618', '#FF9900', '#990099', '#DD4477', '#3B3EAC',
93 '#66AA00', '#0099C6', '#B82E2E', '#AAAA11', '#5574A6', '#994499', '#22AA99',
94 '#6633CC', '#E67300', '#316395', '#8B0707', '#329262', '#3B3EAC' ];
96 // http://www.mulinblog.com/a-color-palette-optimized-for-data-visualization/
97 // (blue) (red) (orange) (green) (pink) (brown) (purple) (yellow) (gray)
98 //NETDATA.colors = [ '#5DA5DA', '#F15854', '#FAA43A', '#60BD68', '#F17CB0', '#B2912F', '#B276B2', '#DECF3F', '#4D4D4D' ];
100 // ----------------------------------------------------------------------------------------------------------------
101 // the defaults for all charts
103 // if the user does not specify any of these, the following will be used
105 NETDATA.chartDefaults = {
106 host: NETDATA.serverDefault, // the server to get data from
107 width: '100%', // the chart width - can be null
108 height: '100%', // the chart height - can be null
109 min_width: null, // the chart minimum width - can be null
110 library: 'dygraph', // the graphing library to use
111 method: 'average', // the grouping method
112 before: 0, // panning
113 after: -600, // panning
114 pixels_per_point: 1, // the detail of the chart
115 fill_luminance: 0.8 // luminance of colors in solit areas
118 // ----------------------------------------------------------------------------------------------------------------
122 pauseCallback: null, // a callback when we are really paused
124 pause: false, // when enabled we don't auto-refresh the charts
126 targets: null, // an array of all the state objects that are
127 // currently active (independently of their
128 // viewport visibility)
130 updated_dom: true, // when true, the DOM has been updated with
131 // new elements we have to check.
133 auto_refresher_fast_weight: 0, // this is the current time in ms, spent
134 // rendering charts continiously.
135 // used with .current.fast_render_timeframe
137 page_is_visible: true, // when true, this page is visible
139 auto_refresher_stop_until: 0, // timestamp in ms - used internaly, to stop the
140 // auto-refresher for some time (when a chart is
141 // performing pan or zoom, we need to stop refreshing
142 // all other charts, to have the maximum speed for
143 // rendering the chart that is panned or zoomed).
144 // Used with .current.global_pan_sync_time
146 last_resized: 0, // the timestamp of the last resize request
148 crossDomainAjax: false, // enable this to request crossDomain AJAX
150 last_page_scroll: 0, // the timestamp the last time the page was scrolled
152 // the current profile
153 // we may have many...
155 pixels_per_point: 1, // the minimum pixels per point for all charts
156 // increase this to speed javascript up
157 // each chart library has its own limit too
158 // the max of this and the chart library is used
159 // the final is calculated every time, so a change
160 // here will have immediate effect on the next chart
163 idle_between_charts: 100, // ms - how much time to wait between chart updates
165 fast_render_timeframe: 200, // ms - render continously until this time of continious
166 // rendering has been reached
167 // this setting is used to make it render e.g. 10
168 // charts at once, sleep idle_between_charts time
169 // and continue for another 10 charts.
171 idle_between_loops: 500, // ms - if all charts have been updated, wait this
172 // time before starting again.
174 idle_parallel_loops: 100, // ms - the time between parallel refresher updates
176 idle_lost_focus: 500, // ms - when the window does not have focus, check
177 // if focus has been regained, every this time
179 global_pan_sync_time: 1000, // ms - when you pan or zoon a chart, the background
180 // autorefreshing of charts is paused for this amount
183 sync_selection_delay: 1500, // ms - when you pan or zoom a chart, wait this amount
184 // of time before setting up synchronized selections
187 sync_selection: true, // enable or disable selection sync
189 pan_and_zoom_delay: 50, // when panning or zooming, how ofter to update the chart
191 sync_pan_and_zoom: true, // enable or disable pan and zoom sync
193 update_only_visible: true, // enable or disable visibility management
195 parallel_refresher: true, // enable parallel refresh of charts
197 concurrent_refreshes: true, // when parallel_refresher is enabled, sync also the charts
199 destroy_on_hide: false, // destroy charts when they are not visible
201 eliminate_zero_dimensions: true, // do not show dimensions with just zeros
203 stop_updates_when_focus_is_lost: true, // boolean - shall we stop auto-refreshes when document does not have user focus
204 stop_updates_while_resizing: 1000, // ms - time to stop auto-refreshes while resizing the charts
206 double_click_speed: 500, // ms - time between clicks / taps to detect double click/tap
208 smooth_plot: true, // enable smooth plot, where possible
210 color_fill_opacity_line: 1.0,
211 color_fill_opacity_area: 0.2,
212 color_fill_opacity_stacked: 0.8,
214 setOptionCallback: function() { ; }
222 chart_data_url: false,
232 // ----------------------------------------------------------------------------------------------------------------
233 // local storage options
235 NETDATA.localStorage = {
238 callback: {} // only used for resetting back to defaults
241 NETDATA.localStorageGet = function(key, def, callback) {
244 if(typeof NETDATA.localStorage.default[key.toString()] === 'undefined') {
245 NETDATA.localStorage.default[key.toString()] = def;
246 NETDATA.localStorage.callback[key.toString()] = callback;
249 if(typeof Storage !== "undefined" && typeof localStorage === 'object') {
251 // console.log('localStorage: loading "' + key.toString() + '"');
252 ret = localStorage.getItem(key.toString());
253 if(ret === null || ret === 'undefined') {
254 // console.log('localStorage: cannot load it, saving "' + key.toString() + '" with value "' + JSON.stringify(def) + '"');
255 localStorage.setItem(key.toString(), JSON.stringify(def));
259 // console.log('localStorage: got "' + key.toString() + '" with value "' + ret + '"');
260 ret = JSON.parse(ret);
261 // console.log('localStorage: loaded "' + key.toString() + '" as value ' + ret + ' of type ' + typeof(ret));
265 console.log('localStorage: failed to read "' + key.toString() + '", using default: "' + def.toString() + '"');
270 if(typeof ret === 'undefined' || ret === 'undefined') {
271 console.log('localStorage: LOADED UNDEFINED "' + key.toString() + '" as value ' + ret + ' of type ' + typeof(ret));
275 NETDATA.localStorage.current[key.toString()] = ret;
279 NETDATA.localStorageSet = function(key, value, callback) {
280 if(typeof value === 'undefined' || value === 'undefined') {
281 console.log('localStorage: ATTEMPT TO SET UNDEFINED "' + key.toString() + '" as value ' + value + ' of type ' + typeof(value));
284 if(typeof NETDATA.localStorage.default[key.toString()] === 'undefined') {
285 NETDATA.localStorage.default[key.toString()] = value;
286 NETDATA.localStorage.current[key.toString()] = value;
287 NETDATA.localStorage.callback[key.toString()] = callback;
290 if(typeof Storage !== "undefined" && typeof localStorage === 'object') {
291 // console.log('localStorage: saving "' + key.toString() + '" with value "' + JSON.stringify(value) + '"');
293 localStorage.setItem(key.toString(), JSON.stringify(value));
296 console.log('localStorage: failed to save "' + key.toString() + '" with value: "' + value.toString() + '"');
300 NETDATA.localStorage.current[key.toString()] = value;
304 NETDATA.localStorageGetRecursive = function(obj, prefix, callback) {
306 if(typeof obj[i] === 'object') {
307 //console.log('object ' + prefix + '.' + i.toString());
308 NETDATA.localStorageGetRecursive(obj[i], prefix + '.' + i.toString(), callback);
312 obj[i] = NETDATA.localStorageGet(prefix + '.' + i.toString(), obj[i], callback);
316 NETDATA.setOption = function(key, value) {
317 if(key.toString() === 'setOptionCallback') {
318 if(typeof NETDATA.options.current.setOptionCallback === 'function') {
319 NETDATA.options.current[key.toString()] = value;
320 NETDATA.options.current.setOptionCallback();
323 else if(NETDATA.options.current[key.toString()] !== value) {
324 var name = 'options.' + key.toString();
326 if(typeof NETDATA.localStorage.default[name.toString()] === 'undefined')
327 console.log('localStorage: setOption() on unsaved option: "' + name.toString() + '", value: ' + value);
329 //console.log(NETDATA.localStorage);
330 //console.log('setOption: setting "' + key.toString() + '" to "' + value + '" of type ' + typeof(value) + ' original type ' + typeof(NETDATA.options.current[key.toString()]));
331 //console.log(NETDATA.options);
332 NETDATA.options.current[key.toString()] = NETDATA.localStorageSet(name.toString(), value, null);
334 if(typeof NETDATA.options.current.setOptionCallback === 'function')
335 NETDATA.options.current.setOptionCallback();
341 NETDATA.getOption = function(key) {
342 return NETDATA.options.current[key.toString()];
345 // read settings from local storage
346 NETDATA.localStorageGetRecursive(NETDATA.options.current, 'options', null);
348 // always start with this option enabled.
349 NETDATA.setOption('stop_updates_when_focus_is_lost', true);
351 NETDATA.resetOptions = function() {
352 for(var i in NETDATA.localStorage.default) {
353 var a = i.split('.');
355 if(a[0] === 'options') {
356 if(a[1] === 'setOptionCallback') continue;
357 if(typeof NETDATA.localStorage.default[i] === 'undefined') continue;
358 if(NETDATA.options.current[i] === NETDATA.localStorage.default[i]) continue;
360 NETDATA.setOption(a[1], NETDATA.localStorage.default[i]);
362 else if(a[0] === 'chart_heights') {
363 if(typeof NETDATA.localStorage.callback[i] === 'function' && typeof NETDATA.localStorage.default[i] !== 'undefined') {
364 NETDATA.localStorage.callback[i](NETDATA.localStorage.default[i]);
370 // ----------------------------------------------------------------------------------------------------------------
372 if(NETDATA.options.debug.main_loop === true)
373 console.log('welcome to NETDATA');
375 window.onresize = function(event) {
376 NETDATA.options.last_page_scroll = new Date().getTime();
377 NETDATA.options.last_resized = new Date().getTime();
380 window.onscroll = function(event) {
381 NETDATA.options.last_page_scroll = new Date().getTime();
382 if(NETDATA.options.targets === null) return;
384 // when the user scrolls he sees that we have
385 // hidden all the not-visible charts
386 // using this little function we try to switch
387 // the charts back to visible quickly
388 var targets = NETDATA.options.targets;
389 var len = targets.length;
390 while(len--) targets[len].isVisible();
393 // ----------------------------------------------------------------------------------------------------------------
396 NETDATA.errorCodes = {
397 100: { message: "Cannot load chart library", alert: true },
398 101: { message: "Cannot load jQuery", alert: true },
399 402: { message: "Chart library not found", alert: false },
400 403: { message: "Chart library not enabled/is failed", alert: false },
401 404: { message: "Chart not found", alert: false }
403 NETDATA.errorLast = {
409 NETDATA.error = function(code, msg) {
410 NETDATA.errorLast.code = code;
411 NETDATA.errorLast.message = msg;
412 NETDATA.errorLast.datetime = new Date().getTime();
414 console.log("ERROR " + code + ": " + NETDATA.errorCodes[code].message + ": " + msg);
416 if(NETDATA.errorCodes[code].alert)
417 alert("ERROR " + code + ": " + NETDATA.errorCodes[code].message + ": " + msg);
420 NETDATA.errorReset = function() {
421 NETDATA.errorLast.code = 0;
422 NETDATA.errorLast.message = "You are doing fine!";
423 NETDATA.errorLast.datetime = 0;
426 // ----------------------------------------------------------------------------------------------------------------
429 // When multiple charts need the same chart, we avoid downloading it
430 // multiple times (and having it in browser memory multiple time)
431 // by using this registry.
433 // Every time we download a chart definition, we save it here with .add()
434 // Then we try to get it back with .get(). If that fails, we download it.
436 NETDATA.chartRegistry = {
439 fixid: function(id) {
440 return id.replace(/:/g, "_").replace(/\//g, "_");
443 add: function(host, id, data) {
444 host = this.fixid(host);
447 if(typeof this.charts[host] === 'undefined')
448 this.charts[host] = {};
450 //console.log('added ' + host + '/' + id);
451 this.charts[host][id] = data;
454 get: function(host, id) {
455 host = this.fixid(host);
458 if(typeof this.charts[host] === 'undefined')
461 if(typeof this.charts[host][id] === 'undefined')
464 //console.log('cached ' + host + '/' + id);
465 return this.charts[host][id];
468 downloadAll: function(host, callback) {
469 while(host.slice(-1) === '/')
470 host = host.substring(0, host.length - 1);
475 url: host + '/api/v1/charts',
476 crossDomain: NETDATA.options.crossDomainAjax,
480 .done(function(data) {
481 var h = NETDATA.chartRegistry.fixid(host);
482 //console.log('downloaded all charts from ' + host + ' (' + h + ')');
483 self.charts[h] = data.charts;
484 if(typeof callback === 'function')
488 if(typeof callback === 'function')
494 // ----------------------------------------------------------------------------------------------------------------
495 // Global Pan and Zoom on charts
497 // Using this structure are synchronize all the charts, so that
498 // when you pan or zoom one, all others are automatically refreshed
499 // to the same timespan.
501 NETDATA.globalPanAndZoom = {
502 seq: 0, // timestamp ms
503 // every time a chart is panned or zoomed
504 // we set the timestamp here
505 // then we use it as a sequence number
506 // to find if other charts are syncronized
509 master: null, // the master chart (state), to which all others
512 force_before_ms: null, // the timespan to sync all other charts
513 force_after_ms: null,
516 setMaster: function(state, after, before) {
517 if(NETDATA.options.current.sync_pan_and_zoom === false)
520 if(this.master !== null && this.master !== state)
521 this.master.resetChart();
523 var now = new Date().getTime();
526 this.force_after_ms = after;
527 this.force_before_ms = before;
528 NETDATA.options.auto_refresher_stop_until = now + NETDATA.options.current.global_pan_sync_time;
532 clearMaster: function() {
533 if(NETDATA.options.current.sync_pan_and_zoom === false)
536 if(this.master !== null) {
537 var state = this.master;
538 this.master = null; // prevent infinite recursion
541 NETDATA.options.auto_refresher_stop_until = 0;
546 this.force_after_ms = null;
547 this.force_before_ms = null;
550 // is the given state the master of the global
551 // pan and zoom sync?
552 isMaster: function(state) {
553 if(this.master === state) return true;
557 // are we currently have a global pan and zoom sync?
558 isActive: function() {
559 if(this.master !== null && this.force_before_ms !== null && this.force_after_ms !== null && this.seq !== 0) return true;
563 // check if a chart, other than the master
564 // needs to be refreshed, due to the global pan and zoom
565 shouldBeAutoRefreshed: function(state) {
566 if(this.master === null || this.seq === 0)
569 if(state.needsRecreation())
572 if(state.tm.pan_and_zoom_seq === this.seq)
579 // ----------------------------------------------------------------------------------------------------------------
580 // dimensions selection
583 // move color assignment to dimensions, here
585 dimensionStatus = function(parent, label, name_div, value_div, color) {
586 this.enabled = false;
587 this.parent = parent;
589 this.name_div = null;
590 this.value_div = null;
593 if(parent.selected === parent.unselected)
594 this.selected = true;
596 this.selected = false;
598 this.setOptions(name_div, value_div, color);
601 dimensionStatus.prototype.invalidate = function() {
602 this.name_div = null;
603 this.value_div = null;
604 this.enabled = false;
607 dimensionStatus.prototype.setOptions = function(name_div, value_div, color) {
610 if(this.name_div != name_div) {
611 this.name_div = name_div;
612 this.name_div.title = this.label;
613 this.name_div.style.color = this.color;
614 if(this.selected === false)
615 this.name_div.className = 'netdata-legend-name not-selected';
617 this.name_div.className = 'netdata-legend-name selected';
620 if(this.value_div != value_div) {
621 this.value_div = value_div;
622 this.value_div.title = this.label;
623 this.value_div.style.color = this.color;
624 if(this.selected === false)
625 this.value_div.className = 'netdata-legend-value not-selected';
627 this.value_div.className = 'netdata-legend-value selected';
634 dimensionStatus.prototype.setHandler = function() {
635 if(this.enabled === false) return;
639 // this.name_div.onmousedown = this.value_div.onmousedown = function(e) {
640 this.name_div.onclick = this.value_div.onclick = function(e) {
642 if(ds.isSelected()) {
644 if(e.shiftKey === true || e.ctrlKey === true) {
645 // control or shift key is pressed -> unselect this (except is none will remain selected, in which case select all)
648 if(ds.parent.countSelected() === 0)
649 ds.parent.selectAll();
652 // no key is pressed -> select only this (except if it is the only selected already, in which case select all)
653 if(ds.parent.countSelected() === 1) {
654 ds.parent.selectAll();
657 ds.parent.selectNone();
663 // this is not selected
664 if(e.shiftKey === true || e.ctrlKey === true) {
665 // control or shift key is pressed -> select this too
669 // no key is pressed -> select only this
670 ds.parent.selectNone();
675 ds.parent.state.redrawChart();
679 dimensionStatus.prototype.select = function() {
680 if(this.enabled === false) return;
682 this.name_div.className = 'netdata-legend-name selected';
683 this.value_div.className = 'netdata-legend-value selected';
684 this.selected = true;
687 dimensionStatus.prototype.unselect = function() {
688 if(this.enabled === false) return;
690 this.name_div.className = 'netdata-legend-name not-selected';
691 this.value_div.className = 'netdata-legend-value hidden';
692 this.selected = false;
695 dimensionStatus.prototype.isSelected = function() {
696 return(this.enabled === true && this.selected === true);
699 // ----------------------------------------------------------------------------------------------------------------
701 dimensionsVisibility = function(state) {
704 this.dimensions = {};
705 this.selected_count = 0;
706 this.unselected_count = 0;
709 dimensionsVisibility.prototype.dimensionAdd = function(label, name_div, value_div, color) {
710 if(typeof this.dimensions[label] === 'undefined') {
712 this.dimensions[label] = new dimensionStatus(this, label, name_div, value_div, color);
715 this.dimensions[label].setOptions(name_div, value_div, color);
717 return this.dimensions[label];
720 dimensionsVisibility.prototype.dimensionGet = function(label) {
721 return this.dimensions[label];
724 dimensionsVisibility.prototype.invalidateAll = function() {
725 for(var d in this.dimensions)
726 this.dimensions[d].invalidate();
729 dimensionsVisibility.prototype.selectAll = function() {
730 for(var d in this.dimensions)
731 this.dimensions[d].select();
734 dimensionsVisibility.prototype.countSelected = function() {
736 for(var d in this.dimensions)
737 if(this.dimensions[d].isSelected()) i++;
742 dimensionsVisibility.prototype.selectNone = function() {
743 for(var d in this.dimensions)
744 this.dimensions[d].unselect();
747 dimensionsVisibility.prototype.selected2BooleanArray = function(array) {
748 var ret = new Array();
749 this.selected_count = 0;
750 this.unselected_count = 0;
752 for(var i = 0, len = array.length; i < len ; i++) {
753 var ds = this.dimensions[array[i]];
754 if(typeof ds === 'undefined') {
755 // console.log(array[i] + ' is not found');
760 if(ds.isSelected()) {
762 this.selected_count++;
766 this.unselected_count++;
770 if(this.selected_count === 0 && this.unselected_count !== 0) {
772 return this.selected2BooleanArray(array);
779 // ----------------------------------------------------------------------------------------------------------------
780 // global selection sync
782 NETDATA.globalSelectionSync = {
789 if(this.state !== null)
790 this.state.globalSelectionSyncStop();
794 if(this.state !== null) {
795 this.state.globalSelectionSyncDelay();
800 // ----------------------------------------------------------------------------------------------------------------
801 // Our state object, where all per-chart values are stored
803 chartState = function(element) {
804 var self = $(element);
805 this.element = element;
808 // all private functions should use 'that', instead of 'this'
812 * show an error instead of the chart
814 var error = function(msg) {
815 that.element.innerHTML = that.id + ': ' + msg;
816 that.enabled = false;
817 that.current = that.pan;
820 // GUID - a unique identifier for the chart
821 this.uuid = NETDATA.guid();
823 // string - the name of chart
824 this.id = self.data('netdata');
826 // string - the key for localStorage settings
827 this.settings_id = self.data('id') || null;
829 // the user given dimensions of the element
830 this.width = self.data('width') || NETDATA.chartDefaults.width;
831 this.height = self.data('height') || NETDATA.chartDefaults.height;
833 if(this.settings_id !== null) {
834 this.height = NETDATA.localStorageGet('chart_heights.' + this.settings_id, this.height, function(height) {
835 // this is the callback that will be called
836 // if and when the user resets all localStorage variables
839 resizeChartToHeight(height);
843 // string - the netdata server URL, without any path
844 this.host = self.data('host') || NETDATA.chartDefaults.host;
846 // make sure the host does not end with /
847 // all netdata API requests use absolute paths
848 while(this.host.slice(-1) === '/')
849 this.host = this.host.substring(0, this.host.length - 1);
851 // string - the grouping method requested by the user
852 this.method = self.data('method') || NETDATA.chartDefaults.method;
854 // the time-range requested by the user
855 this.after = self.data('after') || NETDATA.chartDefaults.after;
856 this.before = self.data('before') || NETDATA.chartDefaults.before;
858 // the pixels per point requested by the user
859 this.pixels_per_point = self.data('pixels-per-point') || 1;
860 this.points = self.data('points') || null;
862 // the dimensions requested by the user
863 this.dimensions = self.data('dimensions') || null;
865 // the chart library requested by the user
866 this.library_name = self.data('chart-library') || NETDATA.chartDefaults.library;
868 // object - the chart library used
873 this.colors_assigned = {};
874 this.colors_available = null;
876 // the element already created by the user
877 this.element_message = null;
879 // the element with the chart
880 this.element_chart = null;
882 // the element with the legend of the chart (if created by us)
883 this.element_legend = null;
884 this.element_legend_childs = {
894 this.chart_url = null; // string - the url to download chart info
895 this.chart = null; // object - the chart as downloaded from the server
897 this.validated = false; // boolean - has the chart been validated?
898 this.enabled = true; // boolean - is the chart enabled for refresh?
899 this.paused = false; // boolean - is the chart paused for any reason?
900 this.selected = false; // boolean - is the chart shown a selection?
901 this.debug = false; // boolean - console.log() debug info about this chart
903 this.netdata_first = 0; // milliseconds - the first timestamp in netdata
904 this.netdata_last = 0; // milliseconds - the last timestamp in netdata
905 this.requested_after = null; // milliseconds - the timestamp of the request after param
906 this.requested_before = null; // milliseconds - the timestamp of the request before param
911 force_update_at: 0, // the timestamp to force the update at
912 force_before_ms: null,
918 force_update_at: 0, // the timestamp to force the update at
919 force_before_ms: null,
925 force_update_at: 0, // the timestamp to force the update at
926 force_before_ms: null,
930 // this is a pointer to one of the sub-classes below
932 this.current = this.auto;
934 // check the requested library is available
935 // we don't initialize it here - it will be initialized when
936 // this chart will be first used
937 if(typeof NETDATA.chartLibraries[that.library_name] === 'undefined') {
938 NETDATA.error(402, that.library_name);
939 error('chart library "' + that.library_name + '" is not found');
942 else if(NETDATA.chartLibraries[that.library_name].enabled === false) {
943 NETDATA.error(403, that.library_name);
944 error('chart library "' + that.library_name + '" is not enabled');
948 that.library = NETDATA.chartLibraries[that.library_name];
950 // milliseconds - the time the last refresh took
951 this.refresh_dt_ms = 0;
953 // if we need to report the rendering speed
954 // find the element that needs to be updated
955 var refresh_dt_element_name = self.data('dt-element-name') || null; // string - the element to print refresh_dt_ms
957 if(refresh_dt_element_name !== null)
958 this.refresh_dt_element = document.getElementById(refresh_dt_element_name) || null;
960 this.refresh_dt_element = null;
962 this.dimensions_visibility = new dimensionsVisibility(this);
964 // ============================================================================================================
967 var createDOM = function() {
968 if(that.enabled == false) return;
970 if(that.element_message !== null) that.element_message.innerHTML = '';
971 if(that.element_legend !== null) that.element_legend.innerHTML = '';
972 if(that.element_chart !== null) that.element_chart.innerHTML = '';
974 that.element.innerHTML = '';
976 that.element_message = document.createElement('div');
977 that.element_message.className = ' netdata-message hidden';
978 that.element.appendChild(that.element_message);
980 that.element_chart = document.createElement('div');
981 that.element_chart.id = that.library_name + '-' + that.uuid + '-chart';
982 that.element.appendChild(that.element_chart);
984 if(that.hasLegend() === true) {
985 that.element.className = "netdata-container-with-legend";
986 that.element_chart.className = 'netdata-chart-with-legend-right netdata-' + that.library_name + '-chart-with-legend-right';
988 that.element_legend = document.createElement('div');
989 that.element_legend.className = 'netdata-chart-legend netdata-' + that.library_name + '-legend';
990 that.element.appendChild(that.element_legend);
993 that.element.className = "netdata-container";
994 that.element_chart.className = ' netdata-chart netdata-' + that.library_name + '-chart';
996 that.element_legend = null;
998 that.element_legend_childs.series = null;
1000 if(that.width !== 0)
1001 $(that.element).css('width', that.width);
1003 if(that.height !== 0)
1004 $(that.element).css('height', that.height);
1006 if(NETDATA.chartDefaults.min_width !== null)
1007 $(that.element).css('min-width', NETDATA.chartDefaults.min_width);
1009 that.tm.last_dom_created = new Date().getTime();
1015 * initialize state viariables
1016 * destroy all (possibly) created state elements
1017 * create the basic DOM for a chart
1019 var init = function() {
1020 if(that.enabled == false) return;
1022 that.paused = false;
1023 that.selected = false;
1025 that.chart_created = false; // boolean - is the library.create() been called?
1026 that.updates_counter = 0; // numeric - the number of refreshes made so far
1027 that.updates_since_last_creation = 0;
1030 last_initialized: 0, // milliseconds - the timestamp it was last initialized
1031 last_dom_created: 0, // milliseconds - the timestamp its DOM was last created
1032 last_mode_switch: 0, // milliseconds - the timestamp it switched modes
1034 last_info_downloaded: 0, // milliseconds - the timestamp we downloaded the chart
1035 last_updated: 0, // the timestamp the chart last updated with data
1036 pan_and_zoom_seq: 0, // the sequence number of the global synchronization
1038 // Used with NETDATA.globalPanAndZoom.seq
1039 last_visible_check: 0, // the time we last checked if it is visible
1040 last_resized: 0, // the time the chart was resized
1041 last_hidden: 0, // the time the chart was hidden
1042 last_unhidden: 0, // the time the chart was unhidden
1043 last_autorefreshed: 0 // the time the chart was last refreshed
1046 that.data = null; // the last data as downloaded from the netdata server
1047 that.data_url = 'invalid://'; // string - the last url used to update the chart
1048 that.data_points = 0; // number - the number of points returned from netdata
1049 that.data_after = 0; // milliseconds - the first timestamp of the data
1050 that.data_before = 0; // milliseconds - the last timestamp of the data
1051 that.data_update_every = 0; // milliseconds - the frequency to update the data
1053 that.tm.last_initialized = new Date().getTime();
1056 that.setMode('auto');
1059 var maxMessageFontSize = function() {
1060 // normally we want a font size, as tall as the element
1061 var h = that.element_message.clientHeight;
1063 // but give it some air, 20% let's say, or 5 pixels min
1064 var lost = Math.max(h * 0.2, 5);
1067 // center the text, verically
1068 var paddingTop = (lost - 5) / 2;
1070 // but check the width too
1071 // it should fit 10 characters in it
1072 var w = that.element_message.clientWidth / 10;
1074 paddingTop += (h - w) / 2;
1078 // and don't make it too huge
1079 // 5% of the screen size is good
1080 if(h > screen.height / 20) {
1081 paddingTop += (h - (screen.height / 20)) / 2;
1082 h = screen.height / 20;
1086 that.element_message.style.fontSize = h.toString() + 'px';
1087 that.element_message.style.paddingTop = paddingTop.toString() + 'px';
1090 var showMessage = function(msg) {
1091 that.element_message.className = 'netdata-message';
1092 that.element_message.innerHTML = msg;
1093 this.element_message.style.fontSize = 'x-small';
1094 that.element_message.style.paddingTop = '0px';
1095 that.___messageHidden___ = undefined;
1098 var showMessageIcon = function(icon) {
1099 that.element_message.innerHTML = icon;
1100 that.element_message.className = 'netdata-message icon';
1101 maxMessageFontSize();
1102 that.___messageHidden___ = undefined;
1105 var hideMessage = function() {
1106 if(typeof that.___messageHidden___ === 'undefined') {
1107 that.___messageHidden___ = true;
1108 that.element_message.className = 'netdata-message hidden';
1112 var showRendering = function() {
1114 if(that.chart !== null) {
1115 if(that.chart.chart_type === 'line')
1116 icon = '<i class="fa fa-line-chart"></i>';
1118 icon = '<i class="fa fa-area-chart"></i>';
1121 icon = '<i class="fa fa-area-chart"></i>';
1123 showMessageIcon(icon + ' netdata');
1126 var showLoading = function() {
1127 if(that.chart_created === false) {
1128 showMessageIcon('<i class="fa fa-refresh"></i> netdata');
1134 // hide the chart, when it is not visible - called from isVisible()
1135 var hideChart = function() {
1137 if(that.chart_created === false) return;
1139 // we should destroy it
1140 if(NETDATA.options.current.destroy_on_hide === true) {
1142 that.___chartIsHidden___ = undefined;
1146 // just hide it, if it is not already hidden
1147 if(typeof that.___chartIsHidden___ === 'undefined') {
1149 that.element_chart.style.display = 'none';
1150 if(that.element_legend !== null) that.element_legend.style.display = 'none';
1151 that.___chartIsHidden___ = true;
1155 // unhide the chart, when it is visible - called from isVisible()
1156 var unhideChart = function() {
1157 if(typeof that.___chartIsHidden___ !== 'undefined') {
1158 that.element_chart.style.display = 'inline-block';
1159 if(that.element_legend !== null) that.element_legend.style.display = 'inline-block';
1160 that.___chartIsHidden___ = undefined;
1166 // ----------------------------------------------------------------------------------------------------------------
1169 // resizeChart() - private
1170 // to be called just before the chart library to make sure that
1171 // a properly sized dom is available
1172 var resizeChart = function() {
1173 if(that.isVisible() === true && that.tm.last_resized < NETDATA.options.last_resized) {
1174 that.tm.last_resized = new Date().getTime();
1175 if(that.chart_created === false) return;
1177 if(that.needsRecreation())
1180 else if(typeof that.library.resize === 'function') {
1181 that.library.resize(that);
1183 if(that.element_legend_childs.nano !== null && that.element_legend_childs.nano_options !== null)
1184 $(that.element_legend_childs.nano).nanoScroller();
1186 maxMessageFontSize();
1191 // this is the actual chart resize algorithm
1193 // - resize the entire container
1194 // - update the internal states
1195 // - resize the chart as the div changes height
1196 // - update the scrollbar of the legend
1197 var resizeChartToHeight = function(h) {
1199 that.element.style.height = h;
1201 if(that.settings_id !== null)
1202 NETDATA.localStorageSet('chart_heights.' + that.settings_id, h);
1204 var now = new Date().getTime();
1205 NETDATA.options.last_page_scroll = now;
1206 NETDATA.options.last_resized = now;
1207 NETDATA.options.auto_refresher_stop_until = now + NETDATA.options.current.stop_updates_while_resizing;
1210 that.tm.last_resized = 0;
1214 this.resizeHandler = function(e) {
1217 if(typeof this.event_resize === 'undefined'
1218 || this.event_resize.chart_original_w === 'undefined'
1219 || this.event_resize.chart_original_h === 'undefined')
1220 this.event_resize = {
1221 chart_original_w: this.element.clientWidth,
1222 chart_original_h: this.element.clientHeight,
1226 if(e.type === 'touchstart') {
1227 this.event_resize.mouse_start_x = e.touches.item(0).pageX;
1228 this.event_resize.mouse_start_y = e.touches.item(0).pageY;
1231 this.event_resize.mouse_start_x = e.clientX;
1232 this.event_resize.mouse_start_y = e.clientY;
1235 this.event_resize.chart_start_w = this.element.clientWidth;
1236 this.event_resize.chart_start_h = this.element.clientHeight;
1237 this.event_resize.chart_last_w = this.element.clientWidth;
1238 this.event_resize.chart_last_h = this.element.clientHeight;
1240 var now = new Date().getTime();
1241 if(now - this.event_resize.last <= NETDATA.options.current.double_click_speed) {
1242 // double click / double tap event
1244 // the optimal height of the chart
1245 // showing the entire legend
1246 var optimal = this.event_resize.chart_last_h
1247 + this.element_legend_childs.content.scrollHeight
1248 - this.element_legend_childs.content.clientHeight;
1250 // if we are not optimal, be optimal
1251 if(this.event_resize.chart_last_h != optimal)
1252 resizeChartToHeight(optimal.toString() + 'px');
1254 // else if we do not have the original height
1255 // reset to the original height
1256 else if(this.event_resize.chart_last_h != this.event_resize.chart_original_h)
1257 resizeChartToHeight(this.event_resize.chart_original_h.toString() + 'px');
1260 this.event_resize.last = now;
1262 // process movement event
1263 document.onmousemove =
1264 document.ontouchmove =
1265 this.element_legend_childs.resize_handler.onmousemove =
1266 this.element_legend_childs.resize_handler.ontouchmove =
1271 case 'mousemove': y = e.clientY; break;
1272 case 'touchmove': y = e.touches.item(e.touches - 1).pageY; break;
1276 var newH = that.event_resize.chart_start_h + y - that.event_resize.mouse_start_y;
1278 if(newH >= 70 && newH !== that.event_resize.chart_last_h) {
1279 resizeChartToHeight(newH.toString() + 'px');
1280 that.event_resize.chart_last_h = newH;
1285 // process end event
1286 document.onmouseup =
1287 document.ontouchend =
1288 this.element_legend_childs.resize_handler.onmouseup =
1289 this.element_legend_childs.resize_handler.ontouchend =
1291 // remove all the hooks
1292 document.onmouseup =
1293 document.onmousemove =
1294 document.ontouchmove =
1295 document.ontouchend =
1296 that.element_legend_childs.resize_handler.onmousemove =
1297 that.element_legend_childs.resize_handler.ontouchmove =
1298 that.element_legend_childs.resize_handler.onmouseout =
1299 that.element_legend_childs.resize_handler.onmouseup =
1300 that.element_legend_childs.resize_handler.ontouchend =
1303 // allow auto-refreshes
1304 NETDATA.options.auto_refresher_stop_until = 0;
1310 var noDataToShow = function() {
1311 this.legendUpdateDOM();
1312 that.tm.last_autorefreshed = new Date().getTime();
1313 that.data_update_every = 30 * 1000;
1316 // ============================================================================================================
1319 this.error = function(msg) {
1323 this.setMode = function(m) {
1324 if(this.current !== null && this.current.name === m) return;
1327 this.current = this.auto;
1328 else if(m === 'pan')
1329 this.current = this.pan;
1330 else if(m === 'zoom')
1331 this.current = this.zoom;
1333 this.current = this.auto;
1335 this.current.force_update_at = 0;
1336 this.current.force_before_ms = null;
1337 this.current.force_after_ms = null;
1339 this.tm.last_mode_switch = new Date().getTime();
1342 // ----------------------------------------------------------------------------------------------------------------
1343 // global selection sync
1345 // prevent to global selection sync for some time
1346 this.globalSelectionSyncDelay = function(ms) {
1347 if(NETDATA.options.current.sync_selection === false)
1350 if(typeof ms === 'number')
1351 NETDATA.globalSelectionSync.dont_sync_before = new Date().getTime() + ms;
1353 NETDATA.globalSelectionSync.dont_sync_before = new Date().getTime() + NETDATA.options.current.sync_selection_delay;
1356 // can we globally apply selection sync?
1357 this.globalSelectionSyncAbility = function() {
1358 if(NETDATA.options.current.sync_selection === false)
1361 if(NETDATA.globalSelectionSync.dont_sync_before > new Date().getTime())
1367 this.globalSelectionSyncIsMaster = function() {
1368 if(NETDATA.globalSelectionSync.state === this)
1374 // this chart is the master of the global selection sync
1375 this.globalSelectionSyncBeMaster = function() {
1377 if(this.globalSelectionSyncIsMaster()) {
1378 if(this.debug === true)
1379 this.log('sync: I am the master already.');
1384 if(NETDATA.globalSelectionSync.state) {
1385 if(this.debug === true)
1386 this.log('sync: I am not the sync master. Resetting global sync.');
1388 this.globalSelectionSyncStop();
1391 // become the master
1392 if(this.debug === true)
1393 this.log('sync: becoming sync master.');
1395 this.selected = true;
1396 NETDATA.globalSelectionSync.state = this;
1398 // find the all slaves
1399 var targets = NETDATA.options.targets;
1400 var len = targets.length;
1405 if(this.debug === true)
1406 st.log('sync: not adding me to sync');
1408 else if(st.globalSelectionSyncIsEligible()) {
1409 if(this.debug === true)
1410 st.log('sync: adding to sync as slave');
1412 st.globalSelectionSyncBeSlave();
1416 // this.globalSelectionSyncDelay(100);
1419 // can the chart participate to the global selection sync as a slave?
1420 this.globalSelectionSyncIsEligible = function() {
1421 if(this.enabled === true
1422 && this.library !== null
1423 && typeof this.library.setSelection === 'function'
1424 && this.isVisible() === true
1425 && this.chart_created === true)
1431 // this chart becomes a slave of the global selection sync
1432 this.globalSelectionSyncBeSlave = function() {
1433 if(NETDATA.globalSelectionSync.state !== this)
1434 NETDATA.globalSelectionSync.slaves.push(this);
1437 // sync all the visible charts to the given time
1438 // this is to be called from the chart libraries
1439 this.globalSelectionSync = function(t) {
1440 if(this.globalSelectionSyncAbility() === false) {
1441 if(this.debug === true)
1442 this.log('sync: cannot sync (yet?).');
1447 if(this.globalSelectionSyncIsMaster() === false) {
1448 if(this.debug === true)
1449 this.log('sync: trying to be sync master.');
1451 this.globalSelectionSyncBeMaster();
1453 if(this.globalSelectionSyncAbility() === false) {
1454 if(this.debug === true)
1455 this.log('sync: cannot sync (yet?).');
1461 NETDATA.globalSelectionSync.last_t = t;
1462 $.each(NETDATA.globalSelectionSync.slaves, function(i, st) {
1467 // stop syncing all charts to the given time
1468 this.globalSelectionSyncStop = function() {
1469 if(NETDATA.globalSelectionSync.slaves.length) {
1470 if(this.debug === true)
1471 this.log('sync: cleaning up...');
1473 $.each(NETDATA.globalSelectionSync.slaves, function(i, st) {
1475 if(that.debug === true)
1476 st.log('sync: not adding me to sync stop');
1479 if(that.debug === true)
1480 st.log('sync: removed slave from sync');
1482 st.clearSelection();
1486 NETDATA.globalSelectionSync.last_t = 0;
1487 NETDATA.globalSelectionSync.slaves = [];
1488 NETDATA.globalSelectionSync.state = null;
1491 this.clearSelection();
1494 this.setSelection = function(t) {
1495 if(typeof this.library.setSelection === 'function') {
1496 if(this.library.setSelection(this, t) === true)
1497 this.selected = true;
1499 this.selected = false;
1501 else this.selected = true;
1503 if(this.selected === true && this.debug === true)
1504 this.log('selection set to ' + t.toString());
1506 return this.selected;
1509 this.clearSelection = function() {
1510 if(this.selected === true) {
1511 if(typeof this.library.clearSelection === 'function') {
1512 if(this.library.clearSelection(this) === true)
1513 this.selected = false;
1515 this.selected = true;
1517 else this.selected = false;
1519 if(this.selected === false && this.debug === true)
1520 this.log('selection cleared');
1525 return this.selected;
1528 // find if a timestamp (ms) is shown in the current chart
1529 this.timeIsVisible = function(t) {
1530 if(t >= this.data_after && t <= this.data_before)
1535 this.calculateRowForTime = function(t) {
1536 if(this.timeIsVisible(t) === false) return -1;
1537 return Math.floor((t - this.data_after) / this.data_update_every);
1540 // ----------------------------------------------------------------------------------------------------------------
1543 this.log = function(msg) {
1544 console.log(this.id + ' (' + this.library_name + ' ' + this.uuid + '): ' + msg);
1547 this.pauseChart = function() {
1548 if(this.paused === false) {
1549 if(this.debug === true)
1556 this.unpauseChart = function() {
1558 if(this.debug === true)
1559 this.log('unpaused');
1561 this.paused = false;
1565 this.resetChart = function() {
1566 if(NETDATA.globalPanAndZoom.isMaster(this) && this.isVisible())
1567 NETDATA.globalPanAndZoom.clearMaster();
1569 this.tm.pan_and_zoom_seq = 0;
1571 this.clearSelection();
1573 this.setMode('auto');
1574 this.current.force_update_at = 0;
1575 this.current.force_before_ms = null;
1576 this.current.force_after_ms = null;
1577 this.tm.last_autorefreshed = 0;
1578 this.paused = false;
1579 this.selected = false;
1580 this.enabled = true;
1583 // do not update the chart here
1584 // or the chart will flip-flop when it is the master
1585 // of a selection sync and another chart becomes
1587 if(NETDATA.options.current.sync_pan_and_zoom === false && this.isVisible() === true)
1591 this.updateChartPanOrZoom = function(after, before) {
1592 if(before < after) return false;
1594 var min_duration = Math.round((this.chartWidth() / 30 * this.chart.update_every * 1000));
1596 if(this.debug === true)
1597 this.log('requested duration of ' + ((before - after) / 1000).toString() + ' (' + after + ' - ' + before + '), minimum ' + min_duration / 1000);
1599 if((before - after) < min_duration) return false;
1601 var current_duration = this.data_before - this.data_after;
1602 var wanted_duration = before - after;
1603 var tolerance = this.data_update_every * 2;
1604 var movement = Math.abs(before - this.data_before);
1606 if(this.debug === true)
1607 this.log('current duration: ' + current_duration / 1000 + ', wanted duration: ' + wanted_duration / 1000 + ', movement: ' + movement / 1000 + ', tolerance: ' + tolerance / 1000);
1609 if(Math.abs(current_duration - wanted_duration) <= tolerance && movement <= tolerance) {
1610 if(this.debug === true)
1611 this.log('IGNORED');
1616 if(this.current.name === 'auto') {
1617 this.setMode('pan');
1619 if(this.debug === true)
1620 this.log('updateChartPanOrZoom(): caller did not set proper mode');
1623 this.current.force_update_at = new Date().getTime() + NETDATA.options.current.pan_and_zoom_delay;
1624 this.current.force_after_ms = after;
1625 this.current.force_before_ms = before;
1626 NETDATA.globalPanAndZoom.setMaster(this, after, before);
1630 this.legendFormatValue = function(value) {
1631 if(value === null || value === 'undefined') return '-';
1632 if(typeof value !== 'number') return value;
1634 var abs = Math.abs(value);
1635 if(abs >= 1) return (Math.round(value * 100) / 100).toLocaleString();
1636 if(abs >= 0.1) return (Math.round(value * 1000) / 1000).toLocaleString();
1637 return (Math.round(value * 10000) / 10000).toLocaleString();
1640 this.legendSetLabelValue = function(label, value) {
1641 var series = this.element_legend_childs.series[label];
1642 if(typeof series === 'undefined') return;
1643 if(series.value === null && series.user === null) return;
1645 // if the value has not changed, skip DOM update
1646 //if(series.last === value) return;
1649 if(typeof value === 'number') {
1650 var v = Math.abs(value);
1651 s = r = this.legendFormatValue(value);
1653 if(typeof series.last === 'number') {
1654 if(v > series.last) s += '<i class="fa fa-angle-up" style="width: 8px; text-align: center; overflow: hidden; vertical-align: middle;"></i>';
1655 else if(v < series.last) s += '<i class="fa fa-angle-down" style="width: 8px; text-align: center; overflow: hidden; vertical-align: middle;"></i>';
1656 else s += '<i class="fa fa-angle-left" style="width: 8px; text-align: center; overflow: hidden; vertical-align: middle;"></i>';
1658 else s += '<i class="fa fa-angle-right" style="width: 8px; text-align: center; overflow: hidden; vertical-align: middle;"></i>';
1663 series.last = value;
1666 if(series.value !== null) series.value.innerHTML = s;
1667 if(series.user !== null) series.user.innerHTML = r;
1670 this.legendSetDate = function(ms) {
1671 if(typeof ms !== 'number') {
1672 this.legendShowUndefined();
1676 var d = new Date(ms);
1678 if(this.element_legend_childs.title_date)
1679 this.element_legend_childs.title_date.innerHTML = d.toLocaleDateString();
1681 if(this.element_legend_childs.title_time)
1682 this.element_legend_childs.title_time.innerHTML = d.toLocaleTimeString();
1684 if(this.element_legend_childs.title_units)
1685 this.element_legend_childs.title_units.innerHTML = this.chart.units;
1688 this.legendShowUndefined = function() {
1689 if(this.element_legend_childs.title_date)
1690 this.element_legend_childs.title_date.innerHTML = ' ';
1692 if(this.element_legend_childs.title_time)
1693 this.element_legend_childs.title_time.innerHTML = this.chart.name;
1695 if(this.element_legend_childs.title_units)
1696 this.element_legend_childs.title_units.innerHTML = ' ';
1698 if(this.data && this.element_legend_childs.series !== null) {
1699 var labels = this.data.dimension_names;
1700 var i = labels.length;
1702 var label = labels[i];
1704 if(typeof label === 'undefined') continue;
1705 if(typeof this.element_legend_childs.series[label] === 'undefined') continue;
1706 this.legendSetLabelValue(label, null);
1711 this.legendShowLatestValues = function() {
1712 if(this.chart === null) return;
1713 if(this.selected) return;
1715 if(this.data === null || this.element_legend_childs.series === null) {
1716 this.legendShowUndefined();
1720 var show_undefined = true;
1721 if(Math.abs(this.data.last_entry - this.data.before) <= this.data.view_update_every)
1722 show_undefined = false;
1724 if(show_undefined) {
1725 this.legendShowUndefined();
1729 this.legendSetDate(this.data.before * 1000);
1731 var labels = this.data.dimension_names;
1732 var i = labels.length;
1734 var label = labels[i];
1736 if(typeof label === 'undefined') continue;
1737 if(typeof this.element_legend_childs.series[label] === 'undefined') continue;
1740 this.legendSetLabelValue(label, null);
1742 this.legendSetLabelValue(label, this.data.view_latest_values[i]);
1746 this.legendReset = function() {
1747 this.legendShowLatestValues();
1750 // this should be called just ONCE per dimension per chart
1751 this._chartDimensionColor = function(label) {
1752 if(this.colors === null) this.chartColors();
1754 if(typeof this.colors_assigned[label] === 'undefined') {
1755 if(this.colors_available.length === 0) {
1756 for(var i = 0, len = NETDATA.colors.length; i < len ; i++)
1757 this.colors_available.push(NETDATA.colors[i]);
1760 this.colors_assigned[label] = this.colors_available.shift();
1762 if(this.debug === true)
1763 this.log('label "' + label + '" got color "' + this.colors_assigned[label]);
1766 if(this.debug === true)
1767 this.log('label "' + label + '" already has color "' + this.colors_assigned[label] + '"');
1770 this.colors.push(this.colors_assigned[label]);
1771 return this.colors_assigned[label];
1774 this.chartColors = function() {
1775 if(this.colors !== null) return this.colors;
1777 this.colors = new Array();
1778 this.colors_available = new Array();
1779 // this.colors_assigned = {};
1781 var c = $(this.element).data('colors');
1782 if(typeof c !== 'undefined' && c !== null) {
1783 if(typeof c !== 'string') {
1784 this.log('invalid color given: ' + c + ' (give a space separated list of colors)');
1788 for(var i = 0, len = c.length; i < len ; i++)
1789 this.colors_available.push(c[i]);
1793 // push all the standard colors too
1794 for(var i = 0, len = NETDATA.colors.length; i < len ; i++)
1795 this.colors_available.push(NETDATA.colors[i]);
1800 this.legendUpdateDOM = function() {
1803 // check that the legend DOM is up to date for the downloaded dimensions
1804 if(typeof this.element_legend_childs.series !== 'object' || this.element_legend_childs.series === null) {
1805 // this.log('the legend does not have any series - requesting legend update');
1808 else if(this.data === null) {
1809 // this.log('the chart does not have any data - requesting legend update');
1812 else if(typeof this.element_legend_childs.series.labels_key === 'undefined') {
1816 var labels = this.data.dimension_names.toString();
1817 if(labels !== this.element_legend_childs.series.labels_key) {
1820 if(this.debug === true)
1821 this.log('NEW LABELS: "' + labels + '" NOT EQUAL OLD LABELS: "' + this.element_legend_childs.series.labels_key + '"');
1825 if(needed === false) {
1826 // make sure colors available
1829 // do we have to update the current values?
1830 // we do this, only when the visible chart is current
1831 if(Math.abs(this.data.last_entry - this.data.before) <= this.data.view_update_every) {
1832 if(this.debug === true)
1833 this.log('chart in running... updating values on legend...');
1835 //var labels = this.data.dimension_names;
1836 //var i = labels.length;
1838 // this.legendSetLabelValue(labels[i], this.data.latest_values[i]);
1842 if(this.colors === null) {
1843 // this is the first time we update the chart
1844 // let's assign colors to all dimensions
1845 if(this.library.track_colors() === true)
1846 for(var dim in this.chart.dimensions)
1847 this._chartDimensionColor(this.chart.dimensions[dim].name);
1849 // we will re-generate the colors for the chart
1852 if(this.debug === true)
1853 this.log('updating Legend DOM');
1855 // mark all dimensions as invalid
1856 this.dimensions_visibility.invalidateAll();
1858 var genLabel = function(state, parent, name, count) {
1859 var color = state._chartDimensionColor(name);
1861 var user_element = null;
1862 var user_id = self.data('show-value-of-' + name + '-at') || null;
1863 if(user_id !== null) {
1864 user_element = document.getElementById(user_id) || null;
1865 if(user_element === null)
1866 me.log('Cannot find element with id: ' + user_id);
1869 state.element_legend_childs.series[name] = {
1870 name: document.createElement('span'),
1871 value: document.createElement('span'),
1876 var label = state.element_legend_childs.series[name];
1878 // create the dimension visibility tracking for this label
1879 var ds = state.dimensions_visibility.dimensionAdd(name, label.name, label.value, color);
1881 var rgb = NETDATA.colorHex2Rgb(color);
1882 label.name.innerHTML = '<table class="netdata-legend-name-table-'
1883 + state.chart.chart_type
1884 + '" style="background-color: '
1885 + 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + NETDATA.options.current['color_fill_opacity_' + state.chart.chart_type] + ')'
1886 + '"><tr class="netdata-legend-name-tr"><td class="netdata-legend-name-td"></td></tr></table>'
1888 var text = document.createTextNode(' ' + name);
1889 label.name.appendChild(text);
1892 parent.appendChild(document.createElement('br'));
1894 parent.appendChild(label.name);
1895 parent.appendChild(label.value);
1898 var content = document.createElement('div');
1900 if(this.hasLegend()) {
1901 this.element_legend_childs = {
1903 resize_handler: document.createElement('div'),
1904 title_date: document.createElement('span'),
1905 title_time: document.createElement('span'),
1906 title_units: document.createElement('span'),
1907 nano: document.createElement('div'),
1909 paneClass: 'netdata-legend-series-pane',
1910 sliderClass: 'netdata-legend-series-slider',
1911 contentClass: 'netdata-legend-series-content',
1912 enabledClass: '__enabled',
1913 flashedClass: '__flashed',
1914 activeClass: '__active',
1916 alwaysVisible: true,
1922 this.element_legend.innerHTML = '';
1924 this.element_legend_childs.resize_handler.className += " netdata-legend-resize-handler";
1925 this.element_legend_childs.resize_handler.innerHTML = '<i class="fa fa-chevron-up"></i><i class="fa fa-chevron-down"></i>';
1926 this.element.appendChild(this.element_legend_childs.resize_handler);
1929 this.element_legend_childs.resize_handler.onmousedown =
1931 that.resizeHandler(e);
1935 this.element_legend_childs.resize_handler.addEventListener('touchstart', function(e) {
1936 that.resizeHandler(e);
1939 this.element_legend_childs.title_date.className += " netdata-legend-title-date";
1940 this.element_legend.appendChild(this.element_legend_childs.title_date);
1942 this.element_legend.appendChild(document.createElement('br'));
1944 this.element_legend_childs.title_time.className += " netdata-legend-title-time";
1945 this.element_legend.appendChild(this.element_legend_childs.title_time);
1947 this.element_legend.appendChild(document.createElement('br'));
1949 this.element_legend_childs.title_units.className += " netdata-legend-title-units";
1950 this.element_legend.appendChild(this.element_legend_childs.title_units);
1952 this.element_legend.appendChild(document.createElement('br'));
1954 this.element_legend_childs.nano.className = 'netdata-legend-series';
1955 this.element_legend.appendChild(this.element_legend_childs.nano);
1957 content.className = 'netdata-legend-series-content';
1958 this.element_legend_childs.nano.appendChild(content);
1961 this.element_legend_childs = {
1963 resize_handler: null,
1974 this.element_legend_childs.series.labels_key = this.data.dimension_names.toString();
1975 if(this.debug === true)
1976 this.log('labels from data: "' + this.element_legend_childs.series.labels_key + '"');
1978 for(var i = 0, len = this.data.dimension_names.length; i < len ;i++) {
1979 genLabel(this, content, this.data.dimension_names[i], i);
1983 var tmp = new Array();
1984 for(var dim in this.chart.dimensions) {
1985 tmp.push(this.chart.dimensions[dim].name);
1986 genLabel(this, content, this.chart.dimensions[dim].name, i);
1988 this.element_legend_childs.series.labels_key = tmp.toString();
1989 if(this.debug === true)
1990 this.log('labels from chart: "' + this.element_legend_childs.series.labels_key + '"');
1993 // create a hidden div to be used for hidding
1994 // the original legend of the chart library
1995 var el = document.createElement('div');
1996 if(this.element_legend !== null)
1997 this.element_legend.appendChild(el);
1998 el.style.display = 'none';
2000 this.element_legend_childs.hidden = document.createElement('div');
2001 el.appendChild(this.element_legend_childs.hidden);
2003 if(this.element_legend_childs.nano !== null && this.element_legend_childs.nano_options !== null)
2004 $(this.element_legend_childs.nano).nanoScroller(this.element_legend_childs.nano_options);
2006 this.legendShowLatestValues();
2009 this.hasLegend = function() {
2010 if(typeof this.___hasLegendCache___ !== 'undefined')
2011 return this.___hasLegendCache___;
2014 if(this.library && this.library.legend(this) === 'right-side') {
2015 var legend = $(this.element).data('legend') || 'yes';
2016 if(legend === 'yes') leg = true;
2019 this.___hasLegendCache___ = leg;
2023 this.legendWidth = function() {
2024 return (this.hasLegend())?140:0;
2027 this.legendHeight = function() {
2028 return $(this.element).height();
2031 this.chartWidth = function() {
2032 return $(this.element).width() - this.legendWidth();
2035 this.chartHeight = function() {
2036 return $(this.element).height();
2039 this.chartPixelsPerPoint = function() {
2040 // force an options provided detail
2041 var px = this.pixels_per_point;
2043 if(this.library && px < this.library.pixels_per_point(this))
2044 px = this.library.pixels_per_point(this);
2046 if(px < NETDATA.options.current.pixels_per_point)
2047 px = NETDATA.options.current.pixels_per_point;
2052 this.needsRecreation = function() {
2054 this.chart_created === true
2056 && this.library.autoresize() === false
2057 && this.tm.last_resized < NETDATA.options.last_resized
2061 this.chartURL = function() {
2064 if(NETDATA.globalPanAndZoom.isActive()) {
2065 after = Math.round(NETDATA.globalPanAndZoom.force_after_ms / 1000);
2066 before = Math.round(NETDATA.globalPanAndZoom.force_before_ms / 1000);
2067 this.tm.pan_and_zoom_seq = NETDATA.globalPanAndZoom.seq;
2070 before = this.current.force_before_ms !== null ? Math.round(this.current.force_before_ms / 1000) : this.before;
2071 after = this.current.force_after_ms !== null ? Math.round(this.current.force_after_ms / 1000) : this.after;
2072 this.tm.pan_and_zoom_seq = 0;
2075 this.requested_after = after * 1000;
2076 this.requested_before = before * 1000;
2078 this.data_points = this.points || Math.round(this.chartWidth() / this.chartPixelsPerPoint());
2080 // build the data URL
2081 this.data_url = this.chart.data_url;
2082 this.data_url += "&format=" + this.library.format();
2083 this.data_url += "&points=" + this.data_points.toString();
2084 this.data_url += "&group=" + this.method;
2085 this.data_url += "&options=" + this.library.options();
2086 this.data_url += '|jsonwrap';
2088 if(NETDATA.options.current.eliminate_zero_dimensions === true)
2089 this.data_url += '|nonzero';
2092 this.data_url += "&after=" + after.toString();
2095 this.data_url += "&before=" + before.toString();
2098 this.data_url += "&dimensions=" + this.dimensions;
2100 if(NETDATA.options.debug.chart_data_url === true || this.debug === true)
2101 this.log('chartURL(): ' + this.data_url + ' WxH:' + this.chartWidth() + 'x' + this.chartHeight() + ' points: ' + this.data_points + ' library: ' + this.library_name);
2104 this.redrawChart = function() {
2105 if(this.data !== null)
2106 this.updateChartWithData(this.data);
2109 this.updateChartWithData = function(data) {
2110 if(this.debug === true)
2111 this.log('got data from netdata server');
2113 // this may force the chart to be re-created
2117 this.updates_counter++;
2119 var started = new Date().getTime();
2121 // if the result is JSON, find the latest update-every
2122 if(typeof data === 'object') {
2123 if(typeof data.view_update_every !== 'undefined')
2124 this.data_update_every = data.view_update_every * 1000;
2126 if(typeof data.after !== 'undefined')
2127 this.data_after = data.after * 1000;
2129 if(typeof data.before !== 'undefined')
2130 this.data_before = data.before * 1000;
2132 if(typeof data.first_entry !== 'undefined')
2133 this.netdata_first = data.first_entry * 1000;
2135 if(typeof data.last_entry !== 'undefined')
2136 this.netdata_last = data.last_entry * 1000;
2138 if(typeof data.points !== 'undefined')
2139 this.data_points = data.points;
2144 if(this.debug === true) {
2145 this.log('UPDATE No ' + this.updates_counter + ' COMPLETED');
2147 if(this.current.force_after_ms)
2148 this.log('STATUS: forced : ' + (this.current.force_after_ms / 1000).toString() + ' - ' + (this.current.force_before_ms / 1000).toString());
2150 this.log('STATUS: forced: unset');
2152 this.log('STATUS: requested: ' + (this.requested_after / 1000).toString() + ' - ' + (this.requested_before / 1000).toString());
2153 this.log('STATUS: rendered : ' + (this.data_after / 1000).toString() + ' - ' + (this.data_before / 1000).toString());
2154 this.log('STATUS: points : ' + (this.data_points).toString());
2157 if(this.data_points === 0) {
2162 if(this.updates_since_last_creation >= this.library.max_updates_to_recreate()) {
2163 if(this.debug === true)
2164 this.log('max updates of ' + this.updates_since_last_creation.toString() + ' reached. Forcing re-generation.');
2166 this.chart_created = false;
2169 // check and update the legend
2170 this.legendUpdateDOM();
2172 if(this.chart_created === true
2173 && typeof this.library.update === 'function') {
2175 if(this.debug === true)
2176 this.log('updating chart...');
2178 this.updates_since_last_creation++;
2179 if(NETDATA.options.debug.chart_errors === true) {
2180 this.library.update(this, data);
2184 this.library.update(this, data);
2187 error('chart failed to be updated as ' + this.library_name);
2192 if(this.debug === true)
2193 this.log('creating chart...');
2195 if(NETDATA.options.debug.chart_errors === true) {
2196 this.library.create(this, data);
2197 this.chart_created = true;
2198 this.updates_since_last_creation = 0;
2202 this.library.create(this, data);
2203 this.chart_created = true;
2204 this.updates_since_last_creation = 0;
2207 error('chart failed to be created as ' + this.library_name);
2212 this.legendShowLatestValues();
2213 NETDATA.globalSelectionSync.stop();
2215 // update the performance counters
2216 var now = new Date().getTime();
2217 this.tm.last_updated = now;
2219 // don't update last_autorefreshed if this chart is
2220 // forced to be updated with global PanAndZoom
2221 if(NETDATA.globalPanAndZoom.isActive())
2222 this.tm.last_autorefreshed = 0;
2224 if(NETDATA.options.current.parallel_refresher === true && NETDATA.options.current.concurrent_refreshes)
2225 this.tm.last_autorefreshed = Math.round(now / this.data_update_every) * this.data_update_every;
2227 this.tm.last_autorefreshed = now;
2230 this.refresh_dt_ms = now - started;
2231 NETDATA.options.auto_refresher_fast_weight += this.refresh_dt_ms;
2233 if(this.refresh_dt_element !== null)
2234 this.refresh_dt_element.innerHTML = this.refresh_dt_ms.toString();
2237 this.updateChart = function(callback) {
2238 // due to late initialization of charts and libraries
2239 // we need to check this too
2240 if(this.enabled === false) {
2241 if(this.debug === true)
2242 this.log('I am not enabled');
2244 if(typeof callback === 'function') callback();
2248 if(this.chart === null) {
2249 this.getChart(function() { that.updateChart(callback); });
2253 if(this.library.initialized === false) {
2254 if(this.library.enabled === true) {
2255 this.library.initialize(function() { that.updateChart(callback); });
2259 error('chart library "' + this.library_name + '" is not available.');
2260 if(typeof callback === 'function') callback();
2265 this.clearSelection();
2268 if(this.debug === true)
2269 this.log('updating from ' + this.data_url);
2271 this.xhr = $.ajax( {
2273 crossDomain: NETDATA.options.crossDomainAjax,
2277 .success(function(data) {
2278 if(that.debug === true)
2279 that.log('data received. updating chart.');
2281 that.updateChartWithData(data);
2284 error('data download failed for url: ' + that.data_url);
2286 .always(function() {
2287 if(typeof callback === 'function') callback();
2291 this.isVisible = function() {
2292 // this.log('last_visible_check: ' + this.tm.last_visible_check + ', last_page_scroll: ' + NETDATA.options.last_page_scroll);
2294 // caching - we do not evaluate the charts visibility
2295 // if the page has not been scrolled since the last check
2296 if(this.tm.last_visible_check > NETDATA.options.last_page_scroll) {
2297 if(this.debug === true)
2298 this.log('isVisible: ' + this.___isVisible___);
2300 return this.___isVisible___;
2303 this.tm.last_visible_check = new Date().getTime();
2305 var wh = window.innerHeight;
2306 var x = this.element.getBoundingClientRect();
2310 if(x.top < 0 && -x.top > x.height) {
2311 // the chart is entirely above
2312 ret = -x.top - x.height;
2314 else if(x.top > wh) {
2315 // the chart is entirely below
2319 if(ret > tolerance) {
2320 // the chart is too far
2323 this.___isVisible___ = false;
2325 if(this.debug === true)
2326 this.log('isVisible: ' + this.___isVisible___);
2328 return this.___isVisible___;
2331 // the chart is inside or very close
2334 this.___isVisible___ = true;
2336 if(this.debug === true)
2337 this.log('isVisible: ' + this.___isVisible___);
2339 return this.___isVisible___;
2343 this.isAutoRefreshed = function() {
2344 return (this.current.autorefresh);
2347 this.canBeAutoRefreshed = function() {
2348 now = new Date().getTime();
2350 if(this.enabled === false) {
2351 if(this.debug === true)
2352 this.log('I am not enabled');
2357 if(this.library === null || this.library.enabled === false) {
2358 error('charting library "' + this.library_name + '" is not available');
2359 if(this.debug === true)
2360 this.log('My chart library ' + this.library_name + ' is not available');
2365 if(this.isVisible() === false) {
2366 if(NETDATA.options.debug.visibility === true || this.debug === true)
2367 this.log('I am not visible');
2372 if(this.current.force_update_at !== 0 && this.current.force_update_at < now) {
2373 if(this.debug === true)
2374 this.log('timed force update detected - allowing this update');
2376 this.current.force_update_at = 0;
2380 if(this.isAutoRefreshed() === true) {
2381 // allow the first update, even if the page is not visible
2382 if(this.updates_counter && NETDATA.options.page_is_visible === false) {
2383 if(NETDATA.options.debug.focus === true || this.debug === true)
2384 this.log('canBeAutoRefreshed(): page does not have focus');
2389 if(this.needsRecreation() === true) {
2390 if(this.debug === true)
2391 this.log('canBeAutoRefreshed(): needs re-creation.');
2396 // options valid only for autoRefresh()
2397 if(NETDATA.options.auto_refresher_stop_until === 0 || NETDATA.options.auto_refresher_stop_until < now) {
2398 if(NETDATA.globalPanAndZoom.isActive()) {
2399 if(NETDATA.globalPanAndZoom.shouldBeAutoRefreshed(this)) {
2400 if(this.debug === true)
2401 this.log('canBeAutoRefreshed(): global panning: I need an update.');
2406 if(this.debug === true)
2407 this.log('canBeAutoRefreshed(): global panning: I am already up to date.');
2413 if(this.selected === true) {
2414 if(this.debug === true)
2415 this.log('canBeAutoRefreshed(): I have a selection in place.');
2420 if(this.paused === true) {
2421 if(this.debug === true)
2422 this.log('canBeAutoRefreshed(): I am paused.');
2427 if(now - this.tm.last_autorefreshed >= this.data_update_every) {
2428 if(this.debug === true)
2429 this.log('canBeAutoRefreshed(): It is time to update me.');
2439 this.autoRefresh = function(callback) {
2440 if(this.canBeAutoRefreshed() === true) {
2441 this.updateChart(callback);
2444 if(typeof callback !== 'undefined')
2449 this._defaultsFromDownloadedChart = function(chart) {
2451 this.chart_url = chart.url;
2452 this.data_update_every = chart.update_every * 1000;
2453 this.data_points = Math.round(this.chartWidth() / this.chartPixelsPerPoint());
2454 this.tm.last_info_downloaded = new Date().getTime();
2457 // fetch the chart description from the netdata server
2458 this.getChart = function(callback) {
2459 this.chart = NETDATA.chartRegistry.get(this.host, this.id);
2461 this._defaultsFromDownloadedChart(this.chart);
2462 if(typeof callback === 'function') callback();
2465 this.chart_url = this.host + "/api/v1/chart?chart=" + this.id;
2467 if(this.debug === true)
2468 this.log('downloading ' + this.chart_url);
2471 url: this.chart_url,
2472 crossDomain: NETDATA.options.crossDomainAjax,
2476 .done(function(chart) {
2477 chart.url = that.chart_url;
2478 chart.data_url = (that.host + chart.data_url);
2479 that._defaultsFromDownloadedChart(chart);
2480 NETDATA.chartRegistry.add(that.host, that.id, chart);
2483 NETDATA.error(404, that.chart_url);
2484 error('chart not found on url "' + that.chart_url + '"');
2486 .always(function() {
2487 if(typeof callback === 'function') callback();
2492 // ============================================================================================================
2498 // get or create a chart state, given a DOM element
2499 NETDATA.chartState = function(element) {
2500 var state = $(element).data('netdata-state-object') || null;
2501 if(state === null) {
2502 state = new chartState(element);
2503 $(element).data('netdata-state-object', state);
2508 // ----------------------------------------------------------------------------------------------------------------
2509 // Library functions
2511 // Load a script without jquery
2512 // This is used to load jquery - after it is loaded, we use jquery
2513 NETDATA._loadjQuery = function(callback) {
2514 if(typeof jQuery === 'undefined') {
2515 if(NETDATA.options.debug.main_loop === true)
2516 console.log('loading ' + NETDATA.jQuery);
2518 var script = document.createElement('script');
2519 script.type = 'text/javascript';
2520 script.async = true;
2521 script.src = NETDATA.jQuery;
2523 // script.onabort = onError;
2524 script.onerror = function(err, t) { NETDATA.error(101, NETDATA.jQuery); };
2525 if(typeof callback === "function")
2526 script.onload = callback;
2528 var s = document.getElementsByTagName('script')[0];
2529 s.parentNode.insertBefore(script, s);
2531 else if(typeof callback === "function")
2535 NETDATA._loadCSS = function(filename) {
2536 // don't use jQuery here
2537 // styles are loaded before jQuery
2538 // to eliminate showing an unstyled page to the user
2540 var fileref = document.createElement("link");
2541 fileref.setAttribute("rel", "stylesheet");
2542 fileref.setAttribute("type", "text/css");
2543 fileref.setAttribute("href", filename);
2545 if (typeof fileref !== 'undefined')
2546 document.getElementsByTagName("head")[0].appendChild(fileref);
2549 NETDATA.colorHex2Rgb = function(hex) {
2550 // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
2551 var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
2552 hex = hex.replace(shorthandRegex, function(m, r, g, b) {
2553 return r + r + g + g + b + b;
2556 var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
2558 r: parseInt(result[1], 16),
2559 g: parseInt(result[2], 16),
2560 b: parseInt(result[3], 16)
2564 NETDATA.colorLuminance = function(hex, lum) {
2565 // validate hex string
2566 hex = String(hex).replace(/[^0-9a-f]/gi, '');
2568 hex = hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2];
2572 // convert to decimal and change luminosity
2573 var rgb = "#", c, i;
2574 for (i = 0; i < 3; i++) {
2575 c = parseInt(hex.substr(i*2,2), 16);
2576 c = Math.round(Math.min(Math.max(0, c + (c * lum)), 255)).toString(16);
2577 rgb += ("00"+c).substr(c.length);
2583 NETDATA.guid = function() {
2585 return Math.floor((1 + Math.random()) * 0x10000)
2590 return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
2593 NETDATA.zeropad = function(x) {
2594 if(x > -10 && x < 10) return '0' + x.toString();
2595 else return x.toString();
2598 // user function to signal us the DOM has been
2600 NETDATA.updatedDom = function() {
2601 NETDATA.options.updated_dom = true;
2604 NETDATA.ready = function(callback) {
2605 NETDATA.options.pauseCallback = callback;
2608 NETDATA.pause = function(callback) {
2609 if(NETDATA.options.pause === true)
2612 NETDATA.options.pauseCallback = callback;
2615 NETDATA.unpause = function() {
2616 NETDATA.options.pauseCallback = null;
2617 NETDATA.options.updated_dom = true;
2618 NETDATA.options.pause = false;
2621 // ----------------------------------------------------------------------------------------------------------------
2623 // this is purely sequencial charts refresher
2624 // it is meant to be autonomous
2625 NETDATA.chartRefresherNoParallel = function(index) {
2626 if(NETDATA.options.debug.mail_loop === true)
2627 console.log('NETDATA.chartRefresherNoParallel(' + index + ')');
2629 if(NETDATA.options.updated_dom === true) {
2630 // the dom has been updated
2631 // get the dom parts again
2632 NETDATA.parseDom(NETDATA.chartRefresher);
2635 if(index >= NETDATA.options.targets.length) {
2636 if(NETDATA.options.debug.main_loop === true)
2637 console.log('waiting to restart main loop...');
2639 NETDATA.options.auto_refresher_fast_weight = 0;
2641 setTimeout(function() {
2642 NETDATA.chartRefresher();
2643 }, NETDATA.options.current.idle_between_loops);
2646 var state = NETDATA.options.targets[index];
2648 if(NETDATA.options.auto_refresher_fast_weight < NETDATA.options.current.fast_render_timeframe) {
2649 if(NETDATA.options.debug.main_loop === true)
2650 console.log('fast rendering...');
2652 state.autoRefresh(function() {
2653 NETDATA.chartRefresherNoParallel(++index);
2657 if(NETDATA.options.debug.main_loop === true) console.log('waiting for next refresh...');
2658 NETDATA.options.auto_refresher_fast_weight = 0;
2660 setTimeout(function() {
2661 state.autoRefresh(function() {
2662 NETDATA.chartRefresherNoParallel(++index);
2664 }, NETDATA.options.current.idle_between_charts);
2669 // this is part of the parallel refresher
2670 // its cause is to refresh sequencially all the charts
2671 // that depend on chart library initialization
2672 // it will call the parallel refresher back
2673 // as soon as it sees a chart that its chart library
2675 NETDATA.chartRefresher_unitialized = function() {
2676 if(NETDATA.options.updated_dom === true) {
2677 // the dom has been updated
2678 // get the dom parts again
2679 NETDATA.parseDom(NETDATA.chartRefresher);
2683 if(NETDATA.options.sequencial.length === 0)
2684 NETDATA.chartRefresher();
2686 var state = NETDATA.options.sequencial.pop();
2687 if(state.library.initialized === true)
2688 NETDATA.chartRefresher();
2690 state.autoRefresh(NETDATA.chartRefresher_unitialized);
2694 NETDATA.chartRefresherWaitTime = function() {
2695 return NETDATA.options.current.idle_parallel_loops;
2698 // the default refresher
2699 // it will create 2 sets of charts:
2700 // - the ones that can be refreshed in parallel
2701 // - the ones that depend on something else
2702 // the first set will be executed in parallel
2703 // the second will be given to NETDATA.chartRefresher_unitialized()
2704 NETDATA.chartRefresher = function() {
2705 if(NETDATA.options.pause === true) {
2706 // console.log('auto-refresher is paused');
2707 setTimeout(NETDATA.chartRefresher,
2708 NETDATA.chartRefresherWaitTime());
2712 if(typeof NETDATA.options.pauseCallback === 'function') {
2713 // console.log('auto-refresher is calling pauseCallback');
2714 NETDATA.options.pause = true;
2715 NETDATA.options.pauseCallback();
2716 NETDATA.chartRefresher();
2720 if(NETDATA.options.current.parallel_refresher === false) {
2721 NETDATA.chartRefresherNoParallel(0);
2725 if(NETDATA.options.updated_dom === true) {
2726 // the dom has been updated
2727 // get the dom parts again
2728 NETDATA.parseDom(NETDATA.chartRefresher);
2732 var parallel = new Array();
2733 var targets = NETDATA.options.targets;
2734 var len = targets.length;
2736 if(targets[len].isVisible() === false)
2739 var state = targets[len];
2740 if(state.library.initialized === false) {
2741 if(state.library.enabled === true) {
2742 state.library.initialize(NETDATA.chartRefresher);
2746 state.error('chart library "' + state.library_name + '" is not enabled.');
2750 parallel.unshift(state);
2753 if(parallel.length > 0) {
2754 var parallel_jobs = parallel.length;
2756 // this will execute the jobs in parallel
2757 $(parallel).each(function() {
2758 this.autoRefresh(function() {
2761 if(parallel_jobs === 0) {
2762 setTimeout(NETDATA.chartRefresher,
2763 NETDATA.chartRefresherWaitTime());
2769 setTimeout(NETDATA.chartRefresher,
2770 NETDATA.chartRefresherWaitTime());
2774 NETDATA.parseDom = function(callback) {
2775 NETDATA.options.last_page_scroll = new Date().getTime();
2776 NETDATA.options.updated_dom = false;
2778 var targets = $('div[data-netdata]').filter(':visible');
2780 if(NETDATA.options.debug.main_loop === true)
2781 console.log('DOM updated - there are ' + targets.length + ' charts on page.');
2783 NETDATA.options.targets = new Array();
2784 var len = targets.length;
2786 // the initialization will take care of sizing
2787 // and the "loading..." message
2788 NETDATA.options.targets.push(NETDATA.chartState(targets[len]));
2791 if(typeof callback === 'function') callback();
2794 // this is the main function - where everything starts
2795 NETDATA.start = function() {
2796 // this should be called only once
2798 NETDATA.options.page_is_visible = true;
2800 $(window).blur(function() {
2801 if(NETDATA.options.current.stop_updates_when_focus_is_lost === true) {
2802 NETDATA.options.page_is_visible = false;
2803 if(NETDATA.options.debug.focus === true)
2804 console.log('Lost Focus!');
2808 $(window).focus(function() {
2809 if(NETDATA.options.current.stop_updates_when_focus_is_lost === true) {
2810 NETDATA.options.page_is_visible = true;
2811 if(NETDATA.options.debug.focus === true)
2812 console.log('Focus restored!');
2816 if(typeof document.hasFocus === 'function' && !document.hasFocus()) {
2817 if(NETDATA.options.current.stop_updates_when_focus_is_lost === true) {
2818 NETDATA.options.page_is_visible = false;
2819 if(NETDATA.options.debug.focus === true)
2820 console.log('Document has no focus!');
2824 NETDATA.parseDom(NETDATA.chartRefresher);
2827 // ----------------------------------------------------------------------------------------------------------------
2830 NETDATA.peityInitialize = function(callback) {
2831 if(typeof netdataNoPeitys === 'undefined' || !netdataNoPeitys) {
2833 url: NETDATA.peity_js,
2838 NETDATA.registerChartLibrary('peity', NETDATA.peity_js);
2841 NETDATA.chartLibraries.peity.enabled = false;
2842 NETDATA.error(100, NETDATA.peity_js);
2844 .always(function() {
2845 if(typeof callback === "function")
2850 NETDATA.chartLibraries.peity.enabled = false;
2851 if(typeof callback === "function")
2856 NETDATA.peityChartUpdate = function(state, data) {
2857 state.peity_instance.innerHTML = data.result;
2859 if(state.peity_options.stroke !== state.chartColors()[0]) {
2860 state.peity_options.stroke = state.chartColors()[0];
2861 if(state.chart.chart_type === 'line')
2862 state.peity_options.fill = '#FFF';
2864 state.peity_options.fill = NETDATA.colorLuminance(state.chartColors()[0], NETDATA.chartDefaults.fill_luminance);
2867 $(state.peity_instance).peity('line', state.peity_options);
2870 NETDATA.peityChartCreate = function(state, data) {
2871 state.peity_instance = document.createElement('div');
2872 state.element_chart.appendChild(state.peity_instance);
2874 var self = $(state.element);
2875 state.peity_options = {
2877 strokeWidth: self.data('peity-strokewidth') || 1,
2878 width: state.chartWidth(),
2879 height: state.chartHeight(),
2883 NETDATA.peityChartUpdate(state, data);
2886 // ----------------------------------------------------------------------------------------------------------------
2889 NETDATA.sparklineInitialize = function(callback) {
2890 if(typeof netdataNoSparklines === 'undefined' || !netdataNoSparklines) {
2892 url: NETDATA.sparkline_js,
2897 NETDATA.registerChartLibrary('sparkline', NETDATA.sparkline_js);
2900 NETDATA.chartLibraries.sparkline.enabled = false;
2901 NETDATA.error(100, NETDATA.sparkline_js);
2903 .always(function() {
2904 if(typeof callback === "function")
2909 NETDATA.chartLibraries.sparkline.enabled = false;
2910 if(typeof callback === "function")
2915 NETDATA.sparklineChartUpdate = function(state, data) {
2916 state.sparkline_options.width = state.chartWidth();
2917 state.sparkline_options.height = state.chartHeight();
2919 $(state.element_chart).sparkline(data.result, state.sparkline_options);
2922 NETDATA.sparklineChartCreate = function(state, data) {
2923 var self = $(state.element);
2924 var type = self.data('sparkline-type') || 'line';
2925 var lineColor = self.data('sparkline-linecolor') || state.chartColors()[0];
2926 var fillColor = self.data('sparkline-fillcolor') || (state.chart.chart_type === 'line')?'#FFF':NETDATA.colorLuminance(lineColor, NETDATA.chartDefaults.fill_luminance);
2927 var chartRangeMin = self.data('sparkline-chartrangemin') || undefined;
2928 var chartRangeMax = self.data('sparkline-chartrangemax') || undefined;
2929 var composite = self.data('sparkline-composite') || undefined;
2930 var enableTagOptions = self.data('sparkline-enabletagoptions') || undefined;
2931 var tagOptionPrefix = self.data('sparkline-tagoptionprefix') || undefined;
2932 var tagValuesAttribute = self.data('sparkline-tagvaluesattribute') || undefined;
2933 var disableHiddenCheck = self.data('sparkline-disablehiddencheck') || undefined;
2934 var defaultPixelsPerValue = self.data('sparkline-defaultpixelspervalue') || undefined;
2935 var spotColor = self.data('sparkline-spotcolor') || undefined;
2936 var minSpotColor = self.data('sparkline-minspotcolor') || undefined;
2937 var maxSpotColor = self.data('sparkline-maxspotcolor') || undefined;
2938 var spotRadius = self.data('sparkline-spotradius') || undefined;
2939 var valueSpots = self.data('sparkline-valuespots') || undefined;
2940 var highlightSpotColor = self.data('sparkline-highlightspotcolor') || undefined;
2941 var highlightLineColor = self.data('sparkline-highlightlinecolor') || undefined;
2942 var lineWidth = self.data('sparkline-linewidth') || undefined;
2943 var normalRangeMin = self.data('sparkline-normalrangemin') || undefined;
2944 var normalRangeMax = self.data('sparkline-normalrangemax') || undefined;
2945 var drawNormalOnTop = self.data('sparkline-drawnormalontop') || undefined;
2946 var xvalues = self.data('sparkline-xvalues') || undefined;
2947 var chartRangeClip = self.data('sparkline-chartrangeclip') || undefined;
2948 var xvalues = self.data('sparkline-xvalues') || undefined;
2949 var chartRangeMinX = self.data('sparkline-chartrangeminx') || undefined;
2950 var chartRangeMaxX = self.data('sparkline-chartrangemaxx') || undefined;
2951 var disableInteraction = self.data('sparkline-disableinteraction') || false;
2952 var disableTooltips = self.data('sparkline-disabletooltips') || false;
2953 var disableHighlight = self.data('sparkline-disablehighlight') || false;
2954 var highlightLighten = self.data('sparkline-highlightlighten') || 1.4;
2955 var highlightColor = self.data('sparkline-highlightcolor') || undefined;
2956 var tooltipContainer = self.data('sparkline-tooltipcontainer') || undefined;
2957 var tooltipClassname = self.data('sparkline-tooltipclassname') || undefined;
2958 var tooltipFormat = self.data('sparkline-tooltipformat') || undefined;
2959 var tooltipPrefix = self.data('sparkline-tooltipprefix') || undefined;
2960 var tooltipSuffix = self.data('sparkline-tooltipsuffix') || ' ' + state.chart.units;
2961 var tooltipSkipNull = self.data('sparkline-tooltipskipnull') || true;
2962 var tooltipValueLookups = self.data('sparkline-tooltipvaluelookups') || undefined;
2963 var tooltipFormatFieldlist = self.data('sparkline-tooltipformatfieldlist') || undefined;
2964 var tooltipFormatFieldlistKey = self.data('sparkline-tooltipformatfieldlistkey') || undefined;
2965 var numberFormatter = self.data('sparkline-numberformatter') || function(n){ return n.toFixed(2); };
2966 var numberDigitGroupSep = self.data('sparkline-numberdigitgroupsep') || undefined;
2967 var numberDecimalMark = self.data('sparkline-numberdecimalmark') || undefined;
2968 var numberDigitGroupCount = self.data('sparkline-numberdigitgroupcount') || undefined;
2969 var animatedZooms = self.data('sparkline-animatedzooms') || false;
2971 state.sparkline_options = {
2973 lineColor: lineColor,
2974 fillColor: fillColor,
2975 chartRangeMin: chartRangeMin,
2976 chartRangeMax: chartRangeMax,
2977 composite: composite,
2978 enableTagOptions: enableTagOptions,
2979 tagOptionPrefix: tagOptionPrefix,
2980 tagValuesAttribute: tagValuesAttribute,
2981 disableHiddenCheck: disableHiddenCheck,
2982 defaultPixelsPerValue: defaultPixelsPerValue,
2983 spotColor: spotColor,
2984 minSpotColor: minSpotColor,
2985 maxSpotColor: maxSpotColor,
2986 spotRadius: spotRadius,
2987 valueSpots: valueSpots,
2988 highlightSpotColor: highlightSpotColor,
2989 highlightLineColor: highlightLineColor,
2990 lineWidth: lineWidth,
2991 normalRangeMin: normalRangeMin,
2992 normalRangeMax: normalRangeMax,
2993 drawNormalOnTop: drawNormalOnTop,
2995 chartRangeClip: chartRangeClip,
2996 chartRangeMinX: chartRangeMinX,
2997 chartRangeMaxX: chartRangeMaxX,
2998 disableInteraction: disableInteraction,
2999 disableTooltips: disableTooltips,
3000 disableHighlight: disableHighlight,
3001 highlightLighten: highlightLighten,
3002 highlightColor: highlightColor,
3003 tooltipContainer: tooltipContainer,
3004 tooltipClassname: tooltipClassname,
3005 tooltipChartTitle: state.chart.title,
3006 tooltipFormat: tooltipFormat,
3007 tooltipPrefix: tooltipPrefix,
3008 tooltipSuffix: tooltipSuffix,
3009 tooltipSkipNull: tooltipSkipNull,
3010 tooltipValueLookups: tooltipValueLookups,
3011 tooltipFormatFieldlist: tooltipFormatFieldlist,
3012 tooltipFormatFieldlistKey: tooltipFormatFieldlistKey,
3013 numberFormatter: numberFormatter,
3014 numberDigitGroupSep: numberDigitGroupSep,
3015 numberDecimalMark: numberDecimalMark,
3016 numberDigitGroupCount: numberDigitGroupCount,
3017 animatedZooms: animatedZooms,
3018 width: state.chartWidth(),
3019 height: state.chartHeight()
3022 $(state.element_chart).sparkline(data.result, state.sparkline_options);
3025 // ----------------------------------------------------------------------------------------------------------------
3032 NETDATA.dygraphSetSelection = function(state, t) {
3033 if(typeof state.dygraph_instance !== 'undefined') {
3034 var r = state.calculateRowForTime(t);
3036 state.dygraph_instance.setSelection(r);
3038 state.dygraph_instance.clearSelection();
3039 state.legendShowUndefined();
3046 NETDATA.dygraphClearSelection = function(state, t) {
3047 if(typeof state.dygraph_instance !== 'undefined') {
3048 state.dygraph_instance.clearSelection();
3053 NETDATA.dygraphSmoothInitialize = function(callback) {
3055 url: NETDATA.dygraph_smooth_js,
3060 NETDATA.dygraph.smooth = true;
3061 smoothPlotter.smoothing = 0.3;
3064 NETDATA.dygraph.smooth = false;
3066 .always(function() {
3067 if(typeof callback === "function")
3072 NETDATA.dygraphInitialize = function(callback) {
3073 if(typeof netdataNoDygraphs === 'undefined' || !netdataNoDygraphs) {
3075 url: NETDATA.dygraph_js,
3080 NETDATA.registerChartLibrary('dygraph', NETDATA.dygraph_js);
3083 NETDATA.chartLibraries.dygraph.enabled = false;
3084 NETDATA.error(100, NETDATA.dygraph_js);
3086 .always(function() {
3087 if(NETDATA.chartLibraries.dygraph.enabled === true && NETDATA.options.current.smooth_plot === true)
3088 NETDATA.dygraphSmoothInitialize(callback);
3089 else if(typeof callback === "function")
3094 NETDATA.chartLibraries.dygraph.enabled = false;
3095 if(typeof callback === "function")
3100 NETDATA.dygraphChartUpdate = function(state, data) {
3101 var dygraph = state.dygraph_instance;
3103 if(typeof dygraph === 'undefined')
3104 NETDATA.dygraphChartCreate(state, data);
3106 // when the chart is not visible, and hidden
3107 // if there is a window resize, dygraph detects
3108 // its element size as 0x0.
3109 // this will make it re-appear properly
3111 if(state.tm.last_unhidden > state.dygraph_last_rendered)
3115 file: data.result.data,
3116 colors: state.chartColors(),
3117 labels: data.result.labels,
3118 labelsDivWidth: state.chartWidth() - 70,
3119 visibility: state.dimensions_visibility.selected2BooleanArray(state.data.dimension_names)
3122 if(state.current.name === 'pan') {
3123 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3124 state.log('dygraphChartUpdate() loose update');
3127 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3128 state.log('dygraphChartUpdate() strict update');
3130 options.dateWindow = null;
3131 options.valueRange = null;
3134 if(state.dygraph_smooth_eligible === true) {
3135 if((NETDATA.options.current.smooth_plot === true && state.dygraph_options.plotter !== smoothPlotter)
3136 || (NETDATA.options.current.smooth_plot === false && state.dygraph_options.plotter === smoothPlotter)) {
3137 NETDATA.dygraphChartCreate(state, data);
3142 dygraph.updateOptions(options);
3143 state.dygraph_last_rendered = new Date().getTime();
3146 NETDATA.dygraphChartCreate = function(state, data) {
3147 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3148 state.log('dygraphChartCreate()');
3150 var self = $(state.element);
3152 var chart_type = state.chart.chart_type;
3153 if(chart_type === 'stacked' && data.dimensions === 1) chart_type = 'area';
3154 chart_type = self.data('dygraph-type') || chart_type;
3156 var smooth = (chart_type === 'line' && !NETDATA.chartLibraries.dygraph.isSparkline(state))?true:false;
3157 smooth = self.data('dygraph-smooth') || smooth;
3159 if(NETDATA.dygraph.smooth === false)
3162 var strokeWidth = (chart_type === 'stacked')?0.1:((smooth)?1.5:0.7)
3163 var highlightCircleSize = (NETDATA.chartLibraries.dygraph.isSparkline(state))?3:4;
3165 state.dygraph_options = {
3166 colors: self.data('dygraph-colors') || state.chartColors(),
3168 // leave a few pixels empty on the right of the chart
3169 rightGap: self.data('dygraph-rightgap') || 5,
3170 showRangeSelector: self.data('dygraph-showrangeselector') || false,
3171 showRoller: self.data('dygraph-showroller') || false,
3173 title: self.data('dygraph-title') || state.chart.title,
3174 titleHeight: self.data('dygraph-titleheight') || 19,
3176 legend: self.data('dygraph-legend') || 'always', // 'onmouseover',
3177 labels: data.result.labels,
3178 labelsDiv: self.data('dygraph-labelsdiv') || state.element_legend_childs.hidden,
3179 labelsDivStyles: self.data('dygraph-labelsdivstyles') || { 'fontSize':'1px' },
3180 labelsDivWidth: self.data('dygraph-labelsdivwidth') || state.chartWidth() - 70,
3181 labelsSeparateLines: self.data('dygraph-labelsseparatelines') || true,
3182 labelsShowZeroValues: self.data('dygraph-labelsshowzerovalues') || true,
3185 showLabelsOnHighlight: self.data('dygraph-showlabelsonhighlight') || true,
3186 hideOverlayOnMouseOut: self.data('dygraph-hideoverlayonmouseout') || true,
3188 ylabel: state.chart.units,
3189 yLabelWidth: self.data('dygraph-ylabelwidth') || 12,
3191 // the function to plot the chart
3194 // The width of the lines connecting data points. This can be used to increase the contrast or some graphs.
3195 strokeWidth: self.data('dygraph-strokewidth') || strokeWidth,
3196 strokePattern: self.data('dygraph-strokepattern') || undefined,
3198 // The size of the dot to draw on each point in pixels (see drawPoints). A dot is always drawn when a point is "isolated",
3199 // i.e. there is a missing point on either side of it. This also controls the size of those dots.
3200 drawPoints: self.data('dygraph-drawpoints') || false,
3202 // Draw points at the edges of gaps in the data. This improves visibility of small data segments or other data irregularities.
3203 drawGapEdgePoints: self.data('dygraph-drawgapedgepoints') || true,
3205 connectSeparatedPoints: self.data('dygraph-connectseparatedpoints') || false,
3206 pointSize: self.data('dygraph-pointsize') || 1,
3208 // enabling this makes the chart with little square lines
3209 stepPlot: self.data('dygraph-stepplot') || false,
3211 // Draw a border around graph lines to make crossing lines more easily distinguishable. Useful for graphs with many lines.
3212 strokeBorderColor: self.data('dygraph-strokebordercolor') || 'white',
3213 strokeBorderWidth: self.data('dygraph-strokeborderwidth') || (chart_type === 'stacked')?0.0:0.0,
3215 fillGraph: self.data('dygraph-fillgraph') || (chart_type === 'area' || chart_type === 'stacked')?true:false,
3216 fillAlpha: self.data('dygraph-fillalpha') || (chart_type === 'stacked')?NETDATA.options.current.color_fill_opacity_stacked:NETDATA.options.current.color_fill_opacity_area,
3217 stackedGraph: self.data('dygraph-stackedgraph') || (chart_type === 'stacked')?true:false,
3218 stackedGraphNaNFill: self.data('dygraph-stackedgraphnanfill') || 'none',
3220 drawAxis: self.data('dygraph-drawaxis') || true,
3221 axisLabelFontSize: self.data('dygraph-axislabelfontsize') || 10,
3222 axisLineColor: self.data('dygraph-axislinecolor') || '#CCC',
3223 axisLineWidth: self.data('dygraph-axislinewidth') || 0.3,
3225 drawGrid: self.data('dygraph-drawgrid') || true,
3226 drawXGrid: self.data('dygraph-drawxgrid') || undefined,
3227 drawYGrid: self.data('dygraph-drawygrid') || undefined,
3228 gridLinePattern: self.data('dygraph-gridlinepattern') || null,
3229 gridLineWidth: self.data('dygraph-gridlinewidth') || 0.3,
3230 gridLineColor: self.data('dygraph-gridlinecolor') || '#DDD',
3232 maxNumberWidth: self.data('dygraph-maxnumberwidth') || 8,
3233 sigFigs: self.data('dygraph-sigfigs') || null,
3234 digitsAfterDecimal: self.data('dygraph-digitsafterdecimal') || 2,
3235 valueFormatter: self.data('dygraph-valueformatter') || function(x){ return x.toFixed(2); },
3237 highlightCircleSize: self.data('dygraph-highlightcirclesize') || highlightCircleSize,
3238 highlightSeriesOpts: self.data('dygraph-highlightseriesopts') || null, // TOO SLOW: { strokeWidth: 1.5 },
3239 highlightSeriesBackgroundAlpha: self.data('dygraph-highlightseriesbackgroundalpha') || null, // TOO SLOW: (chart_type === 'stacked')?0.7:0.5,
3241 pointClickCallback: self.data('dygraph-pointclickcallback') || undefined,
3242 visibility: state.dimensions_visibility.selected2BooleanArray(state.data.dimension_names),
3246 ticker: Dygraph.dateTicker,
3247 axisLabelFormatter: function (d, gran) {
3248 return NETDATA.zeropad(d.getHours()) + ":" + NETDATA.zeropad(d.getMinutes()) + ":" + NETDATA.zeropad(d.getSeconds());
3250 valueFormatter: function (ms) {
3251 var d = new Date(ms);
3252 return d.toLocaleDateString() + ' ' + d.toLocaleTimeString();
3253 // return NETDATA.zeropad(d.getHours()) + ":" + NETDATA.zeropad(d.getMinutes()) + ":" + NETDATA.zeropad(d.getSeconds());
3258 valueFormatter: function (x) {
3259 // we format legends with the state object
3260 // no need to do anything here
3261 // return (Math.round(x*100) / 100).toLocaleString();
3262 // return state.legendFormatValue(x);
3267 legendFormatter: function(data) {
3268 var g = data.dygraph;
3270 var elements = state.element_legend_childs;
3272 // if the hidden div is not there
3273 // we are not managing the legend
3274 if(elements.hidden === null) return;
3276 if (typeof data.x === 'undefined') {
3277 //state.legendReset();
3280 state.legendSetDate(data.x);
3281 var i = data.series.length;
3283 var series = data.series[i];
3284 if(!series.isVisible) continue;
3285 state.legendSetLabelValue(series.label, series.y);
3291 drawCallback: function(dygraph, is_initial) {
3292 if(state.current.name !== 'auto') {
3293 if(NETDATA.options.debug.dygraph === true)
3294 state.log('dygraphDrawCallback()');
3296 var first = state.data.first_entry * 1000;
3297 var last = state.data.last_entry * 1000;
3299 var x_range = dygraph.xAxisRange();
3300 var after = Math.round(x_range[0]);
3301 var before = Math.round(x_range[1]);
3303 if(before <= last && after >= first)
3304 state.updateChartPanOrZoom(after, before);
3307 zoomCallback: function(minDate, maxDate, yRanges) {
3308 if(NETDATA.options.debug.dygraph === true)
3309 state.log('dygraphZoomCallback()');
3311 state.globalSelectionSyncStop();
3312 state.globalSelectionSyncDelay();
3314 if(state.updateChartPanOrZoom(minDate, maxDate) == false) {
3315 // we should not zoom that much
3316 state.dygraph_instance.updateOptions({
3322 highlightCallback: function(event, x, points, row, seriesName) {
3323 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3324 state.log('dygraphHighlightCallback()');
3328 // there is a bug in dygraph when the chart is zoomed enough
3329 // the time it thinks is selected is wrong
3330 // here we calculate the time t based on the row number selected
3332 var t = state.data_after + row * state.data_update_every;
3333 // console.log('row = ' + row + ', x = ' + x + ', t = ' + t + ' ' + ((t === x)?'SAME':'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);
3335 state.globalSelectionSync(t);
3337 // fix legend zIndex using the internal structures of dygraph legend module
3338 // this works, but it is a hack!
3339 // state.dygraph_instance.plugins_[0].plugin.legend_div_.style.zIndex = 10000;
3341 unhighlightCallback: function(event) {
3342 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3343 state.log('dygraphUnhighlightCallback()');
3345 state.unpauseChart();
3346 state.globalSelectionSyncStop();
3348 interactionModel : {
3349 mousedown: function(event, dygraph, context) {
3350 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3351 state.log('interactionModel.mousedown()');
3353 state.globalSelectionSyncStop();
3355 if(NETDATA.options.debug.dygraph === true)
3356 state.log('dygraphMouseDown()');
3358 // Right-click should not initiate a zoom.
3359 if(event.button && event.button === 2) return;
3361 context.initializeMouseDown(event, dygraph, context);
3363 if(event.button && event.button === 1) {
3364 if (event.altKey || event.shiftKey) {
3365 state.setMode('pan');
3366 state.globalSelectionSyncDelay();
3367 Dygraph.startPan(event, dygraph, context);
3370 state.setMode('zoom');
3371 state.globalSelectionSyncDelay();
3372 Dygraph.startZoom(event, dygraph, context);
3376 if (event.altKey || event.shiftKey) {
3377 state.setMode('zoom');
3378 state.globalSelectionSyncDelay();
3379 Dygraph.startZoom(event, dygraph, context);
3382 state.setMode('pan');
3383 state.globalSelectionSyncDelay();
3384 Dygraph.startPan(event, dygraph, context);
3388 mousemove: function(event, dygraph, context) {
3389 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3390 state.log('interactionModel.mousemove()');
3392 if(context.isPanning) {
3393 state.globalSelectionSyncStop();
3394 state.globalSelectionSyncDelay();
3395 state.setMode('pan');
3396 Dygraph.movePan(event, dygraph, context);
3398 else if(context.isZooming) {
3399 state.globalSelectionSyncStop();
3400 state.globalSelectionSyncDelay();
3401 state.setMode('zoom');
3402 Dygraph.moveZoom(event, dygraph, context);
3405 mouseup: function(event, dygraph, context) {
3406 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3407 state.log('interactionModel.mouseup()');
3409 if (context.isPanning) {
3410 state.globalSelectionSyncDelay();
3411 Dygraph.endPan(event, dygraph, context);
3413 else if (context.isZooming) {
3414 state.globalSelectionSyncDelay();
3415 Dygraph.endZoom(event, dygraph, context);
3418 click: function(event, dygraph, context) {
3419 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3420 state.log('interactionModel.click()');
3422 event.preventDefault();
3424 dblclick: function(event, dygraph, context) {
3425 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3426 state.log('interactionModel.dblclick()');
3428 state.globalSelectionSyncStop();
3429 NETDATA.globalPanAndZoom.clearMaster();
3432 mousewheel: function(event, dygraph, context) {
3433 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3434 state.log('interactionModel.mousewheel()');
3436 // Take the offset of a mouse event on the dygraph canvas and
3437 // convert it to a pair of percentages from the bottom left.
3438 // (Not top left, bottom is where the lower value is.)
3439 function offsetToPercentage(g, offsetX, offsetY) {
3440 // This is calculating the pixel offset of the leftmost date.
3441 var xOffset = g.toDomCoords(g.xAxisRange()[0], null)[0];
3442 var yar0 = g.yAxisRange(0);
3444 // This is calculating the pixel of the higest value. (Top pixel)
3445 var yOffset = g.toDomCoords(null, yar0[1])[1];
3447 // x y w and h are relative to the corner of the drawing area,
3448 // so that the upper corner of the drawing area is (0, 0).
3449 var x = offsetX - xOffset;
3450 var y = offsetY - yOffset;
3452 // This is computing the rightmost pixel, effectively defining the
3454 var w = g.toDomCoords(g.xAxisRange()[1], null)[0] - xOffset;
3456 // This is computing the lowest pixel, effectively defining the height.
3457 var h = g.toDomCoords(null, yar0[0])[1] - yOffset;
3459 // Percentage from the left.
3460 var xPct = w === 0 ? 0 : (x / w);
3461 // Percentage from the top.
3462 var yPct = h === 0 ? 0 : (y / h);
3464 // The (1-) part below changes it from "% distance down from the top"
3465 // to "% distance up from the bottom".
3466 return [xPct, (1-yPct)];
3469 // Adjusts [x, y] toward each other by zoomInPercentage%
3470 // Split it so the left/bottom axis gets xBias/yBias of that change and
3471 // tight/top gets (1-xBias)/(1-yBias) of that change.
3473 // If a bias is missing it splits it down the middle.
3474 function zoomRange(g, zoomInPercentage, xBias, yBias) {
3475 xBias = xBias || 0.5;
3476 yBias = yBias || 0.5;
3478 function adjustAxis(axis, zoomInPercentage, bias) {
3479 var delta = axis[1] - axis[0];
3480 var increment = delta * zoomInPercentage;
3481 var foo = [increment * bias, increment * (1-bias)];
3483 return [ axis[0] + foo[0], axis[1] - foo[1] ];
3486 var yAxes = g.yAxisRanges();
3488 for (var i = 0; i < yAxes.length; i++) {
3489 newYAxes[i] = adjustAxis(yAxes[i], zoomInPercentage, yBias);
3492 return adjustAxis(g.xAxisRange(), zoomInPercentage, xBias);
3495 if(event.altKey || event.shiftKey) {
3496 state.globalSelectionSyncStop();
3497 state.globalSelectionSyncDelay();
3499 // http://dygraphs.com/gallery/interaction-api.js
3500 var normal = (event.detail) ? event.detail * -1 : event.wheelDelta / 40;
3501 var percentage = normal / 50;
3503 if (!(event.offsetX && event.offsetY)){
3504 event.offsetX = event.layerX - event.target.offsetLeft;
3505 event.offsetY = event.layerY - event.target.offsetTop;
3508 var percentages = offsetToPercentage(dygraph, event.offsetX, event.offsetY);
3509 var xPct = percentages[0];
3510 var yPct = percentages[1];
3512 var new_x_range = zoomRange(dygraph, percentage, xPct, yPct);
3514 var after = new_x_range[0];
3515 var before = new_x_range[1];
3517 var first = (state.data.first_entry + state.data.view_update_every) * 1000;
3518 var last = (state.data.last_entry + state.data.view_update_every) * 1000;
3521 after -= (before - last);
3528 state.setMode('zoom');
3529 if(state.updateChartPanOrZoom(after, before) === true)
3530 dygraph.updateOptions({ dateWindow: [ after, before ] });
3532 event.preventDefault();
3535 touchstart: function(event, dygraph, context) {
3536 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3537 state.log('interactionModel.touchstart()');
3539 state.setMode('zoom');
3542 Dygraph.defaultInteractionModel.touchstart(event, dygraph, context);
3544 // we overwrite the touch directions at the end, to overwrite
3545 // the internal default of dygraphs
3546 context.touchDirections = { x: true, y: false };
3548 state.dygraph_last_touch_start = new Date().getTime();
3549 state.dygraph_last_touch_move = 0;
3551 if(typeof event.touches[0].pageX === 'number')
3552 state.dygraph_last_touch_page_x = event.touches[0].pageX;
3554 state.dygraph_last_touch_page_x = 0;
3556 touchmove: function(event, dygraph, context) {
3557 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3558 state.log('interactionModel.touchmove()');
3560 Dygraph.defaultInteractionModel.touchmove(event, dygraph, context);
3562 state.dygraph_last_touch_move = new Date().getTime();
3564 touchend: function(event, dygraph, context) {
3565 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3566 state.log('interactionModel.touchend()');
3568 Dygraph.defaultInteractionModel.touchend(event, dygraph, context);
3570 // if it didn't move, it is a selection
3571 if(state.dygraph_last_touch_move === 0 && state.dygraph_last_touch_page_x !== 0) {
3572 // internal api of dygraphs
3573 var pct = (state.dygraph_last_touch_page_x - (dygraph.plotter_.area.x + state.element.getBoundingClientRect().left)) / dygraph.plotter_.area.w;
3574 var t = Math.round(state.data_after + (state.data_before - state.data_after) * pct);
3575 if(NETDATA.dygraphSetSelection(state, t) === true)
3576 state.globalSelectionSync(t);
3579 // if it was double tap within double click time, reset the charts
3580 var now = new Date().getTime();
3581 if(typeof state.dygraph_last_touch_end !== 'undefined') {
3582 if(state.dygraph_last_touch_move === 0) {
3583 var dt = now - state.dygraph_last_touch_end;
3584 if(dt <= NETDATA.options.current.double_click_speed) {
3585 state.globalSelectionSyncStop();
3586 NETDATA.globalPanAndZoom.clearMaster();
3592 // remember the timestamp of the last touch end
3593 state.dygraph_last_touch_end = now;
3598 if(NETDATA.chartLibraries.dygraph.isSparkline(state)) {
3599 state.dygraph_options.drawGrid = false;
3600 state.dygraph_options.drawAxis = false;
3601 state.dygraph_options.title = undefined;
3602 state.dygraph_options.units = undefined;
3603 state.dygraph_options.ylabel = undefined;
3604 state.dygraph_options.yLabelWidth = 0;
3605 state.dygraph_options.labelsDivWidth = 120;
3606 state.dygraph_options.labelsDivStyles.width = '120px';
3607 state.dygraph_options.labelsSeparateLines = true;
3608 state.dygraph_options.rightGap = 0;
3611 if(smooth === true) {
3612 state.dygraph_smooth_eligible = true;
3614 if(NETDATA.options.current.smooth_plot === true)
3615 state.dygraph_options.plotter = smoothPlotter;
3617 else state.dygraph_smooth_eligible = false;
3619 state.dygraph_instance = new Dygraph(state.element_chart,
3620 data.result.data, state.dygraph_options);
3622 state.dygraph_last_rendered = new Date().getTime();
3625 // ----------------------------------------------------------------------------------------------------------------
3628 NETDATA.morrisInitialize = function(callback) {
3629 if(typeof netdataNoMorris === 'undefined' || !netdataNoMorris) {
3631 // morris requires raphael
3632 if(!NETDATA.chartLibraries.raphael.initialized) {
3633 if(NETDATA.chartLibraries.raphael.enabled) {
3634 NETDATA.raphaelInitialize(function() {
3635 NETDATA.morrisInitialize(callback);
3639 NETDATA.chartLibraries.morris.enabled = false;
3640 if(typeof callback === "function")
3645 NETDATA._loadCSS(NETDATA.morris_css);
3648 url: NETDATA.morris_js,
3653 NETDATA.registerChartLibrary('morris', NETDATA.morris_js);
3656 NETDATA.chartLibraries.morris.enabled = false;
3657 NETDATA.error(100, NETDATA.morris_js);
3659 .always(function() {
3660 if(typeof callback === "function")
3666 NETDATA.chartLibraries.morris.enabled = false;
3667 if(typeof callback === "function")
3672 NETDATA.morrisChartUpdate = function(state, data) {
3673 state.morris_instance.setData(data.result.data);
3676 NETDATA.morrisChartCreate = function(state, data) {
3678 state.morris_options = {
3679 element: state.element_chart.id,
3680 data: data.result.data,
3682 ykeys: data.dimension_names,
3683 labels: data.dimension_names,
3689 continuousLine: false,
3690 behaveLikeLine: false
3693 if(state.chart.chart_type === 'line')
3694 state.morris_instance = new Morris.Line(state.morris_options);
3696 else if(state.chart.chart_type === 'area') {
3697 state.morris_options.behaveLikeLine = true;
3698 state.morris_instance = new Morris.Area(state.morris_options);
3701 state.morris_instance = new Morris.Area(state.morris_options);
3704 // ----------------------------------------------------------------------------------------------------------------
3707 NETDATA.raphaelInitialize = function(callback) {
3708 if(typeof netdataStopRaphael === 'undefined' || !netdataStopRaphael) {
3710 url: NETDATA.raphael_js,
3715 NETDATA.registerChartLibrary('raphael', NETDATA.raphael_js);
3718 NETDATA.chartLibraries.raphael.enabled = false;
3719 NETDATA.error(100, NETDATA.raphael_js);
3721 .always(function() {
3722 if(typeof callback === "function")
3727 NETDATA.chartLibraries.raphael.enabled = false;
3728 if(typeof callback === "function")
3733 NETDATA.raphaelChartUpdate = function(state, data) {
3734 $(state.element_chart).raphael(data.result, {
3735 width: state.chartWidth(),
3736 height: state.chartHeight()
3740 NETDATA.raphaelChartCreate = function(state, data) {
3741 $(state.element_chart).raphael(data.result, {
3742 width: state.chartWidth(),
3743 height: state.chartHeight()
3747 // ----------------------------------------------------------------------------------------------------------------
3750 NETDATA.googleInitialize = function(callback) {
3751 if(typeof netdataNoGoogleCharts === 'undefined' || !netdataNoGoogleCharts) {
3753 url: NETDATA.google_js,
3758 NETDATA.registerChartLibrary('google', NETDATA.google_js);
3759 google.load('visualization', '1.1', {
3760 'packages': ['corechart', 'controls'],
3761 'callback': callback
3765 NETDATA.chartLibraries.google.enabled = false;
3766 NETDATA.error(100, NETDATA.google_js);
3767 if(typeof callback === "function")
3772 NETDATA.chartLibraries.google.enabled = false;
3773 if(typeof callback === "function")
3778 NETDATA.googleChartUpdate = function(state, data) {
3779 var datatable = new google.visualization.DataTable(data.result);
3780 state.google_instance.draw(datatable, state.google_options);
3783 NETDATA.googleChartCreate = function(state, data) {
3784 var datatable = new google.visualization.DataTable(data.result);
3786 state.google_options = {
3787 colors: state.chartColors(),
3789 // do not set width, height - the chart resizes itself
3790 //width: state.chartWidth(),
3791 //height: state.chartHeight(),
3793 title: state.chart.title,
3796 // title: "Time of Day",
3797 // format:'HH:mm:ss',
3798 viewWindowMode: 'maximized',
3809 title: state.chart.units,
3810 viewWindowMode: 'pretty',
3825 focusTarget: 'category',
3832 titlePosition: 'out',
3843 curveType: 'function',
3848 switch(state.chart.chart_type) {
3850 state.google_options.vAxis.viewWindowMode = 'maximized';
3851 state.google_options.areaOpacity = NETDATA.options.current.color_fill_opacity_area;
3852 state.google_instance = new google.visualization.AreaChart(state.element_chart);
3856 state.google_options.isStacked = true;
3857 state.google_options.areaOpacity = NETDATA.options.current.color_fill_opacity_stacked;
3858 state.google_options.vAxis.viewWindowMode = 'maximized';
3859 state.google_options.vAxis.minValue = null;
3860 state.google_options.vAxis.maxValue = null;
3861 state.google_instance = new google.visualization.AreaChart(state.element_chart);
3866 state.google_options.lineWidth = 2;
3867 state.google_instance = new google.visualization.LineChart(state.element_chart);
3871 state.google_instance.draw(datatable, state.google_options);
3874 // ----------------------------------------------------------------------------------------------------------------
3877 NETDATA.easypiechartInitialize = function(callback) {
3878 if(typeof netdataNoEasyPieChart === 'undefined' || !netdataNoEasyPieChart) {
3880 url: NETDATA.easypiechart_js,
3885 NETDATA.registerChartLibrary('easypiechart', NETDATA.easypiechart_js);
3888 NETDATA.error(100, NETDATA.easypiechart_js);
3890 .always(function() {
3891 if(typeof callback === "function")
3896 NETDATA.chartLibraries.easypiechart.enabled = false;
3897 if(typeof callback === "function")
3902 NETDATA.easypiechartChartUpdate = function(state, data) {
3904 state.easypiechart_instance.update();
3907 NETDATA.easypiechartChartCreate = function(state, data) {
3908 var self = $(state.element);
3913 $(state.element_chart).data('data-percent', pcent);
3914 data.element_chart.innerHTML = value.toString();
3916 state.easypiechart_instance = new EasyPieChart(state.element_chart, {
3917 barColor: self.data('easypiechart-barcolor') || '#ef1e25',
3918 trackColor: self.data('easypiechart-trackcolor') || '#f2f2f2',
3919 scaleColor: self.data('easypiechart-scalecolor') || '#dfe0e0',
3920 scaleLength: self.data('easypiechart-scalelength') || 5,
3921 lineCap: self.data('easypiechart-linecap') || 'round',
3922 lineWidth: self.data('easypiechart-linewidth') || 3,
3923 trackWidth: self.data('easypiechart-trackwidth') || undefined,
3924 size: self.data('easypiechart-size') || Math.min(state.chartWidth(), state.chartHeight()),
3925 rotate: self.data('easypiechart-rotate') || 0,
3926 animate: self.data('easypiechart-rotate') || {duration: 0, enabled: false},
3927 easing: self.data('easypiechart-easing') || undefined
3931 // ----------------------------------------------------------------------------------------------------------------
3932 // Charts Libraries Registration
3934 NETDATA.chartLibraries = {
3936 initialize: NETDATA.dygraphInitialize,
3937 create: NETDATA.dygraphChartCreate,
3938 update: NETDATA.dygraphChartUpdate,
3939 resize: function(state) {
3940 if(typeof state.dygraph_instance.resize === 'function')
3941 state.dygraph_instance.resize();
3943 setSelection: NETDATA.dygraphSetSelection,
3944 clearSelection: NETDATA.dygraphClearSelection,
3947 format: function(state) { return 'json'; },
3948 options: function(state) { return 'ms|flip'; },
3949 legend: function(state) {
3950 if(this.isSparkline(state) === false)
3951 return 'right-side';
3955 autoresize: function(state) { return true; },
3956 max_updates_to_recreate: function(state) { return 5000; },
3957 track_colors: function(state) { return true; },
3958 pixels_per_point: function(state) {
3959 if(this.isSparkline(state) === false)
3965 isSparkline: function(state) {
3966 if(typeof state.dygraph_sparkline === 'undefined') {
3967 var t = $(state.element).data('dygraph-theme');
3968 if(t === 'sparkline')
3969 state.dygraph_sparkline = true;
3971 state.dygraph_sparkline = false;
3973 return state.dygraph_sparkline;
3977 initialize: NETDATA.sparklineInitialize,
3978 create: NETDATA.sparklineChartCreate,
3979 update: NETDATA.sparklineChartUpdate,
3981 setSelection: function(t) { return true; },
3982 clearSelection: function() { return true; },
3985 format: function(state) { return 'array'; },
3986 options: function(state) { return 'flip|abs'; },
3987 legend: function(state) { return null; },
3988 autoresize: function(state) { return false; },
3989 max_updates_to_recreate: function(state) { return 5000; },
3990 track_colors: function(state) { return false; },
3991 pixels_per_point: function(state) { return 3; }
3994 initialize: NETDATA.peityInitialize,
3995 create: NETDATA.peityChartCreate,
3996 update: NETDATA.peityChartUpdate,
3998 setSelection: function(t) { return true; },
3999 clearSelection: function() { return true; },
4002 format: function(state) { return 'ssvcomma'; },
4003 options: function(state) { return 'null2zero|flip|abs'; },
4004 legend: function(state) { return null; },
4005 autoresize: function(state) { return false; },
4006 max_updates_to_recreate: function(state) { return 5000; },
4007 track_colors: function(state) { return false; },
4008 pixels_per_point: function(state) { return 3; }
4011 initialize: NETDATA.morrisInitialize,
4012 create: NETDATA.morrisChartCreate,
4013 update: NETDATA.morrisChartUpdate,
4015 setSelection: function(t) { return true; },
4016 clearSelection: function() { return true; },
4019 format: function(state) { return 'json'; },
4020 options: function(state) { return 'objectrows|ms'; },
4021 legend: function(state) { return null; },
4022 autoresize: function(state) { return false; },
4023 max_updates_to_recreate: function(state) { return 50; },
4024 track_colors: function(state) { return false; },
4025 pixels_per_point: function(state) { return 15; }
4028 initialize: NETDATA.googleInitialize,
4029 create: NETDATA.googleChartCreate,
4030 update: NETDATA.googleChartUpdate,
4032 setSelection: function(t) { return true; },
4033 clearSelection: function() { return true; },
4036 format: function(state) { return 'datatable'; },
4037 options: function(state) { return ''; },
4038 legend: function(state) { return null; },
4039 autoresize: function(state) { return false; },
4040 max_updates_to_recreate: function(state) { return 300; },
4041 track_colors: function(state) { return false; },
4042 pixels_per_point: function(state) { return 4; }
4045 initialize: NETDATA.raphaelInitialize,
4046 create: NETDATA.raphaelChartCreate,
4047 update: NETDATA.raphaelChartUpdate,
4049 setSelection: function(t) { return true; },
4050 clearSelection: function() { return true; },
4053 format: function(state) { return 'json'; },
4054 options: function(state) { return ''; },
4055 legend: function(state) { return null; },
4056 autoresize: function(state) { return false; },
4057 max_updates_to_recreate: function(state) { return 5000; },
4058 track_colors: function(state) { return false; },
4059 pixels_per_point: function(state) { return 3; }
4062 initialize: NETDATA.easypiechartInitialize,
4063 create: NETDATA.easypiechartChartCreate,
4064 update: NETDATA.easypiechartChartUpdate,
4066 setSelection: function(t) { return true; },
4067 clearSelection: function() { return true; },
4070 format: function(state) { return 'json'; },
4071 options: function(state) { return ''; },
4072 legend: function(state) { return null; },
4073 autoresize: function(state) { return false; },
4074 max_updates_to_recreate: function(state) { return 5000; },
4075 track_colors: function(state) { return false; },
4076 pixels_per_point: function(state) { return 3; }
4080 NETDATA.registerChartLibrary = function(library, url) {
4081 if(NETDATA.options.debug.libraries === true)
4082 console.log("registering chart library: " + library);
4084 NETDATA.chartLibraries[library].url = url;
4085 NETDATA.chartLibraries[library].initialized = true;
4086 NETDATA.chartLibraries[library].enabled = true;
4089 // ----------------------------------------------------------------------------------------------------------------
4092 NETDATA.requiredJs = [
4094 url: NETDATA.serverDefault + 'lib/bootstrap.min.js',
4095 isAlreadyLoaded: function() {
4096 if(typeof $().emulateTransitionEnd == 'function')
4099 if(typeof netdataNoBootstrap !== 'undefined' && netdataNoBootstrap)
4107 url: NETDATA.serverDefault + 'lib/jquery.nanoscroller.min.js',
4108 isAlreadyLoaded: function() { return false; }
4111 url: NETDATA.serverDefault + 'lib/bootstrap-toggle.min.js',
4112 isAlreadyLoaded: function() { return false; }
4116 NETDATA.requiredCSS = [
4118 url: NETDATA.serverDefault + 'css/bootstrap.min.css',
4119 isAlreadyLoaded: function() {
4120 if(typeof netdataNoBootstrap !== 'undefined' && netdataNoBootstrap)
4127 url: NETDATA.serverDefault + 'css/font-awesome.min.css',
4128 isAlreadyLoaded: function() { return false; }
4131 url: NETDATA.dashboard_css,
4132 isAlreadyLoaded: function() { return false; }
4135 url: NETDATA.serverDefault + 'css/bootstrap-toggle.min.css',
4136 isAlreadyLoaded: function() { return false; }
4140 NETDATA.loadRequiredJs = function(index, callback) {
4141 if(index >= NETDATA.requiredJs.length) {
4142 if(typeof callback === 'function')
4147 if(NETDATA.requiredJs[index].isAlreadyLoaded()) {
4148 NETDATA.loadRequiredJs(++index, callback);
4152 if(NETDATA.options.debug.main_loop === true)
4153 console.log('loading ' + NETDATA.requiredJs[index].url);
4156 url: NETDATA.requiredJs[index].url,
4160 .success(function() {
4161 if(NETDATA.options.debug.main_loop === true)
4162 console.log('loaded ' + NETDATA.requiredJs[index].url);
4164 NETDATA.loadRequiredJs(++index, callback);
4167 alert('Cannot load required JS library: ' + NETDATA.requiredJs[index].url);
4171 NETDATA.loadRequiredCSS = function(index) {
4172 if(index >= NETDATA.requiredCSS.length)
4175 if(NETDATA.requiredCSS[index].isAlreadyLoaded()) {
4176 NETDATA.loadRequiredCSS(++index);
4180 if(NETDATA.options.debug.main_loop === true)
4181 console.log('loading ' + NETDATA.requiredCSS[index].url);
4183 NETDATA._loadCSS(NETDATA.requiredCSS[index].url);
4184 NETDATA.loadRequiredCSS(++index);
4187 NETDATA.errorReset();
4188 NETDATA.loadRequiredCSS(0);
4190 NETDATA._loadjQuery(function() {
4191 NETDATA.loadRequiredJs(0, function() {
4192 if(typeof netdataDontStart === 'undefined' || !netdataDontStart) {
4193 if(NETDATA.options.debug.main_loop === true)
4194 console.log('starting chart refresh thread');
4201 // window.NETDATA = NETDATA;
4202 // })(window, document);