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] === '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
584 // move color assignment to dimensions, here
586 dimensionStatus = function(parent, label, name_div, value_div, color) {
587 this.enabled = false;
588 this.parent = parent;
590 this.name_div = null;
591 this.value_div = null;
594 if(parent.selected === parent.unselected)
595 this.selected = true;
597 this.selected = false;
599 this.setOptions(name_div, value_div, color);
602 dimensionStatus.prototype.invalidate = function() {
603 this.name_div = null;
604 this.value_div = null;
605 this.enabled = false;
608 dimensionStatus.prototype.setOptions = function(name_div, value_div, color) {
611 if(this.name_div != name_div) {
612 this.name_div = name_div;
613 this.name_div.title = this.label;
614 this.name_div.style.color = this.color;
615 if(this.selected === false)
616 this.name_div.className = 'netdata-legend-name not-selected';
618 this.name_div.className = 'netdata-legend-name selected';
621 if(this.value_div != value_div) {
622 this.value_div = value_div;
623 this.value_div.title = this.label;
624 this.value_div.style.color = this.color;
625 if(this.selected === false)
626 this.value_div.className = 'netdata-legend-value not-selected';
628 this.value_div.className = 'netdata-legend-value selected';
635 dimensionStatus.prototype.setHandler = function() {
636 if(this.enabled === false) return;
640 // this.name_div.onmousedown = this.value_div.onmousedown = function(e) {
641 this.name_div.onclick = this.value_div.onclick = function(e) {
643 if(ds.isSelected()) {
645 if(e.shiftKey === true || e.ctrlKey === true) {
646 // control or shift key is pressed -> unselect this (except is none will remain selected, in which case select all)
649 if(ds.parent.countSelected() === 0)
650 ds.parent.selectAll();
653 // no key is pressed -> select only this (except if it is the only selected already, in which case select all)
654 if(ds.parent.countSelected() === 1) {
655 ds.parent.selectAll();
658 ds.parent.selectNone();
664 // this is not selected
665 if(e.shiftKey === true || e.ctrlKey === true) {
666 // control or shift key is pressed -> select this too
670 // no key is pressed -> select only this
671 ds.parent.selectNone();
676 ds.parent.state.redrawChart();
680 dimensionStatus.prototype.select = function() {
681 if(this.enabled === false) return;
683 this.name_div.className = 'netdata-legend-name selected';
684 this.value_div.className = 'netdata-legend-value selected';
685 this.selected = true;
688 dimensionStatus.prototype.unselect = function() {
689 if(this.enabled === false) return;
691 this.name_div.className = 'netdata-legend-name not-selected';
692 this.value_div.className = 'netdata-legend-value hidden';
693 this.selected = false;
696 dimensionStatus.prototype.isSelected = function() {
697 return(this.enabled === true && this.selected === true);
700 // ----------------------------------------------------------------------------------------------------------------
702 dimensionsVisibility = function(state) {
705 this.dimensions = {};
706 this.selected_count = 0;
707 this.unselected_count = 0;
710 dimensionsVisibility.prototype.dimensionAdd = function(label, name_div, value_div, color) {
711 if(typeof this.dimensions[label] === 'undefined') {
713 this.dimensions[label] = new dimensionStatus(this, label, name_div, value_div, color);
716 this.dimensions[label].setOptions(name_div, value_div, color);
718 return this.dimensions[label];
721 dimensionsVisibility.prototype.dimensionGet = function(label) {
722 return this.dimensions[label];
725 dimensionsVisibility.prototype.invalidateAll = function() {
726 for(var d in this.dimensions)
727 this.dimensions[d].invalidate();
730 dimensionsVisibility.prototype.selectAll = function() {
731 for(var d in this.dimensions)
732 this.dimensions[d].select();
735 dimensionsVisibility.prototype.countSelected = function() {
737 for(var d in this.dimensions)
738 if(this.dimensions[d].isSelected()) i++;
743 dimensionsVisibility.prototype.selectNone = function() {
744 for(var d in this.dimensions)
745 this.dimensions[d].unselect();
748 dimensionsVisibility.prototype.selected2BooleanArray = function(array) {
749 var ret = new Array();
750 this.selected_count = 0;
751 this.unselected_count = 0;
753 for(var i = 0, len = array.length; i < len ; i++) {
754 var ds = this.dimensions[array[i]];
755 if(typeof ds === 'undefined') {
756 // console.log(array[i] + ' is not found');
761 if(ds.isSelected()) {
763 this.selected_count++;
767 this.unselected_count++;
771 if(this.selected_count === 0 && this.unselected_count !== 0) {
773 return this.selected2BooleanArray(array);
780 // ----------------------------------------------------------------------------------------------------------------
781 // global selection sync
783 NETDATA.globalSelectionSync = {
790 if(this.state !== null)
791 this.state.globalSelectionSyncStop();
795 if(this.state !== null) {
796 this.state.globalSelectionSyncDelay();
801 // ----------------------------------------------------------------------------------------------------------------
802 // Our state object, where all per-chart values are stored
804 chartState = function(element) {
805 var self = $(element);
806 this.element = element;
809 // all private functions should use 'that', instead of 'this'
813 * show an error instead of the chart
815 var error = function(msg) {
816 that.element.innerHTML = that.id + ': ' + msg;
817 that.enabled = false;
818 that.current = that.pan;
821 // GUID - a unique identifier for the chart
822 this.uuid = NETDATA.guid();
824 // string - the name of chart
825 this.id = self.data('netdata');
827 // string - the key for localStorage settings
828 this.settings_id = self.data('id') || null;
830 // the user given dimensions of the element
831 this.width = self.data('width') || NETDATA.chartDefaults.width;
832 this.height = self.data('height') || NETDATA.chartDefaults.height;
834 if(this.settings_id !== null) {
835 this.height = NETDATA.localStorageGet('chart_heights.' + this.settings_id, this.height, function(height) {
836 // this is the callback that will be called
837 // if and when the user resets all localStorage variables
840 resizeChartToHeight(height);
844 // string - the netdata server URL, without any path
845 this.host = self.data('host') || NETDATA.chartDefaults.host;
847 // make sure the host does not end with /
848 // all netdata API requests use absolute paths
849 while(this.host.slice(-1) === '/')
850 this.host = this.host.substring(0, this.host.length - 1);
852 // string - the grouping method requested by the user
853 this.method = self.data('method') || NETDATA.chartDefaults.method;
855 // the time-range requested by the user
856 this.after = self.data('after') || NETDATA.chartDefaults.after;
857 this.before = self.data('before') || NETDATA.chartDefaults.before;
859 // the pixels per point requested by the user
860 this.pixels_per_point = self.data('pixels-per-point') || 1;
861 this.points = self.data('points') || null;
863 // the dimensions requested by the user
864 this.dimensions = self.data('dimensions') || null;
866 // the chart library requested by the user
867 this.library_name = self.data('chart-library') || NETDATA.chartDefaults.library;
869 // object - the chart library used
874 this.colors_assigned = {};
875 this.colors_available = null;
877 // the element already created by the user
878 this.element_message = null;
880 // the element with the chart
881 this.element_chart = null;
883 // the element with the legend of the chart (if created by us)
884 this.element_legend = null;
885 this.element_legend_childs = {
895 this.chart_url = null; // string - the url to download chart info
896 this.chart = null; // object - the chart as downloaded from the server
898 this.validated = false; // boolean - has the chart been validated?
899 this.enabled = true; // boolean - is the chart enabled for refresh?
900 this.paused = false; // boolean - is the chart paused for any reason?
901 this.selected = false; // boolean - is the chart shown a selection?
902 this.debug = false; // boolean - console.log() debug info about this chart
904 this.netdata_first = 0; // milliseconds - the first timestamp in netdata
905 this.netdata_last = 0; // milliseconds - the last timestamp in netdata
906 this.requested_after = null; // milliseconds - the timestamp of the request after param
907 this.requested_before = null; // milliseconds - the timestamp of the request before param
912 force_update_at: 0, // the timestamp to force the update at
913 force_before_ms: null,
919 force_update_at: 0, // the timestamp to force the update at
920 force_before_ms: null,
926 force_update_at: 0, // the timestamp to force the update at
927 force_before_ms: null,
931 // this is a pointer to one of the sub-classes below
933 this.current = this.auto;
935 // check the requested library is available
936 // we don't initialize it here - it will be initialized when
937 // this chart will be first used
938 if(typeof NETDATA.chartLibraries[that.library_name] === 'undefined') {
939 NETDATA.error(402, that.library_name);
940 error('chart library "' + that.library_name + '" is not found');
943 else if(NETDATA.chartLibraries[that.library_name].enabled === false) {
944 NETDATA.error(403, that.library_name);
945 error('chart library "' + that.library_name + '" is not enabled');
949 that.library = NETDATA.chartLibraries[that.library_name];
951 // milliseconds - the time the last refresh took
952 this.refresh_dt_ms = 0;
954 // if we need to report the rendering speed
955 // find the element that needs to be updated
956 var refresh_dt_element_name = self.data('dt-element-name') || null; // string - the element to print refresh_dt_ms
958 if(refresh_dt_element_name !== null)
959 this.refresh_dt_element = document.getElementById(refresh_dt_element_name) || null;
961 this.refresh_dt_element = null;
963 this.dimensions_visibility = new dimensionsVisibility(this);
965 // ============================================================================================================
968 var createDOM = function() {
969 if(that.enabled == false) return;
971 if(that.element_message !== null) that.element_message.innerHTML = '';
972 if(that.element_legend !== null) that.element_legend.innerHTML = '';
973 if(that.element_chart !== null) that.element_chart.innerHTML = '';
975 that.element.innerHTML = '';
977 that.element_message = document.createElement('div');
978 that.element_message.className = ' netdata-message hidden';
979 that.element.appendChild(that.element_message);
981 that.element_chart = document.createElement('div');
982 that.element_chart.id = that.library_name + '-' + that.uuid + '-chart';
983 that.element.appendChild(that.element_chart);
985 if(that.hasLegend() === true) {
986 that.element.className = "netdata-container-with-legend";
987 that.element_chart.className = 'netdata-chart-with-legend-right netdata-' + that.library_name + '-chart-with-legend-right';
989 that.element_legend = document.createElement('div');
990 that.element_legend.className = 'netdata-chart-legend netdata-' + that.library_name + '-legend';
991 that.element.appendChild(that.element_legend);
994 that.element.className = "netdata-container";
995 that.element_chart.className = ' netdata-chart netdata-' + that.library_name + '-chart';
997 that.element_legend = null;
999 that.element_legend_childs.series = null;
1001 if(that.width !== 0)
1002 $(that.element).css('width', that.width);
1004 if(that.height !== 0)
1005 $(that.element).css('height', that.height);
1007 if(NETDATA.chartDefaults.min_width !== null)
1008 $(that.element).css('min-width', NETDATA.chartDefaults.min_width);
1010 that.tm.last_dom_created = new Date().getTime();
1016 * initialize state viariables
1017 * destroy all (possibly) created state elements
1018 * create the basic DOM for a chart
1020 var init = function() {
1021 if(that.enabled == false) return;
1023 that.paused = false;
1024 that.selected = false;
1026 that.chart_created = false; // boolean - is the library.create() been called?
1027 that.updates_counter = 0; // numeric - the number of refreshes made so far
1028 that.updates_since_last_creation = 0;
1031 last_initialized: 0, // milliseconds - the timestamp it was last initialized
1032 last_dom_created: 0, // milliseconds - the timestamp its DOM was last created
1033 last_mode_switch: 0, // milliseconds - the timestamp it switched modes
1035 last_info_downloaded: 0, // milliseconds - the timestamp we downloaded the chart
1036 last_updated: 0, // the timestamp the chart last updated with data
1037 pan_and_zoom_seq: 0, // the sequence number of the global synchronization
1039 // Used with NETDATA.globalPanAndZoom.seq
1040 last_visible_check: 0, // the time we last checked if it is visible
1041 last_resized: 0, // the time the chart was resized
1042 last_hidden: 0, // the time the chart was hidden
1043 last_unhidden: 0, // the time the chart was unhidden
1044 last_autorefreshed: 0 // the time the chart was last refreshed
1047 that.data = null; // the last data as downloaded from the netdata server
1048 that.data_url = 'invalid://'; // string - the last url used to update the chart
1049 that.data_points = 0; // number - the number of points returned from netdata
1050 that.data_after = 0; // milliseconds - the first timestamp of the data
1051 that.data_before = 0; // milliseconds - the last timestamp of the data
1052 that.data_update_every = 0; // milliseconds - the frequency to update the data
1054 that.tm.last_initialized = new Date().getTime();
1057 that.setMode('auto');
1060 var maxMessageFontSize = function() {
1061 // normally we want a font size, as tall as the element
1062 var h = that.element_message.clientHeight;
1064 // but give it some air, 20% let's say, or 5 pixels min
1065 var lost = Math.max(h * 0.2, 5);
1068 // center the text, verically
1069 var paddingTop = (lost - 5) / 2;
1071 // but check the width too
1072 // it should fit 10 characters in it
1073 var w = that.element_message.clientWidth / 10;
1075 paddingTop += (h - w) / 2;
1079 // and don't make it too huge
1080 // 5% of the screen size is good
1081 if(h > screen.height / 20) {
1082 paddingTop += (h - (screen.height / 20)) / 2;
1083 h = screen.height / 20;
1087 that.element_message.style.fontSize = h.toString() + 'px';
1088 that.element_message.style.paddingTop = paddingTop.toString() + 'px';
1091 var showMessage = function(msg) {
1092 that.element_message.className = 'netdata-message';
1093 that.element_message.innerHTML = msg;
1094 this.element_message.style.fontSize = 'x-small';
1095 that.element_message.style.paddingTop = '0px';
1096 that.___messageHidden___ = undefined;
1099 var showMessageIcon = function(icon) {
1100 that.element_message.innerHTML = icon;
1101 that.element_message.className = 'netdata-message icon';
1102 maxMessageFontSize();
1103 that.___messageHidden___ = undefined;
1106 var hideMessage = function() {
1107 if(typeof that.___messageHidden___ === 'undefined') {
1108 that.___messageHidden___ = true;
1109 that.element_message.className = 'netdata-message hidden';
1113 var showRendering = function() {
1115 if(that.chart !== null) {
1116 if(that.chart.chart_type === 'line')
1117 icon = '<i class="fa fa-line-chart"></i>';
1119 icon = '<i class="fa fa-area-chart"></i>';
1122 icon = '<i class="fa fa-area-chart"></i>';
1124 showMessageIcon(icon + ' netdata');
1127 var showLoading = function() {
1128 if(that.chart_created === false) {
1129 showMessageIcon('<i class="fa fa-refresh"></i> netdata');
1135 // hide the chart, when it is not visible - called from isVisible()
1136 var hideChart = function() {
1138 if(that.chart_created === false) return;
1140 // we should destroy it
1141 if(NETDATA.options.current.destroy_on_hide === true) {
1143 that.___chartIsHidden___ = undefined;
1147 // just hide it, if it is not already hidden
1148 if(typeof that.___chartIsHidden___ === 'undefined') {
1150 that.element_chart.style.display = 'none';
1151 if(that.element_legend !== null) that.element_legend.style.display = 'none';
1152 that.___chartIsHidden___ = true;
1156 // unhide the chart, when it is visible - called from isVisible()
1157 var unhideChart = function() {
1158 if(typeof that.___chartIsHidden___ !== 'undefined') {
1159 that.element_chart.style.display = 'inline-block';
1160 if(that.element_legend !== null) that.element_legend.style.display = 'inline-block';
1161 that.___chartIsHidden___ = undefined;
1167 // ----------------------------------------------------------------------------------------------------------------
1170 // resizeChart() - private
1171 // to be called just before the chart library to make sure that
1172 // a properly sized dom is available
1173 var resizeChart = function() {
1174 if(that.isVisible() === true && that.tm.last_resized < NETDATA.options.last_resized) {
1175 that.tm.last_resized = new Date().getTime();
1176 if(that.chart_created === false) return;
1178 if(that.needsRecreation())
1181 else if(typeof that.library.resize === 'function') {
1182 that.library.resize(that);
1184 if(that.element_legend_childs.nano !== null && that.element_legend_childs.nano_options !== null)
1185 $(that.element_legend_childs.nano).nanoScroller();
1187 maxMessageFontSize();
1192 // this is the actual chart resize algorithm
1194 // - resize the entire container
1195 // - update the internal states
1196 // - resize the chart as the div changes height
1197 // - update the scrollbar of the legend
1198 var resizeChartToHeight = function(h) {
1200 that.element.style.height = h;
1202 if(that.settings_id !== null)
1203 NETDATA.localStorageSet('chart_heights.' + that.settings_id, h);
1205 var now = new Date().getTime();
1206 NETDATA.options.last_page_scroll = now;
1207 NETDATA.options.last_resized = now;
1208 NETDATA.options.auto_refresher_stop_until = now + NETDATA.options.current.stop_updates_while_resizing;
1211 that.tm.last_resized = 0;
1215 this.resizeHandler = function(e) {
1218 if(typeof this.event_resize === 'undefined'
1219 || this.event_resize.chart_original_w === 'undefined'
1220 || this.event_resize.chart_original_h === 'undefined')
1221 this.event_resize = {
1222 chart_original_w: this.element.clientWidth,
1223 chart_original_h: this.element.clientHeight,
1227 if(e.type === 'touchstart') {
1228 this.event_resize.mouse_start_x = e.touches.item(0).pageX;
1229 this.event_resize.mouse_start_y = e.touches.item(0).pageY;
1232 this.event_resize.mouse_start_x = e.clientX;
1233 this.event_resize.mouse_start_y = e.clientY;
1236 this.event_resize.chart_start_w = this.element.clientWidth;
1237 this.event_resize.chart_start_h = this.element.clientHeight;
1238 this.event_resize.chart_last_w = this.element.clientWidth;
1239 this.event_resize.chart_last_h = this.element.clientHeight;
1241 var now = new Date().getTime();
1242 if(now - this.event_resize.last <= NETDATA.options.current.double_click_speed) {
1243 // double click / double tap event
1245 // the optimal height of the chart
1246 // showing the entire legend
1247 var optimal = this.event_resize.chart_last_h
1248 + this.element_legend_childs.content.scrollHeight
1249 - this.element_legend_childs.content.clientHeight;
1251 // if we are not optimal, be optimal
1252 if(this.event_resize.chart_last_h != optimal)
1253 resizeChartToHeight(optimal.toString() + 'px');
1255 // else if we do not have the original height
1256 // reset to the original height
1257 else if(this.event_resize.chart_last_h != this.event_resize.chart_original_h)
1258 resizeChartToHeight(this.event_resize.chart_original_h.toString() + 'px');
1261 this.event_resize.last = now;
1263 // process movement event
1264 document.onmousemove =
1265 document.ontouchmove =
1266 this.element_legend_childs.resize_handler.onmousemove =
1267 this.element_legend_childs.resize_handler.ontouchmove =
1272 case 'mousemove': y = e.clientY; break;
1273 case 'touchmove': y = e.touches.item(e.touches - 1).pageY; break;
1277 var newH = that.event_resize.chart_start_h + y - that.event_resize.mouse_start_y;
1279 if(newH >= 70 && newH !== that.event_resize.chart_last_h) {
1280 resizeChartToHeight(newH.toString() + 'px');
1281 that.event_resize.chart_last_h = newH;
1286 // process end event
1287 document.onmouseup =
1288 document.ontouchend =
1289 this.element_legend_childs.resize_handler.onmouseup =
1290 this.element_legend_childs.resize_handler.ontouchend =
1292 // remove all the hooks
1293 document.onmouseup =
1294 document.onmousemove =
1295 document.ontouchmove =
1296 document.ontouchend =
1297 that.element_legend_childs.resize_handler.onmousemove =
1298 that.element_legend_childs.resize_handler.ontouchmove =
1299 that.element_legend_childs.resize_handler.onmouseout =
1300 that.element_legend_childs.resize_handler.onmouseup =
1301 that.element_legend_childs.resize_handler.ontouchend =
1304 // allow auto-refreshes
1305 NETDATA.options.auto_refresher_stop_until = 0;
1311 var noDataToShow = function() {
1312 this.legendUpdateDOM();
1313 that.tm.last_autorefreshed = new Date().getTime();
1314 that.data_update_every = 30 * 1000;
1317 // ============================================================================================================
1320 this.error = function(msg) {
1324 this.setMode = function(m) {
1325 if(this.current !== null && this.current.name === m) return;
1328 this.current = this.auto;
1329 else if(m === 'pan')
1330 this.current = this.pan;
1331 else if(m === 'zoom')
1332 this.current = this.zoom;
1334 this.current = this.auto;
1336 this.current.force_update_at = 0;
1337 this.current.force_before_ms = null;
1338 this.current.force_after_ms = null;
1340 this.tm.last_mode_switch = new Date().getTime();
1343 // ----------------------------------------------------------------------------------------------------------------
1344 // global selection sync
1346 // prevent to global selection sync for some time
1347 this.globalSelectionSyncDelay = function(ms) {
1348 if(NETDATA.options.current.sync_selection === false)
1351 if(typeof ms === 'number')
1352 NETDATA.globalSelectionSync.dont_sync_before = new Date().getTime() + ms;
1354 NETDATA.globalSelectionSync.dont_sync_before = new Date().getTime() + NETDATA.options.current.sync_selection_delay;
1357 // can we globally apply selection sync?
1358 this.globalSelectionSyncAbility = function() {
1359 if(NETDATA.options.current.sync_selection === false)
1362 if(NETDATA.globalSelectionSync.dont_sync_before > new Date().getTime())
1368 this.globalSelectionSyncIsMaster = function() {
1369 if(NETDATA.globalSelectionSync.state === this)
1375 // this chart is the master of the global selection sync
1376 this.globalSelectionSyncBeMaster = function() {
1378 if(this.globalSelectionSyncIsMaster()) {
1379 if(this.debug === true)
1380 this.log('sync: I am the master already.');
1385 if(NETDATA.globalSelectionSync.state) {
1386 if(this.debug === true)
1387 this.log('sync: I am not the sync master. Resetting global sync.');
1389 this.globalSelectionSyncStop();
1392 // become the master
1393 if(this.debug === true)
1394 this.log('sync: becoming sync master.');
1396 this.selected = true;
1397 NETDATA.globalSelectionSync.state = this;
1399 // find the all slaves
1400 var targets = NETDATA.options.targets;
1401 var len = targets.length;
1406 if(this.debug === true)
1407 st.log('sync: not adding me to sync');
1409 else if(st.globalSelectionSyncIsEligible()) {
1410 if(this.debug === true)
1411 st.log('sync: adding to sync as slave');
1413 st.globalSelectionSyncBeSlave();
1417 // this.globalSelectionSyncDelay(100);
1420 // can the chart participate to the global selection sync as a slave?
1421 this.globalSelectionSyncIsEligible = function() {
1422 if(this.enabled === true
1423 && this.library !== null
1424 && typeof this.library.setSelection === 'function'
1425 && this.isVisible() === true
1426 && this.chart_created === true)
1432 // this chart becomes a slave of the global selection sync
1433 this.globalSelectionSyncBeSlave = function() {
1434 if(NETDATA.globalSelectionSync.state !== this)
1435 NETDATA.globalSelectionSync.slaves.push(this);
1438 // sync all the visible charts to the given time
1439 // this is to be called from the chart libraries
1440 this.globalSelectionSync = function(t) {
1441 if(this.globalSelectionSyncAbility() === false) {
1442 if(this.debug === true)
1443 this.log('sync: cannot sync (yet?).');
1448 if(this.globalSelectionSyncIsMaster() === false) {
1449 if(this.debug === true)
1450 this.log('sync: trying to be sync master.');
1452 this.globalSelectionSyncBeMaster();
1454 if(this.globalSelectionSyncAbility() === false) {
1455 if(this.debug === true)
1456 this.log('sync: cannot sync (yet?).');
1462 NETDATA.globalSelectionSync.last_t = t;
1463 $.each(NETDATA.globalSelectionSync.slaves, function(i, st) {
1468 // stop syncing all charts to the given time
1469 this.globalSelectionSyncStop = function() {
1470 if(NETDATA.globalSelectionSync.slaves.length) {
1471 if(this.debug === true)
1472 this.log('sync: cleaning up...');
1474 $.each(NETDATA.globalSelectionSync.slaves, function(i, st) {
1476 if(that.debug === true)
1477 st.log('sync: not adding me to sync stop');
1480 if(that.debug === true)
1481 st.log('sync: removed slave from sync');
1483 st.clearSelection();
1487 NETDATA.globalSelectionSync.last_t = 0;
1488 NETDATA.globalSelectionSync.slaves = [];
1489 NETDATA.globalSelectionSync.state = null;
1492 this.clearSelection();
1495 this.setSelection = function(t) {
1496 if(typeof this.library.setSelection === 'function') {
1497 if(this.library.setSelection(this, t) === true)
1498 this.selected = true;
1500 this.selected = false;
1502 else this.selected = true;
1504 if(this.selected === true && this.debug === true)
1505 this.log('selection set to ' + t.toString());
1507 return this.selected;
1510 this.clearSelection = function() {
1511 if(this.selected === true) {
1512 if(typeof this.library.clearSelection === 'function') {
1513 if(this.library.clearSelection(this) === true)
1514 this.selected = false;
1516 this.selected = true;
1518 else this.selected = false;
1520 if(this.selected === false && this.debug === true)
1521 this.log('selection cleared');
1526 return this.selected;
1529 // find if a timestamp (ms) is shown in the current chart
1530 this.timeIsVisible = function(t) {
1531 if(t >= this.data_after && t <= this.data_before)
1536 this.calculateRowForTime = function(t) {
1537 if(this.timeIsVisible(t) === false) return -1;
1538 return Math.floor((t - this.data_after) / this.data_update_every);
1541 // ----------------------------------------------------------------------------------------------------------------
1544 this.log = function(msg) {
1545 console.log(this.id + ' (' + this.library_name + ' ' + this.uuid + '): ' + msg);
1548 this.pauseChart = function() {
1549 if(this.paused === false) {
1550 if(this.debug === true)
1557 this.unpauseChart = function() {
1559 if(this.debug === true)
1560 this.log('unpaused');
1562 this.paused = false;
1566 this.resetChart = function() {
1567 if(NETDATA.globalPanAndZoom.isMaster(this) && this.isVisible())
1568 NETDATA.globalPanAndZoom.clearMaster();
1570 this.tm.pan_and_zoom_seq = 0;
1572 this.clearSelection();
1574 this.setMode('auto');
1575 this.current.force_update_at = 0;
1576 this.current.force_before_ms = null;
1577 this.current.force_after_ms = null;
1578 this.tm.last_autorefreshed = 0;
1579 this.paused = false;
1580 this.selected = false;
1581 this.enabled = true;
1584 // do not update the chart here
1585 // or the chart will flip-flop when it is the master
1586 // of a selection sync and another chart becomes
1588 if(NETDATA.options.current.sync_pan_and_zoom === false && this.isVisible() === true)
1592 this.updateChartPanOrZoom = function(after, before) {
1593 if(before < after) return false;
1595 var min_duration = Math.round((this.chartWidth() / 30 * this.chart.update_every * 1000));
1597 if(this.debug === true)
1598 this.log('requested duration of ' + ((before - after) / 1000).toString() + ' (' + after + ' - ' + before + '), minimum ' + min_duration / 1000);
1600 if((before - after) < min_duration) return false;
1602 var current_duration = this.data_before - this.data_after;
1603 var wanted_duration = before - after;
1604 var tolerance = this.data_update_every * 2;
1605 var movement = Math.abs(before - this.data_before);
1607 if(this.debug === true)
1608 this.log('current duration: ' + current_duration / 1000 + ', wanted duration: ' + wanted_duration / 1000 + ', movement: ' + movement / 1000 + ', tolerance: ' + tolerance / 1000);
1610 if(Math.abs(current_duration - wanted_duration) <= tolerance && movement <= tolerance) {
1611 if(this.debug === true)
1612 this.log('IGNORED');
1617 if(this.current.name === 'auto') {
1618 this.setMode('pan');
1620 if(this.debug === true)
1621 this.log('updateChartPanOrZoom(): caller did not set proper mode');
1624 this.current.force_update_at = new Date().getTime() + NETDATA.options.current.pan_and_zoom_delay;
1625 this.current.force_after_ms = after;
1626 this.current.force_before_ms = before;
1627 NETDATA.globalPanAndZoom.setMaster(this, after, before);
1631 this.legendFormatValue = function(value) {
1632 if(value === null || value === 'undefined') return '-';
1633 if(typeof value !== 'number') return value;
1635 var abs = Math.abs(value);
1636 if(abs >= 1) return (Math.round(value * 100) / 100).toLocaleString();
1637 if(abs >= 0.1) return (Math.round(value * 1000) / 1000).toLocaleString();
1638 return (Math.round(value * 10000) / 10000).toLocaleString();
1641 this.legendSetLabelValue = function(label, value) {
1642 var series = this.element_legend_childs.series[label];
1643 if(typeof series === 'undefined') return;
1644 if(series.value === null && series.user === null) return;
1646 // if the value has not changed, skip DOM update
1647 //if(series.last === value) return;
1650 if(typeof value === 'number') {
1651 var v = Math.abs(value);
1652 s = r = this.legendFormatValue(value);
1654 if(typeof series.last === 'number') {
1655 if(v > series.last) s += '<i class="fa fa-angle-up" style="width: 8px; text-align: center; overflow: hidden; vertical-align: middle;"></i>';
1656 else if(v < series.last) s += '<i class="fa fa-angle-down" style="width: 8px; text-align: center; overflow: hidden; vertical-align: middle;"></i>';
1657 else s += '<i class="fa fa-angle-left" style="width: 8px; text-align: center; overflow: hidden; vertical-align: middle;"></i>';
1659 else s += '<i class="fa fa-angle-right" style="width: 8px; text-align: center; overflow: hidden; vertical-align: middle;"></i>';
1664 series.last = value;
1667 if(series.value !== null) series.value.innerHTML = s;
1668 if(series.user !== null) series.user.innerHTML = r;
1671 this.legendSetDate = function(ms) {
1672 if(typeof ms !== 'number') {
1673 this.legendShowUndefined();
1677 var d = new Date(ms);
1679 if(this.element_legend_childs.title_date)
1680 this.element_legend_childs.title_date.innerHTML = d.toLocaleDateString();
1682 if(this.element_legend_childs.title_time)
1683 this.element_legend_childs.title_time.innerHTML = d.toLocaleTimeString();
1685 if(this.element_legend_childs.title_units)
1686 this.element_legend_childs.title_units.innerHTML = this.chart.units;
1689 this.legendShowUndefined = function() {
1690 if(this.element_legend_childs.title_date)
1691 this.element_legend_childs.title_date.innerHTML = ' ';
1693 if(this.element_legend_childs.title_time)
1694 this.element_legend_childs.title_time.innerHTML = this.chart.name;
1696 if(this.element_legend_childs.title_units)
1697 this.element_legend_childs.title_units.innerHTML = ' ';
1699 if(this.data && this.element_legend_childs.series !== null) {
1700 var labels = this.data.dimension_names;
1701 var i = labels.length;
1703 var label = labels[i];
1705 if(typeof label === 'undefined') continue;
1706 if(typeof this.element_legend_childs.series[label] === 'undefined') continue;
1707 this.legendSetLabelValue(label, null);
1712 this.legendShowLatestValues = function() {
1713 if(this.chart === null) return;
1714 if(this.selected) return;
1716 if(this.data === null || this.element_legend_childs.series === null) {
1717 this.legendShowUndefined();
1721 var show_undefined = true;
1722 if(Math.abs(this.data.last_entry - this.data.before) <= this.data.view_update_every)
1723 show_undefined = false;
1725 if(show_undefined) {
1726 this.legendShowUndefined();
1730 this.legendSetDate(this.data.before * 1000);
1732 var labels = this.data.dimension_names;
1733 var i = labels.length;
1735 var label = labels[i];
1737 if(typeof label === 'undefined') continue;
1738 if(typeof this.element_legend_childs.series[label] === 'undefined') continue;
1741 this.legendSetLabelValue(label, null);
1743 this.legendSetLabelValue(label, this.data.view_latest_values[i]);
1747 this.legendReset = function() {
1748 this.legendShowLatestValues();
1751 // this should be called just ONCE per dimension per chart
1752 this._chartDimensionColor = function(label) {
1753 if(this.colors === null) this.chartColors();
1755 if(typeof this.colors_assigned[label] === 'undefined') {
1756 if(this.colors_available.length === 0) {
1757 for(var i = 0, len = NETDATA.colors.length; i < len ; i++)
1758 this.colors_available.push(NETDATA.colors[i]);
1761 this.colors_assigned[label] = this.colors_available.shift();
1763 if(this.debug === true)
1764 this.log('label "' + label + '" got color "' + this.colors_assigned[label]);
1767 if(this.debug === true)
1768 this.log('label "' + label + '" already has color "' + this.colors_assigned[label] + '"');
1771 this.colors.push(this.colors_assigned[label]);
1772 return this.colors_assigned[label];
1775 this.chartColors = function() {
1776 if(this.colors !== null) return this.colors;
1778 this.colors = new Array();
1779 this.colors_available = new Array();
1780 // this.colors_assigned = {};
1782 var c = $(this.element).data('colors');
1783 if(typeof c !== 'undefined' && c !== null) {
1784 if(typeof c !== 'string') {
1785 this.log('invalid color given: ' + c + ' (give a space separated list of colors)');
1789 for(var i = 0, len = c.length; i < len ; i++)
1790 this.colors_available.push(c[i]);
1794 // push all the standard colors too
1795 for(var i = 0, len = NETDATA.colors.length; i < len ; i++)
1796 this.colors_available.push(NETDATA.colors[i]);
1801 this.legendUpdateDOM = function() {
1804 // check that the legend DOM is up to date for the downloaded dimensions
1805 if(typeof this.element_legend_childs.series !== 'object' || this.element_legend_childs.series === null) {
1806 // this.log('the legend does not have any series - requesting legend update');
1809 else if(this.data === null) {
1810 // this.log('the chart does not have any data - requesting legend update');
1813 else if(typeof this.element_legend_childs.series.labels_key === 'undefined') {
1817 var labels = this.data.dimension_names.toString();
1818 if(labels !== this.element_legend_childs.series.labels_key) {
1821 if(this.debug === true)
1822 this.log('NEW LABELS: "' + labels + '" NOT EQUAL OLD LABELS: "' + this.element_legend_childs.series.labels_key + '"');
1826 if(needed === false) {
1827 // make sure colors available
1830 // do we have to update the current values?
1831 // we do this, only when the visible chart is current
1832 if(Math.abs(this.data.last_entry - this.data.before) <= this.data.view_update_every) {
1833 if(this.debug === true)
1834 this.log('chart in running... updating values on legend...');
1836 //var labels = this.data.dimension_names;
1837 //var i = labels.length;
1839 // this.legendSetLabelValue(labels[i], this.data.latest_values[i]);
1843 if(this.colors === null) {
1844 // this is the first time we update the chart
1845 // let's assign colors to all dimensions
1846 if(this.library.track_colors() === true)
1847 for(var dim in this.chart.dimensions)
1848 this._chartDimensionColor(this.chart.dimensions[dim].name);
1850 // we will re-generate the colors for the chart
1853 if(this.debug === true)
1854 this.log('updating Legend DOM');
1856 // mark all dimensions as invalid
1857 this.dimensions_visibility.invalidateAll();
1859 var genLabel = function(state, parent, name, count) {
1860 var color = state._chartDimensionColor(name);
1862 var user_element = null;
1863 var user_id = self.data('show-value-of-' + name + '-at') || null;
1864 if(user_id !== null) {
1865 user_element = document.getElementById(user_id) || null;
1866 if(user_element === null)
1867 me.log('Cannot find element with id: ' + user_id);
1870 state.element_legend_childs.series[name] = {
1871 name: document.createElement('span'),
1872 value: document.createElement('span'),
1877 var label = state.element_legend_childs.series[name];
1879 // create the dimension visibility tracking for this label
1880 var ds = state.dimensions_visibility.dimensionAdd(name, label.name, label.value, color);
1882 var rgb = NETDATA.colorHex2Rgb(color);
1883 label.name.innerHTML = '<table class="netdata-legend-name-table-'
1884 + state.chart.chart_type
1885 + '" style="background-color: '
1886 + 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + NETDATA.options.current['color_fill_opacity_' + state.chart.chart_type] + ')'
1887 + '"><tr class="netdata-legend-name-tr"><td class="netdata-legend-name-td"></td></tr></table>'
1889 var text = document.createTextNode(' ' + name);
1890 label.name.appendChild(text);
1893 parent.appendChild(document.createElement('br'));
1895 parent.appendChild(label.name);
1896 parent.appendChild(label.value);
1899 var content = document.createElement('div');
1901 if(this.hasLegend()) {
1902 this.element_legend_childs = {
1904 resize_handler: document.createElement('div'),
1905 title_date: document.createElement('span'),
1906 title_time: document.createElement('span'),
1907 title_units: document.createElement('span'),
1908 nano: document.createElement('div'),
1910 paneClass: 'netdata-legend-series-pane',
1911 sliderClass: 'netdata-legend-series-slider',
1912 contentClass: 'netdata-legend-series-content',
1913 enabledClass: '__enabled',
1914 flashedClass: '__flashed',
1915 activeClass: '__active',
1917 alwaysVisible: true,
1923 this.element_legend.innerHTML = '';
1925 this.element_legend_childs.resize_handler.className += " netdata-legend-resize-handler";
1926 this.element_legend_childs.resize_handler.innerHTML = '<i class="fa fa-chevron-up"></i><i class="fa fa-chevron-down"></i>';
1927 this.element.appendChild(this.element_legend_childs.resize_handler);
1930 this.element_legend_childs.resize_handler.onmousedown =
1932 that.resizeHandler(e);
1936 this.element_legend_childs.resize_handler.addEventListener('touchstart', function(e) {
1937 that.resizeHandler(e);
1940 this.element_legend_childs.title_date.className += " netdata-legend-title-date";
1941 this.element_legend.appendChild(this.element_legend_childs.title_date);
1943 this.element_legend.appendChild(document.createElement('br'));
1945 this.element_legend_childs.title_time.className += " netdata-legend-title-time";
1946 this.element_legend.appendChild(this.element_legend_childs.title_time);
1948 this.element_legend.appendChild(document.createElement('br'));
1950 this.element_legend_childs.title_units.className += " netdata-legend-title-units";
1951 this.element_legend.appendChild(this.element_legend_childs.title_units);
1953 this.element_legend.appendChild(document.createElement('br'));
1955 this.element_legend_childs.nano.className = 'netdata-legend-series';
1956 this.element_legend.appendChild(this.element_legend_childs.nano);
1958 content.className = 'netdata-legend-series-content';
1959 this.element_legend_childs.nano.appendChild(content);
1962 this.element_legend_childs = {
1964 resize_handler: null,
1975 this.element_legend_childs.series.labels_key = this.data.dimension_names.toString();
1976 if(this.debug === true)
1977 this.log('labels from data: "' + this.element_legend_childs.series.labels_key + '"');
1979 for(var i = 0, len = this.data.dimension_names.length; i < len ;i++) {
1980 genLabel(this, content, this.data.dimension_names[i], i);
1984 var tmp = new Array();
1985 for(var dim in this.chart.dimensions) {
1986 tmp.push(this.chart.dimensions[dim].name);
1987 genLabel(this, content, this.chart.dimensions[dim].name, i);
1989 this.element_legend_childs.series.labels_key = tmp.toString();
1990 if(this.debug === true)
1991 this.log('labels from chart: "' + this.element_legend_childs.series.labels_key + '"');
1994 // create a hidden div to be used for hidding
1995 // the original legend of the chart library
1996 var el = document.createElement('div');
1997 if(this.element_legend !== null)
1998 this.element_legend.appendChild(el);
1999 el.style.display = 'none';
2001 this.element_legend_childs.hidden = document.createElement('div');
2002 el.appendChild(this.element_legend_childs.hidden);
2004 if(this.element_legend_childs.nano !== null && this.element_legend_childs.nano_options !== null)
2005 $(this.element_legend_childs.nano).nanoScroller(this.element_legend_childs.nano_options);
2007 this.legendShowLatestValues();
2010 this.hasLegend = function() {
2011 if(typeof this.___hasLegendCache___ !== 'undefined')
2012 return this.___hasLegendCache___;
2015 if(this.library && this.library.legend(this) === 'right-side') {
2016 var legend = $(this.element).data('legend') || 'yes';
2017 if(legend === 'yes') leg = true;
2020 this.___hasLegendCache___ = leg;
2024 this.legendWidth = function() {
2025 return (this.hasLegend())?140:0;
2028 this.legendHeight = function() {
2029 return $(this.element).height();
2032 this.chartWidth = function() {
2033 return $(this.element).width() - this.legendWidth();
2036 this.chartHeight = function() {
2037 return $(this.element).height();
2040 this.chartPixelsPerPoint = function() {
2041 // force an options provided detail
2042 var px = this.pixels_per_point;
2044 if(this.library && px < this.library.pixels_per_point(this))
2045 px = this.library.pixels_per_point(this);
2047 if(px < NETDATA.options.current.pixels_per_point)
2048 px = NETDATA.options.current.pixels_per_point;
2053 this.needsRecreation = function() {
2055 this.chart_created === true
2057 && this.library.autoresize() === false
2058 && this.tm.last_resized < NETDATA.options.last_resized
2062 this.chartURL = function() {
2065 if(NETDATA.globalPanAndZoom.isActive()) {
2066 after = Math.round(NETDATA.globalPanAndZoom.force_after_ms / 1000);
2067 before = Math.round(NETDATA.globalPanAndZoom.force_before_ms / 1000);
2068 this.tm.pan_and_zoom_seq = NETDATA.globalPanAndZoom.seq;
2071 before = this.current.force_before_ms !== null ? Math.round(this.current.force_before_ms / 1000) : this.before;
2072 after = this.current.force_after_ms !== null ? Math.round(this.current.force_after_ms / 1000) : this.after;
2073 this.tm.pan_and_zoom_seq = 0;
2076 this.requested_after = after * 1000;
2077 this.requested_before = before * 1000;
2079 this.data_points = this.points || Math.round(this.chartWidth() / this.chartPixelsPerPoint());
2081 // build the data URL
2082 this.data_url = this.chart.data_url;
2083 this.data_url += "&format=" + this.library.format();
2084 this.data_url += "&points=" + this.data_points.toString();
2085 this.data_url += "&group=" + this.method;
2086 this.data_url += "&options=" + this.library.options();
2087 this.data_url += '|jsonwrap';
2089 if(NETDATA.options.current.eliminate_zero_dimensions === true)
2090 this.data_url += '|nonzero';
2093 this.data_url += "&after=" + after.toString();
2096 this.data_url += "&before=" + before.toString();
2099 this.data_url += "&dimensions=" + this.dimensions;
2101 if(NETDATA.options.debug.chart_data_url === true || this.debug === true)
2102 this.log('chartURL(): ' + this.data_url + ' WxH:' + this.chartWidth() + 'x' + this.chartHeight() + ' points: ' + this.data_points + ' library: ' + this.library_name);
2105 this.redrawChart = function() {
2106 if(this.data !== null)
2107 this.updateChartWithData(this.data);
2110 this.updateChartWithData = function(data) {
2111 if(this.debug === true)
2112 this.log('got data from netdata server');
2114 // this may force the chart to be re-created
2118 this.updates_counter++;
2120 var started = new Date().getTime();
2122 // if the result is JSON, find the latest update-every
2123 if(typeof data === 'object') {
2124 if(typeof data.view_update_every !== 'undefined')
2125 this.data_update_every = data.view_update_every * 1000;
2127 if(typeof data.after !== 'undefined')
2128 this.data_after = data.after * 1000;
2130 if(typeof data.before !== 'undefined')
2131 this.data_before = data.before * 1000;
2133 if(typeof data.first_entry !== 'undefined')
2134 this.netdata_first = data.first_entry * 1000;
2136 if(typeof data.last_entry !== 'undefined')
2137 this.netdata_last = data.last_entry * 1000;
2139 if(typeof data.points !== 'undefined')
2140 this.data_points = data.points;
2145 if(this.debug === true) {
2146 this.log('UPDATE No ' + this.updates_counter + ' COMPLETED');
2148 if(this.current.force_after_ms)
2149 this.log('STATUS: forced : ' + (this.current.force_after_ms / 1000).toString() + ' - ' + (this.current.force_before_ms / 1000).toString());
2151 this.log('STATUS: forced: unset');
2153 this.log('STATUS: requested: ' + (this.requested_after / 1000).toString() + ' - ' + (this.requested_before / 1000).toString());
2154 this.log('STATUS: rendered : ' + (this.data_after / 1000).toString() + ' - ' + (this.data_before / 1000).toString());
2155 this.log('STATUS: points : ' + (this.data_points).toString());
2158 if(this.data_points === 0) {
2163 if(this.updates_since_last_creation >= this.library.max_updates_to_recreate()) {
2164 if(this.debug === true)
2165 this.log('max updates of ' + this.updates_since_last_creation.toString() + ' reached. Forcing re-generation.');
2167 this.chart_created = false;
2170 // check and update the legend
2171 this.legendUpdateDOM();
2173 if(this.chart_created === true
2174 && typeof this.library.update === 'function') {
2176 if(this.debug === true)
2177 this.log('updating chart...');
2179 this.updates_since_last_creation++;
2180 if(NETDATA.options.debug.chart_errors === true) {
2181 this.library.update(this, data);
2185 this.library.update(this, data);
2188 error('chart failed to be updated as ' + this.library_name);
2193 if(this.debug === true)
2194 this.log('creating chart...');
2196 if(NETDATA.options.debug.chart_errors === true) {
2197 this.library.create(this, data);
2198 this.chart_created = true;
2199 this.updates_since_last_creation = 0;
2203 this.library.create(this, data);
2204 this.chart_created = true;
2205 this.updates_since_last_creation = 0;
2208 error('chart failed to be created as ' + this.library_name);
2213 this.legendShowLatestValues();
2214 NETDATA.globalSelectionSync.stop();
2216 // update the performance counters
2217 var now = new Date().getTime();
2218 this.tm.last_updated = now;
2220 // don't update last_autorefreshed if this chart is
2221 // forced to be updated with global PanAndZoom
2222 if(NETDATA.globalPanAndZoom.isActive())
2223 this.tm.last_autorefreshed = 0;
2225 if(NETDATA.options.current.parallel_refresher === true && NETDATA.options.current.concurrent_refreshes)
2226 this.tm.last_autorefreshed = Math.round(now / this.data_update_every) * this.data_update_every;
2228 this.tm.last_autorefreshed = now;
2231 this.refresh_dt_ms = now - started;
2232 NETDATA.options.auto_refresher_fast_weight += this.refresh_dt_ms;
2234 if(this.refresh_dt_element !== null)
2235 this.refresh_dt_element.innerHTML = this.refresh_dt_ms.toString();
2238 this.updateChart = function(callback) {
2239 // due to late initialization of charts and libraries
2240 // we need to check this too
2241 if(this.enabled === false) {
2242 if(this.debug === true)
2243 this.log('I am not enabled');
2245 if(typeof callback === 'function') callback();
2249 if(this.chart === null) {
2250 this.getChart(function() { that.updateChart(callback); });
2254 if(this.library.initialized === false) {
2255 if(this.library.enabled === true) {
2256 this.library.initialize(function() { that.updateChart(callback); });
2260 error('chart library "' + this.library_name + '" is not available.');
2261 if(typeof callback === 'function') callback();
2266 this.clearSelection();
2269 if(this.debug === true)
2270 this.log('updating from ' + this.data_url);
2272 this.xhr = $.ajax( {
2274 crossDomain: NETDATA.options.crossDomainAjax,
2278 .success(function(data) {
2279 if(that.debug === true)
2280 that.log('data received. updating chart.');
2282 that.updateChartWithData(data);
2285 error('data download failed for url: ' + that.data_url);
2287 .always(function() {
2288 if(typeof callback === 'function') callback();
2292 this.isVisible = function() {
2293 // this.log('last_visible_check: ' + this.tm.last_visible_check + ', last_page_scroll: ' + NETDATA.options.last_page_scroll);
2295 // caching - we do not evaluate the charts visibility
2296 // if the page has not been scrolled since the last check
2297 if(this.tm.last_visible_check > NETDATA.options.last_page_scroll) {
2298 if(this.debug === true)
2299 this.log('isVisible: ' + this.___isVisible___);
2301 return this.___isVisible___;
2304 this.tm.last_visible_check = new Date().getTime();
2306 var wh = window.innerHeight;
2307 var x = this.element.getBoundingClientRect();
2311 if(x.top < 0 && -x.top > x.height) {
2312 // the chart is entirely above
2313 ret = -x.top - x.height;
2315 else if(x.top > wh) {
2316 // the chart is entirely below
2320 if(ret > tolerance) {
2321 // the chart is too far
2324 this.___isVisible___ = false;
2326 if(this.debug === true)
2327 this.log('isVisible: ' + this.___isVisible___);
2329 return this.___isVisible___;
2332 // the chart is inside or very close
2335 this.___isVisible___ = true;
2337 if(this.debug === true)
2338 this.log('isVisible: ' + this.___isVisible___);
2340 return this.___isVisible___;
2344 this.isAutoRefreshed = function() {
2345 return (this.current.autorefresh);
2348 this.canBeAutoRefreshed = function() {
2349 now = new Date().getTime();
2351 if(this.enabled === false) {
2352 if(this.debug === true)
2353 this.log('I am not enabled');
2358 if(this.library === null || this.library.enabled === false) {
2359 error('charting library "' + this.library_name + '" is not available');
2360 if(this.debug === true)
2361 this.log('My chart library ' + this.library_name + ' is not available');
2366 if(this.isVisible() === false) {
2367 if(NETDATA.options.debug.visibility === true || this.debug === true)
2368 this.log('I am not visible');
2373 if(this.current.force_update_at !== 0 && this.current.force_update_at < now) {
2374 if(this.debug === true)
2375 this.log('timed force update detected - allowing this update');
2377 this.current.force_update_at = 0;
2381 if(this.isAutoRefreshed() === true) {
2382 // allow the first update, even if the page is not visible
2383 if(this.updates_counter && NETDATA.options.page_is_visible === false) {
2384 if(NETDATA.options.debug.focus === true || this.debug === true)
2385 this.log('canBeAutoRefreshed(): page does not have focus');
2390 if(this.needsRecreation() === true) {
2391 if(this.debug === true)
2392 this.log('canBeAutoRefreshed(): needs re-creation.');
2397 // options valid only for autoRefresh()
2398 if(NETDATA.options.auto_refresher_stop_until === 0 || NETDATA.options.auto_refresher_stop_until < now) {
2399 if(NETDATA.globalPanAndZoom.isActive()) {
2400 if(NETDATA.globalPanAndZoom.shouldBeAutoRefreshed(this)) {
2401 if(this.debug === true)
2402 this.log('canBeAutoRefreshed(): global panning: I need an update.');
2407 if(this.debug === true)
2408 this.log('canBeAutoRefreshed(): global panning: I am already up to date.');
2414 if(this.selected === true) {
2415 if(this.debug === true)
2416 this.log('canBeAutoRefreshed(): I have a selection in place.');
2421 if(this.paused === true) {
2422 if(this.debug === true)
2423 this.log('canBeAutoRefreshed(): I am paused.');
2428 if(now - this.tm.last_autorefreshed >= this.data_update_every) {
2429 if(this.debug === true)
2430 this.log('canBeAutoRefreshed(): It is time to update me.');
2440 this.autoRefresh = function(callback) {
2441 if(this.canBeAutoRefreshed() === true) {
2442 this.updateChart(callback);
2445 if(typeof callback !== 'undefined')
2450 this._defaultsFromDownloadedChart = function(chart) {
2452 this.chart_url = chart.url;
2453 this.data_update_every = chart.update_every * 1000;
2454 this.data_points = Math.round(this.chartWidth() / this.chartPixelsPerPoint());
2455 this.tm.last_info_downloaded = new Date().getTime();
2458 // fetch the chart description from the netdata server
2459 this.getChart = function(callback) {
2460 this.chart = NETDATA.chartRegistry.get(this.host, this.id);
2462 this._defaultsFromDownloadedChart(this.chart);
2463 if(typeof callback === 'function') callback();
2466 this.chart_url = this.host + "/api/v1/chart?chart=" + this.id;
2468 if(this.debug === true)
2469 this.log('downloading ' + this.chart_url);
2472 url: this.chart_url,
2473 crossDomain: NETDATA.options.crossDomainAjax,
2477 .done(function(chart) {
2478 chart.url = that.chart_url;
2479 chart.data_url = (that.host + chart.data_url);
2480 that._defaultsFromDownloadedChart(chart);
2481 NETDATA.chartRegistry.add(that.host, that.id, chart);
2484 NETDATA.error(404, that.chart_url);
2485 error('chart not found on url "' + that.chart_url + '"');
2487 .always(function() {
2488 if(typeof callback === 'function') callback();
2493 // ============================================================================================================
2499 // get or create a chart state, given a DOM element
2500 NETDATA.chartState = function(element) {
2501 var state = $(element).data('netdata-state-object') || null;
2502 if(state === null) {
2503 state = new chartState(element);
2504 $(element).data('netdata-state-object', state);
2509 // ----------------------------------------------------------------------------------------------------------------
2510 // Library functions
2512 // Load a script without jquery
2513 // This is used to load jquery - after it is loaded, we use jquery
2514 NETDATA._loadjQuery = function(callback) {
2515 if(typeof jQuery === 'undefined') {
2516 if(NETDATA.options.debug.main_loop === true)
2517 console.log('loading ' + NETDATA.jQuery);
2519 var script = document.createElement('script');
2520 script.type = 'text/javascript';
2521 script.async = true;
2522 script.src = NETDATA.jQuery;
2524 // script.onabort = onError;
2525 script.onerror = function(err, t) { NETDATA.error(101, NETDATA.jQuery); };
2526 if(typeof callback === "function")
2527 script.onload = callback;
2529 var s = document.getElementsByTagName('script')[0];
2530 s.parentNode.insertBefore(script, s);
2532 else if(typeof callback === "function")
2536 NETDATA._loadCSS = function(filename) {
2537 // don't use jQuery here
2538 // styles are loaded before jQuery
2539 // to eliminate showing an unstyled page to the user
2541 var fileref = document.createElement("link");
2542 fileref.setAttribute("rel", "stylesheet");
2543 fileref.setAttribute("type", "text/css");
2544 fileref.setAttribute("href", filename);
2546 if (typeof fileref !== 'undefined')
2547 document.getElementsByTagName("head")[0].appendChild(fileref);
2550 NETDATA.colorHex2Rgb = function(hex) {
2551 // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
2552 var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
2553 hex = hex.replace(shorthandRegex, function(m, r, g, b) {
2554 return r + r + g + g + b + b;
2557 var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
2559 r: parseInt(result[1], 16),
2560 g: parseInt(result[2], 16),
2561 b: parseInt(result[3], 16)
2565 NETDATA.colorLuminance = function(hex, lum) {
2566 // validate hex string
2567 hex = String(hex).replace(/[^0-9a-f]/gi, '');
2569 hex = hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2];
2573 // convert to decimal and change luminosity
2574 var rgb = "#", c, i;
2575 for (i = 0; i < 3; i++) {
2576 c = parseInt(hex.substr(i*2,2), 16);
2577 c = Math.round(Math.min(Math.max(0, c + (c * lum)), 255)).toString(16);
2578 rgb += ("00"+c).substr(c.length);
2584 NETDATA.guid = function() {
2586 return Math.floor((1 + Math.random()) * 0x10000)
2591 return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
2594 NETDATA.zeropad = function(x) {
2595 if(x > -10 && x < 10) return '0' + x.toString();
2596 else return x.toString();
2599 // user function to signal us the DOM has been
2601 NETDATA.updatedDom = function() {
2602 NETDATA.options.updated_dom = true;
2605 NETDATA.ready = function(callback) {
2606 NETDATA.options.readyCallback = callback;
2609 NETDATA.pause = function(callback) {
2610 NETDATA.options.pauseCallback = callback;
2613 NETDATA.unpause = function() {
2614 NETDATA.options.pauseCallback = null;
2615 NETDATA.options.updated_dom = true;
2616 NETDATA.options.pause = false;
2619 // ----------------------------------------------------------------------------------------------------------------
2621 // this is purely sequencial charts refresher
2622 // it is meant to be autonomous
2623 NETDATA.chartRefresherNoParallel = function(index) {
2624 if(NETDATA.options.debug.mail_loop === true)
2625 console.log('NETDATA.chartRefresherNoParallel(' + index + ')');
2627 if(NETDATA.options.updated_dom === true) {
2628 // the dom has been updated
2629 // get the dom parts again
2630 NETDATA.parseDom(NETDATA.chartRefresher);
2633 if(index >= NETDATA.options.targets.length) {
2634 if(NETDATA.options.debug.main_loop === true)
2635 console.log('waiting to restart main loop...');
2637 NETDATA.options.auto_refresher_fast_weight = 0;
2639 setTimeout(function() {
2640 NETDATA.chartRefresher();
2641 }, NETDATA.options.current.idle_between_loops);
2644 var state = NETDATA.options.targets[index];
2646 if(NETDATA.options.auto_refresher_fast_weight < NETDATA.options.current.fast_render_timeframe) {
2647 if(NETDATA.options.debug.main_loop === true)
2648 console.log('fast rendering...');
2650 state.autoRefresh(function() {
2651 NETDATA.chartRefresherNoParallel(++index);
2655 if(NETDATA.options.debug.main_loop === true) console.log('waiting for next refresh...');
2656 NETDATA.options.auto_refresher_fast_weight = 0;
2658 setTimeout(function() {
2659 state.autoRefresh(function() {
2660 NETDATA.chartRefresherNoParallel(++index);
2662 }, NETDATA.options.current.idle_between_charts);
2667 // this is part of the parallel refresher
2668 // its cause is to refresh sequencially all the charts
2669 // that depend on chart library initialization
2670 // it will call the parallel refresher back
2671 // as soon as it sees a chart that its chart library
2673 NETDATA.chartRefresher_unitialized = function() {
2674 if(NETDATA.options.updated_dom === true) {
2675 // the dom has been updated
2676 // get the dom parts again
2677 NETDATA.parseDom(NETDATA.chartRefresher);
2681 if(NETDATA.options.sequencial.length === 0)
2682 NETDATA.chartRefresher();
2684 var state = NETDATA.options.sequencial.pop();
2685 if(state.library.initialized === true)
2686 NETDATA.chartRefresher();
2688 state.autoRefresh(NETDATA.chartRefresher_unitialized);
2692 NETDATA.chartRefresherWaitTime = function() {
2693 return NETDATA.options.current.idle_parallel_loops;
2696 // the default refresher
2697 // it will create 2 sets of charts:
2698 // - the ones that can be refreshed in parallel
2699 // - the ones that depend on something else
2700 // the first set will be executed in parallel
2701 // the second will be given to NETDATA.chartRefresher_unitialized()
2702 NETDATA.chartRefresher = function() {
2703 if(NETDATA.options.pause === true) {
2704 // console.log('auto-refresher is paused');
2705 setTimeout(NETDATA.chartRefresher,
2706 NETDATA.chartRefresherWaitTime());
2710 if(typeof NETDATA.options.pauseCallback === 'function') {
2711 // console.log('auto-refresher is calling pauseCallback');
2712 NETDATA.options.pause = true;
2713 NETDATA.options.pauseCallback();
2714 NETDATA.chartRefresher();
2718 if(NETDATA.options.current.parallel_refresher === false) {
2719 NETDATA.chartRefresherNoParallel(0);
2723 if(NETDATA.options.updated_dom === true) {
2724 // the dom has been updated
2725 // get the dom parts again
2726 NETDATA.parseDom(NETDATA.chartRefresher);
2730 var parallel = new Array();
2731 var targets = NETDATA.options.targets;
2732 var len = targets.length;
2734 if(targets[len].isVisible() === false)
2737 var state = targets[len];
2738 if(state.library.initialized === false) {
2739 if(state.library.enabled === true) {
2740 state.library.initialize(NETDATA.chartRefresher);
2744 state.error('chart library "' + state.library_name + '" is not enabled.');
2748 parallel.unshift(state);
2751 if(parallel.length > 0) {
2752 var parallel_jobs = parallel.length;
2754 // this will execute the jobs in parallel
2755 $(parallel).each(function() {
2756 this.autoRefresh(function() {
2759 if(parallel_jobs === 0) {
2760 setTimeout(NETDATA.chartRefresher,
2761 NETDATA.chartRefresherWaitTime());
2767 setTimeout(NETDATA.chartRefresher,
2768 NETDATA.chartRefresherWaitTime());
2772 NETDATA.parseDom = function(callback) {
2773 NETDATA.options.last_page_scroll = new Date().getTime();
2774 NETDATA.options.updated_dom = false;
2776 var targets = $('div[data-netdata]').filter(':visible');
2778 if(NETDATA.options.debug.main_loop === true)
2779 console.log('DOM updated - there are ' + targets.length + ' charts on page.');
2781 NETDATA.options.targets = new Array();
2782 var len = targets.length;
2784 // the initialization will take care of sizing
2785 // and the "loading..." message
2786 NETDATA.options.targets.push(NETDATA.chartState(targets[len]));
2789 if(typeof callback === 'function') callback();
2792 // this is the main function - where everything starts
2793 NETDATA.start = function() {
2794 // this should be called only once
2796 NETDATA.options.page_is_visible = true;
2798 $(window).blur(function() {
2799 if(NETDATA.options.current.stop_updates_when_focus_is_lost === true) {
2800 NETDATA.options.page_is_visible = false;
2801 if(NETDATA.options.debug.focus === true)
2802 console.log('Lost Focus!');
2806 $(window).focus(function() {
2807 if(NETDATA.options.current.stop_updates_when_focus_is_lost === true) {
2808 NETDATA.options.page_is_visible = true;
2809 if(NETDATA.options.debug.focus === true)
2810 console.log('Focus restored!');
2814 if(typeof document.hasFocus === 'function' && !document.hasFocus()) {
2815 if(NETDATA.options.current.stop_updates_when_focus_is_lost === true) {
2816 NETDATA.options.page_is_visible = false;
2817 if(NETDATA.options.debug.focus === true)
2818 console.log('Document has no focus!');
2822 NETDATA.parseDom(NETDATA.chartRefresher);
2825 // ----------------------------------------------------------------------------------------------------------------
2828 NETDATA.peityInitialize = function(callback) {
2829 if(typeof netdataNoPeitys === 'undefined' || !netdataNoPeitys) {
2831 url: NETDATA.peity_js,
2836 NETDATA.registerChartLibrary('peity', NETDATA.peity_js);
2839 NETDATA.chartLibraries.peity.enabled = false;
2840 NETDATA.error(100, NETDATA.peity_js);
2842 .always(function() {
2843 if(typeof callback === "function")
2848 NETDATA.chartLibraries.peity.enabled = false;
2849 if(typeof callback === "function")
2854 NETDATA.peityChartUpdate = function(state, data) {
2855 state.peity_instance.innerHTML = data.result;
2857 if(state.peity_options.stroke !== state.chartColors()[0]) {
2858 state.peity_options.stroke = state.chartColors()[0];
2859 if(state.chart.chart_type === 'line')
2860 state.peity_options.fill = '#FFF';
2862 state.peity_options.fill = NETDATA.colorLuminance(state.chartColors()[0], NETDATA.chartDefaults.fill_luminance);
2865 $(state.peity_instance).peity('line', state.peity_options);
2868 NETDATA.peityChartCreate = function(state, data) {
2869 state.peity_instance = document.createElement('div');
2870 state.element_chart.appendChild(state.peity_instance);
2872 var self = $(state.element);
2873 state.peity_options = {
2875 strokeWidth: self.data('peity-strokewidth') || 1,
2876 width: state.chartWidth(),
2877 height: state.chartHeight(),
2881 NETDATA.peityChartUpdate(state, data);
2884 // ----------------------------------------------------------------------------------------------------------------
2887 NETDATA.sparklineInitialize = function(callback) {
2888 if(typeof netdataNoSparklines === 'undefined' || !netdataNoSparklines) {
2890 url: NETDATA.sparkline_js,
2895 NETDATA.registerChartLibrary('sparkline', NETDATA.sparkline_js);
2898 NETDATA.chartLibraries.sparkline.enabled = false;
2899 NETDATA.error(100, NETDATA.sparkline_js);
2901 .always(function() {
2902 if(typeof callback === "function")
2907 NETDATA.chartLibraries.sparkline.enabled = false;
2908 if(typeof callback === "function")
2913 NETDATA.sparklineChartUpdate = function(state, data) {
2914 state.sparkline_options.width = state.chartWidth();
2915 state.sparkline_options.height = state.chartHeight();
2917 $(state.element_chart).sparkline(data.result, state.sparkline_options);
2920 NETDATA.sparklineChartCreate = function(state, data) {
2921 var self = $(state.element);
2922 var type = self.data('sparkline-type') || 'line';
2923 var lineColor = self.data('sparkline-linecolor') || state.chartColors()[0];
2924 var fillColor = self.data('sparkline-fillcolor') || (state.chart.chart_type === 'line')?'#FFF':NETDATA.colorLuminance(lineColor, NETDATA.chartDefaults.fill_luminance);
2925 var chartRangeMin = self.data('sparkline-chartrangemin') || undefined;
2926 var chartRangeMax = self.data('sparkline-chartrangemax') || undefined;
2927 var composite = self.data('sparkline-composite') || undefined;
2928 var enableTagOptions = self.data('sparkline-enabletagoptions') || undefined;
2929 var tagOptionPrefix = self.data('sparkline-tagoptionprefix') || undefined;
2930 var tagValuesAttribute = self.data('sparkline-tagvaluesattribute') || undefined;
2931 var disableHiddenCheck = self.data('sparkline-disablehiddencheck') || undefined;
2932 var defaultPixelsPerValue = self.data('sparkline-defaultpixelspervalue') || undefined;
2933 var spotColor = self.data('sparkline-spotcolor') || undefined;
2934 var minSpotColor = self.data('sparkline-minspotcolor') || undefined;
2935 var maxSpotColor = self.data('sparkline-maxspotcolor') || undefined;
2936 var spotRadius = self.data('sparkline-spotradius') || undefined;
2937 var valueSpots = self.data('sparkline-valuespots') || undefined;
2938 var highlightSpotColor = self.data('sparkline-highlightspotcolor') || undefined;
2939 var highlightLineColor = self.data('sparkline-highlightlinecolor') || undefined;
2940 var lineWidth = self.data('sparkline-linewidth') || undefined;
2941 var normalRangeMin = self.data('sparkline-normalrangemin') || undefined;
2942 var normalRangeMax = self.data('sparkline-normalrangemax') || undefined;
2943 var drawNormalOnTop = self.data('sparkline-drawnormalontop') || undefined;
2944 var xvalues = self.data('sparkline-xvalues') || undefined;
2945 var chartRangeClip = self.data('sparkline-chartrangeclip') || undefined;
2946 var xvalues = self.data('sparkline-xvalues') || undefined;
2947 var chartRangeMinX = self.data('sparkline-chartrangeminx') || undefined;
2948 var chartRangeMaxX = self.data('sparkline-chartrangemaxx') || undefined;
2949 var disableInteraction = self.data('sparkline-disableinteraction') || false;
2950 var disableTooltips = self.data('sparkline-disabletooltips') || false;
2951 var disableHighlight = self.data('sparkline-disablehighlight') || false;
2952 var highlightLighten = self.data('sparkline-highlightlighten') || 1.4;
2953 var highlightColor = self.data('sparkline-highlightcolor') || undefined;
2954 var tooltipContainer = self.data('sparkline-tooltipcontainer') || undefined;
2955 var tooltipClassname = self.data('sparkline-tooltipclassname') || undefined;
2956 var tooltipFormat = self.data('sparkline-tooltipformat') || undefined;
2957 var tooltipPrefix = self.data('sparkline-tooltipprefix') || undefined;
2958 var tooltipSuffix = self.data('sparkline-tooltipsuffix') || ' ' + state.chart.units;
2959 var tooltipSkipNull = self.data('sparkline-tooltipskipnull') || true;
2960 var tooltipValueLookups = self.data('sparkline-tooltipvaluelookups') || undefined;
2961 var tooltipFormatFieldlist = self.data('sparkline-tooltipformatfieldlist') || undefined;
2962 var tooltipFormatFieldlistKey = self.data('sparkline-tooltipformatfieldlistkey') || undefined;
2963 var numberFormatter = self.data('sparkline-numberformatter') || function(n){ return n.toFixed(2); };
2964 var numberDigitGroupSep = self.data('sparkline-numberdigitgroupsep') || undefined;
2965 var numberDecimalMark = self.data('sparkline-numberdecimalmark') || undefined;
2966 var numberDigitGroupCount = self.data('sparkline-numberdigitgroupcount') || undefined;
2967 var animatedZooms = self.data('sparkline-animatedzooms') || false;
2969 state.sparkline_options = {
2971 lineColor: lineColor,
2972 fillColor: fillColor,
2973 chartRangeMin: chartRangeMin,
2974 chartRangeMax: chartRangeMax,
2975 composite: composite,
2976 enableTagOptions: enableTagOptions,
2977 tagOptionPrefix: tagOptionPrefix,
2978 tagValuesAttribute: tagValuesAttribute,
2979 disableHiddenCheck: disableHiddenCheck,
2980 defaultPixelsPerValue: defaultPixelsPerValue,
2981 spotColor: spotColor,
2982 minSpotColor: minSpotColor,
2983 maxSpotColor: maxSpotColor,
2984 spotRadius: spotRadius,
2985 valueSpots: valueSpots,
2986 highlightSpotColor: highlightSpotColor,
2987 highlightLineColor: highlightLineColor,
2988 lineWidth: lineWidth,
2989 normalRangeMin: normalRangeMin,
2990 normalRangeMax: normalRangeMax,
2991 drawNormalOnTop: drawNormalOnTop,
2993 chartRangeClip: chartRangeClip,
2994 chartRangeMinX: chartRangeMinX,
2995 chartRangeMaxX: chartRangeMaxX,
2996 disableInteraction: disableInteraction,
2997 disableTooltips: disableTooltips,
2998 disableHighlight: disableHighlight,
2999 highlightLighten: highlightLighten,
3000 highlightColor: highlightColor,
3001 tooltipContainer: tooltipContainer,
3002 tooltipClassname: tooltipClassname,
3003 tooltipChartTitle: state.chart.title,
3004 tooltipFormat: tooltipFormat,
3005 tooltipPrefix: tooltipPrefix,
3006 tooltipSuffix: tooltipSuffix,
3007 tooltipSkipNull: tooltipSkipNull,
3008 tooltipValueLookups: tooltipValueLookups,
3009 tooltipFormatFieldlist: tooltipFormatFieldlist,
3010 tooltipFormatFieldlistKey: tooltipFormatFieldlistKey,
3011 numberFormatter: numberFormatter,
3012 numberDigitGroupSep: numberDigitGroupSep,
3013 numberDecimalMark: numberDecimalMark,
3014 numberDigitGroupCount: numberDigitGroupCount,
3015 animatedZooms: animatedZooms,
3016 width: state.chartWidth(),
3017 height: state.chartHeight()
3020 $(state.element_chart).sparkline(data.result, state.sparkline_options);
3023 // ----------------------------------------------------------------------------------------------------------------
3030 NETDATA.dygraphSetSelection = function(state, t) {
3031 if(typeof state.dygraph_instance !== 'undefined') {
3032 var r = state.calculateRowForTime(t);
3034 state.dygraph_instance.setSelection(r);
3036 state.dygraph_instance.clearSelection();
3037 state.legendShowUndefined();
3044 NETDATA.dygraphClearSelection = function(state, t) {
3045 if(typeof state.dygraph_instance !== 'undefined') {
3046 state.dygraph_instance.clearSelection();
3051 NETDATA.dygraphSmoothInitialize = function(callback) {
3053 url: NETDATA.dygraph_smooth_js,
3058 NETDATA.dygraph.smooth = true;
3059 smoothPlotter.smoothing = 0.3;
3062 NETDATA.dygraph.smooth = false;
3064 .always(function() {
3065 if(typeof callback === "function")
3070 NETDATA.dygraphInitialize = function(callback) {
3071 if(typeof netdataNoDygraphs === 'undefined' || !netdataNoDygraphs) {
3073 url: NETDATA.dygraph_js,
3078 NETDATA.registerChartLibrary('dygraph', NETDATA.dygraph_js);
3081 NETDATA.chartLibraries.dygraph.enabled = false;
3082 NETDATA.error(100, NETDATA.dygraph_js);
3084 .always(function() {
3085 if(NETDATA.chartLibraries.dygraph.enabled === true && NETDATA.options.current.smooth_plot === true)
3086 NETDATA.dygraphSmoothInitialize(callback);
3087 else if(typeof callback === "function")
3092 NETDATA.chartLibraries.dygraph.enabled = false;
3093 if(typeof callback === "function")
3098 NETDATA.dygraphChartUpdate = function(state, data) {
3099 var dygraph = state.dygraph_instance;
3101 if(typeof dygraph === 'undefined')
3102 NETDATA.dygraphChartCreate(state, data);
3104 // when the chart is not visible, and hidden
3105 // if there is a window resize, dygraph detects
3106 // its element size as 0x0.
3107 // this will make it re-appear properly
3109 if(state.tm.last_unhidden > state.dygraph_last_rendered)
3113 file: data.result.data,
3114 colors: state.chartColors(),
3115 labels: data.result.labels,
3116 labelsDivWidth: state.chartWidth() - 70,
3117 visibility: state.dimensions_visibility.selected2BooleanArray(state.data.dimension_names)
3120 if(state.current.name === 'pan') {
3121 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3122 state.log('dygraphChartUpdate() loose update');
3125 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3126 state.log('dygraphChartUpdate() strict update');
3128 options.dateWindow = null;
3129 options.valueRange = null;
3132 if(state.dygraph_smooth_eligible === true) {
3133 if((NETDATA.options.current.smooth_plot === true && state.dygraph_options.plotter !== smoothPlotter)
3134 || (NETDATA.options.current.smooth_plot === false && state.dygraph_options.plotter === smoothPlotter)) {
3135 NETDATA.dygraphChartCreate(state, data);
3140 dygraph.updateOptions(options);
3141 state.dygraph_last_rendered = new Date().getTime();
3144 NETDATA.dygraphChartCreate = function(state, data) {
3145 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3146 state.log('dygraphChartCreate()');
3148 var self = $(state.element);
3150 var chart_type = state.chart.chart_type;
3151 if(chart_type === 'stacked' && data.dimensions === 1) chart_type = 'area';
3152 chart_type = self.data('dygraph-type') || chart_type;
3154 var smooth = (chart_type === 'line' && !NETDATA.chartLibraries.dygraph.isSparkline(state))?true:false;
3155 smooth = self.data('dygraph-smooth') || smooth;
3157 if(NETDATA.dygraph.smooth === false)
3160 var strokeWidth = (chart_type === 'stacked')?0.1:((smooth)?1.5:0.7)
3161 var highlightCircleSize = (NETDATA.chartLibraries.dygraph.isSparkline(state))?3:4;
3163 state.dygraph_options = {
3164 colors: self.data('dygraph-colors') || state.chartColors(),
3166 // leave a few pixels empty on the right of the chart
3167 rightGap: self.data('dygraph-rightgap') || 5,
3168 showRangeSelector: self.data('dygraph-showrangeselector') || false,
3169 showRoller: self.data('dygraph-showroller') || false,
3171 title: self.data('dygraph-title') || state.chart.title,
3172 titleHeight: self.data('dygraph-titleheight') || 19,
3174 legend: self.data('dygraph-legend') || 'always', // 'onmouseover',
3175 labels: data.result.labels,
3176 labelsDiv: self.data('dygraph-labelsdiv') || state.element_legend_childs.hidden,
3177 labelsDivStyles: self.data('dygraph-labelsdivstyles') || { 'fontSize':'1px' },
3178 labelsDivWidth: self.data('dygraph-labelsdivwidth') || state.chartWidth() - 70,
3179 labelsSeparateLines: self.data('dygraph-labelsseparatelines') || true,
3180 labelsShowZeroValues: self.data('dygraph-labelsshowzerovalues') || true,
3183 showLabelsOnHighlight: self.data('dygraph-showlabelsonhighlight') || true,
3184 hideOverlayOnMouseOut: self.data('dygraph-hideoverlayonmouseout') || true,
3186 ylabel: state.chart.units,
3187 yLabelWidth: self.data('dygraph-ylabelwidth') || 12,
3189 // the function to plot the chart
3192 // The width of the lines connecting data points. This can be used to increase the contrast or some graphs.
3193 strokeWidth: self.data('dygraph-strokewidth') || strokeWidth,
3194 strokePattern: self.data('dygraph-strokepattern') || undefined,
3196 // The size of the dot to draw on each point in pixels (see drawPoints). A dot is always drawn when a point is "isolated",
3197 // i.e. there is a missing point on either side of it. This also controls the size of those dots.
3198 drawPoints: self.data('dygraph-drawpoints') || false,
3200 // Draw points at the edges of gaps in the data. This improves visibility of small data segments or other data irregularities.
3201 drawGapEdgePoints: self.data('dygraph-drawgapedgepoints') || true,
3203 connectSeparatedPoints: self.data('dygraph-connectseparatedpoints') || false,
3204 pointSize: self.data('dygraph-pointsize') || 1,
3206 // enabling this makes the chart with little square lines
3207 stepPlot: self.data('dygraph-stepplot') || false,
3209 // Draw a border around graph lines to make crossing lines more easily distinguishable. Useful for graphs with many lines.
3210 strokeBorderColor: self.data('dygraph-strokebordercolor') || 'white',
3211 strokeBorderWidth: self.data('dygraph-strokeborderwidth') || (chart_type === 'stacked')?0.0:0.0,
3213 fillGraph: self.data('dygraph-fillgraph') || (chart_type === 'area' || chart_type === 'stacked')?true:false,
3214 fillAlpha: self.data('dygraph-fillalpha') || (chart_type === 'stacked')?NETDATA.options.current.color_fill_opacity_stacked:NETDATA.options.current.color_fill_opacity_area,
3215 stackedGraph: self.data('dygraph-stackedgraph') || (chart_type === 'stacked')?true:false,
3216 stackedGraphNaNFill: self.data('dygraph-stackedgraphnanfill') || 'none',
3218 drawAxis: self.data('dygraph-drawaxis') || true,
3219 axisLabelFontSize: self.data('dygraph-axislabelfontsize') || 10,
3220 axisLineColor: self.data('dygraph-axislinecolor') || '#CCC',
3221 axisLineWidth: self.data('dygraph-axislinewidth') || 0.3,
3223 drawGrid: self.data('dygraph-drawgrid') || true,
3224 drawXGrid: self.data('dygraph-drawxgrid') || undefined,
3225 drawYGrid: self.data('dygraph-drawygrid') || undefined,
3226 gridLinePattern: self.data('dygraph-gridlinepattern') || null,
3227 gridLineWidth: self.data('dygraph-gridlinewidth') || 0.3,
3228 gridLineColor: self.data('dygraph-gridlinecolor') || '#DDD',
3230 maxNumberWidth: self.data('dygraph-maxnumberwidth') || 8,
3231 sigFigs: self.data('dygraph-sigfigs') || null,
3232 digitsAfterDecimal: self.data('dygraph-digitsafterdecimal') || 2,
3233 valueFormatter: self.data('dygraph-valueformatter') || function(x){ return x.toFixed(2); },
3235 highlightCircleSize: self.data('dygraph-highlightcirclesize') || highlightCircleSize,
3236 highlightSeriesOpts: self.data('dygraph-highlightseriesopts') || null, // TOO SLOW: { strokeWidth: 1.5 },
3237 highlightSeriesBackgroundAlpha: self.data('dygraph-highlightseriesbackgroundalpha') || null, // TOO SLOW: (chart_type === 'stacked')?0.7:0.5,
3239 pointClickCallback: self.data('dygraph-pointclickcallback') || undefined,
3240 visibility: state.dimensions_visibility.selected2BooleanArray(state.data.dimension_names),
3244 ticker: Dygraph.dateTicker,
3245 axisLabelFormatter: function (d, gran) {
3246 return NETDATA.zeropad(d.getHours()) + ":" + NETDATA.zeropad(d.getMinutes()) + ":" + NETDATA.zeropad(d.getSeconds());
3248 valueFormatter: function (ms) {
3249 var d = new Date(ms);
3250 return d.toLocaleDateString() + ' ' + d.toLocaleTimeString();
3251 // return NETDATA.zeropad(d.getHours()) + ":" + NETDATA.zeropad(d.getMinutes()) + ":" + NETDATA.zeropad(d.getSeconds());
3256 valueFormatter: function (x) {
3257 // we format legends with the state object
3258 // no need to do anything here
3259 // return (Math.round(x*100) / 100).toLocaleString();
3260 // return state.legendFormatValue(x);
3265 legendFormatter: function(data) {
3266 var g = data.dygraph;
3268 var elements = state.element_legend_childs;
3270 // if the hidden div is not there
3271 // we are not managing the legend
3272 if(elements.hidden === null) return;
3274 if (typeof data.x === 'undefined') {
3275 //state.legendReset();
3278 state.legendSetDate(data.x);
3279 var i = data.series.length;
3281 var series = data.series[i];
3282 if(!series.isVisible) continue;
3283 state.legendSetLabelValue(series.label, series.y);
3289 drawCallback: function(dygraph, is_initial) {
3290 if(state.current.name !== 'auto') {
3291 if(NETDATA.options.debug.dygraph === true)
3292 state.log('dygraphDrawCallback()');
3294 var first = state.data.first_entry * 1000;
3295 var last = state.data.last_entry * 1000;
3297 var x_range = dygraph.xAxisRange();
3298 var after = Math.round(x_range[0]);
3299 var before = Math.round(x_range[1]);
3301 if(before <= last && after >= first)
3302 state.updateChartPanOrZoom(after, before);
3305 zoomCallback: function(minDate, maxDate, yRanges) {
3306 if(NETDATA.options.debug.dygraph === true)
3307 state.log('dygraphZoomCallback()');
3309 state.globalSelectionSyncStop();
3310 state.globalSelectionSyncDelay();
3312 if(state.updateChartPanOrZoom(minDate, maxDate) == false) {
3313 // we should not zoom that much
3314 state.dygraph_instance.updateOptions({
3320 highlightCallback: function(event, x, points, row, seriesName) {
3321 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3322 state.log('dygraphHighlightCallback()');
3326 // there is a bug in dygraph when the chart is zoomed enough
3327 // the time it thinks is selected is wrong
3328 // here we calculate the time t based on the row number selected
3330 var t = state.data_after + row * state.data_update_every;
3331 // 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);
3333 state.globalSelectionSync(t);
3335 // fix legend zIndex using the internal structures of dygraph legend module
3336 // this works, but it is a hack!
3337 // state.dygraph_instance.plugins_[0].plugin.legend_div_.style.zIndex = 10000;
3339 unhighlightCallback: function(event) {
3340 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3341 state.log('dygraphUnhighlightCallback()');
3343 state.unpauseChart();
3344 state.globalSelectionSyncStop();
3346 interactionModel : {
3347 mousedown: function(event, dygraph, context) {
3348 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3349 state.log('interactionModel.mousedown()');
3351 state.globalSelectionSyncStop();
3353 if(NETDATA.options.debug.dygraph === true)
3354 state.log('dygraphMouseDown()');
3356 // Right-click should not initiate a zoom.
3357 if(event.button && event.button === 2) return;
3359 context.initializeMouseDown(event, dygraph, context);
3361 if(event.button && event.button === 1) {
3362 if (event.altKey || event.shiftKey) {
3363 state.setMode('pan');
3364 state.globalSelectionSyncDelay();
3365 Dygraph.startPan(event, dygraph, context);
3368 state.setMode('zoom');
3369 state.globalSelectionSyncDelay();
3370 Dygraph.startZoom(event, dygraph, context);
3374 if (event.altKey || event.shiftKey) {
3375 state.setMode('zoom');
3376 state.globalSelectionSyncDelay();
3377 Dygraph.startZoom(event, dygraph, context);
3380 state.setMode('pan');
3381 state.globalSelectionSyncDelay();
3382 Dygraph.startPan(event, dygraph, context);
3386 mousemove: function(event, dygraph, context) {
3387 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3388 state.log('interactionModel.mousemove()');
3390 if(context.isPanning) {
3391 state.globalSelectionSyncStop();
3392 state.globalSelectionSyncDelay();
3393 state.setMode('pan');
3394 Dygraph.movePan(event, dygraph, context);
3396 else if(context.isZooming) {
3397 state.globalSelectionSyncStop();
3398 state.globalSelectionSyncDelay();
3399 state.setMode('zoom');
3400 Dygraph.moveZoom(event, dygraph, context);
3403 mouseup: function(event, dygraph, context) {
3404 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3405 state.log('interactionModel.mouseup()');
3407 if (context.isPanning) {
3408 state.globalSelectionSyncDelay();
3409 Dygraph.endPan(event, dygraph, context);
3411 else if (context.isZooming) {
3412 state.globalSelectionSyncDelay();
3413 Dygraph.endZoom(event, dygraph, context);
3416 click: function(event, dygraph, context) {
3417 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3418 state.log('interactionModel.click()');
3420 event.preventDefault();
3422 dblclick: function(event, dygraph, context) {
3423 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3424 state.log('interactionModel.dblclick()');
3426 state.globalSelectionSyncStop();
3427 NETDATA.globalPanAndZoom.clearMaster();
3430 mousewheel: function(event, dygraph, context) {
3431 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3432 state.log('interactionModel.mousewheel()');
3434 // Take the offset of a mouse event on the dygraph canvas and
3435 // convert it to a pair of percentages from the bottom left.
3436 // (Not top left, bottom is where the lower value is.)
3437 function offsetToPercentage(g, offsetX, offsetY) {
3438 // This is calculating the pixel offset of the leftmost date.
3439 var xOffset = g.toDomCoords(g.xAxisRange()[0], null)[0];
3440 var yar0 = g.yAxisRange(0);
3442 // This is calculating the pixel of the higest value. (Top pixel)
3443 var yOffset = g.toDomCoords(null, yar0[1])[1];
3445 // x y w and h are relative to the corner of the drawing area,
3446 // so that the upper corner of the drawing area is (0, 0).
3447 var x = offsetX - xOffset;
3448 var y = offsetY - yOffset;
3450 // This is computing the rightmost pixel, effectively defining the
3452 var w = g.toDomCoords(g.xAxisRange()[1], null)[0] - xOffset;
3454 // This is computing the lowest pixel, effectively defining the height.
3455 var h = g.toDomCoords(null, yar0[0])[1] - yOffset;
3457 // Percentage from the left.
3458 var xPct = w === 0 ? 0 : (x / w);
3459 // Percentage from the top.
3460 var yPct = h === 0 ? 0 : (y / h);
3462 // The (1-) part below changes it from "% distance down from the top"
3463 // to "% distance up from the bottom".
3464 return [xPct, (1-yPct)];
3467 // Adjusts [x, y] toward each other by zoomInPercentage%
3468 // Split it so the left/bottom axis gets xBias/yBias of that change and
3469 // tight/top gets (1-xBias)/(1-yBias) of that change.
3471 // If a bias is missing it splits it down the middle.
3472 function zoomRange(g, zoomInPercentage, xBias, yBias) {
3473 xBias = xBias || 0.5;
3474 yBias = yBias || 0.5;
3476 function adjustAxis(axis, zoomInPercentage, bias) {
3477 var delta = axis[1] - axis[0];
3478 var increment = delta * zoomInPercentage;
3479 var foo = [increment * bias, increment * (1-bias)];
3481 return [ axis[0] + foo[0], axis[1] - foo[1] ];
3484 var yAxes = g.yAxisRanges();
3486 for (var i = 0; i < yAxes.length; i++) {
3487 newYAxes[i] = adjustAxis(yAxes[i], zoomInPercentage, yBias);
3490 return adjustAxis(g.xAxisRange(), zoomInPercentage, xBias);
3493 if(event.altKey || event.shiftKey) {
3494 state.globalSelectionSyncStop();
3495 state.globalSelectionSyncDelay();
3497 // http://dygraphs.com/gallery/interaction-api.js
3498 var normal = (event.detail) ? event.detail * -1 : event.wheelDelta / 40;
3499 var percentage = normal / 50;
3501 if (!(event.offsetX && event.offsetY)){
3502 event.offsetX = event.layerX - event.target.offsetLeft;
3503 event.offsetY = event.layerY - event.target.offsetTop;
3506 var percentages = offsetToPercentage(dygraph, event.offsetX, event.offsetY);
3507 var xPct = percentages[0];
3508 var yPct = percentages[1];
3510 var new_x_range = zoomRange(dygraph, percentage, xPct, yPct);
3512 var after = new_x_range[0];
3513 var before = new_x_range[1];
3515 var first = (state.data.first_entry + state.data.view_update_every) * 1000;
3516 var last = (state.data.last_entry + state.data.view_update_every) * 1000;
3519 after -= (before - last);
3526 state.setMode('zoom');
3527 if(state.updateChartPanOrZoom(after, before) === true)
3528 dygraph.updateOptions({ dateWindow: [ after, before ] });
3530 event.preventDefault();
3533 touchstart: function(event, dygraph, context) {
3534 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3535 state.log('interactionModel.touchstart()');
3537 state.setMode('zoom');
3540 Dygraph.defaultInteractionModel.touchstart(event, dygraph, context);
3542 // we overwrite the touch directions at the end, to overwrite
3543 // the internal default of dygraphs
3544 context.touchDirections = { x: true, y: false };
3546 state.dygraph_last_touch_start = new Date().getTime();
3547 state.dygraph_last_touch_move = 0;
3549 if(typeof event.touches[0].pageX === 'number')
3550 state.dygraph_last_touch_page_x = event.touches[0].pageX;
3552 state.dygraph_last_touch_page_x = 0;
3554 touchmove: function(event, dygraph, context) {
3555 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3556 state.log('interactionModel.touchmove()');
3558 Dygraph.defaultInteractionModel.touchmove(event, dygraph, context);
3560 state.dygraph_last_touch_move = new Date().getTime();
3562 touchend: function(event, dygraph, context) {
3563 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3564 state.log('interactionModel.touchend()');
3566 Dygraph.defaultInteractionModel.touchend(event, dygraph, context);
3568 // if it didn't move, it is a selection
3569 if(state.dygraph_last_touch_move === 0 && state.dygraph_last_touch_page_x !== 0) {
3570 // internal api of dygraphs
3571 var pct = (state.dygraph_last_touch_page_x - (dygraph.plotter_.area.x + state.element.getBoundingClientRect().left)) / dygraph.plotter_.area.w;
3572 var t = Math.round(state.data_after + (state.data_before - state.data_after) * pct);
3573 if(NETDATA.dygraphSetSelection(state, t) === true)
3574 state.globalSelectionSync(t);
3577 // if it was double tap within double click time, reset the charts
3578 var now = new Date().getTime();
3579 if(typeof state.dygraph_last_touch_end !== 'undefined') {
3580 if(state.dygraph_last_touch_move === 0) {
3581 var dt = now - state.dygraph_last_touch_end;
3582 if(dt <= NETDATA.options.current.double_click_speed) {
3583 state.globalSelectionSyncStop();
3584 NETDATA.globalPanAndZoom.clearMaster();
3590 // remember the timestamp of the last touch end
3591 state.dygraph_last_touch_end = now;
3596 if(NETDATA.chartLibraries.dygraph.isSparkline(state)) {
3597 state.dygraph_options.drawGrid = false;
3598 state.dygraph_options.drawAxis = false;
3599 state.dygraph_options.title = undefined;
3600 state.dygraph_options.units = undefined;
3601 state.dygraph_options.ylabel = undefined;
3602 state.dygraph_options.yLabelWidth = 0;
3603 state.dygraph_options.labelsDivWidth = 120;
3604 state.dygraph_options.labelsDivStyles.width = '120px';
3605 state.dygraph_options.labelsSeparateLines = true;
3606 state.dygraph_options.rightGap = 0;
3609 if(smooth === true) {
3610 state.dygraph_smooth_eligible = true;
3612 if(NETDATA.options.current.smooth_plot === true)
3613 state.dygraph_options.plotter = smoothPlotter;
3615 else state.dygraph_smooth_eligible = false;
3617 state.dygraph_instance = new Dygraph(state.element_chart,
3618 data.result.data, state.dygraph_options);
3620 state.dygraph_last_rendered = new Date().getTime();
3623 // ----------------------------------------------------------------------------------------------------------------
3626 NETDATA.morrisInitialize = function(callback) {
3627 if(typeof netdataNoMorris === 'undefined' || !netdataNoMorris) {
3629 // morris requires raphael
3630 if(!NETDATA.chartLibraries.raphael.initialized) {
3631 if(NETDATA.chartLibraries.raphael.enabled) {
3632 NETDATA.raphaelInitialize(function() {
3633 NETDATA.morrisInitialize(callback);
3637 NETDATA.chartLibraries.morris.enabled = false;
3638 if(typeof callback === "function")
3643 NETDATA._loadCSS(NETDATA.morris_css);
3646 url: NETDATA.morris_js,
3651 NETDATA.registerChartLibrary('morris', NETDATA.morris_js);
3654 NETDATA.chartLibraries.morris.enabled = false;
3655 NETDATA.error(100, NETDATA.morris_js);
3657 .always(function() {
3658 if(typeof callback === "function")
3664 NETDATA.chartLibraries.morris.enabled = false;
3665 if(typeof callback === "function")
3670 NETDATA.morrisChartUpdate = function(state, data) {
3671 state.morris_instance.setData(data.result.data);
3674 NETDATA.morrisChartCreate = function(state, data) {
3676 state.morris_options = {
3677 element: state.element_chart.id,
3678 data: data.result.data,
3680 ykeys: data.dimension_names,
3681 labels: data.dimension_names,
3687 continuousLine: false,
3688 behaveLikeLine: false
3691 if(state.chart.chart_type === 'line')
3692 state.morris_instance = new Morris.Line(state.morris_options);
3694 else if(state.chart.chart_type === 'area') {
3695 state.morris_options.behaveLikeLine = true;
3696 state.morris_instance = new Morris.Area(state.morris_options);
3699 state.morris_instance = new Morris.Area(state.morris_options);
3702 // ----------------------------------------------------------------------------------------------------------------
3705 NETDATA.raphaelInitialize = function(callback) {
3706 if(typeof netdataStopRaphael === 'undefined' || !netdataStopRaphael) {
3708 url: NETDATA.raphael_js,
3713 NETDATA.registerChartLibrary('raphael', NETDATA.raphael_js);
3716 NETDATA.chartLibraries.raphael.enabled = false;
3717 NETDATA.error(100, NETDATA.raphael_js);
3719 .always(function() {
3720 if(typeof callback === "function")
3725 NETDATA.chartLibraries.raphael.enabled = false;
3726 if(typeof callback === "function")
3731 NETDATA.raphaelChartUpdate = function(state, data) {
3732 $(state.element_chart).raphael(data.result, {
3733 width: state.chartWidth(),
3734 height: state.chartHeight()
3738 NETDATA.raphaelChartCreate = function(state, data) {
3739 $(state.element_chart).raphael(data.result, {
3740 width: state.chartWidth(),
3741 height: state.chartHeight()
3745 // ----------------------------------------------------------------------------------------------------------------
3748 NETDATA.googleInitialize = function(callback) {
3749 if(typeof netdataNoGoogleCharts === 'undefined' || !netdataNoGoogleCharts) {
3751 url: NETDATA.google_js,
3756 NETDATA.registerChartLibrary('google', NETDATA.google_js);
3757 google.load('visualization', '1.1', {
3758 'packages': ['corechart', 'controls'],
3759 'callback': callback
3763 NETDATA.chartLibraries.google.enabled = false;
3764 NETDATA.error(100, NETDATA.google_js);
3765 if(typeof callback === "function")
3770 NETDATA.chartLibraries.google.enabled = false;
3771 if(typeof callback === "function")
3776 NETDATA.googleChartUpdate = function(state, data) {
3777 var datatable = new google.visualization.DataTable(data.result);
3778 state.google_instance.draw(datatable, state.google_options);
3781 NETDATA.googleChartCreate = function(state, data) {
3782 var datatable = new google.visualization.DataTable(data.result);
3784 state.google_options = {
3785 colors: state.chartColors(),
3787 // do not set width, height - the chart resizes itself
3788 //width: state.chartWidth(),
3789 //height: state.chartHeight(),
3791 title: state.chart.title,
3794 // title: "Time of Day",
3795 // format:'HH:mm:ss',
3796 viewWindowMode: 'maximized',
3807 title: state.chart.units,
3808 viewWindowMode: 'pretty',
3823 focusTarget: 'category',
3830 titlePosition: 'out',
3841 curveType: 'function',
3846 switch(state.chart.chart_type) {
3848 state.google_options.vAxis.viewWindowMode = 'maximized';
3849 state.google_options.areaOpacity = NETDATA.options.current.color_fill_opacity_area;
3850 state.google_instance = new google.visualization.AreaChart(state.element_chart);
3854 state.google_options.isStacked = true;
3855 state.google_options.areaOpacity = NETDATA.options.current.color_fill_opacity_stacked;
3856 state.google_options.vAxis.viewWindowMode = 'maximized';
3857 state.google_options.vAxis.minValue = null;
3858 state.google_options.vAxis.maxValue = null;
3859 state.google_instance = new google.visualization.AreaChart(state.element_chart);
3864 state.google_options.lineWidth = 2;
3865 state.google_instance = new google.visualization.LineChart(state.element_chart);
3869 state.google_instance.draw(datatable, state.google_options);
3872 // ----------------------------------------------------------------------------------------------------------------
3875 NETDATA.easypiechartInitialize = function(callback) {
3876 if(typeof netdataNoEasyPieChart === 'undefined' || !netdataNoEasyPieChart) {
3878 url: NETDATA.easypiechart_js,
3883 NETDATA.registerChartLibrary('easypiechart', NETDATA.easypiechart_js);
3886 NETDATA.error(100, NETDATA.easypiechart_js);
3888 .always(function() {
3889 if(typeof callback === "function")
3894 NETDATA.chartLibraries.easypiechart.enabled = false;
3895 if(typeof callback === "function")
3900 NETDATA.easypiechartChartUpdate = function(state, data) {
3902 state.easypiechart_instance.update();
3905 NETDATA.easypiechartChartCreate = function(state, data) {
3906 var self = $(state.element);
3911 $(state.element_chart).data('data-percent', pcent);
3912 data.element_chart.innerHTML = value.toString();
3914 state.easypiechart_instance = new EasyPieChart(state.element_chart, {
3915 barColor: self.data('easypiechart-barcolor') || '#ef1e25',
3916 trackColor: self.data('easypiechart-trackcolor') || '#f2f2f2',
3917 scaleColor: self.data('easypiechart-scalecolor') || '#dfe0e0',
3918 scaleLength: self.data('easypiechart-scalelength') || 5,
3919 lineCap: self.data('easypiechart-linecap') || 'round',
3920 lineWidth: self.data('easypiechart-linewidth') || 3,
3921 trackWidth: self.data('easypiechart-trackwidth') || undefined,
3922 size: self.data('easypiechart-size') || Math.min(state.chartWidth(), state.chartHeight()),
3923 rotate: self.data('easypiechart-rotate') || 0,
3924 animate: self.data('easypiechart-rotate') || {duration: 0, enabled: false},
3925 easing: self.data('easypiechart-easing') || undefined
3929 // ----------------------------------------------------------------------------------------------------------------
3930 // Charts Libraries Registration
3932 NETDATA.chartLibraries = {
3934 initialize: NETDATA.dygraphInitialize,
3935 create: NETDATA.dygraphChartCreate,
3936 update: NETDATA.dygraphChartUpdate,
3937 resize: function(state) {
3938 if(typeof state.dygraph_instance.resize === 'function')
3939 state.dygraph_instance.resize();
3941 setSelection: NETDATA.dygraphSetSelection,
3942 clearSelection: NETDATA.dygraphClearSelection,
3945 format: function(state) { return 'json'; },
3946 options: function(state) { return 'ms|flip'; },
3947 legend: function(state) {
3948 if(this.isSparkline(state) === false)
3949 return 'right-side';
3953 autoresize: function(state) { return true; },
3954 max_updates_to_recreate: function(state) { return 5000; },
3955 track_colors: function(state) { return true; },
3956 pixels_per_point: function(state) {
3957 if(this.isSparkline(state) === false)
3963 isSparkline: function(state) {
3964 if(typeof state.dygraph_sparkline === 'undefined') {
3965 var t = $(state.element).data('dygraph-theme');
3966 if(t === 'sparkline')
3967 state.dygraph_sparkline = true;
3969 state.dygraph_sparkline = false;
3971 return state.dygraph_sparkline;
3975 initialize: NETDATA.sparklineInitialize,
3976 create: NETDATA.sparklineChartCreate,
3977 update: NETDATA.sparklineChartUpdate,
3979 setSelection: function(t) { return true; },
3980 clearSelection: function() { return true; },
3983 format: function(state) { return 'array'; },
3984 options: function(state) { return 'flip|abs'; },
3985 legend: function(state) { return null; },
3986 autoresize: function(state) { return false; },
3987 max_updates_to_recreate: function(state) { return 5000; },
3988 track_colors: function(state) { return false; },
3989 pixels_per_point: function(state) { return 3; }
3992 initialize: NETDATA.peityInitialize,
3993 create: NETDATA.peityChartCreate,
3994 update: NETDATA.peityChartUpdate,
3996 setSelection: function(t) { return true; },
3997 clearSelection: function() { return true; },
4000 format: function(state) { return 'ssvcomma'; },
4001 options: function(state) { return 'null2zero|flip|abs'; },
4002 legend: function(state) { return null; },
4003 autoresize: function(state) { return false; },
4004 max_updates_to_recreate: function(state) { return 5000; },
4005 track_colors: function(state) { return false; },
4006 pixels_per_point: function(state) { return 3; }
4009 initialize: NETDATA.morrisInitialize,
4010 create: NETDATA.morrisChartCreate,
4011 update: NETDATA.morrisChartUpdate,
4013 setSelection: function(t) { return true; },
4014 clearSelection: function() { return true; },
4017 format: function(state) { return 'json'; },
4018 options: function(state) { return 'objectrows|ms'; },
4019 legend: function(state) { return null; },
4020 autoresize: function(state) { return false; },
4021 max_updates_to_recreate: function(state) { return 50; },
4022 track_colors: function(state) { return false; },
4023 pixels_per_point: function(state) { return 15; }
4026 initialize: NETDATA.googleInitialize,
4027 create: NETDATA.googleChartCreate,
4028 update: NETDATA.googleChartUpdate,
4030 setSelection: function(t) { return true; },
4031 clearSelection: function() { return true; },
4034 format: function(state) { return 'datatable'; },
4035 options: function(state) { return ''; },
4036 legend: function(state) { return null; },
4037 autoresize: function(state) { return false; },
4038 max_updates_to_recreate: function(state) { return 300; },
4039 track_colors: function(state) { return false; },
4040 pixels_per_point: function(state) { return 4; }
4043 initialize: NETDATA.raphaelInitialize,
4044 create: NETDATA.raphaelChartCreate,
4045 update: NETDATA.raphaelChartUpdate,
4047 setSelection: function(t) { return true; },
4048 clearSelection: function() { return true; },
4051 format: function(state) { return 'json'; },
4052 options: function(state) { return ''; },
4053 legend: function(state) { return null; },
4054 autoresize: function(state) { return false; },
4055 max_updates_to_recreate: function(state) { return 5000; },
4056 track_colors: function(state) { return false; },
4057 pixels_per_point: function(state) { return 3; }
4060 initialize: NETDATA.easypiechartInitialize,
4061 create: NETDATA.easypiechartChartCreate,
4062 update: NETDATA.easypiechartChartUpdate,
4064 setSelection: function(t) { return true; },
4065 clearSelection: function() { return true; },
4068 format: function(state) { return 'json'; },
4069 options: function(state) { return ''; },
4070 legend: function(state) { return null; },
4071 autoresize: function(state) { return false; },
4072 max_updates_to_recreate: function(state) { return 5000; },
4073 track_colors: function(state) { return false; },
4074 pixels_per_point: function(state) { return 3; }
4078 NETDATA.registerChartLibrary = function(library, url) {
4079 if(NETDATA.options.debug.libraries === true)
4080 console.log("registering chart library: " + library);
4082 NETDATA.chartLibraries[library].url = url;
4083 NETDATA.chartLibraries[library].initialized = true;
4084 NETDATA.chartLibraries[library].enabled = true;
4087 // ----------------------------------------------------------------------------------------------------------------
4090 NETDATA.requiredJs = [
4092 url: NETDATA.serverDefault + 'lib/bootstrap.min.js',
4093 isAlreadyLoaded: function() {
4094 if(typeof $().emulateTransitionEnd == 'function')
4097 if(typeof netdataNoBootstrap !== 'undefined' && netdataNoBootstrap)
4105 url: NETDATA.serverDefault + 'lib/jquery.nanoscroller.min.js',
4106 isAlreadyLoaded: function() { return false; }
4109 url: NETDATA.serverDefault + 'lib/bootstrap-toggle.min.js',
4110 isAlreadyLoaded: function() { return false; }
4114 NETDATA.requiredCSS = [
4116 url: NETDATA.serverDefault + 'css/bootstrap.min.css',
4117 isAlreadyLoaded: function() {
4118 if(typeof netdataNoBootstrap !== 'undefined' && netdataNoBootstrap)
4125 url: NETDATA.serverDefault + 'css/font-awesome.min.css',
4126 isAlreadyLoaded: function() { return false; }
4129 url: NETDATA.dashboard_css,
4130 isAlreadyLoaded: function() { return false; }
4133 url: NETDATA.serverDefault + 'css/bootstrap-toggle.min.css',
4134 isAlreadyLoaded: function() { return false; }
4138 NETDATA.loadRequiredJs = function(index, callback) {
4139 if(index >= NETDATA.requiredJs.length) {
4140 if(typeof callback === 'function')
4145 if(NETDATA.requiredJs[index].isAlreadyLoaded()) {
4146 NETDATA.loadRequiredJs(++index, callback);
4150 if(NETDATA.options.debug.main_loop === true)
4151 console.log('loading ' + NETDATA.requiredJs[index].url);
4154 url: NETDATA.requiredJs[index].url,
4158 .success(function() {
4159 if(NETDATA.options.debug.main_loop === true)
4160 console.log('loaded ' + NETDATA.requiredJs[index].url);
4162 NETDATA.loadRequiredJs(++index, callback);
4165 alert('Cannot load required JS library: ' + NETDATA.requiredJs[index].url);
4169 NETDATA.loadRequiredCSS = function(index) {
4170 if(index >= NETDATA.requiredCSS.length)
4173 if(NETDATA.requiredCSS[index].isAlreadyLoaded()) {
4174 NETDATA.loadRequiredCSS(++index);
4178 if(NETDATA.options.debug.main_loop === true)
4179 console.log('loading ' + NETDATA.requiredCSS[index].url);
4181 NETDATA._loadCSS(NETDATA.requiredCSS[index].url);
4182 NETDATA.loadRequiredCSS(++index);
4185 NETDATA.errorReset();
4186 NETDATA.loadRequiredCSS(0);
4188 NETDATA._loadjQuery(function() {
4189 NETDATA.loadRequiredJs(0, function() {
4190 if(typeof netdataDontStart === 'undefined' || !netdataDontStart) {
4191 if(NETDATA.options.debug.main_loop === true)
4192 console.log('starting chart refresh thread');
4197 if(typeof NETDATA.options.readyCallback === 'function')
4198 NETDATA.options.readyCallback();
4202 // window.NETDATA = NETDATA;
4203 // })(window, document);