<commit_before>// From https://gist.github.com/1343518
// Modified by Hakim to handle Markdown indented with tabs
(function(){

    if( typeof Showdown === 'undefined' ) {
        throw 'The reveal.js Markdown plugin requires Showdown to be loaded';
    }

    var stripLeadingWhitespace = function(section) {

        var template = section.querySelector( 'script' );

        // strip leading whitespace so it isn't evaluated as code
        var text = ( template || section ).textContent;

        var leadingWs = text.match(/^\n?(\s*)/)[1].length,
            leadingTabs = text.match(/^\n?(\t*)/)[1].length;

        if( leadingTabs > 0 ) {
            text = text.replace( new RegExp('\\n?\\t{' + leadingTabs + '}','g'), '\n' );
        }
        else if( leadingWs > 1 ) {
            text = text.replace( new RegExp('\\n? {' + leadingWs + '}','g'), '\n' );
        }

        return text;

    };

    var twrap = function(el) {
      return '';
    };

    var slidifyMarkdown = function(markdown, separator, vertical) {

        separator = separator || '^\n---\n$';

        var reSeparator = new RegExp(separator + (vertical ? '|' + vertical : ''), 'mg'),
            reHorSeparator = new RegExp(separator),
            matches,
            lastIndex = 0,
            isHorizontal,
            wasHorizontal = true,
            content,
            sectionStack = [],
            markdownSections = '';

        // iterate until all blocks between separators are stacked up
        while( matches = reSeparator.exec(markdown) ) {

            // determine direction (horizontal by default)
            isHorizontal = reHorSeparator.test(matches[0]);

            if( !isHorizontal && wasHorizontal ) {
                // create vertical stack
                sectionStack.push([]);
            }

            // pluck slide content from markdown input
            content = markdown.substring(lastIndex, matches.index);

            if( isHorizontal && wasHorizontal ) {
                // add to horizontal stack
                sectionStack.push(content);
            } else {
                // add to vertical stack
                sectionStack[sectionStack.length-1].push(content);
            }

            lastIndex = reSeparator.lastIndex;
            wasHorizontal = isHorizontal;

        }

        // add the remaining slide
        (wasHorizontal ? sectionStack : sectionStack[sectionStack.length-1]).push(markdown.substring(lastIndex));

        // flatten the hierarchical stack, and insert
 tags
        for( var k = 0, klen = sectionStack.length; k < klen; k++ ) {
            markdownSections += typeof sectionStack[k] === 'string'
                ? '
' +  twrap( sectionStack[k] )  + '
'
                : '

' +  sectionStack[k].map(twrap).join('

') + '

';
        }

        return markdownSections;
    };

    var querySlidingMarkdown = function() {

        var sections = document.querySelectorAll( '[data-markdown]'),
            section;

        for( var j = 0, jlen = sections.length; j < jlen; j++ ) {

            section = sections[j];

            if( section.getAttribute('data-markdown').length ) {

                var xhr = new XMLHttpRequest(),
                    url = section.getAttribute('data-markdown');

                xhr.onreadystatechange = function () {
                    if( xhr.readyState === 4 ) {
                        if (xhr.status >= 200 && xhr.status < 300) {
                            section.outerHTML = slidifyMarkdown( xhr.responseText, section.getAttribute('data-separator'), section.getAttribute('data-vertical') );
                        } else {
                            section.outerHTML = '
ERROR: The attempt to fetch ' + url + ' failed with the HTTP status ' + xhr.status +
                                '. Check your browser\'s JavaScript console for more details.' +
                                '
Remember that you need to serve the presentation HTML from a HTTP server and the Markdown file must be there too.

';
                        }
                    }
                };

                xhr.open('GET', url, false);
                try {
                    xhr.send();
                } catch (e) {
                    alert('Failed to get the Markdown file ' + url + '. Make sure that the presentation and the file are served by a HTTP server and the file can be found there. ' + e);
                }

            } else if( section.getAttribute('data-separator') ) {

                var markdown = stripLeadingWhitespace(section);
                section.outerHTML = slidifyMarkdown( markdown, section.getAttribute('data-separator'), section.getAttribute('data-vertical') );

            }
        }

    };

    var queryMarkdownSlides = function() {

        var sections = document.querySelectorAll( '[data-markdown]');

        for( var j = 0, jlen = sections.length; j < jlen; j++ ) {

            makeHtml(sections[j]);

        }

    };

    var makeHtml = function(section) {

        var notes = section.querySelector( 'aside.notes' );

        var markdown = stripLeadingWhitespace(section);

        section.innerHTML = (new Showdown.converter()).makeHtml(markdown);

        if( notes ) {
            section.appendChild( notes );
        }

    };

    querySlidingMarkdown();

    queryMarkdownSlides();

})();
<commit_msg>Added support for data-state in section when using external markdown files.<commit_after>// From https://gist.github.com/1343518
// Modified by Hakim to handle Markdown indented with tabs
(function(){

    if( typeof Showdown === 'undefined' ) {
        throw 'The reveal.js Markdown plugin requires Showdown to be loaded';
    }

    var stripLeadingWhitespace = function(section) {

        var template = section.querySelector( 'script' );

        // strip leading whitespace so it isn't evaluated as code
        var text = ( template || section ).textContent;

        var leadingWs = text.match(/^\n?(\s*)/)[1].length,
            leadingTabs = text.match(/^\n?(\t*)/)[1].length;

        if( leadingTabs > 0 ) {
            text = text.replace( new RegExp('\\n?\\t{' + leadingTabs + '}','g'), '\n' );
        }
        else if( leadingWs > 1 ) {
            text = text.replace( new RegExp('\\n? {' + leadingWs + '}','g'), '\n' );
        }

        return text;

    };

    var twrap = function(el) {
      return '';
    };

    var slidifyMarkdown = function(markdown, separator, vertical, state) {

        separator = separator || '^\n---\n$';

        var reSeparator = new RegExp(separator + (vertical ? '|' + vertical : ''), 'mg'),
            reHorSeparator = new RegExp(separator),
            matches,
            lastIndex = 0,
            isHorizontal,
            wasHorizontal = true,
            content,
            sectionStack = [],
            markdownSections = '';

        // iterate until all blocks between separators are stacked up
        while( matches = reSeparator.exec(markdown) ) {

            // determine direction (horizontal by default)
            isHorizontal = reHorSeparator.test(matches[0]);

            if( !isHorizontal && wasHorizontal ) {
                // create vertical stack
                sectionStack.push([]);
            }

            // pluck slide content from markdown input
            content = markdown.substring(lastIndex, matches.index);

            if( isHorizontal && wasHorizontal ) {
                // add to horizontal stack
                sectionStack.push(content);
            } else {
                // add to vertical stack
                sectionStack[sectionStack.length-1].push(content);
            }

            lastIndex = reSeparator.lastIndex;
            wasHorizontal = isHorizontal;

        }

        // add the remaining slide
        (wasHorizontal ? sectionStack : sectionStack[sectionStack.length-1]).push(markdown.substring(lastIndex));

        // flatten the hierarchical stack, and insert
 tags
        for( var k = 0, klen = sectionStack.length; k < klen; k++ ) {
            markdownSections += typeof sectionStack[k] === 'string'
                ? '
' +  twrap( sectionStack[k] )  + '
'
                : '

' +  sectionStack[k].map(twrap).join('

') + '

';
        }

        return markdownSections;
    };

    var querySlidingMarkdown = function() {

        var sections = document.querySelectorAll( '[data-markdown]'),
            section;

        for( var j = 0, jlen = sections.length; j < jlen; j++ ) {

            section = sections[j];

            if( section.getAttribute('data-markdown').length ) {

                var xhr = new XMLHttpRequest(),
                    url = section.getAttribute('data-markdown');

                xhr.onreadystatechange = function () {
                    if( xhr.readyState === 4 ) {
                        if (xhr.status >= 200 && xhr.status < 300) {
                            section.outerHTML = slidifyMarkdown( xhr.responseText, section.getAttribute('data-separator'), section.getAttribute('data-vertical'), section.getAttribute('data-state'));
                        } else {
                            section.outerHTML = '
ERROR: The attempt to fetch ' + url + ' failed with the HTTP status ' + xhr.status +
                                '. Check your browser\'s JavaScript console for more details.' +
                                '
Remember that you need to serve the presentation HTML from a HTTP server and the Markdown file must be there too.

';
                        }
                    }
                };

                xhr.open('GET', url, false);
                try {
                    xhr.send();
                } catch (e) {
                    alert('Failed to get the Markdown file ' + url + '. Make sure that the presentation and the file are served by a HTTP server and the file can be found there. ' + e);
                }

            } else if( section.getAttribute('data-separator') ) {

                var markdown = stripLeadingWhitespace(section);
                section.outerHTML = slidifyMarkdown( markdown, section.getAttribute('data-separator'), section.getAttribute('data-vertical') );

            }
        }

    };

    var queryMarkdownSlides = function() {

        var sections = document.querySelectorAll( '[data-markdown]');

        for( var j = 0, jlen = sections.length; j < jlen; j++ ) {

            makeHtml(sections[j]);

        }

    };

    var makeHtml = function(section) {

        var notes = section.querySelector( 'aside.notes' );

        var markdown = stripLeadingWhitespace(section);

        section.innerHTML = (new Showdown.converter()).makeHtml(markdown);

        if( notes ) {
            section.appendChild( notes );
        }

    };

    querySlidingMarkdown();

    queryMarkdownSlides();

})();
<|endoftext|>


<commit_before>import SharingFilter from '../src/sharing.js';

describe('SharingFilter', function() {
  const Bob = {
    id: 1,
    name: 'Bob'
  };

  const Andy = {
    id: 1,
    name: 'Andy'
  };

  describe('with types', function() {
    const types = ['pdf', 'xlsx'];

    const documents = [{
      id: 1,
      name: 'Public document',
      type: types[0],
      collaborators: []
    }, {
      id: 2,
      name: 'Some other document',
      type: types[1],
      collaborators: []
    }, {
      id: 3,
      name: 'Another document',
      type: types[0],
      collaborators: []
    }, {
      id: 4,
      name: 'Last document on the planet',
      type: types[1],
      collaborators: []
    }];

    describe('combining collaborators', function() {
      it('should fully select a collaborator that has access to ' +
         'every document of a certain type', function() {
        const sharing = new SharingFilter([
          Object.assign({}, documents[0], {collaborators: [Bob.id]}),
          documents[1]
        ], [Bob]);

        expect(sharing.aggregateCollaboratorPermissions()).to.deep.equal([
          Object.assign({}, Bob, {selected: true, partial: false})
        ]);
      });

      it('should partially select a collaborator that has access to ' +
         'some of the documents of a certain type', function() {
        const sharing = new SharingFilter([
          Object.assign({}, documents[0], {collaborators: [Bob.id]}),
          Object.assign({}, documents[1], {collaborators: [Andy.id]}),
          documents[2], documents[3]
        ], [Bob, Andy]);

        expect(sharing.aggregateCollaboratorPermissions()).to.deep.equal([
          Object.assign({}, Bob, {selected: true, partial: true}),
          Object.assign({}, Andy, {selected: true, partial: true}),
        ]);
      });
    });

    describe('updating documents', function() {
      it('should give access to all the documents of a certain type to a ' +
         'fully selected collaborator', function() {
        const sharing = new SharingFilter([
          Object.assign({}, documents[0], {collaborators: [Bob.id]}),
          ...documents.slice(1)
        ], [Bob]);

        expect(sharing.updateDocuments([
          Object.assign({}, Bob, {selected: true, partial: false})
        ])).to.deep.equal([
          Object.assign({}, documents[0], {collaborators: [Bob.id]}),
          documents[1],
          Object.assign({}, documents[2], {collaborators: [Bob.id]}),
          documents[3]
        ]);
      });

      it('should give access to all the documents of a certain type to a ' +
         'fully selected collaborator', function() {
        const sharing = new SharingFilter([
          Object.assign({}, documents[0], {collaborators: [Bob.id]}),
          ...documents.slice(1)
        ], [Bob]);

        expect(sharing.updateDocuments([
          Object.assign({}, Bob, {selected: true, partial: false})
        ])).to.deep.equal([
          Object.assign({}, documents[0], {collaborators: [Bob.id]}),
          documents[1],
          Object.assign({}, documents[2], {collaborators: [Bob.id]}),
          documents[3]
        ]);
      });
    });
  });
});
<commit_msg>Remove duplicated test<commit_after>import SharingFilter from '../src/sharing.js';

