Skip to content

Instantly share code, notes, and snippets.

@jonasfj
Last active January 2, 2016 08:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonasfj/8280124 to your computer and use it in GitHub Desktop.
Save jonasfj/8280124 to your computer and use it in GitHub Desktop.
Custom telemetry dashboard

Custom Telemetry Dashboard

This is an example of how to make a custom telemetry dashboard. The following files are specific to this example dashboard:

  • index.html
  • script.js
  • style.css

These are the files to modify, if you want to build a dashboard based on this example. The other files should also be deployed with your application, though not telemetry.js, which should be included from telemetry.mozilla.org/v1/.

The following files are part of the telemetry-dashboard, no effort will be taken to ensure that they remain API compatible. Thus, they should be deployed with your application. Do, however, feel free to try and upgrade to newer versions from the telemetry-dashboard repository.

  • jquery.telemetry.js
  • bootstrap-selector.js

The rest of the files are external libraries.

/*!
* bootstrap-select v1.3.5
* http://silviomoreto.github.io/bootstrap-select/
*
* Copyright 2013 bootstrap-select
* Licensed under the MIT license
*/.bootstrap-select.btn-group,.bootstrap-select.btn-group[class*="span"]{float:none;display:inline-block;margin-bottom:10px;margin-left:0}.form-search .bootstrap-select.btn-group,.form-inline .bootstrap-select.btn-group,.form-horizontal .bootstrap-select.btn-group{margin-bottom:0}.bootstrap-select.form-control{padding:0;border:0}.bootstrap-select.btn-group.pull-right,.bootstrap-select.btn-group[class*="span"].pull-right,.row-fluid .bootstrap-select.btn-group[class*="span"].pull-right{float:right}.input-append .bootstrap-select.btn-group{margin-left:-1px}.input-prepend .bootstrap-select.btn-group{margin-right:-1px}.bootstrap-select:not([class*="span"]):not([class*="col-"]):not([class*="form-control"]){width:220px}.bootstrap-select{width:220px\0}.bootstrap-select.form-control:not([class*="span"]){width:100%}.bootstrap-select>.btn{width:100%}.error .bootstrap-select .btn{border:1px solid #b94a48}.dropdown-menu{z-index:2000}.bootstrap-select.show-menu-arrow.open>.btn{z-index:2051}.bootstrap-select .btn:focus{outline:thin dotted #333 !important;outline:5px auto -webkit-focus-ring-color !important;outline-offset:-2px}.bootstrap-select.btn-group .btn .filter-option{overflow:hidden;position:absolute;left:12px;right:25px;text-align:left}.bootstrap-select.btn-group .btn .caret{position:absolute;top:50%;right:12px;margin-top:-2px;vertical-align:middle}.bootstrap-select.btn-group>.disabled,.bootstrap-select.btn-group .dropdown-menu li.disabled>a{cursor:not-allowed}.bootstrap-select.btn-group>.disabled:focus{outline:none !important}.bootstrap-select.btn-group[class*="span"] .btn{width:100%}.bootstrap-select.btn-group .dropdown-menu{min-width:100%;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;box-sizing:border-box}.bootstrap-select.btn-group .dropdown-menu.inner{position:static;border:0;padding:0;margin:0;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.bootstrap-select.btn-group .dropdown-menu dt{display:block;padding:3px 20px;cursor:default}.bootstrap-select.btn-group .div-contain{overflow:hidden}.bootstrap-select.btn-group .dropdown-menu li{position:relative}.bootstrap-select.btn-group .dropdown-menu li>a.opt{position:relative;padding-left:35px}.bootstrap-select.btn-group .dropdown-menu li>a{cursor:pointer}.bootstrap-select.btn-group .dropdown-menu li>dt small{font-weight:normal}.bootstrap-select.btn-group.show-tick .dropdown-menu li.selected a i.check-mark{display:inline-block;position:absolute;right:15px;margin-top:2.5px}.bootstrap-select.btn-group .dropdown-menu li a i.check-mark{display:none}.bootstrap-select.btn-group.show-tick .dropdown-menu li a span.text{margin-right:34px}.bootstrap-select.btn-group .dropdown-menu li small{padding-left:.5em}.bootstrap-select.btn-group .dropdown-menu li:not(.disabled)>a:hover small,.bootstrap-select.btn-group .dropdown-menu li:not(.disabled)>a:focus small{color:#64b1d8;color:rgba(255,255,255,0.4)}.bootstrap-select.btn-group .dropdown-menu li>dt small{font-weight:normal}.bootstrap-select.show-menu-arrow .dropdown-toggle:before{content:'';display:inline-block;border-left:7px solid transparent;border-right:7px solid transparent;border-bottom:7px solid #CCC;border-bottom-color:rgba(0,0,0,0.2);position:absolute;bottom:-4px;left:9px;display:none}.bootstrap-select.show-menu-arrow .dropdown-toggle:after{content:'';display:inline-block;border-left:6px solid transparent;border-right:6px solid transparent;border-bottom:6px solid white;position:absolute;bottom:-4px;left:10px;display:none}.bootstrap-select.show-menu-arrow.dropup .dropdown-toggle:before{bottom:auto;top:-3px;border-top:7px solid #ccc;border-bottom:0;border-top-color:rgba(0,0,0,0.2)}.bootstrap-select.show-menu-arrow.dropup .dropdown-toggle:after{bottom:auto;top:-3px;border-top:6px solid #fff;border-bottom:0}.bootstrap-select.show-menu-arrow.pull-right .dropdown-toggle:before{right:12px;left:auto}.bootstrap-select.show-menu-arrow.pull-right .dropdown-toggle:after{right:13px;left:auto}.bootstrap-select.show-menu-arrow.open>.dropdown-toggle:before,.bootstrap-select.show-menu-arrow.open>.dropdown-toggle:after{display:block}.mobile-device{position:absolute;top:0;left:0;display:block !important;width:100%;height:100% !important;opacity:0}.bootstrap-select.fit-width{width:auto !important}.bootstrap-select.btn-group.fit-width .btn .filter-option{position:static}.bootstrap-select.btn-group.fit-width .btn .caret{position:static;top:auto;margin-top:-1px}.control-group.error .bootstrap-select .dropdown-toggle{border-color:#b94a48}.bootstrap-select-searchbox{padding:4px 8px}
/*!
* bootstrap-select v1.3.5
* http://silviomoreto.github.io/bootstrap-select/
*
* Copyright 2013 bootstrap-select
* Licensed under the MIT license
*/
;!function(b){b.expr[":"].icontains=function(e,c,d){return b(e).text().toUpperCase().indexOf(d[3].toUpperCase())>=0};var a=function(d,c,f){if(f){f.stopPropagation();f.preventDefault()}this.$element=b(d);this.$newElement=null;this.$button=null;this.$menu=null;this.options=b.extend({},b.fn.selectpicker.defaults,this.$element.data(),typeof c=="object"&&c);if(this.options.title==null){this.options.title=this.$element.attr("title")}this.val=a.prototype.val;this.render=a.prototype.render;this.refresh=a.prototype.refresh;this.setStyle=a.prototype.setStyle;this.selectAll=a.prototype.selectAll;this.deselectAll=a.prototype.deselectAll;this.init()};a.prototype={constructor:a,init:function(d){this.$element.hide();this.multiple=this.$element.prop("multiple");var f=this.$element.attr("id");this.$newElement=this.createView();this.$element.after(this.$newElement);this.$menu=this.$newElement.find("> .dropdown-menu");this.$button=this.$newElement.find("> button");this.$searchbox=this.$newElement.find("input");if(f!==undefined){var c=this;this.$button.attr("data-id",f);b('label[for="'+f+'"]').click(function(g){g.preventDefault();c.$button.focus()})}this.checkDisabled();this.clickListener();this.liveSearchListener();this.render();this.liHeight();this.setStyle();this.setWidth();if(this.options.container){this.selectPosition()}this.$menu.data("this",this);this.$newElement.data("this",this)},createDropdown:function(){var c=this.multiple?" show-tick":"";var f=this.options.header?'<div class="popover-title"><button type="button" class="close" aria-hidden="true">&times;</button>'+this.options.header+"</div>":"";var e=this.options.liveSearch?'<div class="bootstrap-select-searchbox"><input type="text" class="input-block-level form-control" /></div>':"";var d="<div class='btn-group bootstrap-select"+c+"'><button type='button' class='btn dropdown-toggle' data-toggle='dropdown'><div class='filter-option pull-left'></div>&nbsp;<div class='caret'></div></button><div class='dropdown-menu open'>"+f+e+"<ul class='dropdown-menu inner' role='menu'></ul></div></div>";return b(d)},createView:function(){var c=this.createDropdown();var d=this.createLi();c.find("ul").append(d);return c},reloadLi:function(){this.destroyLi();var c=this.createLi();this.$menu.find("ul").append(c)},destroyLi:function(){this.$menu.find("li").remove()},createLi:function(){var d=this,e=[],c="";this.$element.find("option").each(function(h){var j=b(this);var g=j.attr("class")||"";var i=j.attr("style")||"";var n=j.data("content")?j.data("content"):j.html();var l=j.data("subtext")!==undefined?'<small class="muted text-muted">'+j.data("subtext")+"</small>":"";var k=j.data("icon")!==undefined?'<i class="glyphicon '+j.data("icon")+'"></i> ':"";if(k!==""&&(j.is(":disabled")||j.parent().is(":disabled"))){k="<span>"+k+"</span>"}if(!j.data("content")){n=k+'<span class="text">'+n+l+"</span>"}if(d.options.hideDisabled&&(j.is(":disabled")||j.parent().is(":disabled"))){e.push('<a style="min-height: 0; padding: 0"></a>')}else{if(j.parent().is("optgroup")&&j.data("divider")!=true){if(j.index()==0){var m=j.parent().attr("label");var o=j.parent().data("subtext")!==undefined?'<small class="muted text-muted">'+j.parent().data("subtext")+"</small>":"";var f=j.parent().data("icon")?'<i class="'+j.parent().data("icon")+'"></i> ':"";m=f+'<span class="text">'+m+o+"</span>";if(j[0].index!=0){e.push('<div class="div-contain"><div class="divider"></div></div><dt>'+m+"</dt>"+d.createA(n,"opt "+g,i))}else{e.push("<dt>"+m+"</dt>"+d.createA(n,"opt "+g,i))}}else{e.push(d.createA(n,"opt "+g,i))}}else{if(j.data("divider")==true){e.push('<div class="div-contain"><div class="divider"></div></div>')}else{if(b(this).data("hidden")==true){e.push("")}else{e.push(d.createA(n,g,i))}}}}});b.each(e,function(f,g){c+="<li rel="+f+">"+g+"</li>"});if(!this.multiple&&this.$element.find("option:selected").length==0&&!this.options.title){this.$element.find("option").eq(0).prop("selected",true).attr("selected","selected")}return b(c)},createA:function(e,c,d){return'<a tabindex="0" class="'+c+'" style="'+d+'">'+e+'<i class="glyphicon glyphicon-ok icon-ok check-mark"></i></a>'},render:function(){var d=this;this.$element.find("option").each(function(h){d.setDisabled(h,b(this).is(":disabled")||b(this).parent().is(":disabled"));d.setSelected(h,b(this).is(":selected"))});this.tabIndex();var g=this.$element.find("option:selected").map(function(h,k){var l=b(this);var j=l.data("icon")&&d.options.showIcon?'<i class="glyphicon '+l.data("icon")+'"></i> ':"";var i;if(d.options.showSubtext&&l.attr("data-subtext")&&!d.multiple){i=' <small class="muted text-muted">'+l.data("subtext")+"</small>"}else{i=""}if(l.data("content")&&d.options.showContent){return l.data("content")}else{if(l.attr("title")!=undefined){return l.attr("title")}else{return j+l.html()+i}}}).toArray();var f=!this.multiple?g[0]:g.join(", ");if(this.multiple&&this.options.selectedTextFormat.indexOf("count")>-1){var c=this.options.selectedTextFormat.split(">");var e=this.options.hideDisabled?":not([disabled])":"";if((c.length>1&&g.length>c[1])||(c.length==1&&g.length>=2)){f=this.options.countSelectedText.replace("{0}",g.length).replace("{1}",this.$element.find('option:not([data-divider="true"]):not([data-hidden="true"])'+e).length)}}if(!f){f=this.options.title!=undefined?this.options.title:this.options.noneSelectedText}this.$newElement.find(".filter-option").html(f)},setStyle:function(e,d){if(this.$element.attr("class")){this.$newElement.addClass(this.$element.attr("class").replace(/selectpicker|mobile-device/gi,""))}var c=e?e:this.options.style;if(d=="add"){this.$button.addClass(c)}else{if(d=="remove"){this.$button.removeClass(c)}else{this.$button.removeClass(this.options.style);this.$button.addClass(c)}}},liHeight:function(){var f=this.$newElement.clone();f.appendTo("body");var e=f.addClass("open").find("> .dropdown-menu");var d=e.find("li > a").outerHeight();var c=this.options.header?e.find(".popover-title").outerHeight():0;var g=this.options.liveSearch?e.find(".bootstrap-select-searchbox").outerHeight():0;f.remove();this.$newElement.data("liHeight",d).data("headerHeight",c).data("searchHeight",g)},setSize:function(){var h=this,d=this.$menu,i=d.find(".inner"),p=i.find("li > a"),u=this.$newElement.outerHeight(),f=this.$newElement.data("liHeight"),s=this.$newElement.data("headerHeight"),l=this.$newElement.data("searchHeight"),k=d.find("li .divider").outerHeight(true),r=parseInt(d.css("padding-top"))+parseInt(d.css("padding-bottom"))+parseInt(d.css("border-top-width"))+parseInt(d.css("border-bottom-width")),o=this.options.hideDisabled?":not(.disabled)":"",n=b(window),g=r+parseInt(d.css("margin-top"))+parseInt(d.css("margin-bottom"))+2,q,v,t,j=function(){v=h.$newElement.offset().top-n.scrollTop();t=n.height()-v-u};j();if(this.options.header){d.css("padding-top",0)}if(this.options.size=="auto"){var e=function(){var w;j();q=t-g;h.$newElement.toggleClass("dropup",(v>t)&&(q-g)<d.height()&&h.options.dropupAuto);if(h.$newElement.hasClass("dropup")){q=v-g}if((d.find("li").length+d.find("dt").length)>3){w=f*3+g-2}else{w=0}d.css({"max-height":q+"px",overflow:"hidden","min-height":w+"px"});i.css({"max-height":q-s-l-r+"px","overflow-y":"auto","min-height":w-r+"px"})};e();b(window).resize(e);b(window).scroll(e)}else{if(this.options.size&&this.options.size!="auto"&&d.find("li"+o).length>this.options.size){var m=d.find("li"+o+" > *").filter(":not(.div-contain)").slice(0,this.options.size).last().parent().index();var c=d.find("li").slice(0,m+1).find(".div-contain").length;q=f*this.options.size+c*k+r;this.$newElement.toggleClass("dropup",(v>t)&&q<d.height()&&this.options.dropupAuto);d.css({"max-height":q+s+l+"px",overflow:"hidden"});i.css({"max-height":q-r+"px","overflow-y":"auto"})}}},setWidth:function(){if(this.options.width=="auto"){this.$menu.css("min-width","0");var d=this.$newElement.clone().appendTo("body");var c=d.find("> .dropdown-menu").css("width");d.remove();this.$newElement.css("width",c)}else{if(this.options.width=="fit"){this.$menu.css("min-width","");this.$newElement.css("width","").addClass("fit-width")}else{if(this.options.width){this.$menu.css("min-width","");this.$newElement.css("width",this.options.width)}else{this.$menu.css("min-width","");this.$newElement.css("width","")}}}if(this.$newElement.hasClass("fit-width")&&this.options.width!=="fit"){this.$newElement.removeClass("fit-width")}},selectPosition:function(){var e=this,d="<div />",f=b(d),h,g,c=function(i){f.addClass(i.attr("class")).toggleClass("dropup",i.hasClass("dropup"));h=i.offset();g=i.hasClass("dropup")?0:i[0].offsetHeight;f.css({top:h.top+g,left:h.left,width:i[0].offsetWidth,position:"absolute"})};this.$newElement.on("click",function(i){c(b(this));f.appendTo(e.options.container);f.toggleClass("open",!b(this).hasClass("open"));f.append(e.$menu)});b(window).resize(function(){c(e.$newElement)});b(window).on("scroll",function(i){c(e.$newElement)});b("html").on("click",function(i){if(b(i.target).closest(e.$newElement).length<1){f.removeClass("open")}})},mobile:function(){this.$element.addClass("mobile-device").appendTo(this.$newElement);if(this.options.container){this.$menu.hide()}},refresh:function(){this.reloadLi();this.render();this.setWidth();this.setStyle();this.checkDisabled();this.liHeight()},update:function(){this.reloadLi();this.setWidth();this.setStyle();this.checkDisabled();this.liHeight()},setSelected:function(c,d){this.$menu.find("li").eq(c).toggleClass("selected",d)},setDisabled:function(c,d){if(d){this.$menu.find("li").eq(c).addClass("disabled").find("a").attr("href","#").attr("tabindex",-1)}else{this.$menu.find("li").eq(c).removeClass("disabled").find("a").removeAttr("href").attr("tabindex",0)}},isDisabled:function(){return this.$element.is(":disabled")},checkDisabled:function(){var c=this;if(this.isDisabled()){this.$button.addClass("disabled").attr("tabindex",-1)}else{if(this.$button.hasClass("disabled")){this.$button.removeClass("disabled")}if(this.$button.attr("tabindex")==-1){if(!this.$element.data("tabindex")){this.$button.removeAttr("tabindex")}}}this.$button.click(function(){return !c.isDisabled()})},tabIndex:function(){if(this.$element.is("[tabindex]")){this.$element.data("tabindex",this.$element.attr("tabindex"));this.$button.attr("tabindex",this.$element.data("tabindex"))}},clickListener:function(){var c=this;b("body").on("touchstart.dropdown",".dropdown-menu",function(d){d.stopPropagation()});this.$newElement.on("click",function(){c.setSize()});this.$menu.on("click","li a",function(k){var f=b(this).parent().index(),j=b(this).parent(),i=c.$element.val();if(c.multiple){k.stopPropagation()}k.preventDefault();if(!c.isDisabled()&&!b(this).parent().hasClass("disabled")){var d=c.$element.find("option");var h=d.eq(f);if(!c.multiple){d.prop("selected",false);h.prop("selected",true)}else{var g=h.prop("selected");h.prop("selected",!g)}c.$button.focus();if(i!=c.$element.val()){c.$element.change()}}});this.$menu.on("click","li.disabled a, li dt, li .div-contain, h3.popover-title",function(d){if(d.target==this){d.preventDefault();d.stopPropagation();c.$button.focus()}});this.$searchbox.on("click",function(d){d.stopPropagation()});this.$element.change(function(){c.render()})},liveSearchListener:function(){var c=this;this.$newElement.on("click.dropdown.data-api",function(d){if(c.options.liveSearch){setTimeout(function(){c.$searchbox.focus()},10)}});this.$searchbox.on("input",function(){if(c.$searchbox.val()){c.$menu.find("li").show().not(":icontains("+c.$searchbox.val()+")").hide()}else{c.$menu.find("li").show()}})},val:function(c){if(c!=undefined){this.$element.val(c);this.$element.change();return this.$element}else{return this.$element.val()}},selectAll:function(){this.$element.find("option").prop("selected",true).attr("selected","selected");this.render()},deselectAll:function(){this.$element.find("option").prop("selected",false).removeAttr("selected");this.render()},keydown:function(o){var p,n,h,m,j,i,q,d,g,l;p=b(this);h=p.parent();l=h.data("this");if(l.options.container){h=l.$menu}n=b("[role=menu] li:not(.divider):visible a",h);if(!n.length){return}if(/(38|40)/.test(o.keyCode)){m=n.index(n.filter(":focus"));i=n.parent(":not(.disabled)").first().index();q=n.parent(":not(.disabled)").last().index();j=n.eq(m).parent().nextAll(":not(.disabled)").eq(0).index();d=n.eq(m).parent().prevAll(":not(.disabled)").eq(0).index();g=n.eq(j).parent().prevAll(":not(.disabled)").eq(0).index();if(o.keyCode==38){if(m!=g&&m>d){m=d}if(m<i){m=i}}if(o.keyCode==40){if(m!=g&&m<j){m=j}if(m>q){m=q}if(m==-1){m=0}}n.eq(m).focus()}else{var f={48:"0",49:"1",50:"2",51:"3",52:"4",53:"5",54:"6",55:"7",56:"8",57:"9",59:";",65:"a",66:"b",67:"c",68:"d",69:"e",70:"f",71:"g",72:"h",73:"i",74:"j",75:"k",76:"l",77:"m",78:"n",79:"o",80:"p",81:"q",82:"r",83:"s",84:"t",85:"u",86:"v",87:"w",88:"x",89:"y",90:"z",96:"0",97:"1",98:"2",99:"3",100:"4",101:"5",102:"6",103:"7",104:"8",105:"9"};var c=[];n.each(function(){if(b(this).parent().is(":not(.disabled)")){if(b.trim(b(this).text().toLowerCase()).substring(0,1)==f[o.keyCode]){c.push(b(this).parent().index())}}});var k=b(document).data("keycount");k++;b(document).data("keycount",k);var r=b.trim(b(":focus").text().toLowerCase()).substring(0,1);if(r!=f[o.keyCode]){k=1;b(document).data("keycount",k)}else{if(k>=c.length){b(document).data("keycount",0)}}n.eq(c[k-1]).focus()}if(/(13|32)/.test(o.keyCode)){o.preventDefault();b(":focus").click();b(document).data("keycount",0)}},hide:function(){this.$newElement.hide()},show:function(){this.$newElement.show()},destroy:function(){this.$newElement.remove();this.$element.remove()}};b.fn.selectpicker=function(e,f){var c=arguments;var g;var d=this.each(function(){if(b(this).is("select")){var m=b(this),l=m.data("selectpicker"),h=typeof e=="object"&&e;if(!l){m.data("selectpicker",(l=new a(this,h,f)))}else{if(h){for(var j in h){l.options[j]=h[j]}}}if(typeof e=="string"){var k=e;if(l[k] instanceof Function){[].shift.apply(c);g=l[k].apply(l,c)}else{g=l.options[k]}}}});if(g!=undefined){return g}else{return d}};b.fn.selectpicker.defaults={style:"btn-default",size:"auto",title:null,selectedTextFormat:"values",noneSelectedText:"Nothing selected",countSelectedText:"{0} of {1} selected",width:false,container:false,hideDisabled:false,showSubtext:false,showIcon:true,showContent:true,dropupAuto:true,header:false,liveSearch:false};b(document).data("keycount",0).on("keydown","[data-toggle=dropdown], [role=menu]",a.prototype.keydown)}(window.jQuery);
/**
* This is an implementation of the `selectorType` for `histogramfilter` as
* defined in `jquery.telemetry.js`. This uses bootstrap-select for rendering
* selectors, creating a very nice UI.
*/
var BootstrapSelector = (function($){
function BootstrapSelector(filterName) {
this._filterName = filterName;
this._span = $("<span>");
this._select = $("<select>");
this._span.append(this._select);
this._options = [];
this._select.bind("change", $.proxy(function() {
if (this._callback !== undefined) {
this._callback(this, this.val());
}
}, this));
this._select.addClass("show-tick");
if (this._filterName === "version" || this._filterName === "measure") {
this._select.data("live-search", true);
}
this._select.addClass("filter-" + this._filterName);
this._select.selectpicker();
}
$.extend(BootstrapSelector.prototype, {
element: function BootstrapSelector_element() {
return this._span;
},
options: function BootstrapSelector_options(options) {
if (options !== undefined) {
// Clear existing options
this._select.empty();
var parent = this._select;
var n = options.length;
for(var i = 0; i < n; i++) {
var option = options[i];
var label = option;
// Special label if we're displaying versions
if (this._filterName === "version") {
var opts = option.split("/");
if (opts[0] !== parent.attr("label")) {
parent = $("<optgroup>", {label: opts[0]});
this._select.append(parent);
}
var label = label.replace("/", " ");
}
// Add <option>
parent.append($("<option>", {
text: label,
value: option
}));
}
// Store options for another time
this._options = options;
// Update bootstrap select
this._select.selectpicker('refresh');
}
return this._options;
},
val: function BootstrapSelector_val(value) {
if (value !== undefined) {
this._select.val(value);
this._select.selectpicker('render');
}
return this._select.val();
},
change: function BootstrapSelector_change(cb) {
this._callback = cb;
},
destroy: function BootstrapSelector_destroy() {
this._callback = null;
this._options = null;
this._select.remove();
this._span.remove();
},
});
return BootstrapSelector;
})(jQuery);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Telemetry CSV Histogram Exporter</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Include bootstrap, bootstrap-select and awesome font (3rd party libraries) -->
<link rel="stylesheet"
href="//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css">
<link rel="stylesheet" href="bootstrap-select.min.css">
<link rel="stylesheet"
href="//netdna.bootstrapcdn.com/font-awesome/4.0.2/css/font-awesome.min.css">
<!-- Include application specific styles -->
<link rel="stylesheet" type="text/css" href="style.css">
<!-- Include telemetry.js from telemetry.mozilla.org/v1/ -->
<script src="//telemetry.mozilla.org/v1/big.js"></script>
<script src="//telemetry.mozilla.org/v1/telemetry.js"></script>
<!-- Load jQuery and bootstrap from CDN (3rd party library) -->
<script src="//code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.0.2/js/bootstrap.min.js">
</script>
<!--
Include bootstrap-select and jQuery UI Widget factory (3rd party libraries)
jQuery UI Widget factory is required for jquery.telemetry.js, though full
JQuery UI library may also be used. bootstrap-select is a pretty <select>
implementation with search and groups.
-->
<script src="bootstrap-select.min.js"></script>
<script src="jquery.ui.widget.js"></script>
<!--
jquery.telemetry.js implements a histogram filter that creates
<select>'s, loads histograms and fires an event when the
histogram changes. This frees us from reimplementing complicated
filtering UI. This library should be distributed with your application,
as opposed to being hot-linked like telemetry.js.
-->
<script src="jquery.telemetry.js"></script>
<!-- A <select> strategy for jquery.telemetry.js to use bootstrap-select -->
<script src="bootstrap-selector.js"></script>
<!-- Finally, we include application code -->
<script src="script.js"></script>
</head>
<body class="container">
<header>
<h1>Telemetry CSV Histogram Exporter</h1>
</header>
<nav class="navbar navbar-default navbar-affix-top" role="navigation">
<!--
Histogram filters populated with bootstrap-select's by jquery.telemetry.js
(using bootstrap-selector.js with jquery.telemetry.js)
-->
<form id="filters" class="navbar-form navbar-left form-inline"></form>
</nav>
<section class="row">
<!-- Content to be displayed after loading histogram -->
<div id="content" class="col-md-12">
<!-- Information on filtered histogram -->
<dl class="dl-horizontal">
<dt>Submissions</dt>
<dd id="submissions"></dd>
<dt>Number of dates</dt>
<dd id="dates"></dd>
</dl>
<!-- Download link styled as button -->
<a id="download" class="btn btn-primary" href="#">
<i class="fa fa-download"></i>
Download as CSV
</a>
</div>
<!-- Spinner to be displayed while loading -->
<div id="spinner" class="col-md-12">
<i class="fa fa-spinner fa-spin"></i>
</div>
</section>
</body>
</html>
/**
* jQuery Telemetry plugin, providing utility widgets for easy filtering and
* presentation of Telemetry histograms. Requires jquery.ui.widget.js and
* telemetry.js, please make sure Telemetry.init() has called back before using
* any elements from this module.
*/
(function($){
"use strict";
// Auxiliary function for parsing a state string to an array of fragments
function _parseState(state) {
return (state || "").split("/").map(decodeURIComponent);
}
// Auxiliary function for creating a state string from an array of fragments
function _encodeStateFragments(fragments) {
return fragments.map(encodeURIComponent).join("/");
}
/**
* Telemetry histogramfilter widget, a simple widget that manages the <select>
* elements to filter a histogram. Whenever, the selected filters are changed
* the histogramfilterchange event is triggered.
* This event is triggered with a new state and a histogram, null, if currently
* loading. The state parameter can be used to set window.location.hash and only
* consists of encodeURIComponent() encoded characters and slash "/" characters.
*
* Remark: The histogramfilterchange maybe triggered twice with the same state
* once, when a new filter is selected and histogram is loading, and once when
* the histogram have loaded. This allows UI to present a loading graphics,
* while histogram is loaded. However, sometimes the histogram will only need
* to be filter, thus, no loading will be involved.
*/
$.widget("telemetry.histogramfilter", {
/** Default options */
options: {
/** Class use to style <select> elements */
selectorClass: "histogram-filter",
/** Initial state of histogram filter */
state: null,
/**
* Default version, or function that takes a list of versions and returns
* the default version.
*/
defaultVersion: null,
/**
* Default measure, or function that takes a JSON object of measure ids as
* created by Telemetry.measures() and returns a measure id.
*/
defaultMeasure: null,
/**
* Attempt to auto restore low level filters when a high level filter is
* changed, e.g. restore measure and other filters, when version is changed.
*/
attemptFilterAutoRestore: true,
/**
* Synchronize state with window.location.hash, do not use this option if
* you intend to have multiple instances of histogramfilter!
*/
synchronizeStateWithHash: false,
/**
* List of histogram kinds to which measure selection should be limited,
* this is useful if your dashboard is specialized in a specific kind of
* histograms: linear, exponential, flag, boolean, enumerated
*/
allowedHistogramKinds: null,
/** Prefix for state() if synchronizeStateWithHash is true */
windowHashPrefix: "",
/**
* Load histogram evolution over "Builds" or "Time".
*
* If "Builds" is chosen the HistogramEvolution instances returned by this
* filter will have dates corresponding to build dates.
* If "Time" is chosen, dates in the HistogramEvolution instances returned
* will be telemetry ping submission dates. See telemetry.js for more
* information.
*/
evolutionOver: "Builds",
/**
* Constructor for type to use for selectors. The default constructor
* creates a type that wraps a <select> element.
*
* Objects constructed with `selectorType` should have following methods:
* - element() Get jQuery wrapped element to add to container
* - options(opts) Get/set list of options.
* - val(v) Get/set currently selected option
* - change(cb) Set value changed callback, invoked as
* cb(selectorTypeInstance, value)
* - destroy() Remove jQuery wrapped element, unbind event listeners,
* and release resources held.
*
* The constructor `selectorType` will be given filterName as argument,
* which may take one of the following values:
* - 'version', 'measure', 'reason', 'appName', 'OS', 'osVersion', 'arch'
*/
selectorType: (function(){
/**
* Construct a selector given a filter name, valid filter names are:
* - 'version', 'measure', 'reason', 'appName', 'OS', 'osVersion', 'arch'
* Default option, if supported, is filterName + '*'
*/
function DefaultSelector(filterName) {
this._filterName = filterName;
this._select = $("<select>");
this._options = [];
this._select.bind("change", $.proxy(function() {
if (this._callback !== undefined) {
this._callback(this, this.val());
}
}, this));
}
// Methods for selector strategy
$.extend(DefaultSelector.prototype, {
/** Returns a jQuery wrapper for the underlying DOM element */
element: function DefaultSelector_element() {
return this._select;
},
/** Get/set selectable options */
options: function DefaultSelector_options(options) {
if (options !== undefined) {
// Clear existing options
this._select.empty();
var n = options.length;
for(var i = 0; i < n; i++) {
var option = options[i];
var label = option;
// Special label if we're displaying versions
if (this._filterName === "version") {
label = option.replace("/", " ");
}
// Add <option>
this._select.append($("<option>", {
text: label,
value: option
}));
}
// Store options for another time
this._options = options;
}
return this._options;
},
/** Get/set selected value */
val: function DefaultSelector_value(value) {
if (value !== undefined) {
this._select.val(value);
}
return this._select.val();
},
/**
* Set change callback, only one callback supported, invocation without
* the callback argument unbinds previous callback. The callback is
* invoked as: callback(this, selectedValue)
*/
change: function DefaultSelector_change(callback) {
this._callback = callback;
},
/** Clean up, after element() being detached */
destroy: function DefaultSelector_remove() {
this._callback = null;
this._options = null;
this._select.remove();
}
});
return DefaultSelector;
})()
},
/** Create new histogramfilter */
_create: function histogramfilter__create() {
// Bind event handlers to this
this._versionChanged = $.proxy(this._versionChanged, this);
this._measureChanged = $.proxy(this._measureChanged, this);
this._filterChanged = $.proxy(this._filterChanged, this);
this._windowHashChanged = $.proxy(this._windowHashChanged, this);
// Create version and measure selectors
this._versionSelector = new this.options.selectorType('version');
this._measureSelector = new this.options.selectorType('measure');
this._versionSelector.options(Telemetry.versions());
this._versionSelector.element().addClass(this.options.selectorClass);
this._measureSelector.element().addClass(this.options.selectorClass);
// Append version and measure selectors
this.element.append(this._versionSelector.element());
this.element.append(this._measureSelector.element());
// Flag to ignore changes to select elements
this._ignoreChanges = false;
// Listen for selector changes
this._versionSelector.change(this._versionChanged);
this._measureSelector.change(this._measureChanged);
// List of filters where each filter is represented by:
// {
// select: selectorType, // selectorType instance
// histogram: HistogramEvolution // HistogramEvolution instance to be
// // filtered by selected option
// }
this._filterList = [];
// State to restore from
var state = this.options.state;
// Setup window.location.hash synchronization
if(this.options.synchronizeStateWithHash) {
// Get hash from window, if not provided by
var prefixLength = this.options.windowHashPrefix.length;
state = state || window.location.hash.substr(1 + prefixLength);
// Listen for hashchange events
$(window).bind("hashchange", this._windowHashChanged);
}
// Restore state
this.state(state);
},
/** Get or set state of filter */
state: function histogramfilter_state(state) {
// Restore state if provided
if (state !== undefined) {
// Just set the state as we're restoring it
this.options.state = state;
// Parse state to find fragments
var fragments = _parseState(state);
// Version entry should always contain a slash
var version = fragments.shift() + "/" + fragments.shift();
// Get measure
var measure = fragments.shift();
// Restore version, etc. and trigger an change event
this._restoreVersion(version, measure, fragments);
}
return this.options.state;
},
/**
* Get current histogram, returns an instance of Telemetry.HistogramEvolution
* or null if currently loading.
*/
histogram: function histogramfilter_histogram() {
// Get filter list length
var n = this._filterList.length;
// If there is a last filter, get the histogram from it and apply the
// select option, if not default
var histogram = null;
if (n !== 0) {
// Get last filter
var filter = this._filterList[n - 1];
// Get histogram
histogram = filter.histogram;
// Get selected option
var option = filter.select.val();
// If selected option isn't the default option and the option is available
if (option != histogram.filterName() + "*" &&
histogram.filterOptions().indexOf(option) !== -1) {
// Filter the histogram
histogram = histogram.filter(option);
}
}
// Return the histogram we found
return histogram;
},
/** Set option */
_setOption: function histogramfilter__setOption(option, value) {
if (option == "state") {
// Set state option using state setter
this.state(value);
} else if (option == "evolutionOver") {
// Change what we load evolution over
this.options.evolutionOver = value;
var state = this.state();
// Force reload of filters, so it doesn't believe we're already loaded
this._clearFilterList();
// Reload state, this should refresh and reload as best possible
this.state(state);
} else if (option == "selectorClass") {
// Change class for each selector
var oldValue = this.options.selectorClass;
// Restyle version and measure selectors
this._versionSelector.element()
.removeClass(oldValue)
.addClass(value);
this._measureSelector.element()
.removeClass(oldValue)
.addClass(value);
// Update options
this.options.selectorClass = value;
// Restyle filters by recreating them using set state(get state)
this.state(this.state());
} else if (option == "selectorType") {
// Save current state
var state = this.state();
// Clear existing filters
this._clearFilterList()
// Remove version and measure selectors
this._versionSelector.destroy();
this._measureSelector.destroy();
// Update options
this.options.selectorType = value;
// Create version and measure selectors
this._versionSelector = new this.options.selectorType('version');
this._measureSelector = new this.options.selectorType('measure');
this._versionSelector.options(Telemetry.versions());
this._versionSelector.element().addClass(this.options.selectorClass);
this._measureSelector.element().addClass(this.options.selectorClass);
// Append version and measure selectors
this.element.append(this._versionSelector.element());
this.element.append(this._measureSelector.element());
// Restore state and filters with their new type
this.state(this.state());
} else if (option == "synchronizeStateWithHash") {
// Update options
this.options.synchronizeStateWithHash = value;
// Bind/unbind from hashchange event
if (value) {
$(window).bind("hashchange", this._windowHashChanged);
} else {
$(window).unbind("hashchange", this._windowHashChanged);
}
} else {
this.options[option] = value;
}
},
/**
* Event handler for the hashchange event on window, used if configured to
* synchronize state with window.location.hash.
* See options.synchronizeStateWithHash
*/
_windowHashChanged: function histogramfilter__windowHashChanged() {
// Get state from hash
var prefixLength = this.options.windowHashPrefix.length;
var hashState = window.location.hash.substr(1 + prefixLength);
// Update if it doesn't match current state
if (this.state() != hashState) {
this.state(hashState);
}
},
/** Attempt to restore version with measures and filter fragments */
_restoreVersion: function histogramfilter__restoreVersion(version, measure,
fragments) {
// Validate selected version
var versions = Telemetry.versions();
if (versions.indexOf(version) === -1) {
version = this._defaultVersion(versions);
}
// Select version, but ignore this change in event handlers
this._ignoreChanges = true;
this._versionSelector.val(version);
this._ignoreChanges = false;
// Report that we're loading
this._triggerChange();
// Load measures for selected version
Telemetry.measures(version, $.proxy(function(measures) {
// Abort if another version have been selected while we loaded
if (this._versionSelector.val() !== version) {
return;
}
// If there is a list of allowed histogram kinds, we limit the list of
// measures under consideration to these measures
if (this.options.allowedHistogramKinds !== null) {
var allowedMeasures = {};
for(var m in measures) {
var kind = measures[m].kind;
if (this.options.allowedHistogramKinds.indexOf(kind) != -1) {
allowedMeasures[m] = measures[m];
}
}
}
// Choose default measure if desired isn't available
if(measures[measure] === undefined) {
measure = this._defaultMeasure(measures);
}
// Populate measures selector while ignoring changes in event handlers
this._ignoreChanges = true;
this._measureSelector.options(Object.keys(measures).sort());
this._ignoreChanges = false;
// Restore things at measure level
this._restoreMeasure(measure, fragments);
}, this));
},
/** Attempt to restore measure with filter fragments */
_restoreMeasure: function histogramfilter__restoreMeasure(measure,
fragments) {
// Select measure, ignoring changes in event handlers
this._ignoreChanges = true;
this._measureSelector.val(measure);
this._ignoreChanges = false;
// Get version to load histogram for
var version = this._versionSelector.val();
// Report that we're loading
this._triggerChange();
// Load histogram for desired measure
var loader = "loadEvolutionOver" + this.options.evolutionOver;
Telemetry[loader](version, measure, $.proxy(function(hgram) {
// Abort if another version or measure have been selected while we loaded
if (this._versionSelector.val() !== version ||
this._measureSelector.val() !== measure) {
return;
}
// Clear filters just to be safe
this._clearFilterList();
// Attempt to restore filters from fragments and trigger change event
this._restoreFilters(hgram, fragments);
}, this));
},
/**
* Attempt to restore remaining filters from histogram and state fragments.
* This method assumes filters for which options are listed in fragments have
* already been cleared, and that first option of fragments to be applied to
* hgram immediately.
*/
_restoreFilters: function histogramfilter__restoreFilters(hgram, fragments) {
// Get filter name
var filterName = hgram.filterName();
// Try to restore filter if one exists
if(filterName !== null) {
// Get filter options
var options = hgram.filterOptions();
// Prepend default option
var defaultOption = filterName + "*";
options.unshift(defaultOption);
// Create a filter entry for the _filterList
var filter = {
select: new this.options.selectorType(filterName),
histogram: hgram
};
// Populate select with options and style it
filter.select.options(options);
filter.select.element().addClass(this.options.selectorClass);
// Now add filter to _filterList so it gets index we assigned above
this._filterList.push(filter);
// Restore option
var option = fragments.shift();
// If option is invalid or default, we restore default and clear fragments
if (options.indexOf(option) <= 0) {
option = defaultOption;
fragments = [];
}
// Select option
filter.select.val(option);
// Listen for changes and append to root element
filter.select.change(this._filterChanged);
this.element.append(filter.select.element());
if (option != defaultOption) {
// If we didn't select the default option, filter histogram and continue
// to recursively restore remaining fragments
this._restoreFilters(hgram.filter(option), fragments);
} else {
// If we selected default options then no filters follows and we should
// trigger a change
this._triggerChange();
}
} else {
// If there's no filter available, then we've drilled all the way down and
// should trigger a change event
this._triggerChange();
}
},
/** Select default version from a list of versions, using this.options */
_defaultVersion: function histogramfilter__defaultVersion(versions) {
// Get default version
var version = this.options.defaultVersion;
// If function, use it to choose a version
if (version instanceof Function) {
version = version.call(this.element, versions);
}
// Validate selected version
if (versions.indexOf(version) == -1) {
// Now resort to choose the first version available
version = versions[0];
}
return version;
},
/**
* Select default measure given values as provided by Telemetry.measures(),
* note, you shouldn't have to overwrite this method. The same functionality
* is exposed through options.defaultMeasure which can also be specified as
* a function.
*/
_defaultMeasure:
function histogramfilter__defaultMeasure(measures) {
// Get default measure
var measure = this.options.defaultMeasure;
// If function, use it to choose a measure
if (measure instanceof Function) {
measure = measure.call(this.element, measures);
}
// Validate selected measure
if (measures[measure] === undefined) {
// Now resort to choose the first measure available
measure = Object.keys(measures).sort()[0]
}
return measure;
},
/** Selected version changed event handler */
_versionChanged: function histogramfilter__versionChanged() {
// If flagged to ignore changes in event handler, then we comply. This is
// usually done to avoid recursion and interference from event handlers
if (this._ignoreChanges) {
return;
}
// Get selected version
var version = this._versionSelector.val();
// Get selected measure, so we can restore it
var measure = this._measureSelector.val();
// Clear applied filters
var clearedFilters = this._clearFilterList();
// If we're not supposed to restore from them measure and clear filtered
// forget them
if(!this.options.attemptFilterAutoRestore) {
measure = null;
clearedFilters = [];
}
// Now restore version, measure and cleared filters as desired
// this will also trigger a changed event, so that's it
this._restoreVersion(version, measure, clearedFilters);
},
/** Selected measure changed event handler */
_measureChanged: function histogramfilter__measureChanged() {
// If flagged to ignore changes in event handler, then we comply. This is
// usually done to avoid recursion and interference from event handlers
if (this._ignoreChanges) {
return;
}
// Get selected measure
var measure = this._measureSelector.val();
// Clear applied filters
var clearedFilters = this._clearFilterList();
// If we're not supposed to restore from cleared filters we forget them
if(!this.options.attemptFilterAutoRestore) {
clearedFilters = [];
}
// Now restore measure and cleared filters as desired this will also
// trigger a changed event, so that's it
this._restoreMeasure(measure, clearedFilters);
},
/** Filter changed event handler */
_filterChanged: function histogramfilter__filterChanged(select, option) {
// If flagged to ignore changes in event handler, then we comply. This is
// usually done to avoid recursion and interference from event handlers
if (this._ignoreChanges) {
return;
}
// Find filter index in _filterList
var i, n = this._filterList.length;
for (i = 0; i < n; i++) {
if (this._filterList[i].select === select) {
break;
}
}
if (i >= n) {
throw new Error("Select not in _filterList");
}
// Find filter
var filter = this._filterList[i];
// Clear lower level filters
var clearedFilters = this._clearFilterList(i + 1);
// If we're not supposed to restore from cleared filters we forget them
if(!this.options.attemptFilterAutoRestore) {
clearedFilters = [];
}
// If we haven't chosen the default option, restore filters, or at least
// create next filter and trigger change event
if(filter.histogram.filterName() + "*" !== option) {
this._restoreFilters(filter.histogram.filter(option), clearedFilters);
} else {
// Otherwise, trigger the change event
this._triggerChange();
}
},
/**
* Clear _FilterList starting from given index, all if no index is given,
* and return a list of selected options for removed filters
*/
_clearFilterList: function histogramfilter__clearFilterList(index) {
if (index === undefined) {
index = 0;
}
// Remove filters from index forward from _filterList
var removed = this._filterList.splice(index);
// Remove <select> from removed filters and get selected options
var options = [];
var n = removed.length;
for (var i = 0; i < n; i++) {
// Get i'th removed filter
var filter = removed[i];
// Get selected option
var option = filter.select.val();
// If this isn't the last filter or we haven't selected the default option
// add it to the list of options
if (i != n - 1 || filter.histogram.filterName() + "*" != option) {
options.push(option);
}
// Remove filter
filter.select.destroy();
}
// Return list of removed options, for any body remotely interested in
// trying to restore them.
return options;
},
/** Trigger the histogramfilterchange event */
_triggerChange: function histogramfilter__triggerChange() {
// Version should be channel/version, and we wish to treat this as two
// fragments with respect to serialization
var fragments = this._versionSelector.val().split("/");
if (fragments.length != 2) {
// We need the version to be on format <channel>/<version> this is fairly
// stupid, and we might accidentally break this in the future, but there
// is not easy way to change it now... We should consider doing this when
// refactoring mr2disk.py
console.log("Telemetry versions are supposed to be <channel>/<version>" +
" changing this breaks jquery.telemetry.js");
}
// Append selected measure
fragments.push(this._measureSelector.val());
// For each filter with exception of the last one append selected value
var filter;
var n = this._filterList.length;
for (var i = 0; i < n - 1; i++) {
// Get i'th filter
filter = this._filterList[i];
// Append select option
fragments.push(filter.select.val());
}
// If there is a last filter, get the histogram from it and apply the
// select option, if not default
var histogram = null;
if (n !== 0) {
filter = this._filterList[n - 1];
// Get histogram
histogram = filter.histogram;
// Get selected option
var option = filter.select.val();
// If selected option isn't the default option and the option is available
if (option != histogram.filterName() + "*" &&
histogram.filterOptions().indexOf(option) != -1) {
// Filter the histogram
histogram = histogram.filter(option);
// Append option to fragments
fragments.push(option);
}
}
// Update cache state
this.options.state = _encodeStateFragments(fragments);
// If window.location.hash synchronization is active and we have altered
// the current state, we should update window.location.hash
var hashWithPrefix = this.options.windowHashPrefix + this.options.state;
if (this.options.synchronizeStateWithHash &&
hashWithPrefix != window.location.hash.substr(1)) {
window.location.hash = "#" + hashWithPrefix;
}
// Now trigger the histogramfilterchange event
this._trigger("change", null, {
state: this.options.state,
histogram: histogram
});
},
/** Destroy histogramfilter */
destroy: function histogramfilter_destroy() {
// Remove all selectors
this._versionSelector.remove();
this._measureSelector.remove();
this._clearFilterList();
// Destroy widget base class
$.Widget.prototype.destroy.call(this);
}
});
})(jQuery);
/*!
* jQuery UI Widget 1.10.3
* http://jqueryui.com
*
* Copyright 2013 jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* http://api.jqueryui.com/jQuery.widget/
*/
(function( $, undefined ) {
var uuid = 0,
slice = Array.prototype.slice,
_cleanData = $.cleanData;
$.cleanData = function( elems ) {
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
try {
$( elem ).triggerHandler( "remove" );
// http://bugs.jquery.com/ticket/8235
} catch( e ) {}
}
_cleanData( elems );
};
$.widget = function( name, base, prototype ) {
var fullName, existingConstructor, constructor, basePrototype,
// proxiedPrototype allows the provided prototype to remain unmodified
// so that it can be used as a mixin for multiple widgets (#8876)
proxiedPrototype = {},
namespace = name.split( "." )[ 0 ];
name = name.split( "." )[ 1 ];
fullName = namespace + "-" + name;
if ( !prototype ) {
prototype = base;
base = $.Widget;
}
// create selector for plugin
$.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) {
return !!$.data( elem, fullName );
};
$[ namespace ] = $[ namespace ] || {};
existingConstructor = $[ namespace ][ name ];
constructor = $[ namespace ][ name ] = function( options, element ) {
// allow instantiation without "new" keyword
if ( !this._createWidget ) {
return new constructor( options, element );
}
// allow instantiation without initializing for simple inheritance
// must use "new" keyword (the code above always passes args)
if ( arguments.length ) {
this._createWidget( options, element );
}
};
// extend with the existing constructor to carry over any static properties
$.extend( constructor, existingConstructor, {
version: prototype.version,
// copy the object used to create the prototype in case we need to
// redefine the widget later
_proto: $.extend( {}, prototype ),
// track widgets that inherit from this widget in case this widget is
// redefined after a widget inherits from it
_childConstructors: []
});
basePrototype = new base();
// we need to make the options hash a property directly on the new instance
// otherwise we'll modify the options hash on the prototype that we're
// inheriting from
basePrototype.options = $.widget.extend( {}, basePrototype.options );
$.each( prototype, function( prop, value ) {
if ( !$.isFunction( value ) ) {
proxiedPrototype[ prop ] = value;
return;
}
proxiedPrototype[ prop ] = (function() {
var _super = function() {
return base.prototype[ prop ].apply( this, arguments );
},
_superApply = function( args ) {
return base.prototype[ prop ].apply( this, args );
};
return function() {
var __super = this._super,
__superApply = this._superApply,
returnValue;
this._super = _super;
this._superApply = _superApply;
returnValue = value.apply( this, arguments );
this._super = __super;
this._superApply = __superApply;
return returnValue;
};
})();
});
constructor.prototype = $.widget.extend( basePrototype, {
// TODO: remove support for widgetEventPrefix
// always use the name + a colon as the prefix, e.g., draggable:start
// don't prefix for widgets that aren't DOM-based
widgetEventPrefix: existingConstructor ? basePrototype.widgetEventPrefix : name
}, proxiedPrototype, {
constructor: constructor,
namespace: namespace,
widgetName: name,
widgetFullName: fullName
});
// If this widget is being redefined then we need to find all widgets that
// are inheriting from it and redefine all of them so that they inherit from
// the new version of this widget. We're essentially trying to replace one
// level in the prototype chain.
if ( existingConstructor ) {
$.each( existingConstructor._childConstructors, function( i, child ) {
var childPrototype = child.prototype;
// redefine the child widget using the same prototype that was
// originally used, but inherit from the new version of the base
$.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor, child._proto );
});
// remove the list of existing child constructors from the old constructor
// so the old child constructors can be garbage collected
delete existingConstructor._childConstructors;
} else {
base._childConstructors.push( constructor );
}
$.widget.bridge( name, constructor );
};
$.widget.extend = function( target ) {
var input = slice.call( arguments, 1 ),
inputIndex = 0,
inputLength = input.length,
key,
value;
for ( ; inputIndex < inputLength; inputIndex++ ) {
for ( key in input[ inputIndex ] ) {
value = input[ inputIndex ][ key ];
if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) {
// Clone objects
if ( $.isPlainObject( value ) ) {
target[ key ] = $.isPlainObject( target[ key ] ) ?
$.widget.extend( {}, target[ key ], value ) :
// Don't extend strings, arrays, etc. with objects
$.widget.extend( {}, value );
// Copy everything else by reference
} else {
target[ key ] = value;
}
}
}
}
return target;
};
$.widget.bridge = function( name, object ) {
var fullName = object.prototype.widgetFullName || name;
$.fn[ name ] = function( options ) {
var isMethodCall = typeof options === "string",
args = slice.call( arguments, 1 ),
returnValue = this;
// allow multiple hashes to be passed on init
options = !isMethodCall && args.length ?
$.widget.extend.apply( null, [ options ].concat(args) ) :
options;
if ( isMethodCall ) {
this.each(function() {
var methodValue,
instance = $.data( this, fullName );
if ( !instance ) {
return $.error( "cannot call methods on " + name + " prior to initialization; " +
"attempted to call method '" + options + "'" );
}
if ( !$.isFunction( instance[options] ) || options.charAt( 0 ) === "_" ) {
return $.error( "no such method '" + options + "' for " + name + " widget instance" );
}
methodValue = instance[ options ].apply( instance, args );
if ( methodValue !== instance && methodValue !== undefined ) {
returnValue = methodValue && methodValue.jquery ?
returnValue.pushStack( methodValue.get() ) :
methodValue;
return false;
}
});
} else {
this.each(function() {
var instance = $.data( this, fullName );
if ( instance ) {
instance.option( options || {} )._init();
} else {
$.data( this, fullName, new object( options, this ) );
}
});
}
return returnValue;
};
};
$.Widget = function( /* options, element */ ) {};
$.Widget._childConstructors = [];
$.Widget.prototype = {
widgetName: "widget",
widgetEventPrefix: "",
defaultElement: "<div>",
options: {
disabled: false,
// callbacks
create: null
},
_createWidget: function( options, element ) {
element = $( element || this.defaultElement || this )[ 0 ];
this.element = $( element );
this.uuid = uuid++;
this.eventNamespace = "." + this.widgetName + this.uuid;
this.options = $.widget.extend( {},
this.options,
this._getCreateOptions(),
options );
this.bindings = $();
this.hoverable = $();
this.focusable = $();
if ( element !== this ) {
$.data( element, this.widgetFullName, this );
this._on( true, this.element, {
remove: function( event ) {
if ( event.target === element ) {
this.destroy();
}
}
});
this.document = $( element.style ?
// element within the document
element.ownerDocument :
// element is window or document
element.document || element );
this.window = $( this.document[0].defaultView || this.document[0].parentWindow );
}
this._create();
this._trigger( "create", null, this._getCreateEventData() );
this._init();
},
_getCreateOptions: $.noop,
_getCreateEventData: $.noop,
_create: $.noop,
_init: $.noop,
destroy: function() {
this._destroy();
// we can probably remove the unbind calls in 2.0
// all event bindings should go through this._on()
this.element
.unbind( this.eventNamespace )
// 1.9 BC for #7810
// TODO remove dual storage
.removeData( this.widgetName )
.removeData( this.widgetFullName )
// support: jquery <1.6.3
// http://bugs.jquery.com/ticket/9413
.removeData( $.camelCase( this.widgetFullName ) );
this.widget()
.unbind( this.eventNamespace )
.removeAttr( "aria-disabled" )
.removeClass(
this.widgetFullName + "-disabled " +
"ui-state-disabled" );
// clean up events and states
this.bindings.unbind( this.eventNamespace );
this.hoverable.removeClass( "ui-state-hover" );
this.focusable.removeClass( "ui-state-focus" );
},
_destroy: $.noop,
widget: function() {
return this.element;
},
option: function( key, value ) {
var options = key,
parts,
curOption,
i;
if ( arguments.length === 0 ) {
// don't return a reference to the internal hash
return $.widget.extend( {}, this.options );
}
if ( typeof key === "string" ) {
// handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } }
options = {};
parts = key.split( "." );
key = parts.shift();
if ( parts.length ) {
curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] );
for ( i = 0; i < parts.length - 1; i++ ) {
curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {};
curOption = curOption[ parts[ i ] ];
}
key = parts.pop();
if ( value === undefined ) {
return curOption[ key ] === undefined ? null : curOption[ key ];
}
curOption[ key ] = value;
} else {
if ( value === undefined ) {
return this.options[ key ] === undefined ? null : this.options[ key ];
}
options[ key ] = value;
}
}
this._setOptions( options );
return this;
},
_setOptions: function( options ) {
var key;
for ( key in options ) {
this._setOption( key, options[ key ] );
}
return this;
},
_setOption: function( key, value ) {
this.options[ key ] = value;
if ( key === "disabled" ) {
this.widget()
.toggleClass( this.widgetFullName + "-disabled ui-state-disabled", !!value )
.attr( "aria-disabled", value );
this.hoverable.removeClass( "ui-state-hover" );
this.focusable.removeClass( "ui-state-focus" );
}
return this;
},
enable: function() {
return this._setOption( "disabled", false );
},
disable: function() {
return this._setOption( "disabled", true );
},
_on: function( suppressDisabledCheck, element, handlers ) {
var delegateElement,
instance = this;
// no suppressDisabledCheck flag, shuffle arguments
if ( typeof suppressDisabledCheck !== "boolean" ) {
handlers = element;
element = suppressDisabledCheck;
suppressDisabledCheck = false;
}
// no element argument, shuffle and use this.element
if ( !handlers ) {
handlers = element;
element = this.element;
delegateElement = this.widget();
} else {
// accept selectors, DOM elements
element = delegateElement = $( element );
this.bindings = this.bindings.add( element );
}
$.each( handlers, function( event, handler ) {
function handlerProxy() {
// allow widgets to customize the disabled handling
// - disabled as an array instead of boolean
// - disabled class as method for disabling individual parts
if ( !suppressDisabledCheck &&
( instance.options.disabled === true ||
$( this ).hasClass( "ui-state-disabled" ) ) ) {
return;
}
return ( typeof handler === "string" ? instance[ handler ] : handler )
.apply( instance, arguments );
}
// copy the guid so direct unbinding works
if ( typeof handler !== "string" ) {
handlerProxy.guid = handler.guid =
handler.guid || handlerProxy.guid || $.guid++;
}
var match = event.match( /^(\w+)\s*(.*)$/ ),
eventName = match[1] + instance.eventNamespace,
selector = match[2];
if ( selector ) {
delegateElement.delegate( selector, eventName, handlerProxy );
} else {
element.bind( eventName, handlerProxy );
}
});
},
_off: function( element, eventName ) {
eventName = (eventName || "").split( " " ).join( this.eventNamespace + " " ) + this.eventNamespace;
element.unbind( eventName ).undelegate( eventName );
},
_delay: function( handler, delay ) {
function handlerProxy() {
return ( typeof handler === "string" ? instance[ handler ] : handler )
.apply( instance, arguments );
}
var instance = this;
return setTimeout( handlerProxy, delay || 0 );
},
_hoverable: function( element ) {
this.hoverable = this.hoverable.add( element );
this._on( element, {
mouseenter: function( event ) {
$( event.currentTarget ).addClass( "ui-state-hover" );
},
mouseleave: function( event ) {
$( event.currentTarget ).removeClass( "ui-state-hover" );
}
});
},
_focusable: function( element ) {
this.focusable = this.focusable.add( element );
this._on( element, {
focusin: function( event ) {
$( event.currentTarget ).addClass( "ui-state-focus" );
},
focusout: function( event ) {
$( event.currentTarget ).removeClass( "ui-state-focus" );
}
});
},
_trigger: function( type, event, data ) {
var prop, orig,
callback = this.options[ type ];
data = data || {};
event = $.Event( event );
event.type = ( type === this.widgetEventPrefix ?
type :
this.widgetEventPrefix + type ).toLowerCase();
// the original event may come from any element
// so we need to reset the target on the new event
event.target = this.element[ 0 ];
// copy original event properties over to the new event
orig = event.originalEvent;
if ( orig ) {
for ( prop in orig ) {
if ( !( prop in event ) ) {
event[ prop ] = orig[ prop ];
}
}
}
this.element.trigger( event, data );
return !( $.isFunction( callback ) &&
callback.apply( this.element[0], [ event ].concat( data ) ) === false ||
event.isDefaultPrevented() );
}
};
$.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) {
$.Widget.prototype[ "_" + method ] = function( element, options, callback ) {
if ( typeof options === "string" ) {
options = { effect: options };
}
var hasOptions,
effectName = !options ?
method :
options === true || typeof options === "number" ?
defaultEffect :
options.effect || defaultEffect;
options = options || {};
if ( typeof options === "number" ) {
options = { duration: options };
}
hasOptions = !$.isEmptyObject( options );
options.complete = callback;
if ( options.delay ) {
element.delay( options.delay );
}
if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) {
element[ method ]( options );
} else if ( effectName !== method && element[ effectName ] ) {
element[ effectName ]( options.duration, options.easing, callback );
} else {
element.queue(function( next ) {
$( this )[ method ]();
if ( callback ) {
callback.call( element[ 0 ] );
}
next();
});
}
};
});
})( jQuery );
// First we wait for the page to load using jQuery
$(function(){
// HistogramEvolution instance loaded, null while loading
var histogramEvolution = null;
// Initialize telemetry.js
Telemetry.init(function() {
// Create histogram-filter from jquery.telemetry.js
$('#filters').histogramfilter({
// Synchronize selected histogram with window.location.hash
synchronizeStateWithHash: true,
// We'll use the BootstrapSelector strategy from bootstrap-selector.js
// to render <select>'s using bootstrap-select (3rd party library)
selectorType: BootstrapSelector,
// This demo fetches histograms aggregated by build date
evolutionOver: 'Builds',
// Strategy for selecting default version from list of versions
defaultVersion: function(versions) {
// Find nightlies sorted
var nightlies = versions.filter(function(version) {
return version.substr(0,8) == "nightly/";
}).sort();
// Return the last or the last of any version
return nightlies.pop() || versions.sort().pop();
}
});
// Listen for histogram-filter changes
$("#filters").bind("histogramfilterchange", function(event, data) {
// Get HistogramEvolution instance, and store it
histogramEvolution = data.histogram;
// Offer download once we have it, histogramEvolution will be null
// while loading...
if (histogramEvolution) {
// If not null then we'll update the information table
// and show content while hiding the spinner
update();
$('#content').show();
$('#spinner').hide();
} else {
// If histogramEvolution is null, then we're loading
$('#content').hide();
$('#spinner').show();
}
});
});
// When generating downloads we'll store the URL for the blob in
// _lastBlobUrl and free this when we overwrite the URL in the DOM
var _lastBlobUrl = null;
// Handle download requests, by generating a blob for download on the fly
$('#download').mousedown(function() {
// Free last blob URL if any
if (_lastBlobUrl) {
URL.revokeObjectURL(_lastBlobUrl);
_lastBlobUrl = null;
}
// Create total histogram aggregated accross all dates, note that
// histogramEvolution is a global variable set in the event handler
// for 'histogramfilterchange' on #filters
var total_hgram = histogramEvolution.range();
// Create columns one by one
var cols = [];
// Append column with bucket starts
cols.push(['start'].concat(
total_hgram.map(function(count, start, end, index) {
return start;
})
)
);
// Append column with bucket ends
cols.push(['end'].concat(
total_hgram.map(function(count, start, end, index) {
return end;
})
)
);
// Create and append column for each date, histogram pair
cols = cols.concat(histogramEvolution.map(function(date, histogram) {
return [formatDate(date)].concat(
histogram.map(function (count, start, end, index) {
return count;
})
);
}));
// Append column with bucket totals accross all dates
cols.push(['total'].concat(
total_hgram.map(function(count, start, end, index) {
return count;
})
)
);
// Create list of rows
var rows = [];
// For each row (all columns should have same number of rows)
var n = cols[0].length;
for(var i = 0; i < n; i++) {
rows.push(cols.map(function(col) {
return col[i];
}).join(',\t'));
}
// Join rows with a newline character
var csv = rows.join('\n');
// Create blob and URL for the blob
_lastBlobUrl = URL.createObjectURL(new Blob([csv]));
// Set url and name of the download file
$('#download')[0].href = _lastBlobUrl;
$('#download')[0].download = histogramEvolution.measure() + ".csv";
});
// Update filtered histogram information
function update() {
// Show number of submissions
$('#submissions').text(histogramEvolution.range().submissions());
// Count number of dates
var dates = 0;
histogramEvolution.each(function(date, histogram) {
dates += 1;
});
$('#dates').text(dates);
// This would also be a great place to plot histogramEvoltion as
// you like...
}
// Auxiliary function to pad number with zeroes
function pad(number, size) {
var s = number + "";
while (s.length < size) {
s = "0" + s;
}
return s;
}
// Auxiliary function to format date
function formatDate(date) {
return pad(date.getFullYear(), 4) + '/' + pad(date.getMonth() + 1, 2)
+ '/' + pad(date.getDate(), 2);
}
});
#content {
display: none;
}
#download {
margin-left: 12ex;
}
#filters .bootstrap-select{
margin: 2px;
}
.filter-version {
width: 120px !important;
}
.filter-measure {
width: 300px !important;
}
.filter-reason {
width: 130px !important;
}
.filter-appName, .filter-OS, .filter-osVersion, .filter-arch {
width: 100px !important;
}
#spinner {
font-size: 20px;
position: fixed;
top: 50%;
left: 50%;
margin: -10px 0 0 -10px;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment