<commit_before>var map,dialog,selSym,hc,qt,tempQuery,charts=[{source:"pt",chartType:"column",renderTo:"rainfall",
	labels:{title:"Average monthly rainfall"},plotOptions:{series:{pointWidth:25}},fields:
	[{flds:["rainJan","rainFeb","rainMar","rainApr","rainMay","rainJun","rainJul","rainAug",
	"rainSep","rainOct","rainNov","rainDec"]}],yAxis:{title:{text:"millimetres"}},xAxis:
	[{categories:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]}],
	ttip:{sfx:" mm/month"}},{plotOptions:{marker:{enabled:false}},source:"pt",chartType:"line",
	renderTo:"tempRange",labels:{title:"Average temperature range"},fields:[{flds:
	["minJan","minFeb","minMar","minApr","minMay","minJun","minJul","minAug","minSep","minOct",
	"minNov","minDec"]},{flds:["maxJan","maxFeb","maxMar","maxApr","maxMay","maxJun","maxJul",
	"maxAug","maxSep","maxOct","maxNov","maxDec"]}],yAxis:{title:{text:"deg Celsius"}},
	xAxis:[{categories:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]}],
	ttip:{sfx:" deg C"}},{source:"query",chartType:"spline",renderTo:"maxTemp",ttip:
	{sfx:" deg C"},labels:{title:"Average maximum temperature"},plotOptions:{spline:
	{marker:{enabled:false,states:{hover:{enabled:true,symbol:'circle',radius:5}}}}},yAxis:{title:{text:"deg C"}}}];
var base = "http://www.bom.gov.au/jsp/ncc/cdio/weatherData/av?p_nccObsCode=136&p_display_type=dailyDataFile&p_startYear=&p_c=&p_stn_num=";
require(["dojo/ready","esri/map","esri/tasks/query","esri/dijit/Geocoder","esri/layers/FeatureLayer",
	"dijit/layout/BorderContainer","dijit/layout/ContentPane","dijit/TooltipDialog","dijit/Popup"],function() {
	map = new esri.Map("map",{center: [133.9,-25.8],zoom: 5,basemap: "gray",maxZoom: 10});
	selSym = new esri.symbol.SimpleMarkerSymbol().setStyle(
		esri.symbol.SimpleMarkerSymbol.STYLE_CIRCLE).setColor(new dojo.Color([255,255,0,1]));
	var ws = new esri.layers.FeatureLayer(
		"http://services.azuron.com/arcgis/rest/services/weather/WeatherStations/MapServer/0",{
	    mode: esri.layers.FeatureLayer.MODE_ONDEMAND,outFields: ["*"],opacity: 0.75});
	dojo.connect(map,"onLoad",function(){map.addLayer(ws);});
	dojo.connect(ws,"onClick",function(evt){buildCharts(evt.graphic);});
	dojo.connect(ws,"onMouseOver",function(evt){map.setMapCursor("pointer");
		dialog.setContent(evt.graphic.attributes["Site_name"]);
		dijit.popup.open({popup:dialog,x:evt.pageX,y:evt.pageY});});
	dojo.connect(ws,"onMouseOut",function(evt){map.setMapCursor("default");dijit.popup.close();});
	dojo.connect(ws,"onLoad",function(){
	    var query = new esri.tasks.Query(); //prime the charts with a random station
	    query.objectIds = [Math.floor(Math.random()*1417)]; //there are 1418 stations
	    query.outFields = ["*"];
	    ws.queryFeatures(query,function(featureSet){buildCharts(featureSet.features[0]);});
	    dialog = new dijit.TooltipDialog({id:"tooltipDialog"});
	    dialog.startup();
	});
	var geocoder = new esri.dijit.Geocoder({map:map,autoComplete:true,
		arcgisGeocoder:{placeholder:"Find a place",sourceCountry:"AUS"}},"search");
    geocoder.startup();
    qt = new esri.tasks.QueryTask("http://services.azuron.com/arcgis/rest/services/weather/WeatherStations/MapServer/1");
    tempQuery = new esri.tasks.Query();
    tempQuery.outFields = ["*"];
});
function buildCharts(graphic) { //build charts from this station's values
	var name = graphic.attributes["Site_name"];
	if(name.length>25){name=name.substring(name,23) + "...";}
	$("#name").html(name);
	$("#source a").attr("href",base + graphic.attributes["Site"]);
	map.graphics.clear();
	var highlight = new esri.Graphic(graphic.geometry,selSym);
	map.graphics.add(highlight);
	$(charts).each(function(idx,hc){
		hc.series = new Array();
		hc.url = base + graphic.attributes["Site"];
		if (hc.source == "pt") {
			var attr = graphic.attributes;
			for (var y = 0; y < hc.fields.length; y++) {
				var flds = hc.fields[y].flds;
			    var field = flds[0];
			    var data = new Array();
			    data[0] = attr[field];
			    for (var x = 1; x < flds.length; x++) {data[x] = attr[flds[x]];}
			    hc.series[y] = new Object();
			    hc.series[y].data = data;
			}
			drawChart(hc);
		} else {
			tempQuery.where = "Site = " + graphic.attributes["Site"];
			qt.execute(tempQuery,function(results) {
				var data = [],cats = [];
				for (var j = 0; j < results.features.length; j++) {
					data.push(results.features[j].attributes.maxAvg);
					cats.push(results.features[j].attributes.year.toString());
				}
				hc.xAxis = {"categories": cats,labels: {step: Math.round(cats.length/5)}};
				hc.series[0] = new Object();
				hc.series[0].data = data;
				drawChart(hc);
			});
		}
	});
}
function drawChart(hc) {
	var chart = new Highcharts.Chart({
		credits: {
		            text: 'Bureau of Meteorology',
		            href: hc.url
        },
	    chart: {renderTo: hc.renderTo,defaultSeriesType: hc.chartType,
	    	marginBottom: 50},legend: {enabled: false},title: {text: hc.labels.title},
	    xAxis:hc.xAxis,yAxis: hc.yAxis,colors:['#4572A7','#AA4643'],
	    tooltip: {formatter: function () {return this.point.category+": "+this.point.y+hc.ttip.sfx;}},
	    plotOptions: hc.plotOptions,series: hc.series});}
function toggleWelcomeDialog() {$("#wd").is(':visible') ? $("#wd").hide() : $("#wd").show();}
$(document).on("click","#information",function() {toggleWelcomeDialog()});<commit_msg>chart improvements. Pause before loading initial chart<commit_after>var map,dialog,selSym,hc,qt,tempQuery,charts=[{source:"pt",chartType:"column",renderTo:"rainfall",
	labels:{title:"Average monthly rainfall"},plotOptions:{series:{pointWidth:25}},fields:
	[{flds:["rainJan","rainFeb","rainMar","rainApr","rainMay","rainJun","rainJul","rainAug",
	"rainSep","rainOct","rainNov","rainDec"]}],yAxis:{title:{text:"millimetres"}},xAxis:
	[{categories:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]}],
	ttip:{sfx:" mm/month"}},{plotOptions:{},source:"pt",chartType:"line",renderTo:
	"tempRange",labels:{title:"Average temperature range"},fields:[{flds:
	["minJan","minFeb","minMar","minApr","minMay","minJun","minJul","minAug","minSep","minOct",
	"minNov","minDec"]},{flds:["maxJan","maxFeb","maxMar","maxApr","maxMay","maxJun","maxJul",
	"maxAug","maxSep","maxOct","maxNov","maxDec"]}],yAxis:{title:{text:"deg Celsius"}},
	xAxis:[{categories:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]}],
	ttip:{sfx:" deg C"}},{source:"query",chartType:"spline",renderTo:"maxTemp",ttip:
	{sfx:" deg C"},labels:{title:"Average maximum temperature"},plotOptions:{spline:
	{marker:{enabled:false,states:{hover:{enabled:true,symbol:'circle',radius:5}}}}},yAxis:{title:{text: "deg C"}}}];
var base = "http://www.bom.gov.au/jsp/ncc/cdio/weatherData/av?p_nccObsCode=136&p_display_type=dailyDataFile&p_startYear=&p_c=&p_stn_num=";
require(["dojo/ready","esri/map","esri/tasks/query","esri/dijit/Geocoder","esri/layers/FeatureLayer",
	"dijit/layout/BorderContainer","dijit/layout/ContentPane","dijit/TooltipDialog","dijit/Popup"],function() {
	map = new esri.Map("map",{center: [133.9,-25.8],zoom: 5,basemap: "gray",maxZoom: 10});
	selSym = new esri.symbol.SimpleMarkerSymbol().setStyle(
		esri.symbol.SimpleMarkerSymbol.STYLE_CIRCLE).setColor(new dojo.Color([255,255,0,1]));
	var ws = new esri.layers.FeatureLayer(
		"http://services.azuron.com/arcgis/rest/services/weather/WeatherStations/MapServer/0",{
	    mode: esri.layers.FeatureLayer.MODE_ONDEMAND,outFields: ["*"],opacity: 0.75});
	dojo.connect(map,"onLoad",function(){map.addLayer(ws);});
	dojo.connect(ws,"onClick",function(evt){buildCharts(evt.graphic);});
	dojo.connect(ws,"onMouseOver",function(evt){map.setMapCursor("pointer");
		dialog.setContent(evt.graphic.attributes["Site_name"]);
		dijit.popup.open({popup:dialog,x:evt.pageX,y:evt.pageY});});
	dojo.connect(ws,"onMouseOut",function(evt){map.setMapCursor("default");dijit.popup.close();});
	dojo.connect(ws,"onLoad", function() {setTimeout(function(){
	    var query = new esri.tasks.Query(); //prime the charts with a random station
	    query.objectIds = [Math.floor(Math.random()*1417)]; //there are 1418 stations
	    query.outFields = ["*"];
	    ws.queryFeatures(query, function(featureSet) {
	    	buildCharts(featureSet.features[0]);
	    });}, 1000);
	    dialog = new dijit.TooltipDialog({id: "tooltipDialog"});
	    dialog.startup();
	});
	var geocoder = new esri.dijit.Geocoder({map:map,autoComplete:true,
		arcgisGeocoder:{placeholder:"Find a place",sourceCountry:"AUS"}},"search");
    geocoder.startup();
    qt = new esri.tasks.QueryTask("http://services.azuron.com/arcgis/rest/services/weather/WeatherStations/MapServer/1");
    tempQuery = new esri.tasks.Query();
    tempQuery.outFields = ["*"];
});
function buildCharts(graphic) { //build charts from this station's values
	var name = graphic.attributes["Site_name"];
	if(name.length>25){name=name.substring(name,23) + "...";}
	$("#name").html(name);
	$("#source a").attr("href",base + graphic.attributes["Site"]);
	map.graphics.clear();
	var highlight = new esri.Graphic(graphic.geometry,selSym);
	map.graphics.add(highlight);
	$(charts).each(function(idx,hc){
		hc.series = new Array();
		if (hc.source == "pt") {
			var attr = graphic.attributes;
			for (var y = 0; y < hc.fields.length; y++) {
				var flds = hc.fields[y].flds;
			    var field = flds[0];
			    var data = new Array();
			    data[0] = attr[field];
			    for (var x = 1; x < flds.length; x++) {data[x] = attr[flds[x]];}
			    hc.series[y] = new Object();
			    hc.series[y].data = data;
			}
			drawChart(hc);
		} else {
			tempQuery.where = "Site = " + graphic.attributes["Site"];
			qt.execute(tempQuery,function(results) {
				var data = [],cats = [];
				for (var j = 0; j < results.features.length; j++) {
					data.push(results.features[j].attributes.maxAvg);
					cats.push(results.features[j].attributes.year.toString());
				}
				hc.xAxis = {"categories": cats,labels: {step: Math.round(cats.length/5)}};
				hc.series[0] = new Object();
				hc.series[0].data = data;
				drawChart(hc);
			});
		}
	});
}
function drawChart(hc) {
	var chart = new Highcharts.Chart({
	    chart: {renderTo: hc.renderTo,defaultSeriesType: hc.chartType,
	    	marginBottom: 50},legend: {enabled: false},title: {text: hc.labels.title},
	    xAxis:hc.xAxis,credits: {enabled: false},yAxis: hc.yAxis,colors:['#4572A7','#AA4643'],
	    tooltip: {formatter: function () {return this.point.category+": "+this.point.y+hc.ttip.sfx;}},
	    plotOptions: hc.plotOptions,series: hc.series});}