describe('SharingFilter', function() {
  const Bob = {
    id: 1,
    name: 'Bob'
  };

  const Andy = {
    id: 1,
    name: 'Andy'
  };

  describe('with types', function() {
    const types = ['pdf', 'xlsx'];

    const documents = [{
      id: 1,
      name: 'Public document',
      type: types[0],
      collaborators: []
    }, {
      id: 2,
      name: 'Some other document',
      type: types[1],
      collaborators: []
    }, {
      id: 3,
      name: 'Another document',
      type: types[0],
      collaborators: []
    }, {
      id: 4,
      name: 'Last document on the planet',
      type: types[1],
      collaborators: []
    }];

    describe('combining collaborators', function() {
      it('should fully select a collaborator that has access to ' +
         'every document of a certain type', function() {
        const sharing = new SharingFilter([
          Object.assign({}, documents[0], {collaborators: [Bob.id]}),
          documents[1]
        ], [Bob]);

        expect(sharing.aggregateCollaboratorPermissions()).to.deep.equal([
          Object.assign({}, Bob, {selected: true, partial: false})
        ]);
      });

      it('should partially select a collaborator that has access to ' +
         'some of the documents of a certain type', function() {
        const sharing = new SharingFilter([
          Object.assign({}, documents[0], {collaborators: [Bob.id]}),
          Object.assign({}, documents[1], {collaborators: [Andy.id]}),
          documents[2], documents[3]
        ], [Bob, Andy]);

        expect(sharing.aggregateCollaboratorPermissions()).to.deep.equal([
          Object.assign({}, Bob, {selected: true, partial: true}),
          Object.assign({}, Andy, {selected: true, partial: true}),
        ]);
      });
    });

    describe('updating documents', function() {
      it('should give access to all the documents of a certain type to a ' +
         'fully selected collaborator', function() {
        const sharing = new SharingFilter([
          Object.assign({}, documents[0], {collaborators: [Bob.id]}),
          ...documents.slice(1)
        ], [Bob]);

        expect(sharing.updateDocuments([
          Object.assign({}, Bob, {selected: true, partial: false})
        ])).to.deep.equal([
          Object.assign({}, documents[0], {collaborators: [Bob.id]}),
          documents[1],
          Object.assign({}, documents[2], {collaborators: [Bob.id]}),
          documents[3]
        ]);
      });
    });
  });
});
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2011 Dan Vanderkam (danvdk@gmail.com)
 * MIT-licensed (http://opensource.org/licenses/MIT)
 */

/**
 * @fileoverview Based on PlotKitLayout, but modified to meet the needs of
 * dygraphs.
 */

/*jshint globalstrict: true */
/*global Dygraph:false */
"use strict";

/**
 * Creates a new DygraphLayout object.
 *
 * This class contains all the data to be charted.
 * It uses data coordinates, but also records the chart range (in data
 * coordinates) and hence is able to calculate percentage positions ('In this
 * view, Point A lies 25% down the x-axis.')
 *
 * Two things that it does not do are:
 * 1. Record pixel coordinates for anything.
 * 2. (oddly) determine anything about the layout of chart elements.
 *
 * The naming is a vestige of Dygraph's original PlotKit roots.
 *
 * @constructor
 */
var DygraphLayout = function(dygraph) {
  this.dygraph_ = dygraph;
  this.datasets = [];
  this.setNames = [];
  this.annotations = [];
  this.yAxes_ = null;

  // TODO(danvk): it's odd that xTicks_ and yTicks_ are inputs, but xticks and
  // yticks are outputs. Clean this up.
  this.xTicks_ = null;
  this.yTicks_ = null;
};

DygraphLayout.prototype.attr_ = function(name) {
  return this.dygraph_.attr_(name);
};

DygraphLayout.prototype.addDataset = function(setname, set_xy) {
  this.datasets.push(set_xy);
  this.setNames.push(setname);
};

DygraphLayout.prototype.getPlotArea = function() {
  return this.computePlotArea_();
};

// Compute the box which the chart should be drawn in. This is the canvas's
// box, less space needed for axis and chart labels.
DygraphLayout.prototype.computePlotArea_ = function() {
  var area = {
    // TODO(danvk): per-axis setting.
    x: 0,
    y: 0
  };
  if (this.attr_('drawYAxis')) {
   area.x = this.attr_('yAxisLabelWidth') + 2 * this.attr_('axisTickSize');
  }

  area.w = this.dygraph_.width_ - area.x - this.attr_('rightGap');
  area.h = this.dygraph_.height_;
  if (this.attr_('drawXAxis')) {
    if (this.attr_('xAxisHeight')) {
      area.h -= this.attr_('xAxisHeight');
    } else {
      area.h -= this.attr_('axisLabelFontSize') + 2 * this.attr_('axisTickSize');
    }
  }

  // Shrink the drawing area to accomodate additional y-axes.
  if (this.dygraph_.numAxes() == 2) {
    // TODO(danvk): per-axis setting.
    area.w -= (this.attr_('yAxisLabelWidth') + 2 * this.attr_('axisTickSize'));
  } else if (this.dygraph_.numAxes() > 2) {
    this.dygraph_.error("Only two y-axes are supported at this time. (Trying " +
                        "to use " + this.dygraph_.numAxes() + ")");
  }

  // Add space for chart labels: title, xlabel and ylabel.
  if (this.attr_('title')) {
    area.h -= this.attr_('titleHeight');
    area.y += this.attr_('titleHeight');
  }
  if (this.attr_('xlabel')) {
    area.h -= this.attr_('xLabelHeight');
  }
  if (this.attr_('ylabel')) {
    // It would make sense to shift the chart here to make room for the y-axis
    // label, but the default yAxisLabelWidth is large enough that this results
    // in overly-padded charts. The y-axis label should fit fine. If it
    // doesn't, the yAxisLabelWidth option can be increased.
  }

  if (this.attr_('y2label')) {
    // same logic applies here as for ylabel.
    // TODO(danvk): make yAxisLabelWidth a per-axis property
  }

  // Add space for range selector, if needed.
  if (this.attr_('showRangeSelector')) {
    area.h -= this.attr_('rangeSelectorHeight') + 4;
  }

  return area;
};

DygraphLayout.prototype.setAnnotations = function(ann) {
  // The Dygraph object's annotations aren't parsed. We parse them here and
  // save a copy. If there is no parser, then the user must be using raw format.
  this.annotations = [];
  var parse = this.attr_('xValueParser') || function(x) { return x; };
  for (var i = 0; i < ann.length; i++) {
    var a = {};
    if (!ann[i].xval && !ann[i].x) {
      this.dygraph_.error("Annotations must have an 'x' property");
      return;
    }
    if (ann[i].icon &&
        !(ann[i].hasOwnProperty('width') &&
          ann[i].hasOwnProperty('height'))) {
      this.dygraph_.error("Must set width and height when setting " +
                          "annotation.icon property");
      return;
    }
    Dygraph.update(a, ann[i]);
    if (!a.xval) a.xval = parse(a.x);
    this.annotations.push(a);
  }
};

DygraphLayout.prototype.setXTicks = function(xTicks) {
  this.xTicks_ = xTicks;
};

// TODO(danvk): add this to the Dygraph object's API or move it into Layout.
DygraphLayout.prototype.setYAxes = function (yAxes) {
  this.yAxes_ = yAxes;
};

DygraphLayout.prototype.setDateWindow = function(dateWindow) {
  this.dateWindow_ = dateWindow;
};

DygraphLayout.prototype.evaluate = function() {
  this._evaluateLimits();
  this._evaluateLineCharts();
  this._evaluateLineTicks();
  this._evaluateAnnotations();
};

DygraphLayout.prototype._evaluateLimits = function() {
  this.minxval = this.maxxval = null;
  if (this.dateWindow_) {
    this.minxval = this.dateWindow_[0];
    this.maxxval = this.dateWindow_[1];
  } else {
    for (var setIdx = 0; setIdx < this.datasets.length; ++setIdx) {
      var series = this.datasets[setIdx];
      if (series.length > 1) {
        var x1 = series[0][0];
        if (!this.minxval || x1 < this.minxval) this.minxval = x1;

        var x2 = series[series.length - 1][0];
        if (!this.maxxval || x2 > this.maxxval) this.maxxval = x2;
      }
    }
  }
  this.xrange = this.maxxval - this.minxval;
  this.xscale = (this.xrange !== 0 ? 1/this.xrange : 1.0);

  for (var i = 0; i < this.yAxes_.length; i++) {
    var axis = this.yAxes_[i];
    axis.minyval = axis.computedValueRange[0];
    axis.maxyval = axis.computedValueRange[1];
    axis.yrange = axis.maxyval - axis.minyval;
    axis.yscale = (axis.yrange !== 0 ? 1.0 / axis.yrange : 1.0);

    if (axis.g.attr_("logscale")) {
      axis.ylogrange = Dygraph.log10(axis.maxyval) - Dygraph.log10(axis.minyval);
      axis.ylogscale = (axis.ylogrange !== 0 ? 1.0 / axis.ylogrange : 1.0);
      if (!isFinite(axis.ylogrange) || isNaN(axis.ylogrange)) {
        axis.g.error('axis ' + i + ' of graph at ' + axis.g +
            ' can\'t be displayed in log scale for range [' +
            axis.minyval + ' - ' + axis.maxyval + ']');
      }
    }
  }
};

DygraphLayout._calcYNormal = function(axis, value) {
  if (axis.logscale) {
    return 1.0 - ((Dygraph.log10(value) - Dygraph.log10(axis.minyval)) * axis.ylogscale);
  } else {
    return 1.0 - ((value - axis.minyval) * axis.yscale);
  }
};

DygraphLayout.prototype._evaluateLineCharts = function() {
  // add all the rects
  this.points = [];
  // An array to keep track of how many points will be drawn for each set.
  // This will allow for the canvas renderer to not have to check every point
  // for every data set since the points are added in order of the sets in
  // datasets.
  this.setPointsLengths = [];
  this.setPointsOffsets = [];

  var connectSeparated = this.attr_('connectSeparatedPoints');
  for (var setIdx = 0; setIdx < this.datasets.length; ++setIdx) {
    var dataset = this.datasets[setIdx];
    var setName = this.setNames[setIdx];
    var axis = this.dygraph_.axisPropertiesForSeries(setName);

    this.setPointsOffsets.push(this.points.length);
    var setPointsLength = 0;

    for (var j = 0; j < dataset.length; j++) {
      var item = dataset[j];
      var xValue = parseFloat(item[0]);
      var yValue = parseFloat(item[1]);

      // Range from 0-1 where 0 represents left and 1 represents right.
      var xNormal = (xValue - this.minxval) * this.xscale;
      // Range from 0-1 where 0 represents top and 1 represents bottom
      var yNormal = DygraphLayout._calcYNormal(axis, yValue);

      var point = {
        // TODO(danvk): here
        x: xNormal,
        y: yNormal,
        xval: xValue,
        yval: yValue,
        name: setName
      };
      if (connectSeparated && item[1] === null) {
        point.yval = null;
      }
      this.points.push(point);
      setPointsLength += 1;
    }
    this.setPointsLengths.push(setPointsLength);
  }
};

DygraphLayout.prototype._evaluateLineTicks = function() {
  var i, tick, label, pos;
  this.xticks = [];
  for (i = 0; i < this.xTicks_.length; i++) {
    tick = this.xTicks_[i];
    label = tick.label;
    pos = this.xscale * (tick.v - this.minxval);
    if ((pos >= 0.0) && (pos <= 1.0)) {
      this.xticks.push([pos, label]);
    }
  }

  this.yticks = [];
  for (i = 0; i < this.yAxes_.length; i++ ) {
    var axis = this.yAxes_[i];
    for (var j = 0; j < axis.ticks.length; j++) {
      tick = axis.ticks[j];
      label = tick.label;
      pos = this.dygraph_.toPercentYCoord(tick.v, i);
      if ((pos >= 0.0) && (pos <= 1.0)) {
        this.yticks.push([i, pos, label]);
      }
    }
  }
};

/**
 * Behaves the same way as PlotKit.Layout, but also copies the errors
 * @private
 */
DygraphLayout.prototype.evaluateWithError = function() {
  this.evaluate();
  if (!(this.attr_('errorBars') || this.attr_('customBars'))) return;

  // Copy over the error terms
  var i = 0;  // index in this.points
  for (var setIdx = 0; setIdx < this.datasets.length; ++setIdx) {
    var j = 0;
    var dataset = this.datasets[setIdx];
    var setName = this.setNames[setIdx];
    var axis = this.dygraph_.axisPropertiesForSeries(setName);
    for (j = 0; j < dataset.length; j++, i++) {
      var item = dataset[j];
      var xv = parseFloat(item[0]);
      var yv = parseFloat(item[1]);

      if (xv == this.points[i].xval &&
          yv == this.points[i].yval) {
        var errorMinus = parseFloat(item[2]);
        var errorPlus = parseFloat(item[3]);

        var yv_minus = yv - errorMinus;
        var yv_plus = yv + errorPlus;
        this.points[i].y_top = DygraphLayout._calcYNormal(axis, yv_minus);
        this.points[i].y_bottom = DygraphLayout._calcYNormal(axis, yv_plus);
      }
    }
  }
};

DygraphLayout.prototype._evaluateAnnotations = function() {
  // Add the annotations to the point to which they belong.
  // Make a map from (setName, xval) to annotation for quick lookups.
  var i;
  var annotations = {};
  for (i = 0; i < this.annotations.length; i++) {
    var a = this.annotations[i];
    annotations[a.xval + "," + a.series] = a;
  }

  this.annotated_points = [];

  // Exit the function early if there are no annotations.
  if (!this.annotations || !this.annotations.length) {
    return;
  }

  // TODO(antrob): loop through annotations not points.
  for (i = 0; i < this.points.length; i++) {
    var p = this.points[i];
    var k = p.xval + "," + p.name;
    if (k in annotations) {
      p.annotation = annotations[k];
      this.annotated_points.push(p);
    }
  }
};

/**
 * Convenience function to remove all the data sets from a graph
 */
DygraphLayout.prototype.removeAllDatasets = function() {
  delete this.datasets;
  delete this.setNames;
  delete this.setPointsLengths;
  delete this.setPointsOffsets;
  this.datasets = [];
  this.setNames = [];
  this.setPointsLengths = [];
  this.setPointsOffsets = [];
};

/**
 * Return a copy of the point at the indicated index, with its yval unstacked.
 * @param int index of point in layout_.points
 */
DygraphLayout.prototype.unstackPointAtIndex = function(idx) {
  var point = this.points[idx];
  if (!point.yval) {
    return point;
  }

  // Clone the point since we modify it
  var unstackedPoint = {};
  for (var pt in point) {
    unstackedPoint[pt] = point[pt];
  }

  if (!this.attr_("stackedGraph")) {
    return unstackedPoint;
  }

  // The unstacked yval is equal to the current yval minus the yval of the
  // next point at the same xval.
  for (var i = idx+1; i < this.points.length; i++) {
    if ((this.points[i].xval == point.xval) && this.points[i].yval) {
      unstackedPoint.yval -= this.points[i].yval;
      break;
    }
  }

  return unstackedPoint;
};
<commit_msg>Add comments<commit_after>/**
 * @license
 * Copyright 2011 Dan Vanderkam (danvdk@gmail.com)
 * MIT-licensed (http://opensource.org/licenses/MIT)
 */

/**
 * @fileoverview Based on PlotKitLayout, but modified to meet the needs of
 * dygraphs.
 */

/*jshint globalstrict: true */
/*global Dygraph:false */
"use strict";

/**
 * Creates a new DygraphLayout object.
 *
 * This class contains all the data to be charted.
 * It uses data coordinates, but also records the chart range (in data
 * coordinates) and hence is able to calculate percentage positions ('In this
 * view, Point A lies 25% down the x-axis.')
 *
 * Two things that it does not do are:
 * 1. Record pixel coordinates for anything.
 * 2. (oddly) determine anything about the layout of chart elements.
 *
 * The naming is a vestige of Dygraph's original PlotKit roots.
 *
 * @constructor
 */
var DygraphLayout = function(dygraph) {
  this.dygraph_ = dygraph;
  this.datasets = [];
  this.setNames = [];
  this.annotations = [];
  this.yAxes_ = null;

  // TODO(danvk): it's odd that xTicks_ and yTicks_ are inputs, but xticks and
  // yticks are outputs. Clean this up.
  this.xTicks_ = null;
  this.yTicks_ = null;
};

DygraphLayout.prototype.attr_ = function(name) {
  return this.dygraph_.attr_(name);
};

DygraphLayout.prototype.addDataset = function(setname, set_xy) {
  this.datasets.push(set_xy);
  this.setNames.push(setname);
};

DygraphLayout.prototype.getPlotArea = function() {
  return this.computePlotArea_();
};

// Compute the box which the chart should be drawn in. This is the canvas's
// box, less space needed for axis and chart labels.
DygraphLayout.prototype.computePlotArea_ = function() {
  var area = {
    // TODO(danvk): per-axis setting.
    x: 0,
    y: 0
  };
  if (this.attr_('drawYAxis')) {
   area.x = this.attr_('yAxisLabelWidth') + 2 * this.attr_('axisTickSize');
  }

  area.w = this.dygraph_.width_ - area.x - this.attr_('rightGap');
  area.h = this.dygraph_.height_;
  if (this.attr_('drawXAxis')) {
    if (this.attr_('xAxisHeight')) {
      area.h -= this.attr_('xAxisHeight');
    } else {
      area.h -= this.attr_('axisLabelFontSize') + 2 * this.attr_('axisTickSize');
    }
  }

  // Shrink the drawing area to accomodate additional y-axes.
  if (this.dygraph_.numAxes() == 2) {
    // TODO(danvk): per-axis setting.
    area.w -= (this.attr_('yAxisLabelWidth') + 2 * this.attr_('axisTickSize'));
  } else if (this.dygraph_.numAxes() > 2) {
    this.dygraph_.error("Only two y-axes are supported at this time. (Trying " +
                        "to use " + this.dygraph_.numAxes() + ")");
  }

  // Add space for chart labels: title, xlabel and ylabel.
  if (this.attr_('title')) {
    area.h -= this.attr_('titleHeight');
    area.y += this.attr_('titleHeight');
  }
  if (this.attr_('xlabel')) {
    area.h -= this.attr_('xLabelHeight');
  }
  if (this.attr_('ylabel')) {
    // It would make sense to shift the chart here to make room for the y-axis
    // label, but the default yAxisLabelWidth is large enough that this results
    // in overly-padded charts. The y-axis label should fit fine. If it
    // doesn't, the yAxisLabelWidth option can be increased.
  }

  if (this.attr_('y2label')) {
    // same logic applies here as for ylabel.
    // TODO(danvk): make yAxisLabelWidth a per-axis property
  }

  // Add space for range selector, if needed.
  if (this.attr_('showRangeSelector')) {
    area.h -= this.attr_('rangeSelectorHeight') + 4;
  }

  return area;
};

DygraphLayout.prototype.setAnnotations = function(ann) {
  // The Dygraph object's annotations aren't parsed. We parse them here and
  // save a copy. If there is no parser, then the user must be using raw format.
  this.annotations = [];
  var parse = this.attr_('xValueParser') || function(x) { return x; };
  for (var i = 0; i < ann.length; i++) {
    var a = {};
    if (!ann[i].xval && !ann[i].x) {
      this.dygraph_.error("Annotations must have an 'x' property");
      return;
    }
    if (ann[i].icon &&
        !(ann[i].hasOwnProperty('width') &&
          ann[i].hasOwnProperty('height'))) {
      this.dygraph_.error("Must set width and height when setting " +
                          "annotation.icon property");
      return;
    }
    Dygraph.update(a, ann[i]);
    if (!a.xval) a.xval = parse(a.x);
    this.annotations.push(a);
  }
};

DygraphLayout.prototype.setXTicks = function(xTicks) {
  this.xTicks_ = xTicks;
};

// TODO(danvk): add this to the Dygraph object's API or move it into Layout.
DygraphLayout.prototype.setYAxes = function (yAxes) {
  this.yAxes_ = yAxes;
};

DygraphLayout.prototype.setDateWindow = function(dateWindow) {
  this.dateWindow_ = dateWindow;
};

DygraphLayout.prototype.evaluate = function() {
  this._evaluateLimits();
  this._evaluateLineCharts();
  this._evaluateLineTicks();
  this._evaluateAnnotations();
};

DygraphLayout.prototype._evaluateLimits = function() {
  this.minxval = this.maxxval = null;
  if (this.dateWindow_) {
    this.minxval = this.dateWindow_[0];
    this.maxxval = this.dateWindow_[1];
  } else {
    for (var setIdx = 0; setIdx < this.datasets.length; ++setIdx) {
      var series = this.datasets[setIdx];
      if (series.length > 1) {
        var x1 = series[0][0];
        if (!this.minxval || x1 < this.minxval) this.minxval = x1;

        var x2 = series[series.length - 1][0];
        if (!this.maxxval || x2 > this.maxxval) this.maxxval = x2;
      }
    }
  }
  this.xrange = this.maxxval - this.minxval;
  this.xscale = (this.xrange !== 0 ? 1/this.xrange : 1.0);

  for (var i = 0; i < this.yAxes_.length; i++) {
    var axis = this.yAxes_[i];
    axis.minyval = axis.computedValueRange[0];
    axis.maxyval = axis.computedValueRange[1];
    axis.yrange = axis.maxyval - axis.minyval;
    axis.yscale = (axis.yrange !== 0 ? 1.0 / axis.yrange : 1.0);

    if (axis.g.attr_("logscale")) {
      axis.ylogrange = Dygraph.log10(axis.maxyval) - Dygraph.log10(axis.minyval);
      axis.ylogscale = (axis.ylogrange !== 0 ? 1.0 / axis.ylogrange : 1.0);
      if (!isFinite(axis.ylogrange) || isNaN(axis.ylogrange)) {
        axis.g.error('axis ' + i + ' of graph at ' + axis.g +
            ' can\'t be displayed in log scale for range [' +
            axis.minyval + ' - ' + axis.maxyval + ']');
      }
    }
  }
};

DygraphLayout._calcYNormal = function(axis, value) {
  if (axis.logscale) {
    return 1.0 - ((Dygraph.log10(value) - Dygraph.log10(axis.minyval)) * axis.ylogscale);
  } else {
    return 1.0 - ((value - axis.minyval) * axis.yscale);
  }
};

DygraphLayout.prototype._evaluateLineCharts = function() {
  // add all the rects
  this.points = [];
  // An array to keep track of how many points will be drawn for each set.
  // This will allow for the canvas renderer to not have to check every point
  // for every data set since the points are added in order of the sets in
  // datasets.
  this.setPointsLengths = [];
  this.setPointsOffsets = [];

  var connectSeparated = this.attr_('connectSeparatedPoints');
  for (var setIdx = 0; setIdx < this.datasets.length; ++setIdx) {
    var dataset = this.datasets[setIdx];
    var setName = this.setNames[setIdx];
    var axis = this.dygraph_.axisPropertiesForSeries(setName);

    this.setPointsOffsets.push(this.points.length);
    var setPointsLength = 0;

    for (var j = 0; j < dataset.length; j++) {
      var item = dataset[j];
      var xValue = parseFloat(item[0]);
      var yValue = parseFloat(item[1]);

      // Range from 0-1 where 0 represents left and 1 represents right.
      var xNormal = (xValue - this.minxval) * this.xscale;
      // Range from 0-1 where 0 represents top and 1 represents bottom
      var yNormal = DygraphLayout._calcYNormal(axis, yValue);

      var point = {
        // TODO(danvk): here
        x: xNormal,
        y: yNormal,
        xval: xValue,
        yval: yValue,
        name: setName
      };
      if (connectSeparated && item[1] === null) {
        point.yval = null;
      }
      this.points.push(point);
      setPointsLength += 1;
    }
    this.setPointsLengths.push(setPointsLength);
  }
};

DygraphLayout.prototype._evaluateLineTicks = function() {
  var i, tick, label, pos;
  this.xticks = [];
  for (i = 0; i < this.xTicks_.length; i++) {
    tick = this.xTicks_[i];
    label = tick.label;
    pos = this.xscale * (tick.v - this.minxval);
    if ((pos >= 0.0) && (pos <= 1.0)) {
      this.xticks.push([pos, label]);
    }
  }

  this.yticks = [];
  for (i = 0; i < this.yAxes_.length; i++ ) {
    var axis = this.yAxes_[i];
    for (var j = 0; j < axis.ticks.length; j++) {
      tick = axis.ticks[j];
      label = tick.label;
      pos = this.dygraph_.toPercentYCoord(tick.v, i);
      if ((pos >= 0.0) && (pos <= 1.0)) {
        this.yticks.push([i, pos, label]);
      }
    }
  }
};

/**
 * Behaves the same way as PlotKit.Layout, but also copies the errors
 * @private
 */
DygraphLayout.prototype.evaluateWithError = function() {
  this.evaluate();
  if (!(this.attr_('errorBars') || this.attr_('customBars'))) return;

  // Copy over the error terms
  var i = 0;  // index in this.points
  for (var setIdx = 0; setIdx < this.datasets.length; ++setIdx) {
    var j = 0;
    var dataset = this.datasets[setIdx];
    var setName = this.setNames[setIdx];
    var axis = this.dygraph_.axisPropertiesForSeries(setName);
    for (j = 0; j < dataset.length; j++, i++) {
      var item = dataset[j];
      var xv = parseFloat(item[0]);
      var yv = parseFloat(item[1]);

      if (xv == this.points[i].xval &&
          yv == this.points[i].yval) {
        var errorMinus = parseFloat(item[2]);
        var errorPlus = parseFloat(item[3]);

        var yv_minus = yv - errorMinus;
        var yv_plus = yv + errorPlus;
        this.points[i].y_top = DygraphLayout._calcYNormal(axis, yv_minus);
        this.points[i].y_bottom = DygraphLayout._calcYNormal(axis, yv_plus);
      }
    }
  }
};

DygraphLayout.prototype._evaluateAnnotations = function() {
  // Add the annotations to the point to which they belong.
  // Make a map from (setName, xval) to annotation for quick lookups.
  var i;
  var annotations = {};
  for (i = 0; i < this.annotations.length; i++) {
    var a = this.annotations[i];
    annotations[a.xval + "," + a.series] = a;
  }

  this.annotated_points = [];

  // Exit the function early if there are no annotations.
  if (!this.annotations || !this.annotations.length) {
    return;
  }

  // TODO(antrob): loop through annotations not points.
  for (i = 0; i < this.points.length; i++) {
    var p = this.points[i];
    var k = p.xval + "," + p.name;
    if (k in annotations) {
      p.annotation = annotations[k];
      this.annotated_points.push(p);
    }
  }
};

/**
 * Convenience function to remove all the data sets from a graph
 */
DygraphLayout.prototype.removeAllDatasets = function() {
  delete this.datasets;
  delete this.setNames;
  delete this.setPointsLengths;
  delete this.setPointsOffsets;
  this.datasets = [];
  this.setNames = [];
  this.setPointsLengths = [];
  this.setPointsOffsets = [];
};

/**
 * Return a copy of the point at the indicated index, with its yval unstacked.
 * @param int index of point in layout_.points
 */
DygraphLayout.prototype.unstackPointAtIndex = function(idx) {
  var point = this.points[idx];
  // If the point is missing, no unstacking is necessary
  if (!point.yval) {
    return point;
  }

  // Clone the point since we modify it
  var unstackedPoint = {};
  for (var pt in point) {
    unstackedPoint[pt] = point[pt];
  }

  if (!this.attr_("stackedGraph")) {
    return unstackedPoint;
  }

  // The unstacked yval is equal to the current yval minus the yval of the
  // next point at the same xval.
  for (var i = idx+1; i < this.points.length; i++) {
    if ((this.points[i].xval == point.xval) && this.points[i].yval) {
      unstackedPoint.yval -= this.points[i].yval;
      break;
    }
  }

  return unstackedPoint;
};
<|endoftext|>


<commit_before>var Popup = (function(my){

  var bg = chrome.extension.getBackgroundPage();
  var linkedinData = {};
  var settings = {};

  my.init = function() {
    window.addEventListener('load', showPopup, false);
  };

  function showPopup() {
    updateSettings();
    updateLinkedinData();
    renderContent();
  }

  function updateLinkedinData() {
    linkedinData = bg.App.linkedinData;
  }

  function updateSettings() {
    settings.apiKey = localStorage['apiKey'] || '';
  }

  function renderContent() {
    var result = my.template( $.extend({}, linkedinData, settings) );
    document.body.innerHTML = result.content;
    // attach event listeners
    for (var i = result.eventHandlers.length - 1; i >= 0; i--) {
      var f = result.eventHandlers[i];
      if (typeof f === 'function') f();
    };
  }

  // ========================================= Template
  my.template = function(data) {
    var content = '

',
        inputs = ['firstname', 'lastname', 'domain'];

    content += '

';
    content += '
<form id="submitMake">';
    for (var i = 0, len = inputs.length; i < len; i++) {
      var id = inputs[i];
      content += '
<input id="' + id + '" value="' + (data[id] ? data[id] : '') + '" placeholder="' + id + '"/>
';
    }
    content += '<button type="submit" class="btn btn-success">Submit</button>';
    content += '</form>	';
    content += '<form id="submitEmail">';
    content += '
<input id="email" placeholder="email"/>
';
    content += '<button class="btn btn-success">Submit</button>';
    content += '</form>	';
    content += '

';

    content += '

';

    var eventHandlers = [];
    eventHandlers.push(

      function() {
        var showResult = function(msg, className, delay) {
          var $result = $('#result');
          $result.removeClass();
          if (className) $result.addClass(className);
          $result.html(msg).show();
          if (delay) {
            setTimeout(function(){
              $result.hide();
            }, delay);
          }
        }

        var showLoader = function() {
          showResult('

');
        }

        var checkAPI = function() {
          if (!data.apiKey) {
            showResult('
Please add your Toofr API key.

Find it by logging into Toofr and going to http://toofr.com/api, and then save it in the Chrome extension options.
', 'alert alert-info', false);
            return false;
          }
          return true;
        }

        var sendRequest = function(url, processResponse) {
          $.ajax({
            url: url,
            beforeSend: showLoader,
            dataType: 'json'
          }).done( function(response){
            var result = processResponse(response);
            showResult( result.content, result.type );
          }).fail( function(){
            showResult('Network error', 'alert alert-info', 2000);
          });
        }

        var processMakeResponse = function(json) {
          var type = '',
              content = '';
          if ((content = checkResponseErrors(json)) !== false) {
            type = 'alert alert-danger';
          }
          else if (!json.response.email) {
            content = "Sorry, no email address was found.";
            type = 'alert alert-danger';
          }
          else {
            type = 'alert alert-success';
            content = '';
            $.each(['first', 'last', 'domain', 'email', 'confidence'], function(i, id){
              content += '
' + id + ':' + '' + json.response[id] + '
';
            })
          }
          return {type: type, content: content};
        }

        var processEmailResponse = function(json) {
          var type = '',
              content = '';
          if ((content = checkResponseErrors(json)) !== false) {
            type = 'alert alert-danger';
          }
          else {
            var confidence = json.response.confidence,
            content = '
Confidence:' + confidence + '
';
            content += '
';
            content += '

';
            type = 'alert alert-success';
            if (!confidence) type = 'alert alert-danger';
          }
          return {type: type, content: content};
        }

        var checkResponseErrors = function(json) {
          if (!json.response) return "Bad response";
          else if (json.response.error) return json.response.error;
          else return false;
        }

        $('#submitMake').submit( function(e){
          e.preventDefault();
          if (!checkAPI()) return;
          var url = 'http://toofr.com/api/guess' +
              '?key=' + data.apiKey +
              '&domain=' + $('#domain').val() +
              '&first=' + $('#firstname').val() +
              '&last=' + $('#lastname').val();
          sendRequest(url, processMakeResponse);
        });

        $('#submitEmail').submit( function(e){
          e.preventDefault();
          if (!checkAPI) return;
          var url = 'http://toofr.com/api/test' +
              '?key=' + data.apiKey +
              '&email=' + $('#email').val();
          sendRequest(url, processEmailResponse);
        });

      });

    return {content: content, eventHandlers: eventHandlers};
  }

  return my;

})(Popup || {});

Popup.init();<commit_msg>progress bar on guess too<commit_after>var Popup = (function(my){

  var bg = chrome.extension.getBackgroundPage();
  var linkedinData = {};
  var settings = {};

  my.init = function() {
    window.addEventListener('load', showPopup, false);
  };

  function showPopup() {
    updateSettings();
    updateLinkedinData();
    renderContent();
  }

  function updateLinkedinData() {
    linkedinData = bg.App.linkedinData;
  }

  function updateSettings() {
    settings.apiKey = localStorage['apiKey'] || '';
  }

  function renderContent() {
    var result = my.template( $.extend({}, linkedinData, settings) );
    document.body.innerHTML = result.content;
    // attach event listeners
    for (var i = result.eventHandlers.length - 1; i >= 0; i--) {
      var f = result.eventHandlers[i];
      if (typeof f === 'function') f();
    };
  }

  // ========================================= Template
  my.template = function(data) {
    var content = '

',
        inputs = ['firstname', 'lastname', 'domain'];

    content += '

';
    content += '
<form id="submitMake">';
    for (var i = 0, len = inputs.length; i < len; i++) {
      var id = inputs[i];
      content += '
<input id="' + id + '" value="' + (data[id] ? data[id] : '') + '" placeholder="' + id + '"/>
';
    }
    content += '<button type="submit" class="btn btn-success">Submit</button>';
    content += '</form>	';
    content += '<form id="submitEmail">';
    content += '
<input id="email" placeholder="email"/>
';
    content += '<button class="btn btn-success">Submit</button>';
    content += '</form>	';
    content += '

';

    content += '

';

    var eventHandlers = [];
    eventHandlers.push(

      function() {
        var showResult = function(msg, className, delay) {
          var $result = $('#result');
          $result.removeClass();
          if (className) $result.addClass(className);
          $result.html(msg).show();
          if (delay) {
            setTimeout(function(){
              $result.hide();
            }, delay);
          }
        }

        var showLoader = function() {
          showResult('

');
        }

        var checkAPI = function() {
          if (!data.apiKey) {
            showResult('
Please add your Toofr API key.

Find it by logging into Toofr and going to http://toofr.com/api, and then save it in the Chrome extension options.
', 'alert alert-info', false);
            return false;
          }
          return true;
        }

        var sendRequest = function(url, processResponse) {
          $.ajax({
            url: url,
            beforeSend: showLoader,
            dataType: 'json'
          }).done( function(response){
            var result = processResponse(response);
            showResult( result.content, result.type );
          }).fail( function(){
            showResult('Network error', 'alert alert-info', 2000);
          });
        }

        var processMakeResponse = function(json) {
          var type = '',
              confidence = json.response.confidence,
              content = '';
          if ((content = checkResponseErrors(json)) !== false) {
            type = 'alert alert-danger';
          }
          else if (!json.response.email) {
            content = "Sorry, no email address was found.";
            type = 'alert alert-danger';
          }
          else {
            type = 'alert alert-success';
            content = '';
            $.each(['first', 'last', 'domain', 'email', 'confidence'], function(i, id){
              content += '
' + id + ':' + '' + json.response[id] + '
';
            })
            content += '
';
            content += '

';
          }
          return {type: type, content: content};
        }

        var processEmailResponse = function(json) {
          var type = '',
              content = '';
          if ((content = checkResponseErrors(json)) !== false) {
            type = 'alert alert-danger';
          }
          else {
            var confidence = json.response.confidence,
            content = '
Confidence:' + confidence + '
';
            content += '
';
            content += '

';
            type = 'alert alert-success';
            if (!confidence) type = 'alert alert-danger';
          }
          return {type: type, content: content};
        }

        var checkResponseErrors = function(json) {
          if (!json.response) return "Bad response";
          else if (json.response.error) return json.response.error;
          else return false;
        }

        $('#submitMake').submit( function(e){
          e.preventDefault();
          if (!checkAPI()) return;
          var url = 'http://toofr.com/api/guess' +
              '?key=' + data.apiKey +
              '&domain=' + $('#domain').val() +
              '&first=' + $('#firstname').val() +
              '&last=' + $('#lastname').val();
          sendRequest(url, processMakeResponse);
        });

        $('#submitEmail').submit( function(e){
          e.preventDefault();
          if (!checkAPI) return;
          var url = 'http://toofr.com/api/test' +
              '?key=' + data.apiKey +
              '&email=' + $('#email').val();
          sendRequest(url, processEmailResponse);
        });

      });

    return {content: content, eventHandlers: eventHandlers};
  }

  return my;

})(Popup || {});

Popup.init();<|endoftext|>


<commit_before>/* @flow weak */

/**
 * OfflineMobile Android
 * Sustainable Solutions (NZ) Ltd. 2016
 */

import {
  StyleSheet,
} from 'react-native';
export const APP_FONT_FAMILY = 'Museo_Slab_500';
export const SUSSOL_ORANGE = '#e95c30';
export const BLUE_WHITE = '#ecf3fc';
export const BACKGROUND_COLOR = '#f8fbfe';
export const SHADOW_BORDER = 'rgba(0, 0, 0, 0.1)';
export const DARK_GREY = '#4a4a4a';
export const DARKER_GREY = '#333333';
export const GREY = '#909192';
export const WARM_GREY = '#9b9b9b';
export const WARMER_GREY = '#a8aaac';
export const ROW_BLUE = 'rgba(73, 143, 226, 0.05)';
export const FINALISE_GREEN = '#219d1b';
export const FINALISED_RED = '#f63b30';
export const PAGE_CONTENT_PADDING_HORIZONTAL = 20;
export const PAGE_CONTENT_PADDING_VERTICAL = 10;

export default StyleSheet.create({
  appBackground: {
    flex: 1,
    backgroundColor: BACKGROUND_COLOR,
  },
  container: {
    flex: 1,
    borderWidth: 1,
    borderColor: SHADOW_BORDER,
    backgroundColor: BLUE_WHITE,
  },
  pageContentContainer: {
    flex: 1,
    paddingHorizontal: PAGE_CONTENT_PADDING_HORIZONTAL,
    paddingVertical: PAGE_CONTENT_PADDING_VERTICAL,
    backgroundColor: BACKGROUND_COLOR,
  },
  pageTopSectionContainer: {
    paddingTop: 20,
    paddingHorizontal: 10,
    paddingBottom: 15,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  horizontalContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  modal: {
    justifyContent: 'center',
    alignItems: 'center',
  },
  navBarOffset: {
    paddingTop: 68,
  },
  navBarStyle: {
    backgroundColor: BACKGROUND_COLOR,
    borderBottomWidth: 0,
    elevation: 0,
  },
  text: {
    fontFamily: APP_FONT_FAMILY,
    fontSize: 16,
  },
  buttonText: {
    fontFamily: APP_FONT_FAMILY,
    fontSize: 12,
    color: SUSSOL_ORANGE,
  },
  button: {
    alignItems: 'center',
    justifyContent: 'center',
    height: 45,
    width: 140,
    borderWidth: 1,
    borderRadius: 4,
    padding: 15,
    margin: 5,
    borderColor: SUSSOL_ORANGE,
  },
  menuButtonText: {
    fontFamily: APP_FONT_FAMILY,
    fontSize: 17,
    color: DARKER_GREY,
  },
  menuButton: {
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'white',
    padding: 15,
    marginVertical: 12,
    marginHorizontal: 30,
    width: 240,
    height: 60,
    borderWidth: 1,
    borderRadius: 4,
    borderColor: DARK_GREY,
  },
  navButton: {
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'white',
    padding: 15,
    borderColor: DARK_GREY,
  },
  navBarText: {
    fontFamily: APP_FONT_FAMILY,
    fontSize: 10,
    color: GREY,
    alignSelf: 'flex-end',
    marginRight: 15,
  },
  navBarRightContainer: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'flex-end',
    justifyContent: 'flex-end',
    bottom: 6,
  },
  dataTableText: {
    fontFamily: APP_FONT_FAMILY,
    fontSize: 14,
    marginLeft: 20,
    textAlign: 'left',
  },
  dataTableDropDown: {
    marginHorizontal: 15,
  },
  dataTableHeader: {
    backgroundColor: 'white',
  },
  dataTableHeaderCell: {
    height: 40,
    borderRightWidth: 2,
    backgroundColor: 'white',
    borderColor: BLUE_WHITE,
  },
  dataTableRow: {
    backgroundColor: 'white',
  },
  dataTableCell: {
    height: 45,
    backgroundColor: ROW_BLUE,
    borderTopWidth: 2,
    borderRightWidth: 2,
    borderColor: BLUE_WHITE,
  },
  dataTableEditableCell: {
    backgroundColor: '#f9e4c2',
  },
  dataTableButton: {
    alignItems: 'center',
    justifyContent: 'center',
    height: 30,
    borderWidth: 1,
    borderRadius: 4,
    padding: 15,
    margin: 5,
    borderColor: SUSSOL_ORANGE,
  },
  finaliseButton: {
    color: FINALISE_GREEN,
    fontSize: 40,
  },
  finalisedLock: {
    color: FINALISED_RED,
    fontSize: 28,
    marginHorizontal: 8,
    bottom: 6,
  },
  toggleBar: {
    borderColor: SUSSOL_ORANGE,
    marginHorizontal: 5,
    borderRadius: 4,
  },
  toggleText: {
    fontFamily: APP_FONT_FAMILY,
    fontSize: 12,
    color: SUSSOL_ORANGE,
  },
  toggleTextSelected: {
    fontFamily: APP_FONT_FAMILY,
    fontSize: 12,
    color: 'white',
  },
  toggleOption: {
  },
  toggleOptionSelected: {
    backgroundColor: SUSSOL_ORANGE,
  },
});
<commit_msg>Increasing bottom page padding<commit_after>/* @flow weak */

/**
 * OfflineMobile Android
 * Sustainable Solutions (NZ) Ltd. 2016
 */

import {
  StyleSheet,
} from 'react-native';
export const APP_FONT_FAMILY = 'Museo_Slab_500';
export const SUSSOL_ORANGE = '#e95c30';
export const BLUE_WHITE = '#ecf3fc';
export const BACKGROUND_COLOR = '#f8fbfe';
export const SHADOW_BORDER = 'rgba(0, 0, 0, 0.1)';
export const DARK_GREY = '#4a4a4a';
export const DARKER_GREY = '#333333';
export const GREY = '#909192';
export const WARM_GREY = '#9b9b9b';
export const WARMER_GREY = '#a8aaac';
export const ROW_BLUE = 'rgba(73, 143, 226, 0.05)';
export const FINALISE_GREEN = '#219d1b';
export const FINALISED_RED = '#f63b30';
export const PAGE_CONTENT_PADDING_HORIZONTAL = 20;
export const PAGE_CONTENT_PADDING_TOP = 10;
export const PAGE_CONTENT_PADDING_BOTTOM = 20;

export default StyleSheet.create({
  appBackground: {
    flex: 1,
    backgroundColor: BACKGROUND_COLOR,
  },
  container: {
    flex: 1,
    borderWidth: 1,
    borderColor: SHADOW_BORDER,
    backgroundColor: BLUE_WHITE,
  },
  pageContentContainer: {
    flex: 1,
    paddingHorizontal: PAGE_CONTENT_PADDING_HORIZONTAL,
    paddingTop: PAGE_CONTENT_PADDING_TOP,
    paddingBottom: PAGE_CONTENT_PADDING_BOTTOM,
    backgroundColor: BACKGROUND_COLOR,
  },
  pageTopSectionContainer: {
    paddingTop: 20,
    paddingHorizontal: 10,
    paddingBottom: 15,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  horizontalContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  modal: {
    justifyContent: 'center',
    alignItems: 'center',
  },
  navBarOffset: {
    paddingTop: 68,
  },
  navBarStyle: {
    backgroundColor: BACKGROUND_COLOR,
    borderBottomWidth: 0,
    elevation: 0,
  },
  text: {
    fontFamily: APP_FONT_FAMILY,
    fontSize: 16,
  },
  buttonText: {
    fontFamily: APP_FONT_FAMILY,
    fontSize: 12,
    color: SUSSOL_ORANGE,
  },
  button: {
    alignItems: 'center',
    justifyContent: 'center',
    height: 45,
    width: 140,
    borderWidth: 1,
    borderRadius: 4,
    padding: 15,
    margin: 5,
    borderColor: SUSSOL_ORANGE,
  },
  menuButtonText: {
    fontFamily: APP_FONT_FAMILY,
    fontSize: 17,
    color: DARKER_GREY,
  },
  menuButton: {
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'white',
    padding: 15,
    marginVertical: 12,
    marginHorizontal: 30,
    width: 240,
    height: 60,
    borderWidth: 1,
    borderRadius: 4,
    borderColor: DARK_GREY,
  },
  navButton: {
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'white',
    padding: 15,
    borderColor: DARK_GREY,
  },
  navBarText: {
    fontFamily: APP_FONT_FAMILY,
    fontSize: 10,
    color: GREY,
    alignSelf: 'flex-end',
    marginRight: 15,
  },
  navBarRightContainer: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'flex-end',
    justifyContent: 'flex-end',
    bottom: 6,
  },
  dataTableText: {
    fontFamily: APP_FONT_FAMILY,
    fontSize: 14,
    marginLeft: 20,
    textAlign: 'left',
  },
  dataTableDropDown: {
    marginHorizontal: 15,
  },
  dataTableHeader: {
    backgroundColor: 'white',
  },
  dataTableHeaderCell: {
    height: 40,
    borderRightWidth: 2,
    backgroundColor: 'white',
    borderColor: BLUE_WHITE,
  },
  dataTableRow: {
    backgroundColor: 'white',
  },
  dataTableCell: {
    height: 45,
    backgroundColor: ROW_BLUE,
    borderTopWidth: 2,
    borderRightWidth: 2,
    borderColor: BLUE_WHITE,
  },
  dataTableEditableCell: {
    backgroundColor: '#f9e4c2',
  },
  dataTableButton: {
    alignItems: 'center',
    justifyContent: 'center',
    height: 30,
    borderWidth: 1,
    borderRadius: 4,
    padding: 15,
    margin: 5,
    borderColor: SUSSOL_ORANGE,
  },
  finaliseButton: {
    color: FINALISE_GREEN,
    fontSize: 40,
  },
  finalisedLock: {
    color: FINALISED_RED,
    fontSize: 28,
    marginHorizontal: 8,
    bottom: 6,
  },
  toggleBar: {
    borderColor: SUSSOL_ORANGE,
    marginHorizontal: 5,
    borderRadius: 4,
  },
  toggleText: {
    fontFamily: APP_FONT_FAMILY,
    fontSize: 12,
    color: SUSSOL_ORANGE,
  },
  toggleTextSelected: {
    fontFamily: APP_FONT_FAMILY,
    fontSize: 12,
    color: 'white',
  },
  toggleOption: {
  },
  toggleOptionSelected: {
    backgroundColor: SUSSOL_ORANGE,
  },
});
<|endoftext|>


<commit_before>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var inherits = require('util').inherits;

var OutResponse = require('../out_response');
var StreamingOutResponse = require('../streaming_out_response');

var CallFlags = require('./call_flags');

function V2OutResponse(handler, id, options) {
    var self = this;
    OutResponse.call(self, id, options);
    self.handler = handler;
}

inherits(V2OutResponse, OutResponse);

function V2StreamingOutResponse(handler, id, options) {
    var self = this;
    StreamingOutResponse.call(self, id, options);
    self.handler = handler;
}

inherits(V2StreamingOutResponse, StreamingOutResponse);

V2OutResponse.prototype._sendCallResponse =
V2StreamingOutResponse.prototype._sendCallResponse =
function _sendCallResponse(args, isLast) {
    var self = this;
    var flags = 0;
    if (!isLast) flags |= CallFlags.Fragment;
    self.handler.sendCallResponseFrame(self, flags, args);
};

V2OutResponse.prototype._sendCallResponseCont =
V2StreamingOutResponse.prototype._sendCallResponseCont =
function _sendCallResponseCont(args, isLast) {
    var self = this;
    var flags = 0;
    if (!isLast) flags |= CallFlags.Fragment;
    self.handler.sendCallResponseContFrame(self, flags, args);
};

V2OutResponse.prototype._sendError =
V2StreamingOutResponse.prototype._sendError =
function _sendError(codeString, message) {
    var self = this;
    self.handler.sendErrorFrame(self, codeString, message);
};

module.exports.OutResponse = V2OutResponse;
module.exports.StreamingOutResponse = V2StreamingOutResponse;
<commit_msg>max length limit for arg1 in call response<commit_after>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var inherits = require('util').inherits;

var OutResponse = require('../out_response');
var StreamingOutResponse = require('../streaming_out_response');

var CallFlags = require('./call_flags');
var v2 = require('./index');
var errors = require('../errors');

function V2OutResponse(handler, id, options) {
    var self = this;
    OutResponse.call(self, id, options);
    self.handler = handler;
}

inherits(V2OutResponse, OutResponse);

function V2StreamingOutResponse(handler, id, options) {
    var self = this;
    StreamingOutResponse.call(self, id, options);
    self.handler = handler;
}

inherits(V2StreamingOutResponse, StreamingOutResponse);

V2OutResponse.prototype._sendCallResponse =
V2StreamingOutResponse.prototype._sendCallResponse =
function _sendCallResponse(args, isLast) {
    var self = this;
    var flags = 0;
    if (args && args[0] && args[0].length > v2.Frame.MaxArg1Size) {
        self.errorEvent.emit(self, errors.Arg1OverLengthLimit({
                length: '0x' + args[0].length.toString(16)
        }));
    }
    if (!isLast) flags |= CallFlags.Fragment;
    self.handler.sendCallResponseFrame(self, flags, args);
};

V2OutResponse.prototype._sendCallResponseCont =
V2StreamingOutResponse.prototype._sendCallResponseCont =
function _sendCallResponseCont(args, isLast) {
    var self = this;
    var flags = 0;
    if (!isLast) flags |= CallFlags.Fragment;
    self.handler.sendCallResponseContFrame(self, flags, args);
};

V2OutResponse.prototype._sendError =
V2StreamingOutResponse.prototype._sendError =
function _sendError(codeString, message) {
    var self = this;
    self.handler.sendErrorFrame(self, codeString, message);
};

module.exports.OutResponse = V2OutResponse;
module.exports.StreamingOutResponse = V2StreamingOutResponse;
<|endoftext|>


<commit_before>/**
 * Jenkins JS Modules common utility functions
 */

// Get the modules

var jquery = require('jquery-detached');
var wh = require('window-handle');

var debug = false;

// gets the base Jenkins URL including context path
exports.baseUrl = function() {
	var $ = jquery.getJQuery();
	var u = $('head').attr('data-rooturl');
	if(!u) {
		u = '';
	}
	return u;
};

// awful hack to get around JSONifying things with Prototype taking over wrong. ugh. Prototype is the worst.
exports.stringify = function(o) {
	if(Array.prototype.toJSON) { // Prototype f's this up something bad
		var protoJSON = {
			a: Array.prototype.toJSON,
			o: Object.prototype.toJSON,
			h: Hash.prototype.toJSON,
			s: String.prototype.toJSON
		};
		try {
			delete Array.prototype.toJSON;
		delete Object.prototype.toJSON;
			delete Hash.prototype.toJSON;
			delete String.prototype.toJSON;

		return JSON.stringify(o);
		}
		finally {
		if(protoJSON.a) {
			Array.prototype.toJSON = protoJSON.a;
		}
		if(protoJSON.o) {
			Object.prototype.toJSON = protoJSON.o;
		}
		if(protoJSON.h) {
			Hash.prototype.toJSON = protoJSON.h;
		}
		if(protoJSON.s) {
			String.prototype.toJSON = protoJSON.s;
		}
		}
	}
	else {
		return JSON.stringify(o);
	}
};

/**
 * Take a string and replace non-id characters to make it a friendly-ish XML id
 */
exports.idIfy = function(str) {
	return (''+str).replace(/\W+/g, '_');
};

/**
 * redirect
 */
exports.goTo = function(url) {
	wh.getWindow().location.replace(exports.baseUrl() + url);
};

/**
 * Jenkins AJAX GET callback.
 * If last parameter is an object, will be extended to jQuery options (e.g. pass { error: function() ... } to handle errors)
 */
exports.get = function(url, success, options) {
	if(debug) {
		console.log('get: ' + url);
	}
	var $ = jquery.getJQuery();
	var args = {
		url: exports.baseUrl() + url,
		type: 'GET',
		cache: false,
		dataType: 'json',
		success: success
	};
	if(options instanceof Object) {
		$.extend(args, options);
	}
	$.ajax(args);
};

/**
 * Jenkins AJAX POST callback, formats data as a JSON object post (note: works around prototype.js ugliness using stringify() above)
 * If last parameter is an object, will be extended to jQuery options (e.g. pass { error: function() ... } to handle errors)
 */
exports.post = function(url, data, success, options) {
	if(debug) {
		console.log('post: ' + url);
	}

	var $ = jquery.getJQuery();

	// handle crumbs
	var headers = {};
	var wnd = wh.getWindow();
	var crumb;
	if('crumb' in options) {
		crumb = options.crumb;
	}
	else if('crumb' in wnd) {
		crumb = wnd.crumb;
	}

	if(crumb) {
		headers[crumb.fieldName] = crumb.value;
	}

	var formBody = data;
	if(formBody instanceof Object) {
		if(crumb) {
			formBody = $.extend({}, formBody);
			formBody[crumb.fieldName] = crumb.value;
		}
		formBody = exports.stringify(formBody);
	}

	var args = {
		url: exports.baseUrl() + url,
		type: 'POST',
		cache: false,
		dataType: 'json',
		data: formBody,
		contentType: "application/json",
		success: success,
		headers: headers
	};
	if(options instanceof Object) {
		$.extend(args, options);
	}
	$.ajax(args);
};

/**
 *  handlebars setup, this does not seem to actually work or get called by the require() of this file, so have to explicitly call it
 */
exports.initHandlebars = function() {
	var Handlebars = require('handlebars');

	Handlebars.registerHelper('ifeq', function(o1, o2, options) {
		if(o1 === o2) {
			return options.fn();
		}
	});

	Handlebars.registerHelper('ifneq', function(o1, o2, options) {
		if(o1 !== o2) {
			return options.fn();
		}
	});

	Handlebars.registerHelper('in-array', function(arr, val, options) {
		if(arr.indexOf(val) >= 0) {
			return options.fn();
		}
	});

	Handlebars.registerHelper('id', exports.idIfy);

	Handlebars.registerHelper('replace', function() {
		var val = arguments[0];
		// second, through second to last - options is last
		for (var i = 1; i < arguments.length - 1; i++) {
			val = val.replace('{' + (i-1) + '}', arguments[i]);
		}
		return val;
	});

	return Handlebars;
};

/**
 * Load translations for the given bundle ID, provide the message object to the handler.
 * Optional error handler as the last argument.
 */
exports.loadTranslations = function(bundleName, handler, onError) {
	exports.get('/i18n/resourceBundle?baseName='  +bundleName, function(res) {
		if(res.status !== 'ok') {
			if(onError) {
				onError(res.message);
			}
			throw 'Unable to load localization data: ' + res.message;
		}

		var translations = res.data;

		/* globals Proxy: true */
		if('undefined' !== typeof Proxy) {
			translations = new Proxy(translations, {
				get: function(target, property) {
					if(property in target) {
						return target[property];
					}
					if(debug) {
						console.log('"' + property + '" not found in translation bundle.');
					}
					return property;
				}
			});
		}

		handler(translations);
	});
};

/**
 * Runs a connectivity test, calls handler with a boolean whether there is sufficient connectivity to the internet
 */
exports.testConnectivity = function(siteId, handler) {
	// check the connectivity api
	var testConnectivity = function() {
		exports.get('/updateCenter/connectionStatus?siteId=' + siteId, function(response) {
			if(response.status !== 'ok') {
				handler(false, true, response.message);
			}

			// Define statuses, which need additional check iteration via async job on the Jenkins master
			// Statuses like "OK" or "SKIPPED" are considered as fine.
			var uncheckedStatuses = ['PRECHECK', 'CHECKING', 'UNCHECKED'];
			if(uncheckedStatuses.indexOf(response.data.updatesite) >= 0  || uncheckedStatuses.indexOf(response.data.internet) >= 0) {
				setTimeout(testConnectivity, 100);
			}
			else {
				// Update site should be always reachable, but we do not require the internet connection
				// if it's explicitly skipped by the update center
				if(response.status !== 'ok' || response.data.updatesite !== 'OK' ||
							(response.data.internet !== 'OK' && response.data.internet !== 'SKIPPED')) {
					// no connectivity, but not fatal
					handler(false, false);
				}
				else {
					handler(true);
				}
			}
		});
	};
	testConnectivity();
};

/**
 * gets the window containing a form, taking in to account top-level iframes
 */
exports.getWindow = function($form) {
	var $ = jquery.getJQuery();
	$form = $($form);
	var wnd = wh.getWindow();
	$(top.document).find('iframe').each(function() {
		var windowFrame = this.contentWindow;
		var $f = $(this).contents().find('form');
		$f.each(function() {
			if($form[0] === this) {
				wnd = windowFrame;
			}
		});
	});
	return wnd;
};

/**
 * Builds a stapler form post
 */
exports.buildFormPost = function($form) {
	var $ = jquery.getJQuery();
	$form = $($form);
	var wnd = exports.getWindow($form);
	var form = $form[0];
	if(wnd.buildFormTree(form)) {
		return $form.serialize() +
			'&core:apply=&Submit=Save&json=' + $form.find('input[name=json]').val();
	}
	return '';
};

/**
 * Gets the crumb, if crumbs are enabled
 */
exports.getFormCrumb = function($form) {
	var $ = jquery.getJQuery();
	$form = $($form);
	var wnd = exports.getWindow($form);
	return wnd.crumb;
};

/**
 * Jenkins Stapler JSON POST callback
 * If last parameter is an object, will be extended to jQuery options (e.g. pass { error: function() ... } to handle errors)
 */
exports.staplerPost = function(url, $form, success, options) {
	var $ = jquery.getJQuery();
	$form = $($form);
	var postBody = exports.buildFormPost($form);
	var crumb = exports.getFormCrumb($form);
	exports.post(
		url,
		postBody,
		success, $.extend({
			processData: false,
			contentType: 'application/x-www-form-urlencoded',
			crumb: crumb
		}, options));
};
<commit_msg>[JENKINS-39741] - Redirect to login page after authorisation error when checking connectivity to update center and handle any other error.<commit_after>/**
 * Jenkins JS Modules common utility functions
 */

// Get the modules

var jquery = require('jquery-detached');
var wh = require('window-handle');

var debug = false;

// gets the base Jenkins URL including context path
exports.baseUrl = function() {
	var $ = jquery.getJQuery();
	var u = $('head').attr('data-rooturl');
	if(!u) {
		u = '';
	}
	return u;
};

// awful hack to get around JSONifying things with Prototype taking over wrong. ugh. Prototype is the worst.
exports.stringify = function(o) {
	if(Array.prototype.toJSON) { // Prototype f's this up something bad
		var protoJSON = {
			a: Array.prototype.toJSON,
			o: Object.prototype.toJSON,
			h: Hash.prototype.toJSON,
			s: String.prototype.toJSON
		};
		try {
			delete Array.prototype.toJSON;
		delete Object.prototype.toJSON;
			delete Hash.prototype.toJSON;
			delete String.prototype.toJSON;

		return JSON.stringify(o);
		}
		finally {
		if(protoJSON.a) {
			Array.prototype.toJSON = protoJSON.a;
		}
		if(protoJSON.o) {
			Object.prototype.toJSON = protoJSON.o;
		}
		if(protoJSON.h) {
			Hash.prototype.toJSON = protoJSON.h;
		}
		if(protoJSON.s) {
			String.prototype.toJSON = protoJSON.s;
		}
		}
	}
	else {
		return JSON.stringify(o);
	}
};

/**
 * Take a string and replace non-id characters to make it a friendly-ish XML id
 */
exports.idIfy = function(str) {
	return (''+str).replace(/\W+/g, '_');
};

/**
 * redirect
 */
exports.goTo = function(url) {
	wh.getWindow().location.replace(exports.baseUrl() + url);
};

/**
 * Jenkins AJAX GET callback.
 * If last parameter is an object, will be extended to jQuery options (e.g. pass { error: function() ... } to handle errors)
 */
exports.get = function(url, success, options) {
	if(debug) {
		console.log('get: ' + url);
	}
	var $ = jquery.getJQuery();
	var args = {
		url: exports.baseUrl() + url,
		type: 'GET',
		cache: false,
		dataType: 'json',
		success: success
	};
	if(options instanceof Object) {
		$.extend(args, options);
	}
	$.ajax(args);
};

/**
 * Jenkins AJAX POST callback, formats data as a JSON object post (note: works around prototype.js ugliness using stringify() above)
 * If last parameter is an object, will be extended to jQuery options (e.g. pass { error: function() ... } to handle errors)
 */
exports.post = function(url, data, success, options) {
	if(debug) {
		console.log('post: ' + url);
	}

	var $ = jquery.getJQuery();

	// handle crumbs
	var headers = {};
	var wnd = wh.getWindow();
	var crumb;
	if('crumb' in options) {
		crumb = options.crumb;
	}
	else if('crumb' in wnd) {
		crumb = wnd.crumb;
	}

	if(crumb) {
		headers[crumb.fieldName] = crumb.value;
	}

	var formBody = data;
	if(formBody instanceof Object) {
		if(crumb) {
			formBody = $.extend({}, formBody);
			formBody[crumb.fieldName] = crumb.value;
		}
		formBody = exports.stringify(formBody);
	}

	var args = {
		url: exports.baseUrl() + url,
		type: 'POST',
		cache: false,
		dataType: 'json',
		data: formBody,
		contentType: "application/json",
		success: success,
		headers: headers
	};
	if(options instanceof Object) {
		$.extend(args, options);
	}
	$.ajax(args);
};

/**
 *  handlebars setup, this does not seem to actually work or get called by the require() of this file, so have to explicitly call it
 */
exports.initHandlebars = function() {
	var Handlebars = require('handlebars');

	Handlebars.registerHelper('ifeq', function(o1, o2, options) {
		if(o1 === o2) {
			return options.fn();
		}
	});

	Handlebars.registerHelper('ifneq', function(o1, o2, options) {
		if(o1 !== o2) {
			return options.fn();
		}
	});

	Handlebars.registerHelper('in-array', function(arr, val, options) {
		if(arr.indexOf(val) >= 0) {
			return options.fn();
		}
	});

	Handlebars.registerHelper('id', exports.idIfy);

	Handlebars.registerHelper('replace', function() {
		var val = arguments[0];
		// second, through second to last - options is last
		for (var i = 1; i < arguments.length - 1; i++) {
			val = val.replace('{' + (i-1) + '}', arguments[i]);
		}
		return val;
	});

	return Handlebars;
};

/**
 * Load translations for the given bundle ID, provide the message object to the handler.
 * Optional error handler as the last argument.
 */
exports.loadTranslations = function(bundleName, handler, onError) {
	exports.get('/i18n/resourceBundle?baseName='  +bundleName, function(res) {
		if(res.status !== 'ok') {
			if(onError) {
				onError(res.message);
			}
			throw 'Unable to load localization data: ' + res.message;
		}

		var translations = res.data;

		/* globals Proxy: true */
		if('undefined' !== typeof Proxy) {
			translations = new Proxy(translations, {
				get: function(target, property) {
					if(property in target) {
						return target[property];
					}
					if(debug) {
						console.log('"' + property + '" not found in translation bundle.');
					}
					return property;
				}
			});
		}

		handler(translations);
	});
};

/**
 * Runs a connectivity test, calls handler with a boolean whether there is sufficient connectivity to the internet
 */
exports.testConnectivity = function(siteId, handler) {
	// check the connectivity api
	var testConnectivity = function() {
		exports.get('/updateCenter/connectionStatus?siteId=' + siteId, function(response) {
			if(response.status !== 'ok') {
				handler(false, true, response.message);
			}

			// Define statuses, which need additional check iteration via async job on the Jenkins master
			// Statuses like "OK" or "SKIPPED" are considered as fine.
			var uncheckedStatuses = ['PRECHECK', 'CHECKING', 'UNCHECKED'];
			if(uncheckedStatuses.indexOf(response.data.updatesite) >= 0  || uncheckedStatuses.indexOf(response.data.internet) >= 0) {
				setTimeout(testConnectivity, 100);
			}
			else {
				// Update site should be always reachable, but we do not require the internet connection
				// if it's explicitly skipped by the update center
				if(response.status !== 'ok' || response.data.updatesite !== 'OK' ||
							(response.data.internet !== 'OK' && response.data.internet !== 'SKIPPED')) {
					// no connectivity, but not fatal
					handler(false, false);
				}
				else {
					handler(true);
				}
			}
		}, { error: function(xhr, textStatus, errorThrown) {
                 if (xhr.status === 403) {
                     exports.goTo('/login');
                 } else {
                     handler.call({ isError: true, errorMessage: errorThrown });
                 }
               }
             });
	};
	testConnectivity();
};

/**
 * gets the window containing a form, taking in to account top-level iframes
 */
exports.getWindow = function($form) {
	var $ = jquery.getJQuery();
	$form = $($form);
	var wnd = wh.getWindow();
	$(top.document).find('iframe').each(function() {
		var windowFrame = this.contentWindow;
		var $f = $(this).contents().find('form');
		$f.each(function() {
			if($form[0] === this) {
				wnd = windowFrame;
			}
		});
	});
	return wnd;
};

/**
 * Builds a stapler form post
 */
exports.buildFormPost = function($form) {
	var $ = jquery.getJQuery();
	$form = $($form);
	var wnd = exports.getWindow($form);
	var form = $form[0];
	if(wnd.buildFormTree(form)) {
		return $form.serialize() +
			'&core:apply=&Submit=Save&json=' + $form.find('input[name=json]').val();
	}
	return '';
};

/**
 * Gets the crumb, if crumbs are enabled
 */
exports.getFormCrumb = function($form) {
	var $ = jquery.getJQuery();
	$form = $($form);
	var wnd = exports.getWindow($form);
	return wnd.crumb;
};

/**
 * Jenkins Stapler JSON POST callback
 * If last parameter is an object, will be extended to jQuery options (e.g. pass { error: function() ... } to handle errors)
 */
exports.staplerPost = function(url, $form, success, options) {
	var $ = jquery.getJQuery();
	$form = $($form);
	var postBody = exports.buildFormPost($form);
	var crumb = exports.getFormCrumb($form);
	exports.post(
		url,
		postBody,
		success, $.extend({
			processData: false,
			contentType: 'application/x-www-form-urlencoded',
			crumb: crumb
		}, options));
};
<|endoftext|>


<commit_before>(function () {
  var VisualizationProvider = function () {
    this.visualizations = {};
    this.visualizationTypes = {};
    var defaultConfig = {
      defaultOptions: {},
      skipTypes: false,
      editorTemplate: null
    }

    this.registerVisualization = function (config) {
      var visualization = _.extend({}, defaultConfig, config);

      // TODO: this is prone to errors; better refactor.
      if (_.isEmpty(this.visualizations)) {
        this.defaultVisualization = visualization;
      }

      this.visualizations[config.type] = visualization;

      if (!config.skipTypes) {
        this.visualizationTypes[config.name] = config.type;
      }
      ;
    };

    this.getSwitchTemplate = function (property) {
      var pattern = /(<[a-zA-Z0-9-]*?)( |>)/

      var mergedTemplates = _.reduce(this.visualizations, function (templates, visualization) {
        if (visualization[property]) {
          var ngSwitch = '$1 ng-switch-when="' + visualization.type + '" $2';
          var template = visualization[property].replace(pattern, ngSwitch);

          return templates + "\n" + template;
        }

        return templates;
      }, "");

      mergedTemplates = '
' + mergedTemplates + "
";

      return mergedTemplates;
    }

    this.$get = ['$resource', function ($resource) {
      var Visualization = $resource('/api/visualizations/:id', {id: '@id'});
      Visualization.visualizations = this.visualizations;
      Visualization.visualizationTypes = this.visualizationTypes;
      Visualization.renderVisualizationsTemplate = this.getSwitchTemplate('renderTemplate');
      Visualization.editorTemplate = this.getSwitchTemplate('editorTemplate');
      Visualization.defaultVisualization = this.defaultVisualization;

      return Visualization;
    }];
  };

  var VisualizationRenderer = function ($location, Visualization) {
    return {
      restrict: 'E',
      scope: {
        visualization: '=',
        queryResult: '='
      },
      // TODO: using switch here (and in the options editor) might introduce errors and bad
      // performance wise. It's better to eventually show the correct template based on the
      // visualization type and not make the browser render all of them.
      template: '<filters></filters>\n' + Visualization.renderVisualizationsTemplate,
      replace: false,
      link: function (scope) {

        scope.select2Options = {
          width: '50%'
        };

        function readURL() {
          var searchFilters = angular.fromJson($location.search().filters);
          if (searchFilters) {
            _.forEach(scope.filters, function(filter) {
              var value = searchFilters[filter.friendlyName];
              if (value) {
                filter.current = value;
              }
            });
          }
        }

        function updateURL(filters) {
          var current = {};
          _.each(filters, function(filter) {
            if (filter.current) {
              current[filter.friendlyName] = filter.current;
            }
          });

          var newSearch = angular.extend($location.search(), {
            filters: angular.toJson(current)
          });
          $location.search(newSearch);
        }

        scope.$watch('queryResult && queryResult.getFilters()', function (filters) {
          if (filters) {
            scope.filters = filters;

            if (filters.length) {
              readURL();

              // start watching for changes and update URL
              scope.$watch('filters', updateURL, true);
            }
          }
        });
      }
    }
  };

  var VisualizationOptionsEditor = function (Visualization) {
    return {
      restrict: 'E',
      template: Visualization.editorTemplate,
      replace: false
    }
  };

  var Filters = function () {
    return {
      restrict: 'E',
      templateUrl: '/views/visualizations/filters.html'
    }
  }

  var EditVisualizationForm = function (Events, Visualization, growl) {
    return {
      restrict: 'E',
      templateUrl: '/views/visualizations/edit_visualization.html',
      replace: true,
      scope: {
        query: '=',
        queryResult: '=',
        visualization: '=?',
        openEditor: '=?',
        onNewSuccess: '=?'
      },
      link: function (scope, element, attrs) {
        scope.editRawOptions = currentUser.hasPermission('edit_raw_chart');
        scope.visTypes = Visualization.visualizationTypes;

        scope.newVisualization = function () {
          return {
            'type': Visualization.defaultVisualization.type,
            'name': Visualization.defaultVisualization.name,
            'description': '',
            'options': Visualization.defaultVisualization.defaultOptions
          };
        }

        if (!scope.visualization) {
          var unwatch = scope.$watch('query.id', function (queryId) {
            if (queryId) {
              unwatch();

              scope.visualization = scope.newVisualization();
            }
          });
        }

        scope.$watch('visualization.type', function (type, oldType) {
          // if not edited by user, set name to match type
          if (type && oldType != type && scope.visualization && !scope.visForm.name.$dirty) {
            // poor man's titlecase
            scope.visualization.name = scope.visualization.type[0] + scope.visualization.type.slice(1).toLowerCase();
          }
        });

        scope.submit = function () {
          if (scope.visualization.id) {
            Events.record(currentUser, "update", "visualization", scope.visualization.id, {'type': scope.visualization.type});
          } else {
            Events.record(currentUser, "create", "visualization", null, {'type': scope.visualization.type});
          }

          scope.visualization.query_id = scope.query.id;

          Visualization.save(scope.visualization, function success(result) {
            growl.addSuccessMessage("Visualization saved");

            scope.visualization = scope.newVisualization(scope.query);

            var visIds = _.pluck(scope.query.visualizations, 'id');
            var index = visIds.indexOf(result.id);
            if (index > -1) {
              scope.query.visualizations[index] = result;
            } else {
              // new visualization
              scope.query.visualizations.push(result);
              scope.onNewSuccess && scope.onNewSuccess(result);
            }
          }, function error() {
            growl.addErrorMessage("Visualization could not be saved");
          });
        };
      }
    }
  };

  angular.module('redash.visualization', [])
      .provider('Visualization', VisualizationProvider)
      .directive('visualizationRenderer', ['$location', 'Visualization', VisualizationRenderer])
      .directive('visualizationOptionsEditor', ['Visualization', VisualizationOptionsEditor])
      .directive('filters', Filters)
      .directive('editVisulatizationForm', ['Events', 'Visualization', 'growl', EditVisualizationForm])
})();
<commit_msg>Disable filters url syncing<commit_after>(function () {
  var VisualizationProvider = function () {
    this.visualizations = {};
    this.visualizationTypes = {};
    var defaultConfig = {
      defaultOptions: {},
      skipTypes: false,
      editorTemplate: null
    }

    this.registerVisualization = function (config) {
      var visualization = _.extend({}, defaultConfig, config);

      // TODO: this is prone to errors; better refactor.
      if (_.isEmpty(this.visualizations)) {
        this.defaultVisualization = visualization;
      }

      this.visualizations[config.type] = visualization;

      if (!config.skipTypes) {
        this.visualizationTypes[config.name] = config.type;
      }
      ;
    };

    this.getSwitchTemplate = function (property) {
      var pattern = /(<[a-zA-Z0-9-]*?)( |>)/

      var mergedTemplates = _.reduce(this.visualizations, function (templates, visualization) {
        if (visualization[property]) {
          var ngSwitch = '$1 ng-switch-when="' + visualization.type + '" $2';
          var template = visualization[property].replace(pattern, ngSwitch);

          return templates + "\n" + template;
        }

        return templates;
      }, "");

      mergedTemplates = '
' + mergedTemplates + "
";

      return mergedTemplates;
    }

    this.$get = ['$resource', function ($resource) {
      var Visualization = $resource('/api/visualizations/:id', {id: '@id'});
      Visualization.visualizations = this.visualizations;
      Visualization.visualizationTypes = this.visualizationTypes;
      Visualization.renderVisualizationsTemplate = this.getSwitchTemplate('renderTemplate');
      Visualization.editorTemplate = this.getSwitchTemplate('editorTemplate');
      Visualization.defaultVisualization = this.defaultVisualization;

      return Visualization;
    }];
  };

  var VisualizationRenderer = function ($location, Visualization) {
    return {
      restrict: 'E',
      scope: {
        visualization: '=',
        queryResult: '='
      },
      // TODO: using switch here (and in the options editor) might introduce errors and bad
      // performance wise. It's better to eventually show the correct template based on the
      // visualization type and not make the browser render all of them.
      template: '<filters></filters>\n' + Visualization.renderVisualizationsTemplate,
      replace: false,
      link: function (scope) {
        scope.select2Options = {
          width: '50%'
        };

        function readURL() {
          var searchFilters = angular.fromJson($location.search().filters);
          if (searchFilters) {
            _.forEach(scope.filters, function(filter) {
              var value = searchFilters[filter.friendlyName];
              if (value) {
                filter.current = value;
              }
            });
          }
        }

        function updateURL(filters) {
          var current = {};
          _.each(filters, function(filter) {
            if (filter.current) {
              current[filter.friendlyName] = filter.current;
            }
          });

          var newSearch = angular.extend($location.search(), {
            filters: angular.toJson(current)
          });
          $location.search(newSearch);
        }

        scope.$watch('queryResult && queryResult.getFilters()', function (filters) {
          if (filters) {
            scope.filters = filters;

            if (filters.length && false) {
              readURL();

              // start watching for changes and update URL
              scope.$watch('filters', updateURL, true);
            }
          }
        });
      }
    }
  };

  var VisualizationOptionsEditor = function (Visualization) {
    return {
      restrict: 'E',
      template: Visualization.editorTemplate,
      replace: false
    }
  };

  var Filters = function () {
    return {
      restrict: 'E',
      templateUrl: '/views/visualizations/filters.html'
    }
  }

  var EditVisualizationForm = function (Events, Visualization, growl) {
    return {
      restrict: 'E',
      templateUrl: '/views/visualizations/edit_visualization.html',
      replace: true,
      scope: {
        query: '=',
        queryResult: '=',
        visualization: '=?',
        openEditor: '=?',
        onNewSuccess: '=?'
      },
      link: function (scope, element, attrs) {
        scope.editRawOptions = currentUser.hasPermission('edit_raw_chart');
        scope.visTypes = Visualization.visualizationTypes;

        scope.newVisualization = function () {
          return {
            'type': Visualization.defaultVisualization.type,
            'name': Visualization.defaultVisualization.name,
            'description': '',
            'options': Visualization.defaultVisualization.defaultOptions
          };
        }

        if (!scope.visualization) {
          var unwatch = scope.$watch('query.id', function (queryId) {
            if (queryId) {
              unwatch();

              scope.visualization = scope.newVisualization();
            }
          });
        }

        scope.$watch('visualization.type', function (type, oldType) {
          // if not edited by user, set name to match type
          if (type && oldType != type && scope.visualization && !scope.visForm.name.$dirty) {
            // poor man's titlecase
            scope.visualization.name = scope.visualization.type[0] + scope.visualization.type.slice(1).toLowerCase();
          }
        });

        scope.submit = function () {
          if (scope.visualization.id) {
            Events.record(currentUser, "update", "visualization", scope.visualization.id, {'type': scope.visualization.type});
          } else {
            Events.record(currentUser, "create", "visualization", null, {'type': scope.visualization.type});
          }

          scope.visualization.query_id = scope.query.id;

          Visualization.save(scope.visualization, function success(result) {
            growl.addSuccessMessage("Visualization saved");

            scope.visualization = scope.newVisualization(scope.query);

            var visIds = _.pluck(scope.query.visualizations, 'id');
            var index = visIds.indexOf(result.id);
            if (index > -1) {
              scope.query.visualizations[index] = result;
            } else {
              // new visualization
              scope.query.visualizations.push(result);
              scope.onNewSuccess && scope.onNewSuccess(result);
            }
          }, function error() {
            growl.addErrorMessage("Visualization could not be saved");
          });
        };
      }
    }
  };

  angular.module('redash.visualization', [])
      .provider('Visualization', VisualizationProvider)
      .directive('visualizationRenderer', ['$location', 'Visualization', VisualizationRenderer])
      .directive('visualizationOptionsEditor', ['Visualization', VisualizationOptionsEditor])
      .directive('filters', Filters)
      .directive('editVisulatizationForm', ['Events', 'Visualization', 'growl', EditVisualizationForm])
})();
<|endoftext|>