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 readyCallback: null, // a callback when we load the required stuf
123 pauseCallback: null, // a callback when we are really paused
125 pause: false, // when enabled we don't auto-refresh the charts
127 targets: null, // an array of all the state objects that are
128 // currently active (independently of their
129 // viewport visibility)
131 updated_dom: true, // when true, the DOM has been updated with
132 // new elements we have to check.
134 auto_refresher_fast_weight: 0, // this is the current time in ms, spent
135 // rendering charts continiously.
136 // used with .current.fast_render_timeframe
138 page_is_visible: true, // when true, this page is visible
140 auto_refresher_stop_until: 0, // timestamp in ms - used internaly, to stop the
141 // auto-refresher for some time (when a chart is
142 // performing pan or zoom, we need to stop refreshing
143 // all other charts, to have the maximum speed for
144 // rendering the chart that is panned or zoomed).
145 // Used with .current.global_pan_sync_time
147 last_resized: 0, // the timestamp of the last resize request
149 crossDomainAjax: false, // enable this to request crossDomain AJAX
151 last_page_scroll: 0, // the timestamp the last time the page was scrolled
153 // the current profile
154 // we may have many...
156 pixels_per_point: 1, // the minimum pixels per point for all charts
157 // increase this to speed javascript up
158 // each chart library has its own limit too
159 // the max of this and the chart library is used
160 // the final is calculated every time, so a change
161 // here will have immediate effect on the next chart
164 idle_between_charts: 100, // ms - how much time to wait between chart updates
166 fast_render_timeframe: 200, // ms - render continously until this time of continious
167 // rendering has been reached
168 // this setting is used to make it render e.g. 10
169 // charts at once, sleep idle_between_charts time
170 // and continue for another 10 charts.
172 idle_between_loops: 500, // ms - if all charts have been updated, wait this
173 // time before starting again.
175 idle_parallel_loops: 100, // ms - the time between parallel refresher updates
177 idle_lost_focus: 500, // ms - when the window does not have focus, check
178 // if focus has been regained, every this time
180 global_pan_sync_time: 1000, // ms - when you pan or zoon a chart, the background
181 // autorefreshing of charts is paused for this amount
184 sync_selection_delay: 1500, // ms - when you pan or zoom a chart, wait this amount
185 // of time before setting up synchronized selections
188 sync_selection: true, // enable or disable selection sync
190 pan_and_zoom_delay: 50, // when panning or zooming, how ofter to update the chart
192 sync_pan_and_zoom: true, // enable or disable pan and zoom sync
194 update_only_visible: true, // enable or disable visibility management
196 parallel_refresher: true, // enable parallel refresh of charts
198 concurrent_refreshes: true, // when parallel_refresher is enabled, sync also the charts
200 destroy_on_hide: false, // destroy charts when they are not visible
202 eliminate_zero_dimensions: true, // do not show dimensions with just zeros
204 stop_updates_when_focus_is_lost: true, // boolean - shall we stop auto-refreshes when document does not have user focus
205 stop_updates_while_resizing: 1000, // ms - time to stop auto-refreshes while resizing the charts
207 double_click_speed: 500, // ms - time between clicks / taps to detect double click/tap
209 smooth_plot: true, // enable smooth plot, where possible
211 color_fill_opacity_line: 1.0,
212 color_fill_opacity_area: 0.2,
213 color_fill_opacity_stacked: 0.8,
215 setOptionCallback: function() { ; }
223 chart_data_url: false,
233 // ----------------------------------------------------------------------------------------------------------------
234 // local storage options
236 NETDATA.localStorage = {
239 callback: {} // only used for resetting back to defaults
242 NETDATA.localStorageGet = function(key, def, callback) {
245 if(typeof NETDATA.localStorage.default[key.toString()] === 'undefined') {
246 NETDATA.localStorage.default[key.toString()] = def;
247 NETDATA.localStorage.callback[key.toString()] = callback;
250 if(typeof Storage !== "undefined" && typeof localStorage === 'object') {
252 // console.log('localStorage: loading "' + key.toString() + '"');
253 ret = localStorage.getItem(key.toString());
254 if(ret === null || ret === 'undefined') {
255 // console.log('localStorage: cannot load it, saving "' + key.toString() + '" with value "' + JSON.stringify(def) + '"');
256 localStorage.setItem(key.toString(), JSON.stringify(def));
260 // console.log('localStorage: got "' + key.toString() + '" with value "' + ret + '"');
261 ret = JSON.parse(ret);
262 // console.log('localStorage: loaded "' + key.toString() + '" as value ' + ret + ' of type ' + typeof(ret));
266 console.log('localStorage: failed to read "' + key.toString() + '", using default: "' + def.toString() + '"');
271 if(typeof ret === 'undefined' || ret === 'undefined') {
272 console.log('localStorage: LOADED UNDEFINED "' + key.toString() + '" as value ' + ret + ' of type ' + typeof(ret));
276 NETDATA.localStorage.current[key.toString()] = ret;
280 NETDATA.localStorageSet = function(key, value, callback) {
281 if(typeof value === 'undefined' || value === 'undefined') {
282 console.log('localStorage: ATTEMPT TO SET UNDEFINED "' + key.toString() + '" as value ' + value + ' of type ' + typeof(value));
285 if(typeof NETDATA.localStorage.default[key.toString()] === 'undefined') {
286 NETDATA.localStorage.default[key.toString()] = value;
287 NETDATA.localStorage.current[key.toString()] = value;
288 NETDATA.localStorage.callback[key.toString()] = callback;
291 if(typeof Storage !== "undefined" && typeof localStorage === 'object') {
292 // console.log('localStorage: saving "' + key.toString() + '" with value "' + JSON.stringify(value) + '"');
294 localStorage.setItem(key.toString(), JSON.stringify(value));
297 console.log('localStorage: failed to save "' + key.toString() + '" with value: "' + value.toString() + '"');
301 NETDATA.localStorage.current[key.toString()] = value;
305 NETDATA.localStorageGetRecursive = function(obj, prefix, callback) {
307 if(typeof obj[i] === 'object') {
308 //console.log('object ' + prefix + '.' + i.toString());
309 NETDATA.localStorageGetRecursive(obj[i], prefix + '.' + i.toString(), callback);
313 obj[i] = NETDATA.localStorageGet(prefix + '.' + i.toString(), obj[i], callback);
317 NETDATA.setOption = function(key, value) {
318 if(key.toString() === 'setOptionCallback') {
319 if(typeof NETDATA.options.current.setOptionCallback === 'function') {
320 NETDATA.options.current[key.toString()] = value;
321 NETDATA.options.current.setOptionCallback();
324 else if(NETDATA.options.current[key.toString()] !== value) {
325 var name = 'options.' + key.toString();
327 if(typeof NETDATA.localStorage.default[name.toString()] === 'undefined')
328 console.log('localStorage: setOption() on unsaved option: "' + name.toString() + '", value: ' + value);
330 //console.log(NETDATA.localStorage);
331 //console.log('setOption: setting "' + key.toString() + '" to "' + value + '" of type ' + typeof(value) + ' original type ' + typeof(NETDATA.options.current[key.toString()]));
332 //console.log(NETDATA.options);
333 NETDATA.options.current[key.toString()] = NETDATA.localStorageSet(name.toString(), value, null);
335 if(typeof NETDATA.options.current.setOptionCallback === 'function')
336 NETDATA.options.current.setOptionCallback();
342 NETDATA.getOption = function(key) {
343 return NETDATA.options.current[key.toString()];
346 // read settings from local storage
347 NETDATA.localStorageGetRecursive(NETDATA.options.current, 'options', null);
349 // always start with this option enabled.
350 NETDATA.setOption('stop_updates_when_focus_is_lost', true);
352 NETDATA.resetOptions = function() {
353 for(var i in NETDATA.localStorage.default) {
354 var a = i.split('.');
356 if(a[0] === 'options') {
357 if(a[1] === 'options.setOptionCallback') continue;
358 if(typeof NETDATA.localStorage.default[i] === 'undefined') continue;
359 if(NETDATA.options.current[i] === NETDATA.localStorage.default[i]) continue;
361 NETDATA.setOption(a[1], NETDATA.localStorage.default[i]);
363 else if(a[0] === 'chart_heights') {
364 if(typeof NETDATA.localStorage.callback[i] === 'function' && typeof NETDATA.localStorage.default[i] !== 'undefined') {
365 NETDATA.localStorage.callback[i](NETDATA.localStorage.default[i]);
371 // ----------------------------------------------------------------------------------------------------------------
373 if(NETDATA.options.debug.main_loop === true)
374 console.log('welcome to NETDATA');
376 window.onresize = function(event) {
377 NETDATA.options.last_page_scroll = new Date().getTime();
378 NETDATA.options.last_resized = new Date().getTime();
381 window.onscroll = function(event) {
382 NETDATA.options.last_page_scroll = new Date().getTime();
383 if(NETDATA.options.targets === null) return;
385 // when the user scrolls he sees that we have
386 // hidden all the not-visible charts
387 // using this little function we try to switch
388 // the charts back to visible quickly
389 var targets = NETDATA.options.targets;
390 var len = targets.length;
391 while(len--) targets[len].isVisible();
394 // ----------------------------------------------------------------------------------------------------------------
397 NETDATA.errorCodes = {
398 100: { message: "Cannot load chart library", alert: true },
399 101: { message: "Cannot load jQuery", alert: true },
400 402: { message: "Chart library not found", alert: false },
401 403: { message: "Chart library not enabled/is failed", alert: false },
402 404: { message: "Chart not found", alert: false }
404 NETDATA.errorLast = {
410 NETDATA.error = function(code, msg) {
411 NETDATA.errorLast.code = code;
412 NETDATA.errorLast.message = msg;
413 NETDATA.errorLast.datetime = new Date().getTime();
415 console.log("ERROR " + code + ": " + NETDATA.errorCodes[code].message + ": " + msg);
417 if(NETDATA.errorCodes[code].alert)
418 alert("ERROR " + code + ": " + NETDATA.errorCodes[code].message + ": " + msg);
421 NETDATA.errorReset = function() {
422 NETDATA.errorLast.code = 0;
423 NETDATA.errorLast.message = "You are doing fine!";
424 NETDATA.errorLast.datetime = 0;
427 // ----------------------------------------------------------------------------------------------------------------
430 // When multiple charts need the same chart, we avoid downloading it
431 // multiple times (and having it in browser memory multiple time)
432 // by using this registry.
434 // Every time we download a chart definition, we save it here with .add()
435 // Then we try to get it back with .get(). If that fails, we download it.
437 NETDATA.chartRegistry = {
440 fixid: function(id) {
441 return id.replace(/:/g, "_").replace(/\//g, "_");
444 add: function(host, id, data) {
445 host = this.fixid(host);
448 if(typeof this.charts[host] === 'undefined')
449 this.charts[host] = {};
451 //console.log('added ' + host + '/' + id);
452 this.charts[host][id] = data;
455 get: function(host, id) {
456 host = this.fixid(host);
459 if(typeof this.charts[host] === 'undefined')
462 if(typeof this.charts[host][id] === 'undefined')
465 //console.log('cached ' + host + '/' + id);
466 return this.charts[host][id];
469 downloadAll: function(host, callback) {
470 while(host.slice(-1) === '/')
471 host = host.substring(0, host.length - 1);
476 url: host + '/api/v1/charts',
477 crossDomain: NETDATA.options.crossDomainAjax,
481 .done(function(data) {
482 var h = NETDATA.chartRegistry.fixid(host);
483 //console.log('downloaded all charts from ' + host + ' (' + h + ')');
484 self.charts[h] = data.charts;
485 if(typeof callback === 'function')
489 if(typeof callback === 'function')
495 // ----------------------------------------------------------------------------------------------------------------
496 // Global Pan and Zoom on charts
498 // Using this structure are synchronize all the charts, so that
499 // when you pan or zoom one, all others are automatically refreshed
500 // to the same timespan.
502 NETDATA.globalPanAndZoom = {
503 seq: 0, // timestamp ms
504 // every time a chart is panned or zoomed
505 // we set the timestamp here
506 // then we use it as a sequence number
507 // to find if other charts are syncronized
510 master: null, // the master chart (state), to which all others
513 force_before_ms: null, // the timespan to sync all other charts
514 force_after_ms: null,
517 setMaster: function(state, after, before) {
518 if(NETDATA.options.current.sync_pan_and_zoom === false)
521 if(this.master !== null && this.master !== state)
522 this.master.resetChart();
524 var now = new Date().getTime();
527 this.force_after_ms = after;
528 this.force_before_ms = before;
529 NETDATA.options.auto_refresher_stop_until = now + NETDATA.options.current.global_pan_sync_time;
533 clearMaster: function() {
534 if(NETDATA.options.current.sync_pan_and_zoom === false)
537 if(this.master !== null) {
538 var state = this.master;
539 this.master = null; // prevent infinite recursion
542 NETDATA.options.auto_refresher_stop_until = 0;
547 this.force_after_ms = null;
548 this.force_before_ms = null;
551 // is the given state the master of the global
552 // pan and zoom sync?
553 isMaster: function(state) {
554 if(this.master === state) return true;
558 // are we currently have a global pan and zoom sync?
559 isActive: function() {
560 if(this.master !== null && this.force_before_ms !== null && this.force_after_ms !== null && this.seq !== 0) return true;
564 // check if a chart, other than the master
565 // needs to be refreshed, due to the global pan and zoom
566 shouldBeAutoRefreshed: function(state) {
567 if(this.master === null || this.seq === 0)
570 if(state.needsRecreation())
573 if(state.tm.pan_and_zoom_seq === this.seq)
580 // ----------------------------------------------------------------------------------------------------------------
581 // dimensions selection
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 // Our state object, where all per-chart values are stored
782 resizeCallback = function(state) {
784 this.resize = function(height) {
789 chartState = function(element) {
790 var self = $(element);
792 // GUID - a unique identifier for the chart
793 this.uuid = NETDATA.guid();
795 // string - the name of chart
796 this.id = self.data('netdata');
798 // string - the key for localStorage settings
799 this.settings_id = self.data('id') || null;
801 // the user given dimensions of the element
802 this.width = self.data('width') || NETDATA.chartDefaults.width;
803 this.height = self.data('height') || NETDATA.chartDefaults.height;
805 if(this.settings_id !== null) {
807 this.height = NETDATA.localStorageGet('chart_heights.' + this.settings_id, this.height, function(height) {
808 me.resizeAndRedrawChart(height);
813 // string - the netdata server URL, without any path
814 host: self.data('host') || NETDATA.chartDefaults.host,
816 // string - the grouping method requested by the user
817 method: self.data('method') || NETDATA.chartDefaults.method,
819 // the time-range requested by the user
820 after: self.data('after') || NETDATA.chartDefaults.after,
821 before: self.data('before') || NETDATA.chartDefaults.before,
823 // the pixels per point requested by the user
824 pixels_per_point: self.data('pixels-per-point') || 1,
825 points: self.data('points') || null,
827 // the dimensions requested by the user
828 dimensions: self.data('dimensions') || null,
830 // the chart library requested by the user
831 library_name: self.data('chart-library') || NETDATA.chartDefaults.library,
832 library: null, // object - the chart library used
836 colors_available: null,
838 element: element, // the element already created by the user
839 element_message: null,
840 element_loading: null,
841 element_chart: null, // the element with the chart
842 element_chart_id: null,
843 element_legend: null, // the element with the legend of the chart (if created by us)
844 element_legend_id: null,
845 element_legend_childs: {
855 chart_url: null, // string - the url to download chart info
856 chart: null, // object - the chart as downloaded from the server
858 validated: false, // boolean - has the chart been validated?
859 enabled: true, // boolean - is the chart enabled for refresh?
860 paused: false, // boolean - is the chart paused for any reason?
861 selected: false, // boolean - is the chart shown a selection?
862 debug: false, // boolean - console.log() debug info about this chart
864 dom_created: false, // boolean - is the DOM for the chart created?
865 chart_created: false, // boolean - is the library.create() been called?
867 updates_counter: 0, // numeric - the number of refreshes made so far
868 updates_since_last_creation: 0,
871 last_info_downloaded: 0, // milliseconds - the timestamp we downloaded the chart
873 last_updated: 0, // the timestamp the chart last updated with data
875 pan_and_zoom_seq: 0, // the sequence number of the global synchronization
877 // Used with NETDATA.globalPanAndZoom.seq
879 last_visible_check: 0, // the time we last checked if it is visible
881 last_resized: 0, // the time the chart was resized
882 last_hidden: 0, // the time the chart was hidden
883 last_unhidden: 0, // the time the chart was unhidden
885 last_autorefreshed: 0 // the time the chart was last refreshed
888 data: null, // the last data as downloaded from the netdata server
889 data_url: 'invalid://', // string - the last url used to update the chart
890 data_points: 0, // number - the number of points returned from netdata
891 data_after: 0, // milliseconds - the first timestamp of the data
892 data_before: 0, // milliseconds - the last timestamp of the data
893 data_update_every: 0, // milliseconds - the frequency to update the data
894 netdata_first: 0, // milliseconds - the first timestamp in netdata
895 netdata_last: 0, // milliseconds - the last timestamp in netdata
897 dimensions_visibility: new dimensionsVisibility(this),
899 current: null, // auto, pan, zoom
900 // this is a pointer to one of the sub-classes below
905 force_update_at: 0, // the timestamp to force the update at
906 force_before_ms: null,
907 force_after_ms: null,
908 requested_before_ms: null,
909 requested_after_ms: null,
914 force_update_at: 0, // the timestamp to force the update at
915 force_before_ms: null,
916 force_after_ms: null,
917 requested_before_ms: null,
918 requested_after_ms: null,
923 force_update_at: 0, // the timestamp to force the update at
924 force_before_ms: null,
925 force_after_ms: null,
926 requested_before_ms: null,
927 requested_after_ms: null,
930 refresh_dt_ms: 0, // milliseconds - the time the last refresh took
931 refresh_dt_element_name: self.data('dt-element-name') || null, // string - the element to print refresh_dt_ms
932 refresh_dt_element: null
938 // ----------------------------------------------------------------------------------------------------------------
941 // this is actual chart resize algorithm
943 // - resize the entire container
944 // - update the internal states
945 // - resize the chart as the div changes height
946 // - update the scrollbar of the legend
947 chartState.prototype.resizeAndRedrawChart = function(h) {
949 this.element.style.height = h;
951 if(this.settings_id !== null)
952 NETDATA.localStorageSet('chart_heights.' + this.settings_id, h);
954 var now = new Date().getTime();
955 NETDATA.options.last_page_scroll = now;
956 NETDATA.options.last_resized = now;
957 NETDATA.options.auto_refresher_stop_until = now + NETDATA.options.current.stop_updates_while_resizing;
959 if(typeof this.library.resize === 'function' && this.element_chart !== null)
960 this.library.resize(this);
962 if(this.element_legend_childs.nano !== null && this.element_legend_childs.nano_options !== null)
963 $(this.element_legend_childs.nano).nanoScroller();
966 chartState.prototype.resizeHandler = function(e) {
969 if(typeof this.event_resize === 'undefined'
970 || this.event_resize.chart_original_w === 'undefined'
971 || this.event_resize.chart_original_h === 'undefined')
972 this.event_resize = {
973 chart_original_w: this.element.clientWidth,
974 chart_original_h: this.element.clientHeight,
978 if(e.type === 'touchstart') {
979 this.event_resize.mouse_start_x = e.touches.item(0).pageX;
980 this.event_resize.mouse_start_y = e.touches.item(0).pageY;
983 this.event_resize.mouse_start_x = e.clientX;
984 this.event_resize.mouse_start_y = e.clientY;
987 this.event_resize.chart_start_w = this.element.clientWidth;
988 this.event_resize.chart_start_h = this.element.clientHeight;
989 this.event_resize.chart_last_w = this.element.clientWidth;
990 this.event_resize.chart_last_h = this.element.clientHeight;
992 var now = new Date().getTime();
993 if(now - this.event_resize.last <= NETDATA.options.current.double_click_speed) {
994 // double click / double tap event
996 // the optimal height of the chart
997 // showing the entire legend
998 var optimal = this.event_resize.chart_last_h
999 + this.element_legend_childs.content.scrollHeight
1000 - this.element_legend_childs.content.clientHeight;
1002 // if we are not optimal, be optimal
1003 if(this.event_resize.chart_last_h != optimal)
1004 this.resizeAndRedrawChart(optimal.toString() + 'px');
1006 // else if we do not have the original height
1007 // reset to the original height
1008 else if(this.event_resize.chart_last_h != this.event_resize.chart_original_h)
1009 this.resizeAndRedrawChart(this.event_resize.chart_original_h.toString() + 'px');
1012 this.event_resize.last = now;
1015 // process movement event
1016 document.onmousemove =
1017 document.ontouchmove =
1018 this.element_legend_childs.resize_handler.onmousemove =
1019 this.element_legend_childs.resize_handler.ontouchmove =
1024 case 'mousemove': y = e.clientY; break;
1025 case 'touchmove': y = e.touches.item(e.touches - 1).pageY; break;
1029 var newH = self.event_resize.chart_start_h + y - self.event_resize.mouse_start_y;
1031 if(newH >= 70 && newH !== self.event_resize.chart_last_h) {
1032 self.resizeAndRedrawChart(newH.toString() + 'px');
1033 self.event_resize.chart_last_h = newH;
1038 // process end event
1039 document.onmouseup =
1040 document.ontouchend =
1041 this.element_legend_childs.resize_handler.onmouseup =
1042 this.element_legend_childs.resize_handler.ontouchend =
1044 // remove all the hooks
1045 document.onmouseup =
1046 document.onmousemove =
1047 document.ontouchmove =
1048 document.ontouchend =
1049 self.element_legend_childs.resize_handler.onmousemove =
1050 self.element_legend_childs.resize_handler.ontouchmove =
1051 self.element_legend_childs.resize_handler.onmouseout =
1052 self.element_legend_childs.resize_handler.onmouseup =
1053 self.element_legend_childs.resize_handler.ontouchend =
1056 // allow auto-refreshes
1057 NETDATA.options.auto_refresher_stop_until = 0;
1063 // ----------------------------------------------------------------------------------------------------------------
1064 // global selection sync
1066 NETDATA.globalSelectionSync = {
1068 dont_sync_before: 0,
1072 // prevent to global selection sync for some time
1073 chartState.prototype.globalSelectionSyncDelay = function(ms) {
1074 if(NETDATA.options.current.sync_selection === false)
1077 if(typeof ms === 'number')
1078 NETDATA.globalSelectionSync.dont_sync_before = new Date().getTime() + ms;
1080 NETDATA.globalSelectionSync.dont_sync_before = new Date().getTime() + NETDATA.options.current.sync_selection_delay;
1083 // can we globally apply selection sync?
1084 chartState.prototype.globalSelectionSyncAbility = function() {
1085 if(NETDATA.options.current.sync_selection === false)
1088 if(NETDATA.globalSelectionSync.dont_sync_before > new Date().getTime()) return false;
1092 chartState.prototype.globalSelectionSyncIsMaster = function() {
1093 if(NETDATA.globalSelectionSync.state === this)
1099 // this chart is the master of the global selection sync
1100 chartState.prototype.globalSelectionSyncBeMaster = function() {
1102 if(this.globalSelectionSyncIsMaster()) {
1103 if(this.debug === true)
1104 this.log('sync: I am the master already.');
1109 if(NETDATA.globalSelectionSync.state) {
1110 if(this.debug === true)
1111 this.log('sync: I am not the sync master. Resetting global sync.');
1113 this.globalSelectionSyncStop();
1116 // become the master
1117 if(this.debug === true)
1118 this.log('sync: becoming sync master.');
1120 this.selected = true;
1121 NETDATA.globalSelectionSync.state = this;
1123 // find the all slaves
1124 var targets = NETDATA.options.targets;
1125 var len = targets.length;
1130 if(this.debug === true)
1131 st.log('sync: not adding me to sync');
1133 else if(st.globalSelectionSyncIsEligible()) {
1134 if(this.debug === true)
1135 st.log('sync: adding to sync as slave');
1137 st.globalSelectionSyncBeSlave();
1141 // this.globalSelectionSyncDelay(100);
1144 // can the chart participate to the global selection sync as a slave?
1145 chartState.prototype.globalSelectionSyncIsEligible = function() {
1146 if(this.enabled === true
1147 && this.library !== null
1148 && typeof this.library.setSelection === 'function'
1150 && this.dom_created === true
1151 && this.chart_created === true)
1157 // this chart is a slave of the global selection sync
1158 chartState.prototype.globalSelectionSyncBeSlave = function() {
1159 if(NETDATA.globalSelectionSync.state !== this)
1160 NETDATA.globalSelectionSync.slaves.push(this);
1163 // sync all the visible charts to the given time
1164 // this is to be called from the chart libraries
1165 chartState.prototype.globalSelectionSync = function(t) {
1166 if(this.globalSelectionSyncAbility() === false) {
1167 if(this.debug === true)
1168 this.log('sync: cannot sync (yet?).');
1173 if(this.globalSelectionSyncIsMaster() === false) {
1174 if(this.debug === true)
1175 this.log('sync: trying to be sync master.');
1177 this.globalSelectionSyncBeMaster();
1179 if(this.globalSelectionSyncAbility() === false) {
1180 if(this.debug === true)
1181 this.log('sync: cannot sync (yet?).');
1187 $.each(NETDATA.globalSelectionSync.slaves, function(i, st) {
1192 // stop syncing all charts to the given time
1193 chartState.prototype.globalSelectionSyncStop = function() {
1194 if(NETDATA.globalSelectionSync.slaves.length) {
1195 if(this.debug === true)
1196 this.log('sync: cleaning up...');
1199 $.each(NETDATA.globalSelectionSync.slaves, function(i, st) {
1201 if(self.debug === true)
1202 st.log('sync: not adding me to sync stop');
1205 if(self.debug === true)
1206 st.log('sync: removed slave from sync');
1208 st.clearSelection();
1212 NETDATA.globalSelectionSync.slaves = [];
1213 NETDATA.globalSelectionSync.state = null;
1216 // since we are the sync master, we should not call this.clearSelection()
1217 // dygraphs is taking care of visualizing our selection.
1218 this.selected = false;
1221 chartState.prototype.setSelection = function(t) {
1222 if(typeof this.library.setSelection === 'function') {
1223 if(this.library.setSelection(this, t) === true)
1224 this.selected = true;
1226 this.selected = false;
1228 else this.selected = true;
1230 if(this.selected === true && this.debug === true)
1231 this.log('selection set to ' + t.toString());
1233 return this.selected;
1236 chartState.prototype.clearSelection = function() {
1237 if(this.selected === true) {
1238 if(typeof this.library.clearSelection === 'function') {
1239 if(this.library.clearSelection(this) === true)
1240 this.selected = false;
1242 this.selected = true;
1244 else this.selected = false;
1246 if(this.selected === false && this.debug === true)
1247 this.log('selection cleared');
1251 return this.selected;
1254 // find if a timestamp (ms) is shown in the current chart
1255 chartState.prototype.timeIsVisible = function(t) {
1256 if(t >= this.data_after && t <= this.data_before)
1261 chartState.prototype.calculateRowForTime = function(t) {
1262 if(this.timeIsVisible(t) === false) return -1;
1263 return Math.floor((t - this.data_after) / this.data_update_every);
1266 // ----------------------------------------------------------------------------------------------------------------
1269 chartState.prototype.log = function(msg) {
1270 console.log(this.id + ' (' + this.library_name + ' ' + this.uuid + '): ' + msg);
1273 chartState.prototype.pauseChart = function() {
1274 if(this.paused === false) {
1275 if(this.debug === true)
1282 chartState.prototype.unpauseChart = function() {
1284 if(this.debug === true)
1285 this.log('unpaused');
1287 this.paused = false;
1291 chartState.prototype.resetChart = function() {
1292 if(NETDATA.globalPanAndZoom.isMaster(this) && this.isVisible())
1293 NETDATA.globalPanAndZoom.clearMaster();
1295 this.tm.pan_and_zoom_seq = 0;
1297 this.clearSelection();
1299 this.setMode('auto');
1300 this.current.force_update_at = 0;
1301 this.current.force_before_ms = null;
1302 this.current.force_after_ms = null;
1303 this.tm.last_autorefreshed = 0;
1304 this.paused = false;
1305 this.selected = false;
1306 this.enabled = true;
1309 // do not update the chart here
1310 // or the chart will flip-flop when it is the master
1311 // of a selection sync and another chart becomes
1313 if(NETDATA.options.current.sync_pan_and_zoom === false && this.isVisible() === true)
1317 chartState.prototype.setMode = function(m) {
1319 if(this.current.name === m) return;
1321 this[m].requested_before_ms = this.current.requested_before_ms;
1322 this[m].requested_after_ms = this.current.requested_after_ms;
1326 this.current = this.auto;
1327 else if(m === 'pan')
1328 this.current = this.pan;
1329 else if(m === 'zoom')
1330 this.current = this.zoom;
1332 this.current = this.auto;
1334 this.current.force_update_at = 0;
1335 this.current.force_before_ms = null;
1336 this.current.force_after_ms = null;
1338 if(this.debug === true)
1339 this.log('mode set to ' + this.current.name);
1342 chartState.prototype.updateChartPanOrZoom = function(after, before) {
1343 if(before < after) return false;
1345 var min_duration = Math.round((this.chartWidth() / 30 * this.chart.update_every * 1000));
1347 if(this.debug === true)
1348 this.log('requested duration of ' + ((before - after) / 1000).toString() + ' (' + after + ' - ' + before + '), minimum ' + min_duration / 1000);
1350 if((before - after) < min_duration) return false;
1352 var current_duration = this.data_before - this.data_after;
1353 var wanted_duration = before - after;
1354 var tolerance = this.data_update_every * 2;
1355 var movement = Math.abs(before - this.data_before);
1357 if(this.debug === true)
1358 this.log('current duration: ' + current_duration / 1000 + ', wanted duration: ' + wanted_duration / 1000 + ', movement: ' + movement / 1000 + ', tolerance: ' + tolerance / 1000);
1360 if(Math.abs(current_duration - wanted_duration) <= tolerance && movement <= tolerance) {
1361 if(this.debug === true)
1362 this.log('IGNORED');
1367 if(this.current.name === 'auto') {
1368 this.setMode('pan');
1370 if(this.debug === true)
1371 this.log('updateChartPanOrZoom(): caller did not set proper mode');
1374 this.current.force_update_at = new Date().getTime() + NETDATA.options.current.pan_and_zoom_delay;
1375 this.current.force_after_ms = after;
1376 this.current.force_before_ms = before;
1377 NETDATA.globalPanAndZoom.setMaster(this, after, before);
1381 chartState.prototype.legendFormatValue = function(value) {
1382 if(value === null || value === 'undefined') return '-';
1383 if(typeof value !== 'number') return value;
1385 var abs = Math.abs(value);
1386 if(abs >= 1) return (Math.round(value * 100) / 100).toLocaleString();
1387 if(abs >= 0.1) return (Math.round(value * 1000) / 1000).toLocaleString();
1388 return (Math.round(value * 10000) / 10000).toLocaleString();
1391 chartState.prototype.legendSetLabelValue = function(label, value) {
1392 var series = this.element_legend_childs.series[label];
1393 if(typeof series === 'undefined') return;
1394 if(series.value === null && series.user === null) return;
1396 // if the value has not changed, skip DOM update
1397 //if(series.last === value) return;
1400 if(typeof value === 'number') {
1401 var v = Math.abs(value);
1402 s = r = this.legendFormatValue(value);
1404 if(typeof series.last === 'number') {
1405 if(v > series.last) s += '<i class="fa fa-angle-up" style="width: 8px; text-align: center; overflow: hidden; vertical-align: middle;"></i>';
1406 else if(v < series.last) s += '<i class="fa fa-angle-down" style="width: 8px; text-align: center; overflow: hidden; vertical-align: middle;"></i>';
1407 else s += '<i class="fa fa-angle-left" style="width: 8px; text-align: center; overflow: hidden; vertical-align: middle;"></i>';
1409 else s += '<i class="fa fa-angle-right" style="width: 8px; text-align: center; overflow: hidden; vertical-align: middle;"></i>';
1414 series.last = value;
1417 if(series.value !== null) series.value.innerHTML = s;
1418 if(series.user !== null) series.user.innerHTML = r;
1421 chartState.prototype.legendSetDate = function(ms) {
1422 if(typeof ms !== 'number') {
1423 this.legendShowUndefined();
1427 var d = new Date(ms);
1429 if(this.element_legend_childs.title_date)
1430 this.element_legend_childs.title_date.innerHTML = d.toLocaleDateString();
1432 if(this.element_legend_childs.title_time)
1433 this.element_legend_childs.title_time.innerHTML = d.toLocaleTimeString();
1435 if(this.element_legend_childs.title_units)
1436 this.element_legend_childs.title_units.innerHTML = this.chart.units;
1439 chartState.prototype.legendShowUndefined = function() {
1440 if(this.element_legend_childs.title_date)
1441 this.element_legend_childs.title_date.innerHTML = ' ';
1443 if(this.element_legend_childs.title_time)
1444 this.element_legend_childs.title_time.innerHTML = this.chart.name;
1446 if(this.element_legend_childs.title_units)
1447 this.element_legend_childs.title_units.innerHTML = ' ';
1449 if(this.data && this.element_legend_childs.series !== null) {
1450 var labels = this.data.dimension_names;
1451 var i = labels.length;
1453 var label = labels[i];
1455 if(typeof label === 'undefined') continue;
1456 if(typeof this.element_legend_childs.series[label] === 'undefined') continue;
1457 this.legendSetLabelValue(label, null);
1462 chartState.prototype.legendShowLatestValues = function() {
1463 if(this.chart === null) return;
1464 if(this.selected) return;
1466 if(this.data === null || this.element_legend_childs.series === null) {
1467 this.legendShowUndefined();
1471 var show_undefined = true;
1472 if(Math.abs(this.data.last_entry - this.data.before) <= this.data.view_update_every)
1473 show_undefined = false;
1475 if(show_undefined) {
1476 this.legendShowUndefined();
1480 this.legendSetDate(this.data.before * 1000);
1482 var labels = this.data.dimension_names;
1483 var i = labels.length;
1485 var label = labels[i];
1487 if(typeof label === 'undefined') continue;
1488 if(typeof this.element_legend_childs.series[label] === 'undefined') continue;
1491 this.legendSetLabelValue(label, null);
1493 this.legendSetLabelValue(label, this.data.view_latest_values[i]);
1497 chartState.prototype.legendReset = function() {
1498 this.legendShowLatestValues();
1501 // this should be called just ONCE per dimension per chart
1502 chartState.prototype._chartDimensionColor = function(label) {
1503 if(this.colors === null) this.chartColors();
1505 if(typeof this.colors_assigned[label] === 'undefined') {
1506 if(this.colors_available.length === 0) {
1507 for(var i = 0, len = NETDATA.colors.length; i < len ; i++)
1508 this.colors_available.push(NETDATA.colors[i]);
1511 this.colors_assigned[label] = this.colors_available.shift();
1513 if(this.debug === true)
1514 this.log('label "' + label + '" got color "' + this.colors_assigned[label]);
1517 if(this.debug === true)
1518 this.log('label "' + label + '" already has color "' + this.colors_assigned[label] + '"');
1521 this.colors.push(this.colors_assigned[label]);
1522 return this.colors_assigned[label];
1525 chartState.prototype.chartColors = function() {
1526 if(this.colors !== null) return this.colors;
1528 this.colors = new Array();
1529 this.colors_available = new Array();
1530 // this.colors_assigned = {};
1532 var c = $(this.element).data('colors');
1533 if(typeof c !== 'undefined' && c !== null) {
1534 if(typeof c !== 'string') {
1535 this.log('invalid color given: ' + c + ' (give a space separated list of colors)');
1539 for(var i = 0, len = c.length; i < len ; i++)
1540 this.colors_available.push(c[i]);
1544 // push all the standard colors too
1545 for(var i = 0, len = NETDATA.colors.length; i < len ; i++)
1546 this.colors_available.push(NETDATA.colors[i]);
1551 chartState.prototype.legendUpdateDOM = function() {
1554 // check that the legend DOM is up to date for the downloaded dimensions
1555 if(typeof this.element_legend_childs.series !== 'object' || this.element_legend_childs.series === null) {
1556 // this.log('the legend does not have any series - requesting legend update');
1559 else if(this.data === null) {
1560 // this.log('the chart does not have any data - requesting legend update');
1563 else if(typeof this.element_legend_childs.series.labels_key === 'undefined') {
1567 var labels = this.data.dimension_names.toString();
1568 if(labels !== this.element_legend_childs.series.labels_key) {
1571 if(this.debug === true)
1572 this.log('NEW LABELS: "' + labels + '" NOT EQUAL OLD LABELS: "' + this.element_legend_childs.series.labels_key + '"');
1576 if(needed === false) {
1577 // make sure colors available
1580 // do we have to update the current values?
1581 // we do this, only when the visible chart is current
1582 if(Math.abs(this.data.last_entry - this.data.before) <= this.data.view_update_every) {
1583 if(this.debug === true)
1584 this.log('chart in running... updating values on legend...');
1586 //var labels = this.data.dimension_names;
1587 //var i = labels.length;
1589 // this.legendSetLabelValue(labels[i], this.data.latest_values[i]);
1593 if(this.colors === null) {
1594 // this is the first time we update the chart
1595 // let's assign colors to all dimensions
1596 if(this.library.track_colors() === true)
1597 for(var dim in this.chart.dimensions)
1598 this._chartDimensionColor(this.chart.dimensions[dim].name);
1600 // we will re-generate the colors for the chart
1603 if(this.debug === true)
1604 this.log('updating Legend DOM');
1606 // mark all dimensions as invalid
1607 this.dimensions_visibility.invalidateAll();
1609 var self = $(this.element);
1610 var genLabel = function(state, parent, name, count) {
1611 var color = state._chartDimensionColor(name);
1613 var user_element = null;
1614 var user_id = self.data('show-value-of-' + name + '-at') || null;
1615 if(user_id !== null) {
1616 user_element = document.getElementById(user_id) || null;
1617 if(user_element === null)
1618 me.log('Cannot find element with id: ' + user_id);
1621 state.element_legend_childs.series[name] = {
1622 name: document.createElement('span'),
1623 value: document.createElement('span'),
1628 var label = state.element_legend_childs.series[name];
1630 // create the dimension visibility tracking for this label
1631 var ds = state.dimensions_visibility.dimensionAdd(name, label.name, label.value, color);
1633 var rgb = NETDATA.colorHex2Rgb(color);
1634 label.name.innerHTML = '<table class="netdata-legend-name-table-'
1635 + state.chart.chart_type
1636 + '" style="background-color: '
1637 + 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + NETDATA.options.current['color_fill_opacity_' + state.chart.chart_type] + ')'
1638 + '"><tr class="netdata-legend-name-tr"><td class="netdata-legend-name-td"></td></tr></table>'
1640 var text = document.createTextNode(' ' + name);
1641 label.name.appendChild(text);
1644 parent.appendChild(document.createElement('br'));
1646 parent.appendChild(label.name);
1647 parent.appendChild(label.value);
1650 var content = document.createElement('div');
1652 if(this.hasLegend()) {
1653 this.element_legend_childs = {
1655 resize_handler: document.createElement('div'),
1656 title_date: document.createElement('span'),
1657 title_time: document.createElement('span'),
1658 title_units: document.createElement('span'),
1659 nano: document.createElement('div'),
1661 paneClass: 'netdata-legend-series-pane',
1662 sliderClass: 'netdata-legend-series-slider',
1663 contentClass: 'netdata-legend-series-content',
1664 enabledClass: '__enabled',
1665 flashedClass: '__flashed',
1666 activeClass: '__active',
1668 alwaysVisible: true,
1674 this.element_legend.innerHTML = '';
1676 this.element_legend_childs.resize_handler.className += " netdata-legend-resize-handler";
1677 this.element_legend_childs.resize_handler.innerHTML = '<i class="fa fa-chevron-up"></i><i class="fa fa-chevron-down"></i>';
1678 this.element.appendChild(this.element_legend_childs.resize_handler);
1682 this.element_legend_childs.resize_handler.onmousedown =
1684 self2.resizeHandler(e);
1688 this.element_legend_childs.resize_handler.addEventListener('touchstart', function(e) {
1689 self2.resizeHandler(e);
1692 this.element_legend_childs.title_date.className += " netdata-legend-title-date";
1693 this.element_legend.appendChild(this.element_legend_childs.title_date);
1695 this.element_legend.appendChild(document.createElement('br'));
1697 this.element_legend_childs.title_time.className += " netdata-legend-title-time";
1698 this.element_legend.appendChild(this.element_legend_childs.title_time);
1700 this.element_legend.appendChild(document.createElement('br'));
1702 this.element_legend_childs.title_units.className += " netdata-legend-title-units";
1703 this.element_legend.appendChild(this.element_legend_childs.title_units);
1705 this.element_legend.appendChild(document.createElement('br'));
1707 this.element_legend_childs.nano.className = 'netdata-legend-series';
1708 this.element_legend.appendChild(this.element_legend_childs.nano);
1710 content.className = 'netdata-legend-series-content';
1711 this.element_legend_childs.nano.appendChild(content);
1714 this.element_legend_childs = {
1716 resize_handler: null,
1727 this.element_legend_childs.series.labels_key = this.data.dimension_names.toString();
1728 if(this.debug === true)
1729 this.log('labels from data: "' + this.element_legend_childs.series.labels_key + '"');
1731 for(var i = 0, len = this.data.dimension_names.length; i < len ;i++) {
1732 genLabel(this, content, this.data.dimension_names[i], i);
1736 var tmp = new Array();
1737 for(var dim in this.chart.dimensions) {
1738 tmp.push(this.chart.dimensions[dim].name);
1739 genLabel(this, content, this.chart.dimensions[dim].name, i);
1741 this.element_legend_childs.series.labels_key = tmp.toString();
1742 if(this.debug === true)
1743 this.log('labels from chart: "' + this.element_legend_childs.series.labels_key + '"');
1746 // create a hidden div to be used for hidding
1747 // the original legend of the chart library
1748 var el = document.createElement('div');
1749 this.element_legend.appendChild(el);
1750 el.style.display = 'none';
1752 this.element_legend_childs.hidden = document.createElement('div');
1753 el.appendChild(this.element_legend_childs.hidden);
1755 if(this.element_legend_childs.nano !== null && this.element_legend_childs.nano_options !== null)
1756 $(this.element_legend_childs.nano).nanoScroller(this.element_legend_childs.nano_options);
1758 this.legendShowLatestValues();
1761 chartState.prototype.createChartDOM = function() {
1762 if(this.debug === true)
1763 this.log('creating DOM');
1765 this.element_chart_id = this.library_name + '-' + this.uuid + '-chart';
1766 this.element_chart = document.createElement('div');
1767 this.element_chart.className += ' netdata-chart' + (this.hasLegend()?'-with-legend-right':'').toString();
1768 this.element_chart.className += ' netdata-' + this.library_name + '-chart' + (this.hasLegend()?'-with-legend-right':'').toString();
1769 this.element_chart.id = this.element_chart_id;
1770 $(this.element_chart).data('netdata-state-object', this);
1771 this.element.appendChild(this.element_chart);
1773 this.element_legend_id = this.library_name + '-' + this.uuid + '-legend';
1774 this.element_legend = document.createElement('div');
1775 this.element_legend.className += ' netdata-chart-legend';
1776 this.element_legend.className += ' netdata-' + this.library_name + '-legend';
1777 this.element_legend.id = this.element_legend_id;
1778 $(this.element_legend).data('netdata-state-object', this);
1780 if(this.hasLegend() === false)
1781 this.element_legend.style.display = 'none';
1783 this.element.appendChild(this.element_legend);
1785 this.element_legend_childs.series = null;
1786 this.legendUpdateDOM();
1788 // in case the user has an active global selection sync in place
1790 this.globalSelectionSyncStop();
1791 this.dom_created = true;
1794 chartState.prototype.hasLegend = function() {
1795 if(typeof this.___hasLegendCache___ !== 'undefined')
1796 return this.___hasLegendCache___;
1799 if(this.library && this.library.legend(this) === 'right-side') {
1800 var legend = $(this.element).data('legend') || 'yes';
1801 if(legend === 'yes') leg = true;
1804 this.___hasLegendCache___ = leg;
1808 chartState.prototype.legendWidth = function() {
1809 return (this.hasLegend())?140:0;
1812 chartState.prototype.legendHeight = function() {
1813 return $(this.element).height();
1816 chartState.prototype.chartWidth = function() {
1817 return $(this.element).width() - this.legendWidth();
1820 chartState.prototype.chartHeight = function() {
1821 return $(this.element).height();
1824 chartState.prototype.chartPixelsPerPoint = function() {
1825 // force an options provided detail
1826 var px = this.pixels_per_point;
1828 if(this.library && px < this.library.pixels_per_point(this))
1829 px = this.library.pixels_per_point(this);
1831 if(px < NETDATA.options.current.pixels_per_point)
1832 px = NETDATA.options.current.pixels_per_point;
1837 chartState.prototype.needsRecreation = function() {
1839 this.dom_created === true
1840 && this.chart_created === true
1842 && this.library.autoresize() === false
1843 && this.tm.last_resized < NETDATA.options.last_resized
1847 chartState.prototype.resizeChart = function() {
1848 if(this.needsRecreation()) {
1849 if(this.debug === true)
1850 this.log('forcing re-generation due to window resize.');
1852 this.destroyChart();
1855 this.tm.last_resized = new Date().getTime();
1858 chartState.prototype.chartURL = function() {
1861 if(NETDATA.globalPanAndZoom.isActive()) {
1862 after = Math.round(NETDATA.globalPanAndZoom.force_after_ms / 1000);
1863 before = Math.round(NETDATA.globalPanAndZoom.force_before_ms / 1000);
1864 this.tm.pan_and_zoom_seq = NETDATA.globalPanAndZoom.seq;
1867 before = this.current.force_before_ms !== null ? Math.round(this.current.force_before_ms / 1000) : this.before;
1868 after = this.current.force_after_ms !== null ? Math.round(this.current.force_after_ms / 1000) : this.after;
1869 this.tm.pan_and_zoom_seq = 0;
1872 this.current.requested_after_ms = after * 1000;
1873 this.current.requested_before_ms = before * 1000;
1875 this.data_points = this.points || Math.round(this.chartWidth() / this.chartPixelsPerPoint());
1877 // build the data URL
1878 this.data_url = this.chart.data_url;
1879 this.data_url += "&format=" + this.library.format();
1880 this.data_url += "&points=" + this.data_points.toString();
1881 this.data_url += "&group=" + this.method;
1882 this.data_url += "&options=" + this.library.options();
1883 this.data_url += '|jsonwrap';
1885 if(NETDATA.options.current.eliminate_zero_dimensions === true)
1886 this.data_url += '|nonzero';
1889 this.data_url += "&after=" + after.toString();
1892 this.data_url += "&before=" + before.toString();
1895 this.data_url += "&dimensions=" + this.dimensions;
1897 if(NETDATA.options.debug.chart_data_url === true || this.debug === true)
1898 this.log('chartURL(): ' + this.data_url + ' WxH:' + this.chartWidth() + 'x' + this.chartHeight() + ' points: ' + this.data_points + ' library: ' + this.library_name);
1901 chartState.prototype.redrawChart = function() {
1902 if(this.data !== null)
1903 this.updateChartWithData(this.data);
1906 chartState.prototype.updateChartWithData = function(data) {
1907 if(this.debug === true)
1908 this.log('got data from netdata server');
1911 this.updates_counter++;
1913 var started = new Date().getTime();
1914 this.tm.last_updated = started;
1916 // if the result is JSON, find the latest update-every
1917 if(typeof data === 'object') {
1918 if(typeof data.view_update_every !== 'undefined')
1919 this.data_update_every = data.view_update_every * 1000;
1921 if(typeof data.after !== 'undefined')
1922 this.data_after = data.after * 1000;
1924 if(typeof data.before !== 'undefined')
1925 this.data_before = data.before * 1000;
1927 if(typeof data.first_entry !== 'undefined')
1928 this.netdata_first = data.first_entry * 1000;
1930 if(typeof data.last_entry !== 'undefined')
1931 this.netdata_last = data.last_entry * 1000;
1933 if(typeof data.points !== 'undefined')
1934 this.data_points = data.points;
1939 if(this.debug === true) {
1940 this.log('UPDATE No ' + this.updates_counter + ' COMPLETED');
1942 if(this.current.force_after_ms)
1943 this.log('STATUS: forced : ' + (this.current.force_after_ms / 1000).toString() + ' - ' + (this.current.force_before_ms / 1000).toString());
1945 this.log('STATUS: forced: unset');
1947 this.log('STATUS: requested: ' + (this.current.requested_after_ms / 1000).toString() + ' - ' + (this.current.requested_before_ms / 1000).toString());
1948 this.log('STATUS: rendered : ' + (this.data_after / 1000).toString() + ' - ' + (this.data_before / 1000).toString());
1949 this.log('STATUS: points : ' + (this.data_points).toString());
1952 if(this.data_points === 0) {
1957 // this may force the chart to be re-created
1960 if(this.updates_since_last_creation >= this.library.max_updates_to_recreate()) {
1961 if(this.debug === true)
1962 this.log('max updates of ' + this.updates_since_last_creation.toString() + ' reached. Forcing re-generation.');
1964 this.chart_created = false;
1967 if(this.chart_created === true
1968 && this.dom_created === true
1969 && typeof this.library.update === 'function') {
1971 if(this.debug === true)
1972 this.log('updating chart...');
1974 // check and update the legend
1975 this.legendUpdateDOM();
1977 this.updates_since_last_creation++;
1978 if(NETDATA.options.debug.chart_errors === true) {
1979 this.library.update(this, data);
1983 this.library.update(this, data);
1986 this.error('chart failed to be updated as ' + this.library_name);
1991 if(this.debug === true)
1992 this.log('creating chart...');
1994 this.createChartDOM();
1995 this.updates_since_last_creation = 0;
1997 if(NETDATA.options.debug.chart_errors === true) {
1998 this.library.create(this, data);
1999 this.chart_created = true;
2003 this.library.create(this, data);
2004 this.chart_created = true;
2007 this.error('chart failed to be created as ' + this.library_name);
2011 // this.legendShowLatestValues();
2013 // update the performance counters
2014 var now = new Date().getTime();
2016 // don't update last_autorefreshed if this chart is
2017 // forced to be updated with global PanAndZoom
2018 if(NETDATA.globalPanAndZoom.isActive())
2019 this.tm.last_autorefreshed = 0;
2021 if(NETDATA.options.current.parallel_refresher === true && NETDATA.options.current.concurrent_refreshes)
2022 this.tm.last_autorefreshed = Math.round(now / this.data_update_every) * this.data_update_every;
2024 this.tm.last_autorefreshed = now;
2027 this.refresh_dt_ms = now - started;
2028 NETDATA.options.auto_refresher_fast_weight += this.refresh_dt_ms;
2030 if(this.refresh_dt_element)
2031 this.refresh_dt_element.innerHTML = this.refresh_dt_ms.toString();
2034 chartState.prototype.updateChart = function(callback) {
2035 // due to late initialization of charts and libraries
2036 // we need to check this too
2037 if(this.enabled === false) {
2038 if(this.debug === true)
2039 this.log('I am not enabled');
2041 if(typeof callback === 'function') callback();
2045 if(this.chart === null) {
2047 this.getChart(function() { self.updateChart(callback); });
2051 if(this.library.initialized === false) {
2052 if(this.library.enabled === true) {
2054 this.library.initialize(function() { self.updateChart(callback); });
2058 this.error('chart library "' + this.library_name + '" is not available.');
2059 if(typeof callback === 'function') callback();
2064 this.clearSelection();
2068 if(this.debug === true)
2069 this.log('updating from ' + this.data_url);
2072 this.xhr = $.ajax( {
2074 crossDomain: NETDATA.options.crossDomainAjax,
2078 .success(function(data) {
2081 if(self.debug === true)
2082 self.log('data received. updating chart.');
2084 self.updateChartWithData(data);
2088 self.error('data download failed for url: ' + self.data_url);
2090 .always(function() {
2092 if(typeof callback === 'function') callback();
2096 chartState.prototype.destroyChart = function() {
2097 if(this.debug === true)
2098 this.log('destroying chart');
2100 if(this.element_message !== null) {
2101 this.element_message.innerHTML = '';
2102 this.element_message = null;
2105 if(this.element_loading !== null) {
2106 this.element_loading.innerHTML = '';
2107 this.element_loading = null;
2110 if(this.element_legend !== null) {
2111 this.element_legend.innerHTML = '';
2112 this.element_legend = null;
2115 if(this.element_chart !== null) {
2116 this.element_chart.innerHTML = '';
2117 this.element_chart = null;
2120 this.element_legend_childs = {
2130 this.element.innerHTML = '';
2131 this.refresh_dt_element = null;
2133 this.dom_created = false;
2134 this.chart_created = false;
2135 this.paused = false;
2136 this.selected = false;
2137 this.updates_counter = 0;
2138 this.updates_since_last_creation = 0;
2139 this.tm.pan_and_zoom_seq = 0;
2140 this.tm.last_resized = 0;
2141 this.tm.last_visible_check = 0;
2142 this.tm.last_hidden = 0;
2143 this.tm.last_unhidden = 0;
2144 this.tm.last_autorefreshed = 0;
2147 this.data_points = 0;
2148 this.data_after = 0;
2149 this.data_before = 0;
2150 this.data_update_every = 0;
2151 this.netdata_first = 0;
2152 this.netdata_last = 0;
2153 if(this.current !== null) {
2154 this.current.force_update_at = 0;
2155 this.current.force_after_ms = null;
2156 this.current.force_before_ms = null;
2157 this.current.requested_after_ms = null;
2158 this.current.requested_before_ms = null;
2163 chartState.prototype.unhideChart = function() {
2164 if(typeof this.___isHidden___ !== 'undefined' && this.enabled === true) {
2165 if(this.debug === true)
2166 this.log('unhiding chart');
2168 this.element_message.style.display = 'none';
2169 if(this.element_chart !== null) this.element_chart.style.display = 'inline-block';
2170 if(this.element_legend !== null) this.element_legend.style.display = 'inline-block';
2171 if(this.element_loading !== null) this.element_loading.style.display = 'none';
2172 this.___isHidden___ = undefined;
2173 this.element_message.innerHTML = 'chart ' + this.id + ' is visible now';
2175 // refresh the scrolbar
2176 if(this.element_legend_childs.nano !== null && this.element_legend_childs.nano_options !== null)
2177 $(this.element_legend_childs.nano).nanoScroller(this.element_legend_childs.nano_options);
2179 this.tm.last_unhidden = new Date().getTime();
2183 chartState.prototype.hideChart = function() {
2184 if(typeof this.___isHidden___ === 'undefined' && this.enabled === true) {
2185 if(NETDATA.options.current.destroy_on_hide === true)
2186 this.destroyChart();
2188 if(this.debug === true)
2189 this.log('hiding chart');
2191 this.element_message.style.display = 'inline-block';
2192 if(this.element_chart !== null) this.element_chart.style.display = 'none';
2193 if(this.element_legend !== null) this.element_legend.style.display = 'none';
2194 if(this.element_loading !== null) this.element_loading.style.display = 'none';
2195 this.___isHidden___ = true;
2196 this.___showsLoading___ = undefined;
2197 this.element_message.innerHTML = 'chart ' + this.id + ' is hidden to speed up the browser';
2198 this.tm.last_hidden = new Date().getTime();
2202 chartState.prototype.hideLoading = function() {
2203 if(typeof this.___showsLoading___ !== 'undefined' && this.enabled === true) {
2204 if(this.debug === true)
2205 this.log('hide loading...');
2207 this.element_message.style.display = 'none';
2208 if(this.element_chart !== null) this.element_chart.style.display = 'inline-block';
2209 if(this.element_legend !== null) this.element_legend.style.display = 'inline-block';
2210 if(this.element_loading !== null) this.element_loading.style.display = 'none';
2211 this.___showsLoading___ = undefined;
2212 this.element_loading.innerHTML = 'chart ' + this.id + ' finished loading!';
2213 this.tm.last_unhidden = new Date().getTime();
2217 chartState.prototype.showLoading = function() {
2218 if(typeof this.___showsLoading___ === 'undefined' && this.chart_created === false && this.enabled === true) {
2219 if(this.debug === true)
2220 this.log('show loading...');
2222 this.element_message.style.display = 'none';
2223 if(this.element_chart !== null) this.element_chart.style.display = 'none';
2224 if(this.element_legend !== null) this.element_legend.style.display = 'none';
2225 if(this.element_loading !== null) this.element_loading.style.display = 'inline-block';
2226 this.___showsLoading___ = true;
2227 this.___isHidden___ = undefined;
2228 this.element_loading.innerHTML = 'chart ' + this.id + ' is loading...';
2229 this.tm.last_hidden = new Date().getTime();
2233 chartState.prototype.isVisible = function() {
2234 // this.log('last_visible_check: ' + this.tm.last_visible_check + ', last_page_scroll: ' + NETDATA.options.last_page_scroll);
2236 // caching - we do not evaluate the charts visibility
2237 // if the page has not been scrolled since the last check
2238 if(this.tm.last_visible_check > NETDATA.options.last_page_scroll) {
2239 if(this.debug === true)
2240 this.log('isVisible: ' + this.___isVisible___);
2242 return this.___isVisible___;
2245 this.tm.last_visible_check = new Date().getTime();
2247 var wh = window.innerHeight;
2248 var x = this.element.getBoundingClientRect();
2252 if(x.top < 0 && -x.top > x.height) {
2253 // the chart is entirely above
2254 ret = -x.top - x.height;
2256 else if(x.top > wh) {
2257 // the chart is entirely below
2261 if(ret > tolerance) {
2262 // the chart is too far
2263 this.___isVisible___ = false;
2264 if(this.chart_created === true) this.hideChart();
2266 if(this.debug === true)
2267 this.log('isVisible: ' + this.___isVisible___);
2269 return this.___isVisible___;
2272 // the chart is inside or very close
2273 this.___isVisible___ = true;
2276 if(this.debug === true)
2277 this.log('isVisible: ' + this.___isVisible___);
2279 return this.___isVisible___;
2283 chartState.prototype.isAutoRefreshed = function() {
2284 return (this.current.autorefresh);
2287 chartState.prototype.canBeAutoRefreshed = function() {
2288 now = new Date().getTime();
2290 if(this.enabled === false) {
2291 if(this.debug === true)
2292 this.log('I am not enabled');
2297 if(this.library === null || this.library.enabled === false) {
2298 this.error('charting library "' + this.library_name + '" is not available');
2299 if(this.debug === true)
2300 this.log('My chart library ' + this.library_name + ' is not available');
2305 if(this.isVisible() === false) {
2306 if(NETDATA.options.debug.visibility === true || this.debug === true)
2307 this.log('I am not visible');
2312 if(this.current.force_update_at !== 0 && this.current.force_update_at < now) {
2313 if(this.debug === true)
2314 this.log('timed force update detected - allowing this update');
2316 this.current.force_update_at = 0;
2320 if(this.isAutoRefreshed() === true) {
2321 // allow the first update, even if the page is not visible
2322 if(this.updates_counter && NETDATA.options.page_is_visible === false) {
2323 if(NETDATA.options.debug.focus === true || this.debug === true)
2324 this.log('canBeAutoRefreshed(): page does not have focus');
2329 if(this.needsRecreation() === true) {
2330 if(this.debug === true)
2331 this.log('canBeAutoRefreshed(): needs re-creation.');
2336 // options valid only for autoRefresh()
2337 if(NETDATA.options.auto_refresher_stop_until === 0 || NETDATA.options.auto_refresher_stop_until < now) {
2338 if(NETDATA.globalPanAndZoom.isActive()) {
2339 if(NETDATA.globalPanAndZoom.shouldBeAutoRefreshed(this)) {
2340 if(this.debug === true)
2341 this.log('canBeAutoRefreshed(): global panning: I need an update.');
2346 if(this.debug === true)
2347 this.log('canBeAutoRefreshed(): global panning: I am already up to date.');
2353 if(this.selected === true) {
2354 if(this.debug === true)
2355 this.log('canBeAutoRefreshed(): I have a selection in place.');
2360 if(this.paused === true) {
2361 if(this.debug === true)
2362 this.log('canBeAutoRefreshed(): I am paused.');
2367 if(now - this.tm.last_autorefreshed >= this.data_update_every) {
2368 if(this.debug === true)
2369 this.log('canBeAutoRefreshed(): It is time to update me.');
2379 chartState.prototype.autoRefresh = function(callback) {
2380 if(this.canBeAutoRefreshed() === true) {
2381 this.updateChart(callback);
2384 if(typeof callback !== 'undefined')
2389 chartState.prototype._defaultsFromDownloadedChart = function(chart) {
2391 this.chart_url = chart.url;
2392 this.data_update_every = chart.update_every * 1000;
2393 this.data_points = Math.round(this.chartWidth() / this.chartPixelsPerPoint());
2394 this.tm.last_info_downloaded = new Date().getTime();
2397 // fetch the chart description from the netdata server
2398 chartState.prototype.getChart = function(callback) {
2399 this.chart = NETDATA.chartRegistry.get(this.host, this.id);
2401 this._defaultsFromDownloadedChart(this.chart);
2402 if(typeof callback === 'function') callback();
2405 this.chart_url = this.host + "/api/v1/chart?chart=" + this.id;
2407 if(this.debug === true)
2408 this.log('downloading ' + this.chart_url);
2413 url: this.chart_url,
2414 crossDomain: NETDATA.options.crossDomainAjax,
2418 .done(function(chart) {
2419 chart.url = self.chart_url;
2420 chart.data_url = (self.host + chart.data_url);
2421 self._defaultsFromDownloadedChart(chart);
2422 NETDATA.chartRegistry.add(self.host, self.id, chart);
2425 NETDATA.error(404, self.chart_url);
2426 self.error('chart not found on url "' + self.chart_url + '"');
2428 .always(function() {
2429 if(typeof callback === 'function') callback();
2434 // resize the chart to its real dimensions
2435 // as given by the caller
2436 chartState.prototype.sizeChart = function() {
2437 if(this.hasLegend() === true)
2438 this.element.className += " netdata-container-with-legend";
2440 this.element.className += " netdata-container";
2442 if(this.debug === true)
2443 this.log('sizing element');
2445 if(this.width !== 0)
2446 $(this.element).css('width', this.width);
2448 if(this.height !== 0)
2449 $(this.element).css('height', this.height);
2451 if(NETDATA.chartDefaults.min_width !== null)
2452 $(this.element).css('min-width', NETDATA.chartDefaults.min_width);
2455 chartState.prototype.noData = function() {
2456 if(this.dom_created === false)
2457 this.createChartDOM();
2459 this.tm.last_autorefreshed = new Date().getTime();
2460 this.data_update_every = 30 * 1000;
2463 // show a message in the chart
2464 chartState.prototype.message = function(type, msg) {
2466 this.element_message.innerHTML = msg;
2468 if(this.debug === null)
2472 // show an error on the chart and stop it forever
2473 chartState.prototype.error = function(msg) {
2474 this.message('error', this.id + ': ' + msg);
2475 this.enabled = false;
2478 // show a message indicating the chart is loading
2479 chartState.prototype.info = function(msg) {
2480 this.message('info', this.id + ': ' + msg);
2483 chartState.prototype.init = function() {
2484 this.element.innerHTML = '';
2486 this.element_message = document.createElement('div');
2487 this.element_message.className += ' netdata-message';
2488 this.element.appendChild(this.element_message);
2490 this.element_loading = document.createElement('div');
2491 this.element_loading.className += ' netdata-chart-is-loading';
2492 this.element.appendChild(this.element_loading);
2494 if(this.debug === null)
2495 this.log('created');
2497 // make sure the host does not end with /
2498 // all netdata API requests use absolute paths
2499 while(this.host.slice(-1) === '/')
2500 this.host = this.host.substring(0, this.host.length - 1);
2502 // check the requested library is available
2503 // we don't initialize it here - it will be initialized when
2504 // this chart will be first used
2505 if(typeof NETDATA.chartLibraries[this.library_name] === 'undefined') {
2506 NETDATA.error(402, this.library_name);
2507 this.error('chart library "' + this.library_name + '" is not found');
2509 else if(NETDATA.chartLibraries[this.library_name].enabled === false) {
2510 NETDATA.error(403, this.library_name);
2511 this.error('chart library "' + this.library_name + '" is not enabled');
2514 this.library = NETDATA.chartLibraries[this.library_name];
2518 // if we need to report the rendering speed
2519 // find the element that needs to be updated
2520 if(this.refresh_dt_element_name)
2521 this.refresh_dt_element = document.getElementById(this.refresh_dt_element_name) || null;
2523 // the default mode for all charts
2524 this.setMode('auto');
2527 // get or create a chart state, given a DOM element
2528 NETDATA.chartState = function(element) {
2529 var state = $(element).data('netdata-state-object') || null;
2530 if(state === null) {
2531 state = new chartState(element);
2532 $(element).data('netdata-state-object', state);
2537 // ----------------------------------------------------------------------------------------------------------------
2538 // Library functions
2540 // Load a script without jquery
2541 // This is used to load jquery - after it is loaded, we use jquery
2542 NETDATA._loadjQuery = function(callback) {
2543 if(typeof jQuery === 'undefined') {
2544 if(NETDATA.options.debug.main_loop === true)
2545 console.log('loading ' + NETDATA.jQuery);
2547 var script = document.createElement('script');
2548 script.type = 'text/javascript';
2549 script.async = true;
2550 script.src = NETDATA.jQuery;
2552 // script.onabort = onError;
2553 script.onerror = function(err, t) { NETDATA.error(101, NETDATA.jQuery); };
2554 if(typeof callback === "function")
2555 script.onload = callback;
2557 var s = document.getElementsByTagName('script')[0];
2558 s.parentNode.insertBefore(script, s);
2560 else if(typeof callback === "function")
2564 NETDATA._loadCSS = function(filename) {
2565 // don't use jQuery here
2566 // styles are loaded before jQuery
2567 // to eliminate showing an unstyled page to the user
2569 var fileref = document.createElement("link");
2570 fileref.setAttribute("rel", "stylesheet");
2571 fileref.setAttribute("type", "text/css");
2572 fileref.setAttribute("href", filename);
2574 if (typeof fileref !== 'undefined')
2575 document.getElementsByTagName("head")[0].appendChild(fileref);
2578 NETDATA.colorHex2Rgb = function(hex) {
2579 // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
2580 var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
2581 hex = hex.replace(shorthandRegex, function(m, r, g, b) {
2582 return r + r + g + g + b + b;
2585 var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
2587 r: parseInt(result[1], 16),
2588 g: parseInt(result[2], 16),
2589 b: parseInt(result[3], 16)
2593 NETDATA.colorLuminance = function(hex, lum) {
2594 // validate hex string
2595 hex = String(hex).replace(/[^0-9a-f]/gi, '');
2597 hex = hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2];
2601 // convert to decimal and change luminosity
2602 var rgb = "#", c, i;
2603 for (i = 0; i < 3; i++) {
2604 c = parseInt(hex.substr(i*2,2), 16);
2605 c = Math.round(Math.min(Math.max(0, c + (c * lum)), 255)).toString(16);
2606 rgb += ("00"+c).substr(c.length);
2612 NETDATA.guid = function() {
2614 return Math.floor((1 + Math.random()) * 0x10000)
2619 return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
2622 NETDATA.zeropad = function(x) {
2623 if(x > -10 && x < 10) return '0' + x.toString();
2624 else return x.toString();
2627 // user function to signal us the DOM has been
2629 NETDATA.updatedDom = function() {
2630 NETDATA.options.updated_dom = true;
2633 NETDATA.ready = function(callback) {
2634 NETDATA.options.readyCallback = callback;
2637 NETDATA.pause = function(callback) {
2638 NETDATA.options.pauseCallback = callback;
2641 NETDATA.unpause = function() {
2642 NETDATA.options.pauseCallback = null;
2643 NETDATA.options.updated_dom = true;
2644 NETDATA.options.pause = false;
2647 // ----------------------------------------------------------------------------------------------------------------
2649 // this is purely sequencial charts refresher
2650 // it is meant to be autonomous
2651 NETDATA.chartRefresherNoParallel = function(index) {
2652 if(NETDATA.options.debug.mail_loop === true)
2653 console.log('NETDATA.chartRefresherNoParallel(' + index + ')');
2655 if(NETDATA.options.updated_dom === true) {
2656 // the dom has been updated
2657 // get the dom parts again
2658 NETDATA.parseDom(NETDATA.chartRefresher);
2661 if(index >= NETDATA.options.targets.length) {
2662 if(NETDATA.options.debug.main_loop === true)
2663 console.log('waiting to restart main loop...');
2665 NETDATA.options.auto_refresher_fast_weight = 0;
2667 setTimeout(function() {
2668 NETDATA.chartRefresher();
2669 }, NETDATA.options.current.idle_between_loops);
2672 var state = NETDATA.options.targets[index];
2674 if(NETDATA.options.auto_refresher_fast_weight < NETDATA.options.current.fast_render_timeframe) {
2675 if(NETDATA.options.debug.main_loop === true)
2676 console.log('fast rendering...');
2678 state.autoRefresh(function() {
2679 NETDATA.chartRefresherNoParallel(++index);
2683 if(NETDATA.options.debug.main_loop === true) console.log('waiting for next refresh...');
2684 NETDATA.options.auto_refresher_fast_weight = 0;
2686 setTimeout(function() {
2687 state.autoRefresh(function() {
2688 NETDATA.chartRefresherNoParallel(++index);
2690 }, NETDATA.options.current.idle_between_charts);
2695 // this is part of the parallel refresher
2696 // its cause is to refresh sequencially all the charts
2697 // that depend on chart library initialization
2698 // it will call the parallel refresher back
2699 // as soon as it sees a chart that its chart library
2701 NETDATA.chartRefresher_unitialized = function() {
2702 if(NETDATA.options.updated_dom === true) {
2703 // the dom has been updated
2704 // get the dom parts again
2705 NETDATA.parseDom(NETDATA.chartRefresher);
2709 if(NETDATA.options.sequencial.length === 0)
2710 NETDATA.chartRefresher();
2712 var state = NETDATA.options.sequencial.pop();
2713 if(state.library.initialized === true)
2714 NETDATA.chartRefresher();
2716 state.autoRefresh(NETDATA.chartRefresher_unitialized);
2720 NETDATA.chartRefresherWaitTime = function() {
2721 return NETDATA.options.current.idle_parallel_loops;
2724 // the default refresher
2725 // it will create 2 sets of charts:
2726 // - the ones that can be refreshed in parallel
2727 // - the ones that depend on something else
2728 // the first set will be executed in parallel
2729 // the second will be given to NETDATA.chartRefresher_unitialized()
2730 NETDATA.chartRefresher = function() {
2731 if(NETDATA.options.pause === true) {
2732 // console.log('auto-refresher is paused');
2733 setTimeout(NETDATA.chartRefresher,
2734 NETDATA.chartRefresherWaitTime());
2738 if(typeof NETDATA.options.pauseCallback === 'function') {
2739 // console.log('auto-refresher is calling pauseCallback');
2740 NETDATA.options.pause = true;
2741 NETDATA.options.pauseCallback();
2742 NETDATA.chartRefresher();
2746 if(NETDATA.options.current.parallel_refresher === false) {
2747 NETDATA.chartRefresherNoParallel(0);
2751 if(NETDATA.options.updated_dom === true) {
2752 // the dom has been updated
2753 // get the dom parts again
2754 NETDATA.parseDom(NETDATA.chartRefresher);
2758 var parallel = new Array();
2759 var targets = NETDATA.options.targets;
2760 var len = targets.length;
2762 if(targets[len].isVisible() === false)
2765 var state = targets[len];
2766 if(state.library.initialized === false) {
2767 if(state.library.enabled === true) {
2768 state.library.initialize(NETDATA.chartRefresher);
2772 state.error('chart library "' + state.library_name + '" is not enabled.');
2773 state.enabled = false;
2777 parallel.unshift(state);
2780 if(parallel.length > 0) {
2781 var parallel_jobs = parallel.length;
2783 // this will execute the jobs in parallel
2784 $(parallel).each(function() {
2785 this.autoRefresh(function() {
2788 if(parallel_jobs === 0) {
2789 setTimeout(NETDATA.chartRefresher,
2790 NETDATA.chartRefresherWaitTime());
2796 setTimeout(NETDATA.chartRefresher,
2797 NETDATA.chartRefresherWaitTime());
2801 NETDATA.parseDom = function(callback) {
2802 NETDATA.options.last_page_scroll = new Date().getTime();
2803 NETDATA.options.updated_dom = false;
2805 var targets = $('div[data-netdata]').filter(':visible');
2807 if(NETDATA.options.debug.main_loop === true)
2808 console.log('DOM updated - there are ' + targets.length + ' charts on page.');
2810 NETDATA.options.targets = new Array();
2811 var len = targets.length;
2813 // the initialization will take care of sizing
2814 // and the "loading..." message
2815 NETDATA.options.targets.push(NETDATA.chartState(targets[len]));
2818 if(typeof callback === 'function') callback();
2821 // this is the main function - where everything starts
2822 NETDATA.start = function() {
2823 // this should be called only once
2825 NETDATA.options.page_is_visible = true;
2827 $(window).blur(function() {
2828 if(NETDATA.options.current.stop_updates_when_focus_is_lost === true) {
2829 NETDATA.options.page_is_visible = false;
2830 if(NETDATA.options.debug.focus === true)
2831 console.log('Lost Focus!');
2835 $(window).focus(function() {
2836 if(NETDATA.options.current.stop_updates_when_focus_is_lost === true) {
2837 NETDATA.options.page_is_visible = true;
2838 if(NETDATA.options.debug.focus === true)
2839 console.log('Focus restored!');
2843 if(typeof document.hasFocus === 'function' && !document.hasFocus()) {
2844 if(NETDATA.options.current.stop_updates_when_focus_is_lost === true) {
2845 NETDATA.options.page_is_visible = false;
2846 if(NETDATA.options.debug.focus === true)
2847 console.log('Document has no focus!');
2851 NETDATA.parseDom(NETDATA.chartRefresher);
2854 // ----------------------------------------------------------------------------------------------------------------
2857 NETDATA.peityInitialize = function(callback) {
2858 if(typeof netdataNoPeitys === 'undefined' || !netdataNoPeitys) {
2860 url: NETDATA.peity_js,
2865 NETDATA.registerChartLibrary('peity', NETDATA.peity_js);
2868 NETDATA.chartLibraries.peity.enabled = false;
2869 NETDATA.error(100, NETDATA.peity_js);
2871 .always(function() {
2872 if(typeof callback === "function")
2877 NETDATA.chartLibraries.peity.enabled = false;
2878 if(typeof callback === "function")
2883 NETDATA.peityChartUpdate = function(state, data) {
2884 state.peity_instance.innerHTML = data.result;
2886 if(state.peity_options.stroke !== state.chartColors()[0]) {
2887 state.peity_options.stroke = state.chartColors()[0];
2888 if(state.chart.chart_type === 'line')
2889 state.peity_options.fill = '#FFF';
2891 state.peity_options.fill = NETDATA.colorLuminance(state.chartColors()[0], NETDATA.chartDefaults.fill_luminance);
2894 $(state.peity_instance).peity('line', state.peity_options);
2897 NETDATA.peityChartCreate = function(state, data) {
2898 state.peity_instance = document.createElement('div');
2899 state.element_chart.appendChild(state.peity_instance);
2901 var self = $(state.element);
2902 state.peity_options = {
2904 strokeWidth: self.data('peity-strokewidth') || 1,
2905 width: state.chartWidth(),
2906 height: state.chartHeight(),
2910 NETDATA.peityChartUpdate(state, data);
2913 // ----------------------------------------------------------------------------------------------------------------
2916 NETDATA.sparklineInitialize = function(callback) {
2917 if(typeof netdataNoSparklines === 'undefined' || !netdataNoSparklines) {
2919 url: NETDATA.sparkline_js,
2924 NETDATA.registerChartLibrary('sparkline', NETDATA.sparkline_js);
2927 NETDATA.chartLibraries.sparkline.enabled = false;
2928 NETDATA.error(100, NETDATA.sparkline_js);
2930 .always(function() {
2931 if(typeof callback === "function")
2936 NETDATA.chartLibraries.sparkline.enabled = false;
2937 if(typeof callback === "function")
2942 NETDATA.sparklineChartUpdate = function(state, data) {
2943 state.sparkline_options.width = state.chartWidth();
2944 state.sparkline_options.height = state.chartHeight();
2946 $(state.element_chart).sparkline(data.result, state.sparkline_options);
2949 NETDATA.sparklineChartCreate = function(state, data) {
2950 var self = $(state.element);
2951 var type = self.data('sparkline-type') || 'line';
2952 var lineColor = self.data('sparkline-linecolor') || state.chartColors()[0];
2953 var fillColor = self.data('sparkline-fillcolor') || (state.chart.chart_type === 'line')?'#FFF':NETDATA.colorLuminance(lineColor, NETDATA.chartDefaults.fill_luminance);
2954 var chartRangeMin = self.data('sparkline-chartrangemin') || undefined;
2955 var chartRangeMax = self.data('sparkline-chartrangemax') || undefined;
2956 var composite = self.data('sparkline-composite') || undefined;
2957 var enableTagOptions = self.data('sparkline-enabletagoptions') || undefined;
2958 var tagOptionPrefix = self.data('sparkline-tagoptionprefix') || undefined;
2959 var tagValuesAttribute = self.data('sparkline-tagvaluesattribute') || undefined;
2960 var disableHiddenCheck = self.data('sparkline-disablehiddencheck') || undefined;
2961 var defaultPixelsPerValue = self.data('sparkline-defaultpixelspervalue') || undefined;
2962 var spotColor = self.data('sparkline-spotcolor') || undefined;
2963 var minSpotColor = self.data('sparkline-minspotcolor') || undefined;
2964 var maxSpotColor = self.data('sparkline-maxspotcolor') || undefined;
2965 var spotRadius = self.data('sparkline-spotradius') || undefined;
2966 var valueSpots = self.data('sparkline-valuespots') || undefined;
2967 var highlightSpotColor = self.data('sparkline-highlightspotcolor') || undefined;
2968 var highlightLineColor = self.data('sparkline-highlightlinecolor') || undefined;
2969 var lineWidth = self.data('sparkline-linewidth') || undefined;
2970 var normalRangeMin = self.data('sparkline-normalrangemin') || undefined;
2971 var normalRangeMax = self.data('sparkline-normalrangemax') || undefined;
2972 var drawNormalOnTop = self.data('sparkline-drawnormalontop') || undefined;
2973 var xvalues = self.data('sparkline-xvalues') || undefined;
2974 var chartRangeClip = self.data('sparkline-chartrangeclip') || undefined;
2975 var xvalues = self.data('sparkline-xvalues') || undefined;
2976 var chartRangeMinX = self.data('sparkline-chartrangeminx') || undefined;
2977 var chartRangeMaxX = self.data('sparkline-chartrangemaxx') || undefined;
2978 var disableInteraction = self.data('sparkline-disableinteraction') || false;
2979 var disableTooltips = self.data('sparkline-disabletooltips') || false;
2980 var disableHighlight = self.data('sparkline-disablehighlight') || false;
2981 var highlightLighten = self.data('sparkline-highlightlighten') || 1.4;
2982 var highlightColor = self.data('sparkline-highlightcolor') || undefined;
2983 var tooltipContainer = self.data('sparkline-tooltipcontainer') || undefined;
2984 var tooltipClassname = self.data('sparkline-tooltipclassname') || undefined;
2985 var tooltipFormat = self.data('sparkline-tooltipformat') || undefined;
2986 var tooltipPrefix = self.data('sparkline-tooltipprefix') || undefined;
2987 var tooltipSuffix = self.data('sparkline-tooltipsuffix') || ' ' + state.chart.units;
2988 var tooltipSkipNull = self.data('sparkline-tooltipskipnull') || true;
2989 var tooltipValueLookups = self.data('sparkline-tooltipvaluelookups') || undefined;
2990 var tooltipFormatFieldlist = self.data('sparkline-tooltipformatfieldlist') || undefined;
2991 var tooltipFormatFieldlistKey = self.data('sparkline-tooltipformatfieldlistkey') || undefined;
2992 var numberFormatter = self.data('sparkline-numberformatter') || function(n){ return n.toFixed(2); };
2993 var numberDigitGroupSep = self.data('sparkline-numberdigitgroupsep') || undefined;
2994 var numberDecimalMark = self.data('sparkline-numberdecimalmark') || undefined;
2995 var numberDigitGroupCount = self.data('sparkline-numberdigitgroupcount') || undefined;
2996 var animatedZooms = self.data('sparkline-animatedzooms') || false;
2998 state.sparkline_options = {
3000 lineColor: lineColor,
3001 fillColor: fillColor,
3002 chartRangeMin: chartRangeMin,
3003 chartRangeMax: chartRangeMax,
3004 composite: composite,
3005 enableTagOptions: enableTagOptions,
3006 tagOptionPrefix: tagOptionPrefix,
3007 tagValuesAttribute: tagValuesAttribute,
3008 disableHiddenCheck: disableHiddenCheck,
3009 defaultPixelsPerValue: defaultPixelsPerValue,
3010 spotColor: spotColor,
3011 minSpotColor: minSpotColor,
3012 maxSpotColor: maxSpotColor,
3013 spotRadius: spotRadius,
3014 valueSpots: valueSpots,
3015 highlightSpotColor: highlightSpotColor,
3016 highlightLineColor: highlightLineColor,
3017 lineWidth: lineWidth,
3018 normalRangeMin: normalRangeMin,
3019 normalRangeMax: normalRangeMax,
3020 drawNormalOnTop: drawNormalOnTop,
3022 chartRangeClip: chartRangeClip,
3023 chartRangeMinX: chartRangeMinX,
3024 chartRangeMaxX: chartRangeMaxX,
3025 disableInteraction: disableInteraction,
3026 disableTooltips: disableTooltips,
3027 disableHighlight: disableHighlight,
3028 highlightLighten: highlightLighten,
3029 highlightColor: highlightColor,
3030 tooltipContainer: tooltipContainer,
3031 tooltipClassname: tooltipClassname,
3032 tooltipChartTitle: state.chart.title,
3033 tooltipFormat: tooltipFormat,
3034 tooltipPrefix: tooltipPrefix,
3035 tooltipSuffix: tooltipSuffix,
3036 tooltipSkipNull: tooltipSkipNull,
3037 tooltipValueLookups: tooltipValueLookups,
3038 tooltipFormatFieldlist: tooltipFormatFieldlist,
3039 tooltipFormatFieldlistKey: tooltipFormatFieldlistKey,
3040 numberFormatter: numberFormatter,
3041 numberDigitGroupSep: numberDigitGroupSep,
3042 numberDecimalMark: numberDecimalMark,
3043 numberDigitGroupCount: numberDigitGroupCount,
3044 animatedZooms: animatedZooms,
3045 width: state.chartWidth(),
3046 height: state.chartHeight()
3049 $(state.element_chart).sparkline(data.result, state.sparkline_options);
3052 // ----------------------------------------------------------------------------------------------------------------
3059 NETDATA.dygraphSetSelection = function(state, t) {
3060 if(typeof state.dygraph_instance !== 'undefined') {
3061 var r = state.calculateRowForTime(t);
3063 state.dygraph_instance.setSelection(r);
3065 state.dygraph_instance.clearSelection();
3066 state.legendShowUndefined();
3073 NETDATA.dygraphClearSelection = function(state, t) {
3074 if(typeof state.dygraph_instance !== 'undefined') {
3075 state.dygraph_instance.clearSelection();
3080 NETDATA.dygraphSmoothInitialize = function(callback) {
3082 url: NETDATA.dygraph_smooth_js,
3087 NETDATA.dygraph.smooth = true;
3088 smoothPlotter.smoothing = 0.3;
3091 NETDATA.dygraph.smooth = false;
3093 .always(function() {
3094 if(typeof callback === "function")
3099 NETDATA.dygraphInitialize = function(callback) {
3100 if(typeof netdataNoDygraphs === 'undefined' || !netdataNoDygraphs) {
3102 url: NETDATA.dygraph_js,
3107 NETDATA.registerChartLibrary('dygraph', NETDATA.dygraph_js);
3110 NETDATA.chartLibraries.dygraph.enabled = false;
3111 NETDATA.error(100, NETDATA.dygraph_js);
3113 .always(function() {
3114 if(NETDATA.chartLibraries.dygraph.enabled === true && NETDATA.options.current.smooth_plot === true)
3115 NETDATA.dygraphSmoothInitialize(callback);
3116 else if(typeof callback === "function")
3121 NETDATA.chartLibraries.dygraph.enabled = false;
3122 if(typeof callback === "function")
3127 NETDATA.dygraphChartUpdate = function(state, data) {
3128 var dygraph = state.dygraph_instance;
3130 if(typeof dygraph === 'undefined')
3131 NETDATA.dygraphChartCreate(state, data);
3133 // when the chart is not visible, and hidden
3134 // if there is a window resize, dygraph detects
3135 // its element size as 0x0.
3136 // this will make it re-appear properly
3138 if(state.tm.last_unhidden > state.dygraph_last_rendered)
3142 file: data.result.data,
3143 colors: state.chartColors(),
3144 labels: data.result.labels,
3145 labelsDivWidth: state.chartWidth() - 70,
3146 visibility: state.dimensions_visibility.selected2BooleanArray(state.data.dimension_names)
3149 if(state.current.name === 'pan') {
3150 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3151 state.log('dygraphChartUpdate() loose update');
3154 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3155 state.log('dygraphChartUpdate() strict update');
3157 options.dateWindow = null;
3158 options.valueRange = null;
3161 if(state.dygraph_smooth_eligible === true) {
3162 if((NETDATA.options.current.smooth_plot === true && state.dygraph_options.plotter !== smoothPlotter)
3163 || (NETDATA.options.current.smooth_plot === false && state.dygraph_options.plotter === smoothPlotter)) {
3164 NETDATA.dygraphChartCreate(state, data);
3169 dygraph.updateOptions(options);
3170 state.dygraph_last_rendered = new Date().getTime();
3173 NETDATA.dygraphChartCreate = function(state, data) {
3174 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3175 state.log('dygraphChartCreate()');
3177 var self = $(state.element);
3179 var chart_type = state.chart.chart_type;
3180 if(chart_type === 'stacked' && data.dimensions === 1) chart_type = 'area';
3181 chart_type = self.data('dygraph-type') || chart_type;
3183 var smooth = (chart_type === 'line' && !NETDATA.chartLibraries.dygraph.isSparkline(state))?true:false;
3184 smooth = self.data('dygraph-smooth') || smooth;
3186 if(NETDATA.dygraph.smooth === false)
3189 var strokeWidth = (chart_type === 'stacked')?0.1:((smooth)?1.5:0.7)
3190 var highlightCircleSize = (NETDATA.chartLibraries.dygraph.isSparkline(state))?3:4;
3192 state.dygraph_options = {
3193 colors: self.data('dygraph-colors') || state.chartColors(),
3195 // leave a few pixels empty on the right of the chart
3196 rightGap: self.data('dygraph-rightgap') || 5,
3197 showRangeSelector: self.data('dygraph-showrangeselector') || false,
3198 showRoller: self.data('dygraph-showroller') || false,
3200 title: self.data('dygraph-title') || state.chart.title,
3201 titleHeight: self.data('dygraph-titleheight') || 19,
3203 legend: self.data('dygraph-legend') || 'always', // 'onmouseover',
3204 labels: data.result.labels,
3205 labelsDiv: self.data('dygraph-labelsdiv') || state.element_legend_childs.hidden,
3206 labelsDivStyles: self.data('dygraph-labelsdivstyles') || { 'fontSize':'1px' },
3207 labelsDivWidth: self.data('dygraph-labelsdivwidth') || state.chartWidth() - 70,
3208 labelsSeparateLines: self.data('dygraph-labelsseparatelines') || true,
3209 labelsShowZeroValues: self.data('dygraph-labelsshowzerovalues') || true,
3212 showLabelsOnHighlight: self.data('dygraph-showlabelsonhighlight') || true,
3213 hideOverlayOnMouseOut: self.data('dygraph-hideoverlayonmouseout') || true,
3215 ylabel: state.chart.units,
3216 yLabelWidth: self.data('dygraph-ylabelwidth') || 12,
3218 // the function to plot the chart
3221 // The width of the lines connecting data points. This can be used to increase the contrast or some graphs.
3222 strokeWidth: self.data('dygraph-strokewidth') || strokeWidth,
3223 strokePattern: self.data('dygraph-strokepattern') || undefined,
3225 // The size of the dot to draw on each point in pixels (see drawPoints). A dot is always drawn when a point is "isolated",
3226 // i.e. there is a missing point on either side of it. This also controls the size of those dots.
3227 drawPoints: self.data('dygraph-drawpoints') || false,
3229 // Draw points at the edges of gaps in the data. This improves visibility of small data segments or other data irregularities.
3230 drawGapEdgePoints: self.data('dygraph-drawgapedgepoints') || true,
3232 connectSeparatedPoints: self.data('dygraph-connectseparatedpoints') || false,
3233 pointSize: self.data('dygraph-pointsize') || 1,
3235 // enabling this makes the chart with little square lines
3236 stepPlot: self.data('dygraph-stepplot') || false,
3238 // Draw a border around graph lines to make crossing lines more easily distinguishable. Useful for graphs with many lines.
3239 strokeBorderColor: self.data('dygraph-strokebordercolor') || 'white',
3240 strokeBorderWidth: self.data('dygraph-strokeborderwidth') || (chart_type === 'stacked')?0.0:0.0,
3242 fillGraph: self.data('dygraph-fillgraph') || (chart_type === 'area' || chart_type === 'stacked')?true:false,
3243 fillAlpha: self.data('dygraph-fillalpha') || (chart_type === 'stacked')?NETDATA.options.current.color_fill_opacity_stacked:NETDATA.options.current.color_fill_opacity_area,
3244 stackedGraph: self.data('dygraph-stackedgraph') || (chart_type === 'stacked')?true:false,
3245 stackedGraphNaNFill: self.data('dygraph-stackedgraphnanfill') || 'none',
3247 drawAxis: self.data('dygraph-drawaxis') || true,
3248 axisLabelFontSize: self.data('dygraph-axislabelfontsize') || 10,
3249 axisLineColor: self.data('dygraph-axislinecolor') || '#CCC',
3250 axisLineWidth: self.data('dygraph-axislinewidth') || 0.3,
3252 drawGrid: self.data('dygraph-drawgrid') || true,
3253 drawXGrid: self.data('dygraph-drawxgrid') || undefined,
3254 drawYGrid: self.data('dygraph-drawygrid') || undefined,
3255 gridLinePattern: self.data('dygraph-gridlinepattern') || null,
3256 gridLineWidth: self.data('dygraph-gridlinewidth') || 0.3,
3257 gridLineColor: self.data('dygraph-gridlinecolor') || '#DDD',
3259 maxNumberWidth: self.data('dygraph-maxnumberwidth') || 8,
3260 sigFigs: self.data('dygraph-sigfigs') || null,
3261 digitsAfterDecimal: self.data('dygraph-digitsafterdecimal') || 2,
3262 valueFormatter: self.data('dygraph-valueformatter') || function(x){ return x.toFixed(2); },
3264 highlightCircleSize: self.data('dygraph-highlightcirclesize') || highlightCircleSize,
3265 highlightSeriesOpts: self.data('dygraph-highlightseriesopts') || null, // TOO SLOW: { strokeWidth: 1.5 },
3266 highlightSeriesBackgroundAlpha: self.data('dygraph-highlightseriesbackgroundalpha') || null, // TOO SLOW: (chart_type === 'stacked')?0.7:0.5,
3268 pointClickCallback: self.data('dygraph-pointclickcallback') || undefined,
3269 visibility: state.dimensions_visibility.selected2BooleanArray(state.data.dimension_names),
3273 ticker: Dygraph.dateTicker,
3274 axisLabelFormatter: function (d, gran) {
3275 return NETDATA.zeropad(d.getHours()) + ":" + NETDATA.zeropad(d.getMinutes()) + ":" + NETDATA.zeropad(d.getSeconds());
3277 valueFormatter: function (ms) {
3278 var d = new Date(ms);
3279 return d.toLocaleDateString() + ' ' + d.toLocaleTimeString();
3280 // return NETDATA.zeropad(d.getHours()) + ":" + NETDATA.zeropad(d.getMinutes()) + ":" + NETDATA.zeropad(d.getSeconds());
3285 valueFormatter: function (x) {
3286 // return (Math.round(x*100) / 100).toLocaleString();
3287 //return state.legendFormatValue(x);
3293 legendFormatter: function(data) {
3294 var g = data.dygraph;
3296 var elements = state.element_legend_childs;
3298 // if the hidden div is not there
3299 // we are not managing the legend
3300 if(elements.hidden === null) return;
3302 if (typeof data.x === 'undefined') {
3303 //state.legendReset();
3306 state.legendSetDate(data.x);
3307 var i = data.series.length;
3309 var series = data.series[i];
3310 if(!series.isVisible) continue;
3311 state.legendSetLabelValue(series.label, series.y);
3317 drawCallback: function(dygraph, is_initial) {
3318 if(state.current.name !== 'auto') {
3319 if(NETDATA.options.debug.dygraph === true)
3320 state.log('dygraphDrawCallback()');
3322 var first = state.data.first_entry * 1000;
3323 var last = state.data.last_entry * 1000;
3325 var x_range = dygraph.xAxisRange();
3326 var after = Math.round(x_range[0]);
3327 var before = Math.round(x_range[1]);
3329 if(before <= last && after >= first)
3330 state.updateChartPanOrZoom(after, before);
3333 zoomCallback: function(minDate, maxDate, yRanges) {
3334 if(NETDATA.options.debug.dygraph === true)
3335 state.log('dygraphZoomCallback()');
3337 state.globalSelectionSyncStop();
3338 state.globalSelectionSyncDelay();
3340 if(state.updateChartPanOrZoom(minDate, maxDate) == false) {
3341 // we should not zoom that much
3342 state.dygraph_instance.updateOptions({
3348 highlightCallback: function(event, x, points, row, seriesName) {
3349 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3350 state.log('dygraphHighlightCallback()');
3354 // there is a bug in dygraph when the chart is zoomed enough
3355 // the time it thinks is selected is wrong
3356 // here we calculate the time t based on the row number selected
3358 var t = state.data_after + row * state.data_update_every;
3359 // 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);
3361 state.globalSelectionSync(t);
3363 // fix legend zIndex using the internal structures of dygraph legend module
3364 // this works, but it is a hack!
3365 // state.dygraph_instance.plugins_[0].plugin.legend_div_.style.zIndex = 10000;
3367 unhighlightCallback: function(event) {
3368 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3369 state.log('dygraphUnhighlightCallback()');
3371 state.unpauseChart();
3372 state.globalSelectionSyncStop();
3374 interactionModel : {
3375 mousedown: function(event, dygraph, context) {
3376 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3377 state.log('interactionModel.mousedown()');
3379 state.globalSelectionSyncStop();
3381 if(NETDATA.options.debug.dygraph === true)
3382 state.log('dygraphMouseDown()');
3384 // Right-click should not initiate a zoom.
3385 if(event.button && event.button === 2) return;
3387 context.initializeMouseDown(event, dygraph, context);
3389 if(event.button && event.button === 1) {
3390 if (event.altKey || event.shiftKey) {
3391 state.setMode('pan');
3392 state.globalSelectionSyncDelay();
3393 Dygraph.startPan(event, dygraph, context);
3396 state.setMode('zoom');
3397 state.globalSelectionSyncDelay();
3398 Dygraph.startZoom(event, dygraph, context);
3402 if (event.altKey || event.shiftKey) {
3403 state.setMode('zoom');
3404 state.globalSelectionSyncDelay();
3405 Dygraph.startZoom(event, dygraph, context);
3408 state.setMode('pan');
3409 state.globalSelectionSyncDelay();
3410 Dygraph.startPan(event, dygraph, context);
3414 mousemove: function(event, dygraph, context) {
3415 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3416 state.log('interactionModel.mousemove()');
3418 if(context.isPanning) {
3419 state.globalSelectionSyncStop();
3420 state.globalSelectionSyncDelay();
3421 state.setMode('pan');
3422 Dygraph.movePan(event, dygraph, context);
3424 else if(context.isZooming) {
3425 state.globalSelectionSyncStop();
3426 state.globalSelectionSyncDelay();
3427 state.setMode('zoom');
3428 Dygraph.moveZoom(event, dygraph, context);
3431 mouseup: function(event, dygraph, context) {
3432 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3433 state.log('interactionModel.mouseup()');
3435 if (context.isPanning) {
3436 state.globalSelectionSyncDelay();
3437 Dygraph.endPan(event, dygraph, context);
3439 else if (context.isZooming) {
3440 state.globalSelectionSyncDelay();
3441 Dygraph.endZoom(event, dygraph, context);
3444 click: function(event, dygraph, context) {
3445 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3446 state.log('interactionModel.click()');
3448 event.preventDefault();
3450 dblclick: function(event, dygraph, context) {
3451 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3452 state.log('interactionModel.dblclick()');
3454 state.globalSelectionSyncStop();
3455 NETDATA.globalPanAndZoom.clearMaster();
3458 mousewheel: function(event, dygraph, context) {
3459 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3460 state.log('interactionModel.mousewheel()');
3462 // Take the offset of a mouse event on the dygraph canvas and
3463 // convert it to a pair of percentages from the bottom left.
3464 // (Not top left, bottom is where the lower value is.)
3465 function offsetToPercentage(g, offsetX, offsetY) {
3466 // This is calculating the pixel offset of the leftmost date.
3467 var xOffset = g.toDomCoords(g.xAxisRange()[0], null)[0];
3468 var yar0 = g.yAxisRange(0);
3470 // This is calculating the pixel of the higest value. (Top pixel)
3471 var yOffset = g.toDomCoords(null, yar0[1])[1];
3473 // x y w and h are relative to the corner of the drawing area,
3474 // so that the upper corner of the drawing area is (0, 0).
3475 var x = offsetX - xOffset;
3476 var y = offsetY - yOffset;
3478 // This is computing the rightmost pixel, effectively defining the
3480 var w = g.toDomCoords(g.xAxisRange()[1], null)[0] - xOffset;
3482 // This is computing the lowest pixel, effectively defining the height.
3483 var h = g.toDomCoords(null, yar0[0])[1] - yOffset;
3485 // Percentage from the left.
3486 var xPct = w === 0 ? 0 : (x / w);
3487 // Percentage from the top.
3488 var yPct = h === 0 ? 0 : (y / h);
3490 // The (1-) part below changes it from "% distance down from the top"
3491 // to "% distance up from the bottom".
3492 return [xPct, (1-yPct)];
3495 // Adjusts [x, y] toward each other by zoomInPercentage%
3496 // Split it so the left/bottom axis gets xBias/yBias of that change and
3497 // tight/top gets (1-xBias)/(1-yBias) of that change.
3499 // If a bias is missing it splits it down the middle.
3500 function zoomRange(g, zoomInPercentage, xBias, yBias) {
3501 xBias = xBias || 0.5;
3502 yBias = yBias || 0.5;
3504 function adjustAxis(axis, zoomInPercentage, bias) {
3505 var delta = axis[1] - axis[0];
3506 var increment = delta * zoomInPercentage;
3507 var foo = [increment * bias, increment * (1-bias)];
3509 return [ axis[0] + foo[0], axis[1] - foo[1] ];
3512 var yAxes = g.yAxisRanges();
3514 for (var i = 0; i < yAxes.length; i++) {
3515 newYAxes[i] = adjustAxis(yAxes[i], zoomInPercentage, yBias);
3518 return adjustAxis(g.xAxisRange(), zoomInPercentage, xBias);
3521 if(event.altKey || event.shiftKey) {
3522 state.globalSelectionSyncStop();
3523 state.globalSelectionSyncDelay();
3525 // http://dygraphs.com/gallery/interaction-api.js
3526 var normal = (event.detail) ? event.detail * -1 : event.wheelDelta / 40;
3527 var percentage = normal / 50;
3529 if (!(event.offsetX && event.offsetY)){
3530 event.offsetX = event.layerX - event.target.offsetLeft;
3531 event.offsetY = event.layerY - event.target.offsetTop;
3534 var percentages = offsetToPercentage(dygraph, event.offsetX, event.offsetY);
3535 var xPct = percentages[0];
3536 var yPct = percentages[1];
3538 var new_x_range = zoomRange(dygraph, percentage, xPct, yPct);
3540 var after = new_x_range[0];
3541 var before = new_x_range[1];
3543 var first = (state.data.first_entry + state.data.view_update_every) * 1000;
3544 var last = (state.data.last_entry + state.data.view_update_every) * 1000;
3547 after -= (before - last);
3554 state.setMode('zoom');
3555 if(state.updateChartPanOrZoom(after, before) === true)
3556 dygraph.updateOptions({ dateWindow: [ after, before ] });
3558 event.preventDefault();
3561 touchstart: function(event, dygraph, context) {
3562 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3563 state.log('interactionModel.touchstart()');
3565 state.setMode('zoom');
3568 Dygraph.defaultInteractionModel.touchstart(event, dygraph, context);
3570 // we overwrite the touch directions at the end, to overwrite
3571 // the internal default of dygraphs
3572 context.touchDirections = { x: true, y: false };
3574 state.dygraph_last_touch_start = new Date().getTime();
3575 state.dygraph_last_touch_move = 0;
3577 if(typeof event.touches[0].pageX === 'number')
3578 state.dygraph_last_touch_page_x = event.touches[0].pageX;
3580 state.dygraph_last_touch_page_x = 0;
3582 touchmove: function(event, dygraph, context) {
3583 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3584 state.log('interactionModel.touchmove()');
3586 Dygraph.defaultInteractionModel.touchmove(event, dygraph, context);
3588 state.dygraph_last_touch_move = new Date().getTime();
3590 touchend: function(event, dygraph, context) {
3591 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3592 state.log('interactionModel.touchend()');
3594 Dygraph.defaultInteractionModel.touchend(event, dygraph, context);
3596 // if it didn't move, it is a selection
3597 if(state.dygraph_last_touch_move === 0 && state.dygraph_last_touch_page_x !== 0) {
3598 // internal api of dygraphs
3599 var pct = (state.dygraph_last_touch_page_x - (dygraph.plotter_.area.x + state.element.getBoundingClientRect().left)) / dygraph.plotter_.area.w;
3600 var t = Math.round(state.data_after + (state.data_before - state.data_after) * pct);
3601 if(NETDATA.dygraphSetSelection(state, t) === true)
3602 state.globalSelectionSync(t);
3605 // if it was double tap within double click time, reset the charts
3606 var now = new Date().getTime();
3607 if(typeof state.dygraph_last_touch_end !== 'undefined') {
3608 if(state.dygraph_last_touch_move === 0) {
3609 var dt = now - state.dygraph_last_touch_end;
3610 if(dt <= NETDATA.options.current.double_click_speed) {
3611 state.globalSelectionSyncStop();
3612 NETDATA.globalPanAndZoom.clearMaster();
3618 // remember the timestamp of the last touch end
3619 state.dygraph_last_touch_end = now;
3624 if(NETDATA.chartLibraries.dygraph.isSparkline(state)) {
3625 state.dygraph_options.drawGrid = false;
3626 state.dygraph_options.drawAxis = false;
3627 state.dygraph_options.title = undefined;
3628 state.dygraph_options.units = undefined;
3629 state.dygraph_options.ylabel = undefined;
3630 state.dygraph_options.yLabelWidth = 0;
3631 state.dygraph_options.labelsDivWidth = 120;
3632 state.dygraph_options.labelsDivStyles.width = '120px';
3633 state.dygraph_options.labelsSeparateLines = true;
3634 state.dygraph_options.rightGap = 0;
3637 if(smooth === true) {
3638 state.dygraph_smooth_eligible = true;
3640 if(NETDATA.options.current.smooth_plot === true)
3641 state.dygraph_options.plotter = smoothPlotter;
3643 else state.dygraph_smooth_eligible = false;
3645 state.dygraph_instance = new Dygraph(state.element_chart,
3646 data.result.data, state.dygraph_options);
3648 state.dygraph_last_rendered = new Date().getTime();
3651 // ----------------------------------------------------------------------------------------------------------------
3654 NETDATA.morrisInitialize = function(callback) {
3655 if(typeof netdataNoMorris === 'undefined' || !netdataNoMorris) {
3657 // morris requires raphael
3658 if(!NETDATA.chartLibraries.raphael.initialized) {
3659 if(NETDATA.chartLibraries.raphael.enabled) {
3660 NETDATA.raphaelInitialize(function() {
3661 NETDATA.morrisInitialize(callback);
3665 NETDATA.chartLibraries.morris.enabled = false;
3666 if(typeof callback === "function")
3671 NETDATA._loadCSS(NETDATA.morris_css);
3674 url: NETDATA.morris_js,
3679 NETDATA.registerChartLibrary('morris', NETDATA.morris_js);
3682 NETDATA.chartLibraries.morris.enabled = false;
3683 NETDATA.error(100, NETDATA.morris_js);
3685 .always(function() {
3686 if(typeof callback === "function")
3692 NETDATA.chartLibraries.morris.enabled = false;
3693 if(typeof callback === "function")
3698 NETDATA.morrisChartUpdate = function(state, data) {
3699 state.morris_instance.setData(data.result.data);
3702 NETDATA.morrisChartCreate = function(state, data) {
3704 state.morris_options = {
3705 element: state.element_chart_id,
3706 data: data.result.data,
3708 ykeys: data.dimension_names,
3709 labels: data.dimension_names,
3715 continuousLine: false,
3716 behaveLikeLine: false
3719 if(state.chart.chart_type === 'line')
3720 state.morris_instance = new Morris.Line(state.morris_options);
3722 else if(state.chart.chart_type === 'area') {
3723 state.morris_options.behaveLikeLine = true;
3724 state.morris_instance = new Morris.Area(state.morris_options);
3727 state.morris_instance = new Morris.Area(state.morris_options);
3730 // ----------------------------------------------------------------------------------------------------------------
3733 NETDATA.raphaelInitialize = function(callback) {
3734 if(typeof netdataStopRaphael === 'undefined' || !netdataStopRaphael) {
3736 url: NETDATA.raphael_js,
3741 NETDATA.registerChartLibrary('raphael', NETDATA.raphael_js);
3744 NETDATA.chartLibraries.raphael.enabled = false;
3745 NETDATA.error(100, NETDATA.raphael_js);
3747 .always(function() {
3748 if(typeof callback === "function")
3753 NETDATA.chartLibraries.raphael.enabled = false;
3754 if(typeof callback === "function")
3759 NETDATA.raphaelChartUpdate = function(state, data) {
3760 $(state.element_chart).raphael(data.result, {
3761 width: state.chartWidth(),
3762 height: state.chartHeight()
3766 NETDATA.raphaelChartCreate = function(state, data) {
3767 $(state.element_chart).raphael(data.result, {
3768 width: state.chartWidth(),
3769 height: state.chartHeight()
3773 // ----------------------------------------------------------------------------------------------------------------
3776 NETDATA.googleInitialize = function(callback) {
3777 if(typeof netdataNoGoogleCharts === 'undefined' || !netdataNoGoogleCharts) {
3779 url: NETDATA.google_js,
3784 NETDATA.registerChartLibrary('google', NETDATA.google_js);
3785 google.load('visualization', '1.1', {
3786 'packages': ['corechart', 'controls'],
3787 'callback': callback
3791 NETDATA.chartLibraries.google.enabled = false;
3792 NETDATA.error(100, NETDATA.google_js);
3793 if(typeof callback === "function")
3798 NETDATA.chartLibraries.google.enabled = false;
3799 if(typeof callback === "function")
3804 NETDATA.googleChartUpdate = function(state, data) {
3805 var datatable = new google.visualization.DataTable(data.result);
3806 state.google_instance.draw(datatable, state.google_options);
3809 NETDATA.googleChartCreate = function(state, data) {
3810 var datatable = new google.visualization.DataTable(data.result);
3812 state.google_options = {
3813 colors: state.chartColors(),
3815 // do not set width, height - the chart resizes itself
3816 //width: state.chartWidth(),
3817 //height: state.chartHeight(),
3819 title: state.chart.title,
3822 // title: "Time of Day",
3823 // format:'HH:mm:ss',
3824 viewWindowMode: 'maximized',
3835 title: state.chart.units,
3836 viewWindowMode: 'pretty',
3851 focusTarget: 'category',
3858 titlePosition: 'out',
3869 curveType: 'function',
3874 switch(state.chart.chart_type) {
3876 state.google_options.vAxis.viewWindowMode = 'maximized';
3877 state.google_options.areaOpacity = NETDATA.options.current.color_fill_opacity_area;
3878 state.google_instance = new google.visualization.AreaChart(state.element_chart);
3882 state.google_options.isStacked = true;
3883 state.google_options.areaOpacity = NETDATA.options.current.color_fill_opacity_stacked;
3884 state.google_options.vAxis.viewWindowMode = 'maximized';
3885 state.google_options.vAxis.minValue = null;
3886 state.google_options.vAxis.maxValue = null;
3887 state.google_instance = new google.visualization.AreaChart(state.element_chart);
3892 state.google_options.lineWidth = 2;
3893 state.google_instance = new google.visualization.LineChart(state.element_chart);
3897 state.google_instance.draw(datatable, state.google_options);
3900 // ----------------------------------------------------------------------------------------------------------------
3903 NETDATA.easypiechartInitialize = function(callback) {
3904 if(typeof netdataNoEasyPieChart === 'undefined' || !netdataNoEasyPieChart) {
3906 url: NETDATA.easypiechart_js,
3911 NETDATA.registerChartLibrary('easypiechart', NETDATA.easypiechart_js);
3914 NETDATA.error(100, NETDATA.easypiechart_js);
3916 .always(function() {
3917 if(typeof callback === "function")
3922 NETDATA.chartLibraries.easypiechart.enabled = false;
3923 if(typeof callback === "function")
3928 NETDATA.easypiechartChartUpdate = function(state, data) {
3930 state.easypiechart_instance.update();
3933 NETDATA.easypiechartChartCreate = function(state, data) {
3934 var self = $(state.element);
3939 $(state.element_chart).data('data-percent', pcent);
3940 data.element_chart.innerHTML = value.toString();
3942 state.easypiechart_instance = new EasyPieChart(state.element_chart, {
3943 barColor: self.data('easypiechart-barcolor') || '#ef1e25',
3944 trackColor: self.data('easypiechart-trackcolor') || '#f2f2f2',
3945 scaleColor: self.data('easypiechart-scalecolor') || '#dfe0e0',
3946 scaleLength: self.data('easypiechart-scalelength') || 5,
3947 lineCap: self.data('easypiechart-linecap') || 'round',
3948 lineWidth: self.data('easypiechart-linewidth') || 3,
3949 trackWidth: self.data('easypiechart-trackwidth') || undefined,
3950 size: self.data('easypiechart-size') || Math.min(state.chartWidth(), state.chartHeight()),
3951 rotate: self.data('easypiechart-rotate') || 0,
3952 animate: self.data('easypiechart-rotate') || {duration: 0, enabled: false},
3953 easing: self.data('easypiechart-easing') || undefined
3957 // ----------------------------------------------------------------------------------------------------------------
3958 // Charts Libraries Registration
3960 NETDATA.chartLibraries = {
3962 initialize: NETDATA.dygraphInitialize,
3963 create: NETDATA.dygraphChartCreate,
3964 update: NETDATA.dygraphChartUpdate,
3965 resize: function(state) {
3966 if(typeof state.dygraph_instance.resize === 'function')
3967 state.dygraph_instance.resize();
3969 setSelection: NETDATA.dygraphSetSelection,
3970 clearSelection: NETDATA.dygraphClearSelection,
3973 format: function(state) { return 'json'; },
3974 options: function(state) { return 'ms|flip'; },
3975 legend: function(state) {
3976 if(this.isSparkline(state) === false)
3977 return 'right-side';
3981 autoresize: function(state) { return true; },
3982 max_updates_to_recreate: function(state) { return 5000; },
3983 track_colors: function(state) { return true; },
3984 pixels_per_point: function(state) {
3985 if(this.isSparkline(state) === false)
3991 isSparkline: function(state) {
3992 if(typeof state.dygraph_sparkline === 'undefined') {
3993 var t = $(state.element).data('dygraph-theme');
3994 if(t === 'sparkline')
3995 state.dygraph_sparkline = true;
3997 state.dygraph_sparkline = false;
3999 return state.dygraph_sparkline;
4003 initialize: NETDATA.sparklineInitialize,
4004 create: NETDATA.sparklineChartCreate,
4005 update: NETDATA.sparklineChartUpdate,
4007 setSelection: function(t) { return true; },
4008 clearSelection: function() { return true; },
4011 format: function(state) { return 'array'; },
4012 options: function(state) { return 'flip|abs'; },
4013 legend: function(state) { return null; },
4014 autoresize: function(state) { return false; },
4015 max_updates_to_recreate: function(state) { return 5000; },
4016 track_colors: function(state) { return false; },
4017 pixels_per_point: function(state) { return 3; }
4020 initialize: NETDATA.peityInitialize,
4021 create: NETDATA.peityChartCreate,
4022 update: NETDATA.peityChartUpdate,
4024 setSelection: function(t) { return true; },
4025 clearSelection: function() { return true; },
4028 format: function(state) { return 'ssvcomma'; },
4029 options: function(state) { return 'null2zero|flip|abs'; },
4030 legend: function(state) { return null; },
4031 autoresize: function(state) { return false; },
4032 max_updates_to_recreate: function(state) { return 5000; },
4033 track_colors: function(state) { return false; },
4034 pixels_per_point: function(state) { return 3; }
4037 initialize: NETDATA.morrisInitialize,
4038 create: NETDATA.morrisChartCreate,
4039 update: NETDATA.morrisChartUpdate,
4041 setSelection: function(t) { return true; },
4042 clearSelection: function() { return true; },
4045 format: function(state) { return 'json'; },
4046 options: function(state) { return 'objectrows|ms'; },
4047 legend: function(state) { return null; },
4048 autoresize: function(state) { return false; },
4049 max_updates_to_recreate: function(state) { return 50; },
4050 track_colors: function(state) { return false; },
4051 pixels_per_point: function(state) { return 15; }
4054 initialize: NETDATA.googleInitialize,
4055 create: NETDATA.googleChartCreate,
4056 update: NETDATA.googleChartUpdate,
4058 setSelection: function(t) { return true; },
4059 clearSelection: function() { return true; },
4062 format: function(state) { return 'datatable'; },
4063 options: function(state) { return ''; },
4064 legend: function(state) { return null; },
4065 autoresize: function(state) { return false; },
4066 max_updates_to_recreate: function(state) { return 300; },
4067 track_colors: function(state) { return false; },
4068 pixels_per_point: function(state) { return 4; }
4071 initialize: NETDATA.raphaelInitialize,
4072 create: NETDATA.raphaelChartCreate,
4073 update: NETDATA.raphaelChartUpdate,
4075 setSelection: function(t) { return true; },
4076 clearSelection: function() { return true; },
4079 format: function(state) { return 'json'; },
4080 options: function(state) { return ''; },
4081 legend: function(state) { return null; },
4082 autoresize: function(state) { return false; },
4083 max_updates_to_recreate: function(state) { return 5000; },
4084 track_colors: function(state) { return false; },
4085 pixels_per_point: function(state) { return 3; }
4088 initialize: NETDATA.easypiechartInitialize,
4089 create: NETDATA.easypiechartChartCreate,
4090 update: NETDATA.easypiechartChartUpdate,
4092 setSelection: function(t) { return true; },
4093 clearSelection: function() { return true; },
4096 format: function(state) { return 'json'; },
4097 options: function(state) { return ''; },
4098 legend: function(state) { return null; },
4099 autoresize: function(state) { return false; },
4100 max_updates_to_recreate: function(state) { return 5000; },
4101 track_colors: function(state) { return false; },
4102 pixels_per_point: function(state) { return 3; }
4106 NETDATA.registerChartLibrary = function(library, url) {
4107 if(NETDATA.options.debug.libraries === true)
4108 console.log("registering chart library: " + library);
4110 NETDATA.chartLibraries[library].url = url;
4111 NETDATA.chartLibraries[library].initialized = true;
4112 NETDATA.chartLibraries[library].enabled = true;
4115 // ----------------------------------------------------------------------------------------------------------------
4118 NETDATA.requiredJs = [
4120 url: NETDATA.serverDefault + 'lib/bootstrap.min.js',
4121 isAlreadyLoaded: function() {
4122 if(typeof $().emulateTransitionEnd == 'function')
4125 if(typeof netdataNoBootstrap !== 'undefined' && netdataNoBootstrap)
4133 url: NETDATA.serverDefault + 'lib/jquery.nanoscroller.min.js',
4134 isAlreadyLoaded: function() { return false; }
4137 url: NETDATA.serverDefault + 'lib/bootstrap-toggle.min.js',
4138 isAlreadyLoaded: function() { return false; }
4142 NETDATA.requiredCSS = [
4144 url: NETDATA.serverDefault + 'css/bootstrap.min.css',
4145 isAlreadyLoaded: function() {
4146 if(typeof netdataNoBootstrap !== 'undefined' && netdataNoBootstrap)
4153 url: NETDATA.serverDefault + 'css/font-awesome.min.css',
4154 isAlreadyLoaded: function() { return false; }
4157 url: NETDATA.dashboard_css,
4158 isAlreadyLoaded: function() { return false; }
4161 url: NETDATA.serverDefault + 'css/bootstrap-toggle.min.css',
4162 isAlreadyLoaded: function() { return false; }
4166 NETDATA.loadRequiredJs = function(index, callback) {
4167 if(index >= NETDATA.requiredJs.length) {
4168 if(typeof callback === 'function')
4173 if(NETDATA.requiredJs[index].isAlreadyLoaded()) {
4174 NETDATA.loadRequiredJs(++index, callback);
4178 if(NETDATA.options.debug.main_loop === true)
4179 console.log('loading ' + NETDATA.requiredJs[index].url);
4182 url: NETDATA.requiredJs[index].url,
4186 .success(function() {
4187 if(NETDATA.options.debug.main_loop === true)
4188 console.log('loaded ' + NETDATA.requiredJs[index].url);
4190 NETDATA.loadRequiredJs(++index, callback);
4193 alert('Cannot load required JS library: ' + NETDATA.requiredJs[index].url);
4197 NETDATA.loadRequiredCSS = function(index) {
4198 if(index >= NETDATA.requiredCSS.length)
4201 if(NETDATA.requiredCSS[index].isAlreadyLoaded()) {
4202 NETDATA.loadRequiredCSS(++index);
4206 if(NETDATA.options.debug.main_loop === true)
4207 console.log('loading ' + NETDATA.requiredCSS[index].url);
4209 NETDATA._loadCSS(NETDATA.requiredCSS[index].url);
4210 NETDATA.loadRequiredCSS(++index);
4213 NETDATA.errorReset();
4214 NETDATA.loadRequiredCSS(0);
4216 NETDATA._loadjQuery(function() {
4217 NETDATA.loadRequiredJs(0, function() {
4218 if(typeof netdataDontStart === 'undefined' || !netdataDontStart) {
4219 if(NETDATA.options.debug.main_loop === true)
4220 console.log('starting chart refresh thread');
4225 if(typeof NETDATA.options.readyCallback === 'function')
4226 NETDATA.options.readyCallback();
4230 // window.NETDATA = NETDATA;
4231 // })(window, document);