function toggleWelcomeDialog() {$("#wd").is(':visible') ? $("#wd").hide() : $("#wd").show();}
$(document).on("click","#information",function() {toggleWelcomeDialog()});<|endoftext|>


<commit_before>var api_version = "1";

(function () {
    Parse.initialize(parseComAppId, parseComJsKey);

    var Benchmark = Parse.Object.extend("Benchmark");
    var BenchmarkCollection = Parse.Collection.extend({
        model: Benchmark
    });
    var benchmarks = new BenchmarkCollection();
    benchmarks.fetch({
        success: function (benchmarks) {
            var aggregatedData = {};
            benchmarks.each(function (object) {
                var bm = object.attributes;
                console.log('Benchmark:', bm);

                var test_name = bm.app_label + " Django " + bm.django_version + " " + bm.database_vendor;

                if (aggregatedData[test_name] === undefined) {
                    aggregatedData[test_name] = []
                }
                aggregatedData[test_name].push({x: bm.num_models, y: bm.query_time_sql});
            });

            var rawData = [];
            $.each(aggregatedData, function(key, values) {
                rawData.push({
                    key: key,
                    values: values,
                });
            });

            nv.addGraph(function() {
              var chart = nv.models.lineWithFocusChart();

              chart.xAxis
                  .tickFormat(d3.format(',f'));
              chart.x2Axis
                  .tickFormat(d3.format(',f'));

              chart.yAxis
                  .tickFormat(d3.format(',.2f'));
              chart.y2Axis
                  .tickFormat(d3.format(',.2f'));

              d3.select("#canvas svg")
                  .datum(rawData)
                  .call(chart);

              nv.utils.windowResize(chart.update);

              return chart;
            });
        }
    });

})();
<commit_msg>Remove console.log from mti.js<commit_after>var api_version = "1";

(function () {
    Parse.initialize(parseComAppId, parseComJsKey);

    var Benchmark = Parse.Object.extend("Benchmark");
    var BenchmarkCollection = Parse.Collection.extend({
        model: Benchmark
    });
    var benchmarks = new BenchmarkCollection();
    benchmarks.fetch({
        success: function (benchmarks) {
            var aggregatedData = {};
            benchmarks.each(function (object) {
                var bm = object.attributes;
                var test_name = bm.app_label + " Django " + bm.django_version + " " + bm.database_vendor;

                if (aggregatedData[test_name] === undefined) {
                    aggregatedData[test_name] = []
                }
                aggregatedData[test_name].push({x: bm.num_models, y: bm.query_time_sql});
            });

            var rawData = [];
            $.each(aggregatedData, function(key, values) {
                rawData.push({
                    key: key,
                    values: values,
                });
            });

            nv.addGraph(function() {
              var chart = nv.models.lineWithFocusChart();

              chart.xAxis
                  .tickFormat(d3.format(',f'));
              chart.x2Axis
                  .tickFormat(d3.format(',f'));

              chart.yAxis
                  .tickFormat(d3.format(',.2f'));
              chart.y2Axis
                  .tickFormat(d3.format(',.2f'));

              d3.select("#canvas svg")
                  .datum(rawData)
                  .call(chart);

              nv.utils.windowResize(chart.update);

              return chart;
            });
        }
    });

})();
<|endoftext|>


<commit_before>$(function(){
    return $.getJSON('/api/v1/assign_roles/users', function (data) {
      window.users=Object.keys(data)
        .map(n=>{
            return {val:n.split('@')[0]};
        });
    });
});

function generate_category_label(category){
     var cat_classes = {
        'Workset': ['primary', 'calendar-plus'],
        'Flowcell': ['success', 'grip-vertical'],
        'Decision': ['info', 'thumbs-up'],
        'Lab': ['success', 'flask'],
        'Bioinformatics': ['warning', 'laptop-code'],
        'User Communication': ['usr', 'people-arrows'],
        'Administration': ['danger', 'folder-open'],
        'Important': ['imp', 'exclamation-circle'],
        'Deviation': ['devi', 'frown']
    }
    // Remove the whitespace
    var category = category.trim()
    // Check if we recognise this category in the class object keys
    if (Object.keys(cat_classes).indexOf(category) != -1){
        cat_label = ''+ category + ' ' + ''+"";
    }else{
    // Default button formatting
        cat_label = ''+ category +"";
    }
    return cat_label;
}

function get_note_url() {
    // URL for the notes
    if ((typeof notetype !== 'undefined' && notetype == 'lims_step') || ('lims_step' in window && lims_step !== null)){
        note_url='/api/v1/workset_notes/' + lims_step;
    } else if ((typeof notetype !== 'undefined' && notetype == 'flowcell') || ('flowcell' in window && flowcell!== null)){
        note_url='/api/v1/flowcell_notes/' + flowcell;
    } else {
        note_url='/api/v1/running_notes/' + project;
    }
    return note_url;
}

function make_running_note(date, note){
  try {
    var category = '';
    var date = date.replace(/-/g, '/');
    date = date.replace(/\.\d{6}/, '');
    date = new Date(date);
    if (note['note'] != undefined){
        if(date > new Date('2015-01-01')){
          noteText = make_markdown(note['note']);
        } else {
          noteText = '
'+make_project_links(note['note'])+'
';
        }
        datestring = date.toDateString() + ', ' + date.toLocaleTimeString(date);
        var page_to_link = '';
        if(typeof project !== 'undefined'){
          page_to_link = project;
        }
        else if (typeof flowcell!== 'undefined') {
          page_to_link = flowcell;
        }
        else if(typeof workset_name !== 'undefined'){
          page_to_link = workset_name
        }
        note_id = 'running_note_'+page_to_link+'_'+(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(),
                   date.getUTCDate(), date.getHours(), date.getMinutes(), date.getSeconds())/1000);
        if ('category' in note){
            category=generate_category_label(note['category']);
        }
    }
  } catch(e){
    noteText = '
'+make_project_links(note['note'])+'
';
    var datestring = '?';
  }
  var printHyphen =category? ' - ': ' ';
  var panelClass='';
  if (note['category'] == 'Important') {
    panelClass = 'card-important';
  }
  return '
' +
      '
'+
        ''+note['user']+' - '+
       '' + datestring + '' + printHyphen +category +'

'+noteText+'

';
}

function load_running_notes(wait) {
  // Clear previously loaded notes, if so
  note_url = get_note_url();
  $("#running_notes_panels").empty();
  return $.getJSON(note_url, function(data) {
    if(Object.keys(data).length == 0 || typeof data === 'undefined'){
      $('#running_notes_panels').html('
No running notes found.
');
    } else {
      $.each(data, function(date, note) {
        $('#running_notes_panels').append(make_running_note(date, note));
      });
      check_img_sources($('#running_notes_panels img'));
    }
  }).fail(function( jqxhr, textStatus, error ) {
      try {
        var response = JSON.parse(jqxhr.responseText);
        var err = response['page_title'];
        var exception = $('
').text(response['error_exception']).html(); // HTML encode string
        var debugging = "
For debugging purposes, we've tried to grab the error that triggered this page for you:
"+
                        '

'+exception+'';
      } catch(e) {
        var err = error+', '+textStatus;
        var debugging = '';
      }
      $('#running_notes_panels').append('
' +
          '
Error Loading Running Notes: '+err+'
' +
          '
Apologies, running notes could not be loaded.' +
          'Running notes are retrieved from the LIMS, so these problems are usually ' +
          'due to connection problems. Please try again later and report if the problem persists.

'+debugging);
  });
}
function preview_running_notes(){
    var now = new Date();
    $('.todays_date').text(now.toDateString() + ', ' + now.toLocaleTimeString());
    var category = generate_category_label($('.rn-categ button.active').text());
    category = category ? ' - '+ category : category;
    $('#preview_category').html(category);
    var text = $('#new_note_text').val().trim();
    text = $('
').text(text).html();
    if (text.length > 0) {
        $('#running_note_preview_body').html(make_markdown(text));
        check_img_sources($('#running_note_preview_body img'));
    } else {
        $('#running_note_preview_body').html('
Nothing to preview..
');
    }
    // update textarea height
    $('#new_note_text').css('height', $('#running_note_preview_panel').css('height'));
}
function filter_running_notes(search){
    search=search.toLowerCase();
    $('#running_notes_panels').children().each(function(){
        var header=$(this).children('.card-header').text();
        var note=$(this).children('.card-body').children().text();
        if (header.toLowerCase().indexOf(search) != -1 || note.toLowerCase().indexOf(search) != -1){
            $(this).show();
        }else{
            $(this).hide();
        }
    });
}
//Filter notes
$('#rn_search').keyup(function() {
    var search=$('#rn_search').val();
    filter_running_notes(search);
});

$(document).ready(function() {
    $('#rn_category').change(function() {
        var search=$('#rn_category :selected').text();
        if (search == 'All'){
            search='';
        }
        filter_running_notes(search);
    });
});

// Update the category buttons
$('.rn-categ button').click(function(e){
    e.preventDefault();
    var was_selected = $(this).hasClass('active');
    $('.rn-categ button').removeClass('active');
    if(!was_selected){
        $(this).addClass('active');
    }
    preview_running_notes();
});

//Remove hover text from clicked button
$(document).ready(function(){
      $('[data-toggle="tooltip"]').click(function (){
         $('[data-toggle="tooltip"]').tooltip("hide");
      });
})

// Preview running notes
$('#new_note_text').keyup(preview_running_notes);

// Insert new running note and reload the running notes table
$("#running_notes_form").submit( function(e) {
    e.preventDefault();
    var text = $('#new_note_text').val().trim();
    text = $('
').text(text).html();
    var category = $('.rn-categ button.active').text();
    if (text.length == 0) {
        alert("Error: No running note entered.");
        return false;
    }
    if (!$('.rn-categ button.active').text()) {
       if (!confirm("Are you sure that you want to submit without choosing a category?")) {
          return false;
       }
    }

    note_url = get_note_url()
    $('#save_note_button').addClass('disabled').text('Submitting..');
    $.ajax({
      type: 'POST',
      url: note_url,
      dataType: 'json',
      data: {"note": text, "category": category},
      error: function(xhr, textStatus, errorThrown) {
        alert('Error: '+xhr['responseText']+' ('+errorThrown+')');
        $('#save_note_button').removeClass('disabled').text('Submit Running Note');
        console.log(xhr);
        console.log(textStatus);
        console.log(errorThrown);
      },
      success: function(data, textStatus, xhr) {
        // Manually check whether the running note has saved - LIMS API always returns success
        note_url=get_note_url()
        $.getJSON(note_url, function(newdata) {
          var newNote = false;
          $.each(newdata, function(date, note) {
            if(data['note'] == note['note']){
              newNote = make_running_note(date, note);
            }
          });
          if(newNote){
            // Enable the submit button again
            $('#save_note_button').removeClass('disabled').text('Submit Running Note');
            // Clear the text box
            $('#new_note_text').val('');
            $('#running_note_preview_body').html('
Nothing to preview..
');
            $('#new_note_text').css('height', $('#running_note_preview_panel').css('height'));
            // Cler the 'no running notes found' box if it's there
            if($('#running_notes_panels').html() == '
No running notes found.
'){
              $('#running_notes_panels .well').slideUp(function(){ $(this).remove(); });
            }
            // Create a new running note and slide it in..
            var now = new Date();
            category=generate_category_label(category);
            var printHyphen =category? ' - ': ' ';
            $('

'+
                  ''+data['user']+' - '+
                  now.toDateString() + ', ' + now.toLocaleTimeString(now)+ printHyphen + category +
                '

'+make_markdown(data['note'])+
                '

').hide().prependTo('#running_notes_panels').slideDown();
            check_img_sources($('#running_notes_panels img'));
          } else {
            alert('Error - LIMS did not save your running note.');
            $('#save_note_button').removeClass('disabled').text('Submit Running Note');
          }
        });
      }
    });
});

$(document).ready().delay(1000).queue(function(){$('#new_note_text').sew({values:window.users})});
<commit_msg>Fix orientation of newly created running note<commit_after>$(function(){
    return $.getJSON('/api/v1/assign_roles/users', function (data) {
      window.users=Object.keys(data)
        .map(n=>{
            return {val:n.split('@')[0]};
        });
    });
});

function generate_category_label(category){
     var cat_classes = {
        'Workset': ['primary', 'calendar-plus'],
        'Flowcell': ['success', 'grip-vertical'],
        'Decision': ['info', 'thumbs-up'],
        'Lab': ['success', 'flask'],
        'Bioinformatics': ['warning', 'laptop-code'],
        'User Communication': ['usr', 'people-arrows'],
        'Administration': ['danger', 'folder-open'],
        'Important': ['imp', 'exclamation-circle'],
        'Deviation': ['devi', 'frown']
    }
    // Remove the whitespace
    var category = category.trim()
    // Check if we recognise this category in the class object keys
    if (Object.keys(cat_classes).indexOf(category) != -1){
        cat_label = ''+ category + ' ' + ''+"";
    }else{
    // Default button formatting
        cat_label = ''+ category +"";
    }
    return cat_label;
}

function get_note_url() {
    // URL for the notes
    if ((typeof notetype !== 'undefined' && notetype == 'lims_step') || ('lims_step' in window && lims_step !== null)){
        note_url='/api/v1/workset_notes/' + lims_step;
    } else if ((typeof notetype !== 'undefined' && notetype == 'flowcell') || ('flowcell' in window && flowcell!== null)){
        note_url='/api/v1/flowcell_notes/' + flowcell;
    } else {
        note_url='/api/v1/running_notes/' + project;
    }
    return note_url;
}

function make_running_note(date, note){
  try {
    var category = '';
    var date = date.replace(/-/g, '/');
    date = date.replace(/\.\d{6}/, '');
    date = new Date(date);
    if (note['note'] != undefined){
        if(date > new Date('2015-01-01')){
          noteText = make_markdown(note['note']);
        } else {
          noteText = '
'+make_project_links(note['note'])+'
';
        }
        datestring = date.toDateString() + ', ' + date.toLocaleTimeString(date);
        var page_to_link = '';
        if(typeof project !== 'undefined'){
          page_to_link = project;
        }
        else if (typeof flowcell!== 'undefined') {
          page_to_link = flowcell;
        }
        else if(typeof workset_name !== 'undefined'){
          page_to_link = workset_name
        }
        note_id = 'running_note_'+page_to_link+'_'+(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(),
                   date.getUTCDate(), date.getHours(), date.getMinutes(), date.getSeconds())/1000);
        if ('category' in note){
            category=generate_category_label(note['category']);
        }
    }
  } catch(e){
    noteText = '
'+make_project_links(note['note'])+'
';
    var datestring = '?';
  }
  var printHyphen =category? ' - ': ' ';
  var panelClass='';
  if (note['category'] == 'Important') {
    panelClass = 'card-important';
  }
  return '
' +
      '
'+
        ''+note['user']+' - '+
       '' + datestring + '' + printHyphen +category +'

'+noteText+'

';
}

function load_running_notes(wait) {
  // Clear previously loaded notes, if so
  note_url = get_note_url();
  $("#running_notes_panels").empty();
  return $.getJSON(note_url, function(data) {
    if(Object.keys(data).length == 0 || typeof data === 'undefined'){
      $('#running_notes_panels').html('
No running notes found.
');
    } else {
      $.each(data, function(date, note) {
        $('#running_notes_panels').append(make_running_note(date, note));
      });
      check_img_sources($('#running_notes_panels img'));
    }
  }).fail(function( jqxhr, textStatus, error ) {
      try {
        var response = JSON.parse(jqxhr.responseText);
        var err = response['page_title'];
        var exception = $('
').text(response['error_exception']).html(); // HTML encode string
        var debugging = "
For debugging purposes, we've tried to grab the error that triggered this page for you:
"+
                        '

'+exception+'';
      } catch(e) {
        var err = error+', '+textStatus;
        var debugging = '';
      }
      $('#running_notes_panels').append('
' +
          '
Error Loading Running Notes: '+err+'
' +
          '
Apologies, running notes could not be loaded.' +
          'Running notes are retrieved from the LIMS, so these problems are usually ' +
          'due to connection problems. Please try again later and report if the problem persists.

'+debugging);
  });
}
function preview_running_notes(){
    var now = new Date();
    $('.todays_date').text(now.toDateString() + ', ' + now.toLocaleTimeString());
    var category = generate_category_label($('.rn-categ button.active').text());
    category = category ? ' - '+ category : category;
    $('#preview_category').html(category);
    var text = $('#new_note_text').val().trim();
    text = $('
').text(text).html();
    if (text.length > 0) {
        $('#running_note_preview_body').html(make_markdown(text));
        check_img_sources($('#running_note_preview_body img'));
    } else {
        $('#running_note_preview_body').html('
Nothing to preview..
');
    }
    // update textarea height
    $('#new_note_text').css('height', $('#running_note_preview_panel').css('height'));
}
function filter_running_notes(search){
    search=search.toLowerCase();
    $('#running_notes_panels').children().each(function(){
        var header=$(this).children('.card-header').text();
        var note=$(this).children('.card-body').children().text();
        if (header.toLowerCase().indexOf(search) != -1 || note.toLowerCase().indexOf(search) != -1){
            $(this).show();
        }else{
            $(this).hide();
        }
    });
}
//Filter notes
$('#rn_search').keyup(function() {
    var search=$('#rn_search').val();
    filter_running_notes(search);
});

$(document).ready(function() {
    $('#rn_category').change(function() {
        var search=$('#rn_category :selected').text();
        if (search == 'All'){
            search='';
        }
        filter_running_notes(search);
    });
});

// Update the category buttons
$('.rn-categ button').click(function(e){
    e.preventDefault();
    var was_selected = $(this).hasClass('active');
    $('.rn-categ button').removeClass('active');
    if(!was_selected){
        $(this).addClass('active');
    }
    preview_running_notes();
});

//Remove hover text from clicked button
$(document).ready(function(){
      $('[data-toggle="tooltip"]').click(function (){
         $('[data-toggle="tooltip"]').tooltip("hide");
      });
})

// Preview running notes
$('#new_note_text').keyup(preview_running_notes);

// Insert new running note and reload the running notes table
$("#running_notes_form").submit( function(e) {
    e.preventDefault();
    var text = $('#new_note_text').val().trim();
    text = $('
').text(text).html();
    var category = $('.rn-categ button.active').text();
    if (text.length == 0) {
        alert("Error: No running note entered.");
        return false;
    }
    if (!$('.rn-categ button.active').text()) {
       if (!confirm("Are you sure that you want to submit without choosing a category?")) {
          return false;
       }
    }

    note_url = get_note_url()
    $('#save_note_button').addClass('disabled').text('Submitting...');
    $.ajax({
      type: 'POST',
      url: note_url,
      dataType: 'json',
      data: {"note": text, "category": category},
      error: function(xhr, textStatus, errorThrown) {
        alert('Error: '+xhr['responseText']+' ('+errorThrown+')');
        $('#save_note_button').removeClass('disabled').text('Submit Running Note');
        console.log(xhr);
        console.log(textStatus);
        console.log(errorThrown);
      },
      success: function(data, textStatus, xhr) {
        // Manually check whether the running note has saved - LIMS API always returns success
        note_url=get_note_url()
        $.getJSON(note_url, function(newdata) {
          var newNote = false;
          $.each(newdata, function(date, note) {
            if(data['note'] == note['note']){
              newNote = make_running_note(date, note);
            }
          });
          if(newNote){
            // Enable the submit button again
            $('#save_note_button').removeClass('disabled').text('Submit Running Note');
            // Clear the text box
            $('#new_note_text').val('');
            $('#running_note_preview_body').html('
Nothing to preview..
');
            $('#new_note_text').css('height', $('#running_note_preview_panel').css('height'));
            // Cler the 'no running notes found' box if it's there
            if($('#running_notes_panels').html() == '
No running notes found.
'){
              $('#running_notes_panels .well').slideUp(function(){ $(this).remove(); });
            }
            // Create a new running note and slide it in..
            var now = new Date();
            category=generate_category_label(category);
            var printHyphen =category? ' - ': ' ';
            $('

'+
                  ''+data['user']+' - '+
                  now.toDateString() + ', ' + now.toLocaleTimeString(now)+ printHyphen + category +
                '

'+make_markdown(data['note'])+
                '

').hide().prependTo('#running_notes_panels').slideDown();
            check_img_sources($('#running_notes_panels img'));
          } else {
            alert('Error - LIMS did not save your running note.');
            $('#save_note_button').removeClass('disabled').text('Submit Running Note');
          }
        });
      }
    });
});

$(document).ready().delay(1000).queue(function(){$('#new_note_text').sew({values:window.users})});
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree.
 */
'use strict';

function WebRTCCall(config) {
  this.pc1 = new RTCPeerConnection(config);
  this.pc2 = new RTCPeerConnection(config);

  this.pc1.addEventListener('icecandidate', this.onIceCandidate_.bind(this, this.pc2));
  this.pc2.addEventListener('icecandidate', this.onIceCandidate_.bind(this, this.pc1));

  this.iceCandidateFilter_ = WebRTCCall.noFilter;
}

WebRTCCall.prototype = {
  establishConnection: function () {
    this.pc1.createOffer(this.gotOffer_.bind(this));
  },

  close: function () {
    this.pc1.close();
    this.pc2.close();
  },

  setIceCandidateFilter: function (filter) {
    this.iceCandidateFilter_ = filter;
  },

  // Constraint max video bitrate by modifying the SDP when creating an answer.
  constrainVideoBitrate: function (maxVideoBitrateKbps) {
    this.constrainVideoBitrateKbps_ = maxVideoBitrateKbps;
  },

  // Remove video FEC if available on the offer.
  disableVideoFec: function () {
    this.constrainOfferToRemoveVideoFec_ = true;
  },

  gotOffer_: function (offer) {
    if (this.constrainOfferToRemoveVideoFec_) {
      offer.sdp = offer.sdp.replace(/(m=video 1 [^\r]+)(116 117)(\r\n)/g,
                                    '$1\r\n');
      offer.sdp = offer.sdp.replace(/a=rtpmap:116 red\/90000\r\n/g, '');
      offer.sdp = offer.sdp.replace(/a=rtpmap:117 ulpfec\/90000\r\n/g, '');
    }
    this.pc1.setLocalDescription(offer);
    this.pc2.setRemoteDescription(offer);
    this.pc2.createAnswer(this.gotAnswer_.bind(this));
  },

  gotAnswer_: function (answer) {
    if (this.constrainVideoBitrateKbps_) {
      answer.sdp = answer.sdp.replace(
          /a=mid:video\r\n/g,
          'a=mid:video\r\nb=AS:' + this.constrainVideoBitrateKbps_ + '\r\n');
    }
    this.pc2.setLocalDescription(answer);
    this.pc1.setRemoteDescription(answer);
  },

  onIceCandidate_: function (otherPeer) {
    if (event.candidate) {
      var parsed = WebRTCCall.parseCandidate(event.candidate.candidate);
      if (this.iceCandidateFilter_(parsed)) {
        otherPeer.addIceCandidate(event.candidate);
      }
    }
  }
};

WebRTCCall.noFilter = function () {
  return true;
};

WebRTCCall.isRelay = function (candidate) {
  return candidate.type === 'relay';
};

WebRTCCall.isIpv6 = function (candidate) {
  return candidate.address.indexOf(':') !== -1;
};

// Parse a 'candidate:' line into a JSON object.
WebRTCCall.parseCandidate = function (text) {
  var candidateStr = 'candidate:';
  var pos = text.indexOf(candidateStr) + candidateStr.length;
  var fields = text.substr(pos).split(' ');
  return {
    'type': fields[7],
    'protocol': fields[2],
    'address': fields[4],
  };
}

// Ask computeengineondemand to give us TURN server credentials and URIs.
WebRTCCall.CEOD_URL = 'https://computeengineondemand.appspot.com/turn?username=1234&key=5678';
WebRTCCall.asyncCreateTurnConfig = function (onSuccess, onError) {
  var xhr = new XMLHttpRequest();
  function onResult() {
    if (xhr.readyState !== 4) {
      return;
    }

    if (xhr.status !== 200) {
      onError('TURN request failed');
      return;
    }

    var response = JSON.parse(xhr.responseText);
    var iceServer = {
      'username': response.username,
      'credential': response.password,
      'urls': response.uris
    };
    onSuccess({ 'iceServers': [ iceServer ] });
  }

  xhr.onreadystatechange = onResult;
  xhr.open('GET', WebRTCCall.CEOD_URL, true);
  xhr.send();
}
<commit_msg>jshint fixes.<commit_after>/*
 *  Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree.
 */
'use strict';

function WebRTCCall(config) {
  this.pc1 = new RTCPeerConnection(config);
  this.pc2 = new RTCPeerConnection(config);

  this.pc1.addEventListener('icecandidate', this.onIceCandidate_.bind(this, this.pc2));
  this.pc2.addEventListener('icecandidate', this.onIceCandidate_.bind(this, this.pc1));

  this.iceCandidateFilter_ = WebRTCCall.noFilter;
}

WebRTCCall.prototype = {
  establishConnection: function () {
    this.pc1.createOffer(this.gotOffer_.bind(this));
  },

  close: function () {
    this.pc1.close();
    this.pc2.close();
  },

  setIceCandidateFilter: function (filter) {
    this.iceCandidateFilter_ = filter;
  },

  // Constraint max video bitrate by modifying the SDP when creating an answer.
  constrainVideoBitrate: function (maxVideoBitrateKbps) {
    this.constrainVideoBitrateKbps_ = maxVideoBitrateKbps;
  },

  // Remove video FEC if available on the offer.
  disableVideoFec: function () {
    this.constrainOfferToRemoveVideoFec_ = true;
  },

  gotOffer_: function (offer) {
    if (this.constrainOfferToRemoveVideoFec_) {
      offer.sdp = offer.sdp.replace(/(m=video 1 [^\r]+)(116 117)(\r\n)/g,
                                    '$1\r\n');
      offer.sdp = offer.sdp.replace(/a=rtpmap:116 red\/90000\r\n/g, '');
      offer.sdp = offer.sdp.replace(/a=rtpmap:117 ulpfec\/90000\r\n/g, '');
    }
    this.pc1.setLocalDescription(offer);
    this.pc2.setRemoteDescription(offer);
    this.pc2.createAnswer(this.gotAnswer_.bind(this));
  },

  gotAnswer_: function (answer) {
    if (this.constrainVideoBitrateKbps_) {
      answer.sdp = answer.sdp.replace(
          /a=mid:video\r\n/g,
          'a=mid:video\r\nb=AS:' + this.constrainVideoBitrateKbps_ + '\r\n');
    }
    this.pc2.setLocalDescription(answer);
    this.pc1.setRemoteDescription(answer);
  },

  onIceCandidate_: function (otherPeer) {
    if (event.candidate) {
      var parsed = WebRTCCall.parseCandidate(event.candidate.candidate);
      if (this.iceCandidateFilter_(parsed)) {
        otherPeer.addIceCandidate(event.candidate);
      }
    }
  }
};

WebRTCCall.noFilter = function () {
  return true;
};

WebRTCCall.isRelay = function (candidate) {
  return candidate.type === 'relay';
};

WebRTCCall.isIpv6 = function (candidate) {
  return candidate.address.indexOf(':') !== -1;
};

// Parse a 'candidate:' line into a JSON object.
WebRTCCall.parseCandidate = function (text) {
  var candidateStr = 'candidate:';
  var pos = text.indexOf(candidateStr) + candidateStr.length;
  var fields = text.substr(pos).split(' ');
  return {
    'type': fields[7],
    'protocol': fields[2],
    'address': fields[4],
  };
};

// Ask computeengineondemand to give us TURN server credentials and URIs.
WebRTCCall.CEOD_URL =
  'https://computeengineondemand.appspot.com/turn?username=1234&key=5678';
WebRTCCall.asyncCreateTurnConfig = function (onSuccess, onError) {
  var xhr = new XMLHttpRequest();
  function onResult() {
    if (xhr.readyState !== 4) {
      return;
    }

    if (xhr.status !== 200) {
      onError('TURN request failed');
      return;
    }

    var response = JSON.parse(xhr.responseText);
    var iceServer = {
      'username': response.username,
      'credential': response.password,
      'urls': response.uris
    };
    onSuccess({ 'iceServers': [ iceServer ] });
  }

  xhr.onreadystatechange = onResult;
  xhr.open('GET', WebRTCCall.CEOD_URL, true);
  xhr.send();
};
<|endoftext|>


<commit_before>import { dirname } from 'path'
import commonjs from 'rollup-plugin-commonjs'
import resolve from 'rollup-plugin-node-resolve'
import uglify from 'rollup-plugin-uglify'
import pkg from './package.json'

// `npm run build` -> `production` is true
// `npm run dev` -> `production` is false
const production = ! process.env.ROLLUP_WATCH

const name = parseName(pkg.name)
const targetDir = dirname(pkg.main)

const banner = `
/**
 * ${pkg.name}
 * ${pkg.description}
 *
 * @version ${pkg.version}
 * @author ${pkg.author}
 * @license ${pkg.license}
 * @link ${pkg.homepage}
 */
`.trimLeft()
const uglifyOpts = {
  output: {
    preamble: banner,
  },
}

const globals = {
  'rxjs/operators': 'rxjs.operators',
  'rxjs/websocket': 'rxjs.websocket',
}
const external = [
  'rxjs', 'rxjs/operators', 'rxjs/websocket',
  'fs', 'path', 'util', 'os',
]

const config = [
  // CommonJS (for Node) and ES module (for bundlers) build.
  {
    external,
    input: pkg.module,
    output: [
      {
        banner,
        format: 'es',
        file: pkg.es2015,
      },
      { file: pkg.main,
        amd: { id: name },
        banner,
        format: 'cjs',
        globals,
        name,
      },
    ],
  },

  // esm minify
  {
    external: production ? external : [],
    input: pkg.module,
    plugins: production
      ? [ uglify(uglifyOpts) ]
      : [
        resolve({
          browser: true,
          jsnext: true,
          main: true,
        }),
        commonjs(),
      ],
    output: {
      banner,
      file: parseName(pkg.es2015) + '.min.js',
      format: 'es',
      sourcemap: production ? true : false,
    },
  },

]

if (pkg.browser) {
  config.push(
    // umd bundle min
    {
      external: [],
      input: pkg.module,
      plugins: [
        resolve({
          browser: true,
          jsnext: true,
          main: true,
        }),
        commonjs(),
        production && uglify(uglifyOpts),
      ],
      output: {
        amd: { id: name },
        banner,
        file: `${targetDir}/${name}.umd.min.js`,
        format: 'umd',
        globals,
        name,
        sourcemap: production ? true : false,
      },
    },
  )
}

// remove pkg.name extension if exists
function parseName(name) {
  if (name && name.slice(-3).toLowerCase() === '.js') {
    return name.slice(0, -3)
  }
  return name
}

export default config

<commit_msg>chore: update uglifyOpts<commit_after>import { dirname } from 'path'
import commonjs from 'rollup-plugin-commonjs'
import resolve from 'rollup-plugin-node-resolve'
import uglify from 'rollup-plugin-uglify'
import pkg from './package.json'

// `npm run build` -> `production` is true
// `npm run dev` -> `production` is false
const production = ! process.env.ROLLUP_WATCH

const name = parseName(pkg.name)
const targetDir = dirname(pkg.main)

const banner = `
/**
 * ${pkg.name}
 * ${pkg.description}
 *
 * @version ${pkg.version}
 * @author ${pkg.author}
 * @license ${pkg.license}
 * @link ${pkg.homepage}
 */
`.trimLeft()
const uglifyOpts = {
  mangle:   true,
  compress: {
    unused:        false,
    sequences:     true,
    dead_code:     true,
    conditionals:  true,
    booleans:      true,
    if_return:     true,
    join_vars:     true,
    drop_console:  false,
    drop_debugger: false,
    typeofs:       false,
  },
  output: {
    preamble: banner,
  },
}

const globals = {
  'rxjs/operators': 'rxjs.operators',
  'rxjs/websocket': 'rxjs.websocket',
}
const external = [
  'rxjs', 'rxjs/operators', 'rxjs/websocket',
  'fs', 'path', 'util', 'os',
]

const config = [
  // CommonJS (for Node) and ES module (for bundlers) build.
  {
    external,
    input: pkg.module,
    output: [
      {
        banner,
        format: 'es',
        file: pkg.es2015,
      },
      { file: pkg.main,
        amd: { id: name },
        banner,
        format: 'cjs',
        globals,
        name,
      },
    ],
  },

  // esm minify
  {
    external: production ? external : [],
    input: pkg.module,
    plugins: production
      ? [ uglify(uglifyOpts) ]
      : [
        resolve({
          browser: true,
          jsnext: true,
          main: true,
        }),
        commonjs(),
      ],
    output: {
      banner,
      file: parseName(pkg.es2015) + '.min.js',
      format: 'es',
      sourcemap: production ? true : false,
    },
  },

]

if (pkg.browser) {
  config.push(
    // umd bundle min
    {
      external: [],
      input: pkg.module,
      plugins: [
        resolve({
          browser: true,
          jsnext: true,
          main: true,
        }),
        commonjs(),
        production && uglify(uglifyOpts),
      ],
      output: {
        amd: { id: name },
        banner,
        file: `${targetDir}/${name}.umd.min.js`,
        format: 'umd',
        globals,
        name,
        sourcemap: production ? true : false,
      },
    },
  )
}

// remove pkg.name extension if exists
function parseName(name) {
  if (name && name.slice(-3).toLowerCase() === '.js') {
    return name.slice(0, -3)
  }
  return name
}

export default config

<|endoftext|>


<commit_before>import React from 'react';
import Three from 'three';

export default class Box extends React.Component {
  render() {
    var width = this.props.width || 1;
    var height = this.props.height || 1;
    var depth = this.props.depth || 1;
    var geometry = new Three.BoxGeometry(width, height, depth);
    var material = this.props.material || new Three.MeshNormalMaterial();
    return (
      <mesh
        {...this.props}
        geometry={geometry}
        material={material} />
    );
  }
}
<commit_msg>box takes color prop<commit_after>import React from 'react';
import Three from 'three';

export default class Box extends React.Component {
  render() {
    console.log("rendering Box with props:");
    console.log(this.props);
    console.log("---");
    var width = this.props.width || 1;
    var height = this.props.height || 1;
    var depth = this.props.depth || 1;
    var geometry = new Three.BoxGeometry(width, height, depth);
    var material = this.props.material;
    if (!material) {
      if (this.props.color) {
        material = new Three.MeshBasicMaterial({color: this.props.color});
      } else {
        material = new Three.MeshNormalMaterial();
      }
    }
    return (
      <mesh
        {...this.props}
        geometry={geometry}
        material={material} />
    );
  }
}
<|endoftext|>


<commit_before>/**
 * SearchFunnelWidget Component Stories.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Internal dependencies
 */
import {
	createTestRegistry,
	provideModuleRegistrations,
	provideModules,
	provideSiteInfo,
	provideUserCapabilities,
	WithTestRegistry,
} from '../../../../../../../tests/js/utils';
import WithRegistrySetup from '../../../../../../../tests/js/WithRegistrySetup';
import { Provider as ViewContextProvider } from '../../../../../components/Root/ViewContextContext';
import {
	VIEW_CONTEXT_DASHBOARD,
	VIEW_CONTEXT_DASHBOARD_VIEW_ONLY,
	VIEW_CONTEXT_PAGE_DASHBOARD,
} from '../../../../../googlesitekit/constants';
import {
	CORE_USER,
	PERMISSION_READ_SHARED_MODULE_DATA,
} from '../../../../../googlesitekit/datastore/user/constants';
import { getMetaCapabilityPropertyName } from '../../../../../googlesitekit/datastore/util/permissions';
import { withWidgetComponentProps } from '../../../../../googlesitekit/widgets/util';
import { MODULES_ANALYTICS } from '../../../../analytics/datastore/constants';
import { goals } from '../../../../analytics/datastore/__fixtures__';
import { provideAnalyticsMockReport } from '../../../../analytics/util/data-mock';
import { MODULES_SEARCH_CONSOLE } from '../../../datastore/constants';
import { provideSearchConsoleMockReport } from '../../../util/data-mock';
import SearchFunnelWidget from './index';

const searchConsoleArgs = {
	startDate: '2021-08-18',
	endDate: '2021-10-12',
	dimensions: 'date',
};
const analyticsArgs = [
	{
		startDate: '2021-09-15',
		endDate: '2021-10-12',
		compareStartDate: '2021-08-18',
		compareEndDate: '2021-09-14',
		metrics: [
			{
				expression: 'ga:goalCompletionsAll',
				alias: 'Goal Completions',
			},
			'ga:bounceRate',
		],
	},
	{
		startDate: '2021-09-15',
		endDate: '2021-10-12',
		compareStartDate: '2021-08-18',
		compareEndDate: '2021-09-14',
		dimensions: 'ga:date',
		metrics: [
			{
				expression: 'ga:goalCompletionsAll',
				alias: 'Goal Completions',
			},
			'ga:bounceRate',
		],
	},
	{
		startDate: '2021-09-15',
		endDate: '2021-10-12',
		compareStartDate: '2021-08-18',
		compareEndDate: '2021-09-14',
		metrics: [
			{
				expression: 'ga:users',
				alias: 'Total Users',
			},
		],
		dimensions: [ 'ga:channelGrouping' ],
		dimensionFilters: { 'ga:channelGrouping': 'Organic Search' },
	},
	{
		startDate: '2021-09-15',
		endDate: '2021-10-12',
		compareStartDate: '2021-08-18',
		compareEndDate: '2021-09-14',
		metrics: [
			{
				expression: 'ga:users',
				alias: 'Total Users',
			},
		],
		dimensions: [ 'ga:date' ],
		dimensionFilters: { 'ga:channelGrouping': 'Organic Search' },
	},
	{
		dimensions: [ 'ga:date' ],
		metrics: [
			{
				expression: 'ga:users',
			},
		],
		startDate: '2021-09-15',
		endDate: '2021-10-12',
	},
];

const WidgetWithComponentProps = withWidgetComponentProps( 'widget-slug' )(
	SearchFunnelWidget
);

const Template = ( { setupRegistry = () => {}, viewContext, ...args } ) => (
	<WithRegistrySetup func={ setupRegistry }>
		<ViewContextProvider value={ viewContext || VIEW_CONTEXT_DASHBOARD }>
			<WidgetWithComponentProps { ...args } />
		</ViewContextProvider>
	</WithRegistrySetup>
);

export const Ready = Template.bind( {} );
Ready.storyName = 'Ready';
Ready.args = {
	setupRegistry: ( registry ) => {
		provideSearchConsoleMockReport( registry, searchConsoleArgs );
		for ( const options of analyticsArgs ) {
			provideAnalyticsMockReport( registry, options );
		}
		registry.dispatch( MODULES_ANALYTICS ).receiveGetGoals( goals );
	},
};

export const AnalyticsGatheringData = Template.bind( {} );
AnalyticsGatheringData.storyName = 'Analytics Gathering Data';
AnalyticsGatheringData.args = {
	setupRegistry: ( registry ) => {
		provideSearchConsoleMockReport( registry, searchConsoleArgs );

		for ( const options of analyticsArgs ) {
			registry
				.dispatch( MODULES_ANALYTICS )
				.receiveGetReport( [], { options } );
		}
	},
};

export const SearchConsoleZeroState = Template.bind( {} );
SearchConsoleZeroState.storyName = 'Search Console Zero State';
SearchConsoleZeroState.args = {
	setupRegistry: ( registry ) => {
		registry.dispatch( MODULES_SEARCH_CONSOLE ).receiveGetReport(
			[
				{
					clicks: 0,
					ctr: 0,
					impressions: 0,
					keys: [ '2021-08-18' ],
					position: 0,
				},
			],
			{
				options: searchConsoleArgs,
			}
		);
	},
};

export const ReadyWithAnalyticsNotActive = Template.bind( {} );
ReadyWithAnalyticsNotActive.storyName = 'Ready with Analytics not active';
ReadyWithAnalyticsNotActive.args = {
	setupRegistry: ( registry ) => {
		provideModules( registry, [
			{
				active: true,
				connected: true,
				slug: 'search-console',
			},
			{
				active: false,
				connected: false,
				slug: 'analytics',
			},
		] );

		provideSearchConsoleMockReport( registry, searchConsoleArgs );
	},
};

export const ReadyWithActivateAnalyticsCTA = Template.bind( {} );
ReadyWithActivateAnalyticsCTA.storyName = 'Ready with Activate Analytics CTA';
ReadyWithActivateAnalyticsCTA.args = {
	setupRegistry: ( registry ) => {
		provideModules( registry, [
			{
				active: true,
				connected: true,
				slug: 'search-console',
			},
			{
				active: false,
				connected: false,
				slug: 'analytics',
			},
		] );

		provideSearchConsoleMockReport( registry, searchConsoleArgs );
	},
};
ReadyWithActivateAnalyticsCTA.parameters = {
	features: [ 'zeroDataStates' ],
};
ReadyWithActivateAnalyticsCTA.scenario = {
	label: 'SearchConsole/SearchFunnelWidget/ReadyWithActivateAnalyticsCTA',
	delay: 3000,
};

export const ReadyWithCompleteAnalyticsActivationCTA = Template.bind( {} );
ReadyWithCompleteAnalyticsActivationCTA.storyName =
	'Ready with Complete Analytics Activation CTA';
ReadyWithCompleteAnalyticsActivationCTA.args = {
	setupRegistry: ( registry ) => {
		provideModules( registry, [
			{
				active: true,
				connected: true,
				slug: 'search-console',
			},
			{
				active: true,
				connected: false,
				slug: 'analytics',
			},
		] );

		provideSearchConsoleMockReport( registry, searchConsoleArgs );
		provideModuleRegistrations( registry );
	},
};
ReadyWithCompleteAnalyticsActivationCTA.parameters = {
	features: [ 'zeroDataStates' ],
};

export const ReadyWithCreateGoalCTA = Template.bind( {} );
ReadyWithCreateGoalCTA.storyName = 'Ready with Create Goal CTA';
ReadyWithCreateGoalCTA.args = {
	setupRegistry: ( registry ) => {
		provideSearchConsoleMockReport( registry, searchConsoleArgs );
		for ( const options of analyticsArgs ) {
			provideAnalyticsMockReport( registry, options );
		}
	},
};
ReadyWithCreateGoalCTA.parameters = {
	features: [ 'zeroDataStates' ],
};
ReadyWithCreateGoalCTA.scenario = {
	label: 'SearchConsole/SearchFunnelWidget/ReadyWithCreateGoalCTA',
	delay: 3000,
};

export const Loading = Template.bind( {} );
Loading.storyName = 'Loading';
Loading.args = {
	setupRegistry: ( registry ) => {
		registry
			.dispatch( MODULES_SEARCH_CONSOLE )
			.startResolution( 'getReport', [ searchConsoleArgs ] );
		for ( const options of analyticsArgs ) {
			registry
				.dispatch( MODULES_ANALYTICS )
				.startResolution( 'getReport', [ options ] );
		}
	},
};

export const DataUnavailable = Template.bind( {} );
DataUnavailable.storyName = 'Data Unavailable';
DataUnavailable.args = {
	setupRegistry: ( registry ) => {
		registry
			.dispatch( MODULES_SEARCH_CONSOLE )
			.receiveGetReport( [], { options: searchConsoleArgs } );

		for ( const options of analyticsArgs ) {
			registry
				.dispatch( MODULES_ANALYTICS )
				.receiveGetReport( [], { options } );
		}
	},
};

export const Error = Template.bind( {} );
Error.storyName = 'Error';
Error.args = {
	setupRegistry: ( registry ) => {
		const error = {
			code: 'test_error',
			message: 'Error message.',
			data: {},
		};

		registry
			.dispatch( MODULES_SEARCH_CONSOLE )
			.receiveError( error, 'getReport', [ searchConsoleArgs ] );
		registry
			.dispatch( MODULES_SEARCH_CONSOLE )
			.finishResolution( 'getReport', [ searchConsoleArgs ] );
	},
};

export const ErrorAnalytics = Template.bind( {} );
ErrorAnalytics.storyName = 'Error Analytics';
ErrorAnalytics.args = {
	setupRegistry: ( registry ) => {
		const error = {
			code: 'test_error',
			message: 'Error message.',
			data: {},
		};

		provideSearchConsoleMockReport( registry, searchConsoleArgs );
		registry
			.dispatch( MODULES_ANALYTICS )
			.receiveError( error, 'getReport', [ analyticsArgs[ 0 ] ] );
		registry
			.dispatch( MODULES_ANALYTICS )
			.finishResolution( 'getReport', [ analyticsArgs[ 0 ] ] );
	},
};

export const GatheringDataZeroDataStates = Template.bind( {} );
GatheringDataZeroDataStates.storyName = 'Gathering w/ zeroDataStates';
GatheringDataZeroDataStates.args = {
	setupRegistry: ( registry ) => {
		registry
			.dispatch( MODULES_SEARCH_CONSOLE )
			.receiveGetReport( [], { options: searchConsoleArgs } );
		for ( const options of analyticsArgs ) {
			registry
				.dispatch( MODULES_ANALYTICS )
				.receiveGetReport( [], { options } );
		}
	},
};
GatheringDataZeroDataStates.parameters = {
	features: [ 'zeroDataStates' ],
};

export const ReadyEntityDashboard = Template.bind( {} );
ReadyEntityDashboard.storyName = 'Ready Entity Dashboard';
ReadyEntityDashboard.args = {
	setupRegistry: ( registry ) => {
		provideSearchConsoleMockReport( registry, searchConsoleArgs );

		for ( const options of analyticsArgs ) {
			provideAnalyticsMockReport( registry, options );
		}
	},
	viewContext: VIEW_CONTEXT_PAGE_DASHBOARD,
};

export const ViewOnlySearchConsoleOnlyReady = Template.bind( {} );
ViewOnlySearchConsoleOnlyReady.storyName =
	'ViewOnly - Only Search Console Shared - Ready';
ViewOnlySearchConsoleOnlyReady.args = {
	setupRegistry: ( registry ) => {
		provideModules( registry, [
			{
				active: true,
				connected: true,
				slug: 'search-console',
				shareable: true,
			},
			{
				active: true,
				connected: true,
				slug: 'analytics',
				shareable: false,
			},
		] );
		provideUserCapabilities( registry, {
			[ getMetaCapabilityPropertyName(
				PERMISSION_READ_SHARED_MODULE_DATA,
				'search-console'
			) ]: true,
			[ getMetaCapabilityPropertyName(
				PERMISSION_READ_SHARED_MODULE_DATA,
				'analytics'
			) ]: false,
		} );
		provideSearchConsoleMockReport( registry, searchConsoleArgs );
		for ( const options of analyticsArgs ) {
			provideAnalyticsMockReport( registry, options );
		}
		registry.dispatch( MODULES_ANALYTICS ).receiveGetGoals( goals );
	},
	viewContext: VIEW_CONTEXT_DASHBOARD_VIEW_ONLY,
};
ViewOnlySearchConsoleOnlyReady.parameters = {
	features: [ 'dashboardSharing' ],
};

export default {
	title: 'Modules/SearchConsole/Widgets/SearchFunnelWidget',
	decorators: [
		( Story ) => (

					<Story />

		),
		( Story, { parameters } ) => {
			const registry = createTestRegistry();
			provideSiteInfo( registry );
			registry.dispatch( CORE_USER ).setReferenceDate( '2021-10-13' );
			registry.dispatch( CORE_USER ).receiveGetAuthentication( {
				needsReauthentication: false,
			} );

			provideModules( registry, [
				{
					active: true,
					connected: true,
					slug: 'search-console',
				},
				{
					active: true,
					connected: true,
					slug: 'analytics',
				},
			] );

			return (
				<WithTestRegistry
					registry={ registry }
					features={ parameters.features || [] }
				>
					<Story />
				</WithTestRegistry>
			);
		},
	],
};
<commit_msg>Update story to mock provideUserAuthentication.<commit_after>/**
 * SearchFunnelWidget Component Stories.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Internal dependencies
 */
import {
	createTestRegistry,
	provideModuleRegistrations,
	provideModules,
	provideSiteInfo,
	provideUserAuthentication,
	provideUserCapabilities,
	WithTestRegistry,
} from '../../../../../../../tests/js/utils';
import WithRegistrySetup from '../../../../../../../tests/js/WithRegistrySetup';
import { Provider as ViewContextProvider } from '../../../../../components/Root/ViewContextContext';
import {
	VIEW_CONTEXT_DASHBOARD,
	VIEW_CONTEXT_DASHBOARD_VIEW_ONLY,
	VIEW_CONTEXT_PAGE_DASHBOARD,
} from '../../../../../googlesitekit/constants';
import {
	CORE_USER,
	PERMISSION_READ_SHARED_MODULE_DATA,
} from '../../../../../googlesitekit/datastore/user/constants';
import { getMetaCapabilityPropertyName } from '../../../../../googlesitekit/datastore/util/permissions';
import { withWidgetComponentProps } from '../../../../../googlesitekit/widgets/util';
import { MODULES_ANALYTICS } from '../../../../analytics/datastore/constants';
import { goals } from '../../../../analytics/datastore/__fixtures__';
import { provideAnalyticsMockReport } from '../../../../analytics/util/data-mock';
import { MODULES_SEARCH_CONSOLE } from '../../../datastore/constants';
import { provideSearchConsoleMockReport } from '../../../util/data-mock';
import SearchFunnelWidget from './index';

const searchConsoleArgs = {
	startDate: '2021-08-18',
	endDate: '2021-10-12',
	dimensions: 'date',
};
const analyticsArgs = [
	{
		startDate: '2021-09-15',
		endDate: '2021-10-12',
		compareStartDate: '2021-08-18',
		compareEndDate: '2021-09-14',
		metrics: [
			{
				expression: 'ga:goalCompletionsAll',
				alias: 'Goal Completions',
			},
			'ga:bounceRate',
		],
	},
	{
		startDate: '2021-09-15',
		endDate: '2021-10-12',
		compareStartDate: '2021-08-18',
		compareEndDate: '2021-09-14',
		dimensions: 'ga:date',
		metrics: [
			{
				expression: 'ga:goalCompletionsAll',
				alias: 'Goal Completions',
			},
			'ga:bounceRate',
		],
	},
	{
		startDate: '2021-09-15',
		endDate: '2021-10-12',
		compareStartDate: '2021-08-18',
		compareEndDate: '2021-09-14',
		metrics: [
			{
				expression: 'ga:users',
				alias: 'Total Users',
			},
		],
		dimensions: [ 'ga:channelGrouping' ],
		dimensionFilters: { 'ga:channelGrouping': 'Organic Search' },
	},
	{
		startDate: '2021-09-15',
		endDate: '2021-10-12',
		compareStartDate: '2021-08-18',
		compareEndDate: '2021-09-14',
		metrics: [
			{
				expression: 'ga:users',
				alias: 'Total Users',
			},
		],
		dimensions: [ 'ga:date' ],
		dimensionFilters: { 'ga:channelGrouping': 'Organic Search' },
	},
	{
		dimensions: [ 'ga:date' ],
		metrics: [
			{
				expression: 'ga:users',
			},
		],
		startDate: '2021-09-15',
		endDate: '2021-10-12',
	},
];

const WidgetWithComponentProps = withWidgetComponentProps( 'widget-slug' )(
	SearchFunnelWidget
);

const Template = ( { setupRegistry = () => {}, viewContext, ...args } ) => (
	<WithRegistrySetup func={ setupRegistry }>
		<ViewContextProvider value={ viewContext || VIEW_CONTEXT_DASHBOARD }>
			<WidgetWithComponentProps { ...args } />
		</ViewContextProvider>
	</WithRegistrySetup>
);

export const Ready = Template.bind( {} );
Ready.storyName = 'Ready';
Ready.args = {
	setupRegistry: ( registry ) => {
		provideSearchConsoleMockReport( registry, searchConsoleArgs );
		for ( const options of analyticsArgs ) {
			provideAnalyticsMockReport( registry, options );
		}
		registry.dispatch( MODULES_ANALYTICS ).receiveGetGoals( goals );
	},
};

export const AnalyticsGatheringData = Template.bind( {} );
AnalyticsGatheringData.storyName = 'Analytics Gathering Data';
AnalyticsGatheringData.args = {
	setupRegistry: ( registry ) => {
		provideSearchConsoleMockReport( registry, searchConsoleArgs );

		for ( const options of analyticsArgs ) {
			registry
				.dispatch( MODULES_ANALYTICS )
				.receiveGetReport( [], { options } );
		}
	},
};

export const SearchConsoleZeroState = Template.bind( {} );
SearchConsoleZeroState.storyName = 'Search Console Zero State';
SearchConsoleZeroState.args = {
	setupRegistry: ( registry ) => {
		registry.dispatch( MODULES_SEARCH_CONSOLE ).receiveGetReport(
			[
				{
					clicks: 0,
					ctr: 0,
					impressions: 0,
					keys: [ '2021-08-18' ],
					position: 0,
				},
			],
			{
				options: searchConsoleArgs,
			}
		);
	},
};

export const ReadyWithAnalyticsNotActive = Template.bind( {} );
ReadyWithAnalyticsNotActive.storyName = 'Ready with Analytics not active';
ReadyWithAnalyticsNotActive.args = {
	setupRegistry: ( registry ) => {
		provideModules( registry, [
			{
				active: true,
				connected: true,
				slug: 'search-console',
			},
			{
				active: false,
				connected: false,
				slug: 'analytics',
			},
		] );

		provideSearchConsoleMockReport( registry, searchConsoleArgs );
	},
};

export const ReadyWithActivateAnalyticsCTA = Template.bind( {} );
ReadyWithActivateAnalyticsCTA.storyName = 'Ready with Activate Analytics CTA';
ReadyWithActivateAnalyticsCTA.args = {
	setupRegistry: ( registry ) => {
		provideModules( registry, [
			{
				active: true,
				connected: true,
				slug: 'search-console',
			},
			{
				active: false,
				connected: false,
				slug: 'analytics',
			},
		] );

		provideSearchConsoleMockReport( registry, searchConsoleArgs );
	},
};
ReadyWithActivateAnalyticsCTA.parameters = {
	features: [ 'zeroDataStates' ],
};
ReadyWithActivateAnalyticsCTA.scenario = {
	label: 'SearchConsole/SearchFunnelWidget/ReadyWithActivateAnalyticsCTA',
	delay: 3000,
};

export const ReadyWithCompleteAnalyticsActivationCTA = Template.bind( {} );
ReadyWithCompleteAnalyticsActivationCTA.storyName =
	'Ready with Complete Analytics Activation CTA';
ReadyWithCompleteAnalyticsActivationCTA.args = {
	setupRegistry: ( registry ) => {
		provideModules( registry, [
			{
				active: true,
				connected: true,
				slug: 'search-console',
			},
			{
				active: true,
				connected: false,
				slug: 'analytics',
			},
		] );

		provideSearchConsoleMockReport( registry, searchConsoleArgs );
		provideModuleRegistrations( registry );
	},
};
ReadyWithCompleteAnalyticsActivationCTA.parameters = {
	features: [ 'zeroDataStates' ],
};

export const ReadyWithCreateGoalCTA = Template.bind( {} );
ReadyWithCreateGoalCTA.storyName = 'Ready with Create Goal CTA';
ReadyWithCreateGoalCTA.args = {
	setupRegistry: ( registry ) => {
		provideUserAuthentication( registry );
		provideSearchConsoleMockReport( registry, searchConsoleArgs );
		for ( const options of analyticsArgs ) {
			provideAnalyticsMockReport( registry, options );
		}
	},
};
ReadyWithCreateGoalCTA.parameters = {
	features: [ 'zeroDataStates' ],
};
ReadyWithCreateGoalCTA.scenario = {
	label: 'SearchConsole/SearchFunnelWidget/ReadyWithCreateGoalCTA',
	delay: 3000,
};

export const Loading = Template.bind( {} );
Loading.storyName = 'Loading';
Loading.args = {
	setupRegistry: ( registry ) => {
		registry
			.dispatch( MODULES_SEARCH_CONSOLE )
			.startResolution( 'getReport', [ searchConsoleArgs ] );
		for ( const options of analyticsArgs ) {
			registry
				.dispatch( MODULES_ANALYTICS )
				.startResolution( 'getReport', [ options ] );
		}
	},
};

export const DataUnavailable = Template.bind( {} );
DataUnavailable.storyName = 'Data Unavailable';
DataUnavailable.args = {
	setupRegistry: ( registry ) => {
		registry
			.dispatch( MODULES_SEARCH_CONSOLE )
			.receiveGetReport( [], { options: searchConsoleArgs } );

		for ( const options of analyticsArgs ) {
			registry
				.dispatch( MODULES_ANALYTICS )
				.receiveGetReport( [], { options } );
		}
	},
};

export const Error = Template.bind( {} );
Error.storyName = 'Error';
Error.args = {
	setupRegistry: ( registry ) => {
		const error = {
			code: 'test_error',
			message: 'Error message.',
			data: {},
		};

		registry
			.dispatch( MODULES_SEARCH_CONSOLE )
			.receiveError( error, 'getReport', [ searchConsoleArgs ] );
		registry
			.dispatch( MODULES_SEARCH_CONSOLE )
			.finishResolution( 'getReport', [ searchConsoleArgs ] );
	},
};

export const ErrorAnalytics = Template.bind( {} );
ErrorAnalytics.storyName = 'Error Analytics';
ErrorAnalytics.args = {
	setupRegistry: ( registry ) => {
		const error = {
			code: 'test_error',
			message: 'Error message.',
			data: {},
		};

		provideSearchConsoleMockReport( registry, searchConsoleArgs );
		registry
			.dispatch( MODULES_ANALYTICS )
			.receiveError( error, 'getReport', [ analyticsArgs[ 0 ] ] );
		registry
			.dispatch( MODULES_ANALYTICS )
			.finishResolution( 'getReport', [ analyticsArgs[ 0 ] ] );
	},
};

export const GatheringDataZeroDataStates = Template.bind( {} );
GatheringDataZeroDataStates.storyName = 'Gathering w/ zeroDataStates';
GatheringDataZeroDataStates.args = {
	setupRegistry: ( registry ) => {
		registry
			.dispatch( MODULES_SEARCH_CONSOLE )
			.receiveGetReport( [], { options: searchConsoleArgs } );
		for ( const options of analyticsArgs ) {
			registry
				.dispatch( MODULES_ANALYTICS )
				.receiveGetReport( [], { options } );
		}
	},
};
GatheringDataZeroDataStates.parameters = {
	features: [ 'zeroDataStates' ],
};

export const ReadyEntityDashboard = Template.bind( {} );
ReadyEntityDashboard.storyName = 'Ready Entity Dashboard';
ReadyEntityDashboard.args = {
	setupRegistry: ( registry ) => {
		provideSearchConsoleMockReport( registry, searchConsoleArgs );

		for ( const options of analyticsArgs ) {
			provideAnalyticsMockReport( registry, options );
		}
	},
	viewContext: VIEW_CONTEXT_PAGE_DASHBOARD,
};

export const ViewOnlySearchConsoleOnlyReady = Template.bind( {} );
ViewOnlySearchConsoleOnlyReady.storyName =
	'ViewOnly - Only Search Console Shared - Ready';
ViewOnlySearchConsoleOnlyReady.args = {
	setupRegistry: ( registry ) => {
		provideModules( registry, [
			{
				active: true,
				connected: true,
				slug: 'search-console',
				shareable: true,
			},
			{
				active: true,
				connected: true,
				slug: 'analytics',
				shareable: false,
			},
		] );
		provideUserCapabilities( registry, {
			[ getMetaCapabilityPropertyName(
				PERMISSION_READ_SHARED_MODULE_DATA,
				'search-console'
			) ]: true,
			[ getMetaCapabilityPropertyName(
				PERMISSION_READ_SHARED_MODULE_DATA,
				'analytics'
			) ]: false,
		} );
		provideSearchConsoleMockReport( registry, searchConsoleArgs );
		for ( const options of analyticsArgs ) {
			provideAnalyticsMockReport( registry, options );
		}
		registry.dispatch( MODULES_ANALYTICS ).receiveGetGoals( goals );
	},
	viewContext: VIEW_CONTEXT_DASHBOARD_VIEW_ONLY,
};
ViewOnlySearchConsoleOnlyReady.parameters = {
	features: [ 'dashboardSharing' ],
};

export default {
	title: 'Modules/SearchConsole/Widgets/SearchFunnelWidget',
	decorators: [
		( Story ) => (

					<Story />

		),
		( Story, { parameters } ) => {
			const registry = createTestRegistry();
			provideSiteInfo( registry );
			registry.dispatch( CORE_USER ).setReferenceDate( '2021-10-13' );
			registry.dispatch( CORE_USER ).receiveGetAuthentication( {
				needsReauthentication: false,
			} );

			provideModules( registry, [
				{
					active: true,
					connected: true,
					slug: 'search-console',
				},
				{
					active: true,
					connected: true,
					slug: 'analytics',
				},
			] );

			return (
				<WithTestRegistry
					registry={ registry }
					features={ parameters.features || [] }
				>
					<Story />
				</WithTestRegistry>
			);
		},
	],
};
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import {
   Grid,
   GridCell,
   Spacer,
   Text,
   Title,
   TitleBar,
   View
} from '../../../src'

import style from '../../style.less'

export default class DemoContentView extends Component {
   static propTypes = {
      contents: React.PropTypes.array
   }

   render() {
      return (
         <View width="100%" className={style.docs}>
            <TitleBar title="View" flush />
            <Spacer size="9" />
            <Grid columns="1[a] 2[b] 4[c-e]" gutter="60px">
               <GridCell>
                  <Title>Introduction</Title>
               </GridCell>
               <GridCell colspan="3">
                  <Text size="6" weight="light">
                     The View component is probably one of the most important components within OIO.
                     It is the core OIO component you should use to structure your pages, layouts and components for your application.
                     You can think of the View component as OIO‘s take on a div.
                  </Text>
               </GridCell>
               <GridCell>
                  <Title>View Configurations</Title>
                  <Text size="2" color="gray50">
                     Props for using the View component
                  </Text>
               </GridCell>
               <GridCell colspan="3">

                           Prop
                           Prop Type
                           Default Value
                           Description/Options

                           aspectRatio
                           String
                           -

                                 Enter a value such as 16:9
                                 to get a box with a width and height aspect ratio of 16:9.

                                 Important: aspectRatio relies on the width set on the View.
                                  It will override any height values.

                           height
                           String
                           -

                              Enter a pixel-based size. ie. 12px

                           format
                           String
                           float

                              float
                              auto

                           padding
                           String
                           -

                                 Enter a pixel-based size. Padding can be set with 1 unit:
                                 ie. padding="12px"

                                 Padding can also be set with 2 or 4 units representing
                                 top, right, bottom, left padding.
                                 This is the same as what can be done with CSS shorthand.
                                 ie. padding="12px 24px"
                                 ie. padding="12px 24px 12px 24px"

                              <Spacer size="2" />

                                    Learn more about padding here

                           position
                           String
                           -

                              Ability to set both the vertical and horizontal position of a View.
                              When setting position, enter a string like:
                              vertical-option horizontal-option.
                              ie. position="center center"

                              Available vertical options include:
                              top middle bottom
                              Available horizontal options include:
                              left center right

                           width
                           String
                           -

                              Enter a pixel-based size. ie. 12px

               </GridCell>
            </Grid>
         </View>
      )
   }
}
<commit_msg>Updated View Docs<commit_after>import React, { Component } from 'react'
import {
   Grid,
   GridCell,
   GridRow,
   Spacer,
   Text,
   Title,
   TitleBar,
   View
} from '../../../src'

import style from '../../style.less'

export default class DemoContentView extends Component {
   static propTypes = {
      contents: React.PropTypes.array
   }

   render() {
      return (
         <View width="100%" className={style.docs}>
            <TitleBar title="View" flush />
            <Spacer size="9" />
            <Grid columns="1[a] 2[b] 4[c-e]" gutter="60px">
               <GridCell>
                  <Title>Introduction</Title>
               </GridCell>
               <GridCell colspan="3">
                  <Text size="6" weight="light">
                     The View component is probably one of the most important components within OIO.
                     It is the core OIO component you should use to structure your pages,
                     layouts and components for your application. You can think of the
                     View component as OIO‘s take on a div.
                  </Text>
               </GridCell>
               <GridRow>
                  <GridCell>
                     <Title>View Example 1</Title>
                     <Text size="2" color="gray50">
                        Example of a View component where format equals float
                     </Text>
                  </GridCell>
                  <GridCell colspan="3">
                     <View width="100%" height="360px" className={style.docsWindow}>
                        <View width="30%" height="100%" padding="30px" className="bgGray10">
                           <Text weight="semibold">View 1</Text>
                           <Spacer size="2" />
                           View with format of fixed with width of
                           20%
                           and height of 100% and padding of 30px
                        </View>
                        <View width="70%" height="100%" padding="30px 60px">
                           <Text weight="semibold">View 2</Text>
                           <Spacer size="2" />
                           View with format of fixed with width of
                           80%
                           and height of 100% and padding of 30px 60px
                        </View>
                     </View>
                  </GridCell>
               </GridRow>
               <GridRow>
                  <GridCell>
                     <Title>View Example 2</Title>
                     <Text size="2" color="gray50">
                        Similar to previous example, but implemented slightly differently.
                     </Text>
                  </GridCell>
                  <GridCell colspan="3">
                     <View width="100%" height="360px" className={style.docsWindow}>
                        <View width="30%" height="100%" padding="30px" className="bgGray10">
                           <Text weight="semibold">View 1</Text>
                           <Spacer size="2" />
                           View with format of fixed with width of
                           30%
                           and height of 100% and padding of 30px
                        </View>
                        <View format="auto" left="30%" padding="30px 60px" scroll="on">
                           <Text weight="semibold">View 2 (Scroll Me!)</Text>
                           <Spacer size="2" />
                           View with format of auto with left of
                           30% and padding of 30px 60px and
                           scroll is set to on
                           <Spacer size="5" />
                           Fingerstache next level pickled, sriracha swag portland disrupt.
                           Schlitz synth pourover, activated charcoal kale chips echo park
                           narwhal viral drinking vinegar. Quinoa kitsch PBRB, everyday carry
                           godard woke occupy. Hot chicken lumbersexual swag,
                           lomo flexitarian post-ironic crucifix vegan bitters.
                           Williamsburg lo-fi fam biodiesel, disrupt whatever health goth fashion
                           axe kickstarter pitchfork brooklyn pabst hot chicken food truck brunch.
                           Af neutra lyft schlitz. Activated charcoal biodiesel af food truck
                           succulents, readymade fam fashion axe mixtape vape portland pinterest
                           irony narwhal. Fap chicharrones normcore plaid. Keffiyeh irony schlitz,
                           roof party poke paleo hashtag skateboard
                           succulents gochujang glutenfree pok pok locavore.
                           Iceland put a bird on it four loko prism affogato kinfolk,
                           franzen etsy listicle fixie. Williamsburg hashtag pinterest lyft
                           cornhole listicle. Chambray gochujang hammock YOLO small batch.
                           Typewriter microdosing direct trade jean shorts,
                           godard messenger bag hexagon street art copper mug fashion
                           axe chartreuse mixtape authentic fap. Helvetica pug twee,
                           wolf bespoke subway tile kickstarter chicharrones single-origin coffee
                           viral mumblecore flannel heirloom.
                        </View>
                     </View>
                  </GridCell>
               </GridRow>
               <GridRow>
                  <GridCell>
                     <Title>View Example 3</Title>
                     <Text size="2" color="gray50">
                        Example of a View component where format equals float
                     </Text>
                  </GridCell>
                  <GridCell colspan="3">
                     <View width="100%" height="360px" className={style.docsWindow}>
                        <View format="auto" padding="30px 330px 30px 30px" scroll="on">
                           <Text weight="semibold">View 1 (Scroll Me)</Text>
                           <Spacer size="2" />
                           View with format of fixed with width of
                           20%
                           and height of 100% and padding of 30px
                           <Spacer size="5" />
                           Fingerstache next level pickled, sriracha swag portland disrupt.
                           Schlitz synth pourover, activated charcoal kale chips echo park
                           narwhal viral drinking vinegar. Quinoa kitsch PBRB, everyday carry
                           godard woke occupy. Hot chicken lumbersexual swag,
                           lomo flexitarian post-ironic crucifix vegan bitters.
                           Williamsburg lo-fi fam biodiesel, disrupt whatever health goth fashion
                           axe kickstarter pitchfork brooklyn pabst hot chicken food truck brunch.
                           Af neutra lyft schlitz. Activated charcoal biodiesel af food truck
                           succulents, readymade fam fashion axe mixtape vape portland pinterest
                           irony narwhal. Fap chicharrones normcore plaid. Keffiyeh irony schlitz,
                           roof party poke paleo hashtag skateboard
                           succulents gochujang glutenfree pok pok locavore.
                           Iceland put a bird on it four loko prism affogato kinfolk,
                           franzen etsy listicle fixie. Williamsburg hashtag pinterest lyft
                           cornhole listicle. Chambray gochujang hammock YOLO small batch.
                           Typewriter microdosing direct trade jean shorts,
                           godard messenger bag hexagon street art copper mug fashion
                           axe chartreuse mixtape authentic fap. Helvetica pug twee,
                           wolf bespoke subway tile kickstarter chicharrones single-origin coffee
                           viral mumblecore flannel heirloom.
                        </View>
                        <View
                           format="auto"
                           className="bgGray10"
                           width="300px"
                           height="180px"
                           padding="30px"
                           position="top right">
                           <Text weight="semibold">View 2 (I Stick)</Text>
                           <Spacer size="2" />
                           View with format of fixed with width of
                           80%
                           and height of 100% and padding of 30px 60px
                        </View>
                     </View>
                  </GridCell>
               </GridRow>
               <GridCell>
                  <Title>View Configurations</Title>
                  <Text size="2" color="gray50">
                     Props for using the View component
                  </Text>
               </GridCell>
               <GridCell colspan="3">

                           Prop
                           Prop Type
                           Default Value
                           Description/Options

                           aspectRatio
                           String
                           -

                                 Enter a value such as 16:9
                                 to get a box with a width and height aspect ratio of 16:9.

                                 Important: aspectRatio relies on the width set on the View.
                                  It will override any height values.

                           height
                           String
                           -

                              Enter a pixel-based size. ie. 12px

                           format
                           String
                           float

                              float
                              auto

                           padding
                           String
                           -

                                 Enter a pixel-based size. Padding can be set with 1 unit:
                                 ie. padding="12px"

                                 Padding can also be set with 2 or 4 units representing
                                 top, right, bottom, left padding.
                                 This is the same as what can be done with CSS shorthand.
                                 ie. padding="12px 24px"
                                 ie. padding="12px 24px 12px 24px"

                              <Spacer size="2" />

                                    Learn more about padding here

                           position
                           String
                           -

                              Ability to set both the vertical and horizontal position of a View.
                              When setting position, enter a string like:
                              vertical-option horizontal-option.
                              ie. position="center center"

                              Available vertical options include:
                              top middle bottom
                              Available horizontal options include:
                              left center right

                           width
                           String
                           -

                              Enter a pixel-based size. ie. 12px

               </GridCell>
            </Grid>
         </View>
      )
   }
}
<|endoftext|>


<commit_before>/**
 * @author Pablo
 */

$(document).ready(function(){
	//Instantiate APE Client
	window.client = new APS("ape.crusthq.com:45138", null, {
		//transport: "lp",
		debug: true
	});

	client.identifier = "ST";

	var stock = {
		//Variables
		tray: $("#stock-list"),		//Element for stock list
		tpl: $("#stock-list").find(".stock:first").clone(),	//Stock stream Template
		addInput: $("#add-stock"),	//Element - Button to add new Stock
		visual: [],					//Store Graph values

		update: function(value, direction, change, chanName){
			chanName = chanName.substring(1);
			var obj = $("#"+chanName);
			if(obj.length == 0){
				//Creates a new stock stream element for the DOM
				obj = stock.tpl.clone();
				obj.attr('id', chanName);
				obj.find(".stock-name").html(chanName);
				//Inject the element to the DOM
				obj.prependTo(stock.tray);

				//Creates visual entry for the stock stream
				stock.visual[chanName] = [];
			}

			//Convert Values from string to integers
			value = parseFloat(value).toFixed(2);
			change = parseFloat(change).toFixed(2);

			//Update stock visual array
			stock.visual[chanName].push(value);

			//Limit stock visual array to 30 entries
			if(stock.visual[chanName].length > 30) stock.visual[chanName].splice(0,1);

			//Generates stock line graph
			obj.find(".stock-visual").sparkline(stock.visual[chanName], {
				height: 72,
				width: stock.visual[chanName].length * 0.7 +"em"
			});

			//Update the document with new data
			obj.find(".stock-value").html(value);
			obj.find(".stock-change").html(change);

			//Handles the stock value color, red OR green
			if(value < 0){
				obj.find(".stock-value:not('.red')").addClass('red');
			}else{
				obj.find(".stock-value.red").removeClass('red');
			}

			//Handles the stock direction(arrow) up(green)/down(red)
			if(direction == "up"){
				obj.find(".stock-direction-down").attr("class","stock-direction-up").html("▲");
			}else{
				obj.find(".stock-direction-up").attr("class","stock-direction-down").html("▼");
			}
		},

		//Add a new stock stream
		add: function(){
			var count = Object.keys(client.channels).length;
			if(count > 4){
				stock.addInput.prop("disabled", true)
			}else{
				client.sub("*stock"+randomString(5));
			}
		}

	}//END of stock Object
	/////////////////////////////////////

	//Connect/Restore
	client.connect();

	//APS events
	client.on({
		stockUpdate: stock.update,
		ready: function(){
			if(stock.tray.lenght > 4)
				stock.addInput.prop("disabled", false);
		}
	})

	//Clear the stock Template
	stock.tray.empty();

	//Bind Add stock button input
	stock.addInput.click(stock.add.bind(stock));

});<commit_msg>prepended the event with the new raw  requirement<commit_after>/**
 * @author Pablo
 */

$(document).ready(function(){
	//Instantiate APE Client
	window.client = new APS("ape.crusthq.com:45138", null, {
		//transport: "lp",
		debug: true
	});

	client.identifier = "ST";

	var stock = {
		//Variables
		tray: $("#stock-list"),		//Element for stock list
		tpl: $("#stock-list").find(".stock:first").clone(),	//Stock stream Template
		addInput: $("#add-stock"),	//Element - Button to add new Stock
		visual: [],					//Store Graph values

		update: function(value, direction, change, chanName){
			chanName = chanName.substring(1);
			var obj = $("#"+chanName);
			if(obj.length == 0){
				//Creates a new stock stream element for the DOM
				obj = stock.tpl.clone();
				obj.attr('id', chanName);
				obj.find(".stock-name").html(chanName);
				//Inject the element to the DOM
				obj.prependTo(stock.tray);

				//Creates visual entry for the stock stream
				stock.visual[chanName] = [];
			}

			//Convert Values from string to integers
			value = parseFloat(value).toFixed(2);
			change = parseFloat(change).toFixed(2);

			//Update stock visual array
			stock.visual[chanName].push(value);

			//Limit stock visual array to 30 entries
			if(stock.visual[chanName].length > 30) stock.visual[chanName].splice(0,1);

			//Generates stock line graph
			obj.find(".stock-visual").sparkline(stock.visual[chanName], {
				height: 72,
				width: stock.visual[chanName].length * 0.7 +"em"
			});

			//Update the document with new data
			obj.find(".stock-value").html(value);
			obj.find(".stock-change").html(change);

			//Handles the stock value color, red OR green
			if(value < 0){
				obj.find(".stock-value:not('.red')").addClass('red');
			}else{
				obj.find(".stock-value.red").removeClass('red');
			}

			//Handles the stock direction(arrow) up(green)/down(red)
			if(direction == "up"){
				obj.find(".stock-direction-down").attr("class","stock-direction-up").html("▲");
			}else{
				obj.find(".stock-direction-up").attr("class","stock-direction-down").html("▼");
			}
		},

		//Add a new stock stream
		add: function(){
			var count = Object.keys(client.channels).length;
			if(count > 4){
				stock.addInput.prop("disabled", true)
			}else{
				client.sub("*stock"+randomString(5));
			}
		}

	}//END of stock Object
	/////////////////////////////////////

	//Connect/Restore
	client.connect();

	//APS events
	client.on({
		rawStockUpdate: stock.update,
		ready: function(){
			if(stock.tray.lenght > 4)
				stock.addInput.prop("disabled", false);
		}
	})

	//Clear the stock Template
	stock.tray.empty();

	//Bind Add stock button input
	stock.addInput.click(stock.add.bind(stock));

});<|endoftext|>


<commit_before>import { select } from "d3-selection";

export default function (tagName, className){
  var render = function(){};

  function component(selection, data){
    var components = selection
      .selectAll(className ? "." + className : tagName)
      .data(Array.isArray(data) ? data : [data]);
    components
      .exit().remove();
    components
      .enter().append(tagName)
        .attr("class", className)
      .merge(components)
        .each(function (d){ select(this).call(render, d); });
  }

  component.render = function(_) {
    return arguments.length ? (render = _, component) : render;
  };

  return component;
};
<commit_msg>Add setters for render, create, destroy.<commit_after>import { select } from "d3-selection";

var noop = function (){};

export default function (tagName, className){
  var render = noop,
      create = noop,
      destroy = noop;

  function component(selection, data){
    var components = selection
      .selectAll(className ? "." + className : tagName)
      .data(Array.isArray(data) ? data : [data]);
    components
      .exit().remove();
    components
      .enter().append(tagName)
        .attr("class", className)
      .merge(components)
        .each(function (d){ select(this).call(render, d); });
  }

  component.render = function(_) { return (render = _, component); };
  component.create = function(_) { return (create = _, component); };
  component.destroy = function(_) { return (destroy = _, component); };

  return component;
};
<|endoftext|>


<commit_before>import Vue from 'vue';
import Router from 'vue-router';
import Content from 'components/Content';

Vue.use(Router);

export default new Router({
  routes: [
    {
      path: '/',
      name: 'Content',
      component: Content,
    },
  ],
});
<commit_msg>Change routing to FileManager<commit_after>import Vue from 'vue';
import Router from 'vue-router';
import FileManager from 'components/FileManager';

Vue.use(Router);

export default new Router({
  routes: [
    {
      path: '/',
      name: 'fileManager',
      component: FileManager,
    },
  ],
});
<|endoftext|>


<commit_before>const constants = module.exports = { }; // eslint-disable-line no-multi-assign
constants.RULES_DIRECTORY = 'rules';
constants.RULES_STAGES = [
  'login_success'
];
constants.DEFAULT_RULE_STAGE = constants.RULES_STAGES[0];

constants.RULES_CONFIGS_DIRECTORY = 'rules-configs';

constants.PAGES_DIRECTORY = 'pages';
constants.PAGE_LOGIN = 'login';
constants.PAGE_PASSWORD_RESET = 'password_reset';
constants.PAGE_GUARDIAN_MULTIFACTOR = 'guardian_multifactor';
constants.PAGE_ERROR = 'error_page';

constants.PAGE_NAMES = [
  constants.PAGE_GUARDIAN_MULTIFACTOR + '.html',
  constants.PAGE_GUARDIAN_MULTIFACTOR + '.json',
  constants.PAGE_PASSWORD_RESET + '.html',
  constants.PAGE_PASSWORD_RESET + '.json',
  constants.PAGE_LOGIN + '.html',
  constants.PAGE_LOGIN + '.json',
  constants.PAGE_ERROR + '.html',
  constants.PAGE_ERROR + '.json'
];

constants.DATABASE_CONNECTIONS_DIRECTORY = 'database-connections';
constants.DATABASE_SCRIPTS_CHANGE_EMAIL = 'change_email';
constants.DATABASE_SCRIPTS_GET_USER = 'get_user';
constants.DATABASE_SCRIPTS = [
  constants.DATABASE_SCRIPTS_GET_USER,
  'create',
  'verify',
  'login',
  'change_password',
  'delete',
  constants.DATABASE_SCRIPTS_CHANGE_EMAIL
];
constants.DATABASE_SCRIPTS_NO_IMPORT = [
  constants.DATABASE_SCRIPTS_GET_USER,
  'create',
  'verify',
  'login',
  'change_password',
  'delete'
];
constants.DATABASE_SCRIPTS_IMPORT = [
  constants.DATABASE_SCRIPTS_GET_USER,
  'login'
];

constants.RESOURCE_SERVERS_DIRECTORY = 'resource-servers';
constants.RESOURCE_SERVERS_CLIENT_NAME = 'resourceServers';
constants.RESOURCE_SERVERS_MANAGEMENT_API_NAME = 'Auth0 Management API';
constants.RESOURCE_SERVERS_ID_NAME = 'id';

constants.CLIENTS_DIRECTORY = 'clients';
constants.CLIENTS_CLIENT_NAME = 'clients';
constants.CLIENTS_CLIENT_ID_NAME = 'client_id';

constants.CONNECTIONS_DIRECTORY = 'connections';
constants.CONNECTIONS_CLIENT_NAME = 'connections';
constants.CONNECTIONS_ID_NAME = 'id';

constants.CONCURRENT_CALLS = 5;
<commit_msg>constrants export<commit_after>const constants = {};

constants.RULES_DIRECTORY = 'rules';
constants.RULES_STAGES = [
  'login_success'
];

constants.DEFAULT_RULE_STAGE = constants.RULES_STAGES[0];  // eslint-disable-line

constants.RULES_CONFIGS_DIRECTORY = 'rules-configs';

constants.PAGES_DIRECTORY = 'pages';
constants.PAGE_LOGIN = 'login';
constants.PAGE_PASSWORD_RESET = 'password_reset';
constants.PAGE_GUARDIAN_MULTIFACTOR = 'guardian_multifactor';
constants.PAGE_ERROR = 'error_page';

constants.PAGE_NAMES = [
  constants.PAGE_GUARDIAN_MULTIFACTOR + '.html',
  constants.PAGE_GUARDIAN_MULTIFACTOR + '.json',
  constants.PAGE_PASSWORD_RESET + '.html',
  constants.PAGE_PASSWORD_RESET + '.json',
  constants.PAGE_LOGIN + '.html',
  constants.PAGE_LOGIN + '.json',
  constants.PAGE_ERROR + '.html',
  constants.PAGE_ERROR + '.json'
];

constants.DATABASE_CONNECTIONS_DIRECTORY = 'database-connections';
constants.DATABASE_SCRIPTS_CHANGE_EMAIL = 'change_email';
constants.DATABASE_SCRIPTS_GET_USER = 'get_user';
constants.DATABASE_SCRIPTS = [
  constants.DATABASE_SCRIPTS_GET_USER,
  'create',
  'verify',
  'login',
  'change_password',
  'delete',
  constants.DATABASE_SCRIPTS_CHANGE_EMAIL
];
constants.DATABASE_SCRIPTS_NO_IMPORT = [
  constants.DATABASE_SCRIPTS_GET_USER,
  'create',
  'verify',
  'login',
  'change_password',
  'delete'
];
constants.DATABASE_SCRIPTS_IMPORT = [
  constants.DATABASE_SCRIPTS_GET_USER,
  'login'
];

constants.RESOURCE_SERVERS_DIRECTORY = 'resource-servers';
constants.RESOURCE_SERVERS_CLIENT_NAME = 'resourceServers';
constants.RESOURCE_SERVERS_MANAGEMENT_API_NAME = 'Auth0 Management API';
constants.RESOURCE_SERVERS_ID_NAME = 'id';

constants.CLIENTS_DIRECTORY = 'clients';
constants.CLIENTS_CLIENT_NAME = 'clients';
constants.CLIENTS_CLIENT_ID_NAME = 'client_id';

constants.CONNECTIONS_DIRECTORY = 'connections';
constants.CONNECTIONS_CLIENT_NAME = 'connections';
constants.CONNECTIONS_ID_NAME = 'id';

constants.CONCURRENT_CALLS = 5;

export default constants;
<|endoftext|>