<commit_before>//= require "codemirror"
//= require "mobileCodeMirror"
//= require "library"
//= require "unsaved"
//= require "panel"
//= require "../render/live"
//= require "../render/console"
//= require "keycontrol"

var panels = {};

panels.getVisible = function () {
  var panels = this.panels,
      visible = [];
  for (var panel in panels) {
    if (panels[panel].visible) visible.push(panels[panel]);
  }
  return visible;
};

panels.save = function () {
  var visible = this.getVisible(),
      state = {},
      panel;

  for (var i = 0; i < visible.length; i++) {
    panel = visible[i];
    state[panel.name] = panel.$el.css('left');
  }

  localStorage.setItem('jsbin.panels', JSON.stringify(state));
}

panels.restore = function () {
  // if there are panel names on the hash (v2 of jsbin) or in the jquery (v3)
  // then restore those specific panels and evenly distribute them.
  var open = [],
      location = window.location,
      search = location.search.substring(1),
      hash = location.hash.substring(1),
      toopen = search || hash ? (search || hash).split(',') : [],
      state = JSON.parse(localStorage.getItem('jsbin.panels') || '{}'),
      name = '',
      i = 0,
      panel = null,
      init = [],
      panelURLValue = '',
      openWithSameDimensions = false,
      width = window.innerWidth,
      deferredCodeInsert = '';

  // otherwise restore the user's regular settings
  // also set a flag indicating whether or not we should save the panel settings
  // this is based on whether they're on jsbin.com or if they're on an existing
  // bin. Also, if they hit save - *always* save their layout.
  if (location.pathname && location.pathname !== '/') {
    panels.saveOnExit = false;
  } else {
    panels.saveOnExit = true;
  }

  // TODO decide whether the above code I'm trying too hard.

  /* Boot code */
  // then allow them to view specific panels based on comma separated hash fragment
  if (toopen.length) {
    for (name in state) {
      if (toopen.indexOf(name) !== -1) {
        i++;
      }
    }

    if (i === toopen.length) openWithSameDimensions = true;

    for (i = 0; i < toopen.length; i++) {
      panelURLValue = '';
      name = toopen[i];

      // if name contains an `=` it means we also need to set that particular panel to that code
      if (name.indexOf('=') !== -1) {
        panelURLValue = name.substring(name.indexOf('=') + 1);
        name = name.substring(0, name.indexOf('='));
      }

      if (panels.panels[name]) {
        panel = panels.panels[name];
        // console.log(name, 'width', state[name], width * parseFloat(state[name]) / 100);
        if (panel.editor && panelURLValue) {
          panel.setCode(decodeURIComponent(panelURLValue));
        }

        if (openWithSameDimensions) {
          panel.show(width * parseFloat(state[name]) / 100);
        } else {
          panel.show();
        }
        init.push(panel);
      } else if (name === 'code' && panelURLValue) { // TODO support any varible insertion
        (function (panelURLValue) {
          var todo = ['html', 'javascript', 'css'];

          var deferredInsert = function (event, data) {
            var code, parts, panel = panels.panels[data.panelId] || {};

            console.log(data.panelId && panel.editor && panel.ready, data.panelId, panel.editor, panel.ready);
            if (data.panelId && panel.editor && panel.ready === true) {
              todo.splice(todo.indexOf(data.panelId), 1);
              try {
                code = panel.getCode();
              } catch (e) {
                console.error(e);
              }
              console.log('ok', code.indexOf('%code%'), code);
              if (code.indexOf('%code%') !== -1) {
                parts = code.split('%code%');
                code = parts[0] + decodeURIComponent(panelURLValue) + parts[1];
                panel.setCode(code);
                $document.unbind('codeChange', deferredInsert);
                console.log('deferred code inserted');
              }
            }

            if (todo.length === 0) {
              console.log('unbinding');
              $document.unbind('codeChange', deferredInsert);
              console.log('giving up - no insertion point');
            }
          };

          $document.bind('codeChange', deferredInsert);
        }(panelURLValue));
      }
    }

    // support the old jsbin v1 links directly to the preview
    if (toopen.length === 1 && toopen[0] === 'preview') {
      panels.panels.live.show();
    }

    if (!openWithSameDimensions) this.distribute();
  } else {
    for (name in state) {
      panels.panels[name].show(width * parseFloat(state[name]) / 100);
    }
  }

  // now restore any data from sessionStorage
  // TODO add default templates somewhere
  // var template = {};
  // for (name in this.panels) {
  //   panel = this.panels[name];
  //   if (panel.editor) {
  //     // panel.setCode(sessionStorage.getItem('jsbin.content.' + name) || template[name]);
  //   }
  // }

  for (i = 0; i < init.length; i++) {
    init[i].init();
  }

  if (panels.getVisible().length) $body.addClass('panelsVisible');

};

panels.savecontent = function () {
  // loop through each panel saving it's content to sessionStorage
  var name, panel;
  for (name in this.panels) {
    panel = this.panels[name];
    if (panel.editor) sessionStorage.setItem('jsbin.content.' + name, panel.getCode());
  }
};

panels.focus = function (panel) {
  this.focused = panel;
  if (panel) {
    $('.panel').removeClass('focus').filter('.' + panel.id).addClass('focus');
  }
}

// evenly distribute the width of all the visible panels
panels.distribute = function () {
  var visible = $('#source .panelwrapper:visible'),
      width = 100,
      height = 0,
      innerW = window.innerWidth - (visible.length - 1), // to compensate for border-left
      innerH = $('#source').outerHeight(),
      left = 0,
      right = 0,
      top = 0,
      panel,
      nestedPanels = [];

  if (visible.length) {
    $body.addClass('panelsVisible');

    // visible = visible.sort(function (a, b) {
    //   return a.order < b.order ? -1 : 1;
    // });

    width = 100 / visible.length;
    for (var i = 0; i < visible.length; i++) {
      panel = $.data(visible[i], 'panel');
      right = 100 - (width * (i+1));
      panel.$el.css({ top: 0, bottom: 0, left: left + '%', right: right + '%' });
      panel.splitter.trigger('init', innerW * left/100);
      panel.splitter[i == 0 ? 'hide' : 'show']();
      left += width;

      nestedPanels = $(visible[i]).find('.panel');
      if (nestedPanels.length > 1) {
        top = 0;
        nestedPanels = nestedPanels.filter(':visible');
        height = 100 / nestedPanels.length;
        nestedPanels.each(function (i) {
          bottom = 100 - (height * (i+1));
          var panel = jsbin.panels.panels[$.data(this, 'name')];
          // $(this).css({ top: top + '%', bottom: bottom + '%' });
          $(this).css('top', top + '%');
          $(this).css('bottom', bottom + '%' );
          if (panel.splitter.hasClass('vertical')) {
            panel.splitter.trigger('init', innerH * top/100);
            panel.splitter[i == 0 ? 'hide' : 'show']();
          }
          top += height;
        });
      }
    }
  } else {
    $('#history').show();
    setTimeout(function () {
      $body.removeClass('panelsVisible');
    }, 100); // 100 is on purpose to add to the effect of the reveal
  }
};

panels.show = function (panelId) {
  this.panels[panelId].show();
  if (this.panels[panelId].editor) {
    this.panels[panelId].editor.focus();
  }
  this.panels[panelId].focus();
}

panels.hideAll = function () {
  var visible = panels.getVisible(),
      i = visible.length;
  while (i--) {
    visible[i].hide();
  }
}

// dirty, but simple
Panel.prototype.distribute = function () {
  panels.distribute();
};

jsbin.panels = panels;

var editors = panels.panels = {
  html: new Panel('html', { editor: true, label: 'HTML' }),
  css: new Panel('css', { editor: true, label: 'CSS' }),
  javascript: new Panel('javascript', { editor: true, label: 'JavaScript', init: function () {
    // checkForErrors();
  } }),
  console: new Panel('console', { label: 'Console' }),
  live: new Panel('live', { label: 'Output', show: function () {
    // contained in live.js
    var panel = this;
    $(document).bind('codeChange.live', function (event, data) {
      if (panels.ready) {
        if (jsbin.settings.includejs === false && data.panelId === 'javascript') {
          // ignore
        } else if (panel.visible) {
          throttledPreview();
        }
      }
    });
    renderLivePreview();
  } })
};

// jsconsole.init(); // sets up render functions etc.
editors.live.settings.render = function () {
  editors.console.render();
  renderLivePreview();
};

// IMPORTANT this is nasty, but the sequence is important, because the
// show/hide method is being called as the panels are being called as
// the panel is setup - so we hook these handlers on *afterwards*.
panels.update = function () {
  var visiblePanels = panels.getVisible(),
      visible = [],
      i = 0;
  for (i = 0; i < visiblePanels.length; i++) {
    visible.push(visiblePanels[i].name);
  }

  if (history.replaceState) {
    history.replaceState(null, null, '?' + visible.join(','));
  } else {
    // :( this will break jquery mobile - but we're talking IE only at this point, right?
    location.hash = '#' + visible.join(',');
  }
}

Panel.prototype._show = Panel.prototype.show;
Panel.prototype.show = function () {
  this._show.apply(this, arguments);
  panels.update();
}

Panel.prototype._hide = Panel.prototype.hide;
Panel.prototype.hide = function () {
  this._hide.apply(this, arguments);
  panels.update();
}

panels.restore();
panels.focus(panels.getVisible()[0] || null);

// allow panels to be reordered - TODO re-enable
(function () {
  var panelsEl = document.getElementById('panels'),
      moving = null;

  panelsEl.ondragstart = function (e) {
    if (e.target.nodeName == 'A') {
      moving = e.target;
    } else {
      return false;
    }
  };

  panelsEl.ondragover = function (e) {
    console.log(e)
    return false;
  };

  panelsEl.ondragend = function () {
    moving = false;
    return false;
  };

  panelsEl.ondrop = function (e) {
    console.log(e.dataTransfer);
    if (moving) {

    }
    return false;
  };

});

var editorsReady = setInterval(function () {
  var ready = true,
      resizeTimer = null,
      panel,
      panelId;

  for (panelId in panels.panels) {
    panel = panels.panels[panelId];
    if (panel.visible && !panel.ready) ready = false;
  }

  panels.ready = ready;

  if (ready) {
    clearInterval(editorsReady);
    // panels.ready = true;
    // if (typeof editors.onReady == 'function') editors.onReady();
    // panels.distribute();

    // if live is visible, render it
    if (panels.panels.live.visible) {
      panels.panels.live.render();
    }

    if (panels.panels.console.visible) {
      panels.panels.console.render();
    }

    $(window).resize(function () {
      clearTimeout(resizeTimer);
      resizeTimer = setTimeout(function () {
        $document.trigger('sizeeditors');
      }, 100);
    });

    $document.trigger('sizeeditors');
    $document.trigger('jsbinReady');
  }
}, 100);
<commit_msg>Removed logging and support any number of custom insertion points<commit_after>//= require "codemirror"
//= require "mobileCodeMirror"
//= require "library"
//= require "unsaved"
//= require "panel"
//= require "../render/live"
//= require "../render/console"
//= require "keycontrol"

var panels = {};

panels.getVisible = function () {
  var panels = this.panels,
      visible = [];
  for (var panel in panels) {
    if (panels[panel].visible) visible.push(panels[panel]);
  }
  return visible;
};

panels.save = function () {
  var visible = this.getVisible(),
      state = {},
      panel;

  for (var i = 0; i < visible.length; i++) {
    panel = visible[i];
    state[panel.name] = panel.$el.css('left');
  }

  localStorage.setItem('jsbin.panels', JSON.stringify(state));
}

panels.restore = function () {
  // if there are panel names on the hash (v2 of jsbin) or in the jquery (v3)
  // then restore those specific panels and evenly distribute them.
  var open = [],
      location = window.location,
      search = location.search.substring(1),
      hash = location.hash.substring(1),
      toopen = search || hash ? (search || hash).split(',') : [],
      state = JSON.parse(localStorage.getItem('jsbin.panels') || '{}'),
      name = '',
      i = 0,
      panel = null,
      init = [],
      panelURLValue = '',
      openWithSameDimensions = false,
      width = window.innerWidth,
      deferredCodeInsert = '';

  // otherwise restore the user's regular settings
  // also set a flag indicating whether or not we should save the panel settings
  // this is based on whether they're on jsbin.com or if they're on an existing
  // bin. Also, if they hit save - *always* save their layout.
  if (location.pathname && location.pathname !== '/') {
    panels.saveOnExit = false;
  } else {
    panels.saveOnExit = true;
  }

  // TODO decide whether the above code I'm trying too hard.

  /* Boot code */
  // then allow them to view specific panels based on comma separated hash fragment
  if (toopen.length) {
    for (name in state) {
      if (toopen.indexOf(name) !== -1) {
        i++;
      }
    }

    if (i === toopen.length) openWithSameDimensions = true;

    for (i = 0; i < toopen.length; i++) {
      panelURLValue = '';
      name = toopen[i];

      // if name contains an `=` it means we also need to set that particular panel to that code
      if (name.indexOf('=') !== -1) {
        panelURLValue = name.substring(name.indexOf('=') + 1);
        name = name.substring(0, name.indexOf('='));
      }

      if (panels.panels[name]) {
        panel = panels.panels[name];
        // console.log(name, 'width', state[name], width * parseFloat(state[name]) / 100);
        if (panel.editor && panelURLValue) {
          panel.setCode(decodeURIComponent(panelURLValue));
        }

        if (openWithSameDimensions) {
          panel.show(width * parseFloat(state[name]) / 100);
        } else {
          panel.show();
        }
        init.push(panel);
      } else if (name && panelURLValue) { // TODO support any varible insertion
        (function (name, panelURLValue) {
          var todo = ['html', 'javascript', 'css'];

          var deferredInsert = function (event, data) {
            var code, parts, panel = panels.panels[data.panelId] || {};

            if (data.panelId && panel.editor && panel.ready === true) {
              todo.splice(todo.indexOf(data.panelId), 1);
              try {
                code = panel.getCode();
              } catch (e) {
                // this really shouldn't happen
                // console.error(e);
              }
              if (code.indexOf('%' + name + '%') !== -1) {
                parts = code.split('%' + name + '%');
                code = parts[0] + decodeURIComponent(panelURLValue) + parts[1];
                panel.setCode(code);
                $document.unbind('codeChange', deferredInsert);
              }
            }

            if (todo.length === 0) {
              $document.unbind('codeChange', deferredInsert);
            }
          };

          $document.bind('codeChange', deferredInsert);
        }(name, panelURLValue));
      }
    }

    // support the old jsbin v1 links directly to the preview
    if (toopen.length === 1 && toopen[0] === 'preview') {
      panels.panels.live.show();
    }

    if (!openWithSameDimensions) this.distribute();
  } else {
    for (name in state) {
      panels.panels[name].show(width * parseFloat(state[name]) / 100);
    }
  }

  // now restore any data from sessionStorage
  // TODO add default templates somewhere
  // var template = {};
  // for (name in this.panels) {
  //   panel = this.panels[name];
  //   if (panel.editor) {
  //     // panel.setCode(sessionStorage.getItem('jsbin.content.' + name) || template[name]);
  //   }
  // }

  for (i = 0; i < init.length; i++) {
    init[i].init();
  }

  if (panels.getVisible().length) $body.addClass('panelsVisible');

};

panels.savecontent = function () {
  // loop through each panel saving it's content to sessionStorage
  var name, panel;
  for (name in this.panels) {
    panel = this.panels[name];
    if (panel.editor) sessionStorage.setItem('jsbin.content.' + name, panel.getCode());
  }
};

panels.focus = function (panel) {
  this.focused = panel;
  if (panel) {
    $('.panel').removeClass('focus').filter('.' + panel.id).addClass('focus');
  }
}

// evenly distribute the width of all the visible panels
panels.distribute = function () {
  var visible = $('#source .panelwrapper:visible'),
      width = 100,
      height = 0,
      innerW = window.innerWidth - (visible.length - 1), // to compensate for border-left
      innerH = $('#source').outerHeight(),
      left = 0,
      right = 0,
      top = 0,
      panel,
      nestedPanels = [];

  if (visible.length) {
    $body.addClass('panelsVisible');

    // visible = visible.sort(function (a, b) {
    //   return a.order < b.order ? -1 : 1;
    // });

    width = 100 / visible.length;
    for (var i = 0; i < visible.length; i++) {
      panel = $.data(visible[i], 'panel');
      right = 100 - (width * (i+1));
      panel.$el.css({ top: 0, bottom: 0, left: left + '%', right: right + '%' });
      panel.splitter.trigger('init', innerW * left/100);
      panel.splitter[i == 0 ? 'hide' : 'show']();
      left += width;

      nestedPanels = $(visible[i]).find('.panel');
      if (nestedPanels.length > 1) {
        top = 0;
        nestedPanels = nestedPanels.filter(':visible');
        height = 100 / nestedPanels.length;
        nestedPanels.each(function (i) {
          bottom = 100 - (height * (i+1));
          var panel = jsbin.panels.panels[$.data(this, 'name')];
          // $(this).css({ top: top + '%', bottom: bottom + '%' });
          $(this).css('top', top + '%');
          $(this).css('bottom', bottom + '%' );
          if (panel.splitter.hasClass('vertical')) {
            panel.splitter.trigger('init', innerH * top/100);
            panel.splitter[i == 0 ? 'hide' : 'show']();
          }
          top += height;
        });
      }
    }
  } else {
    $('#history').show();
    setTimeout(function () {
      $body.removeClass('panelsVisible');
    }, 100); // 100 is on purpose to add to the effect of the reveal
  }
};

panels.show = function (panelId) {
  this.panels[panelId].show();
  if (this.panels[panelId].editor) {
    this.panels[panelId].editor.focus();
  }
  this.panels[panelId].focus();
}

panels.hideAll = function () {
  var visible = panels.getVisible(),
      i = visible.length;
  while (i--) {
    visible[i].hide();
  }
}

// dirty, but simple
Panel.prototype.distribute = function () {
  panels.distribute();
};

jsbin.panels = panels;

var editors = panels.panels = {
  html: new Panel('html', { editor: true, label: 'HTML' }),
  css: new Panel('css', { editor: true, label: 'CSS' }),
  javascript: new Panel('javascript', { editor: true, label: 'JavaScript', init: function () {
    // checkForErrors();
  } }),
  console: new Panel('console', { label: 'Console' }),
  live: new Panel('live', { label: 'Output', show: function () {
    // contained in live.js
    var panel = this;
    $(document).bind('codeChange.live', function (event, data) {
      if (panels.ready) {
        if (jsbin.settings.includejs === false && data.panelId === 'javascript') {
          // ignore
        } else if (panel.visible) {
          throttledPreview();
        }
      }
    });
    renderLivePreview();
  } })
};

// jsconsole.init(); // sets up render functions etc.
editors.live.settings.render = function () {
  editors.console.render();
  renderLivePreview();
};

// IMPORTANT this is nasty, but the sequence is important, because the
// show/hide method is being called as the panels are being called as
// the panel is setup - so we hook these handlers on *afterwards*.
panels.update = function () {
  var visiblePanels = panels.getVisible(),
      visible = [],
      i = 0;
  for (i = 0; i < visiblePanels.length; i++) {
    visible.push(visiblePanels[i].name);
  }

  if (history.replaceState) {
    history.replaceState(null, null, '?' + visible.join(','));
  } else {
    // :( this will break jquery mobile - but we're talking IE only at this point, right?
    location.hash = '#' + visible.join(',');
  }
}

Panel.prototype._show = Panel.prototype.show;
Panel.prototype.show = function () {
  this._show.apply(this, arguments);
  panels.update();
}

Panel.prototype._hide = Panel.prototype.hide;
Panel.prototype.hide = function () {
  this._hide.apply(this, arguments);
  panels.update();
}

panels.restore();
panels.focus(panels.getVisible()[0] || null);

// allow panels to be reordered - TODO re-enable
(function () {
  var panelsEl = document.getElementById('panels'),
      moving = null;

  panelsEl.ondragstart = function (e) {
    if (e.target.nodeName == 'A') {
      moving = e.target;
    } else {
      return false;
    }
  };

  panelsEl.ondragover = function (e) {
    console.log(e)
    return false;
  };

  panelsEl.ondragend = function () {
    moving = false;
    return false;
  };

  panelsEl.ondrop = function (e) {
    console.log(e.dataTransfer);
    if (moving) {

    }
    return false;
  };

});

var editorsReady = setInterval(function () {
  var ready = true,
      resizeTimer = null,
      panel,
      panelId;

  for (panelId in panels.panels) {
    panel = panels.panels[panelId];
    if (panel.visible && !panel.ready) ready = false;
  }

  panels.ready = ready;

  if (ready) {
    clearInterval(editorsReady);
    // panels.ready = true;
    // if (typeof editors.onReady == 'function') editors.onReady();
    // panels.distribute();

    // if live is visible, render it
    if (panels.panels.live.visible) {
      panels.panels.live.render();
    }

    if (panels.panels.console.visible) {
      panels.panels.console.render();
    }

    $(window).resize(function () {
      clearTimeout(resizeTimer);
      resizeTimer = setTimeout(function () {
        $document.trigger('sizeeditors');
      }, 100);
    });

    $document.trigger('sizeeditors');
    $document.trigger('jsbinReady');
  }
}, 100);
<|endoftext|>


<commit_before>// Karma configuration
// http://karma-runner.github.io/0.12/config/configuration-file.html
// Generated on 2015-06-23 using
// generator-karma 1.0.0

module.exports = function(config) {
  'use strict';

  config.set({
    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // base path, that will be used to resolve files and exclude
    basePath: '../',

    // testing framework to use (jasmine/mocha/qunit/...)
    // as well as any additional frameworks (requirejs/chai/sinon/...)
    frameworks: [
      'jasmine'
    ],

    // list of files / patterns to load in the browser
    files: [
      // bower:js
      'bower_components/jquery/dist/jquery.js',
      'bower_components/angular/angular.js',
      'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap.js',
      'bower_components/angular-animate/angular-animate.js',
      'bower_components/angular-ui-router/release/angular-ui-router.js',
      'bower_components/angular-bootstrap/ui-bootstrap-tpls.js',
      'bower_components/leaflet-dist/leaflet.js',
      'bower_components/leaflet-draw/dist/leaflet.draw-src.js',
      'bower_components/angular-mocks/angular-mocks.js',
      // endbower
      'test/mock/**/*.js',
      'app/scripts/config.js',
      'app/scripts/affix/module.js',
      'app/scripts/affix/action-bar-affix-directive.js',
      'app/scripts/brand/module.js',
      'app/scripts/brand/brand-directive.js',
      'app/scripts/views/footer/module.js',
      'app/scripts/views/footer/footer-directive.js',
      'app/scripts/views/home/module.js',
      'app/scripts/views/home/home-controller.js',
      'app/scripts/views/about/module.js',
      'app/scripts/views/about/about-controller.js',
      'app/scripts/views/contact/module.js',
      'app/scripts/views/contact/contact-controller.js',
      'app/scripts/views/museum/module.js',
      'app/scripts/views/museum/museum-controller.js',
      'app/scripts/app.js',
      'test/spec/**/*.js'
    ],

    // list of files / patterns to exclude
    exclude: [
    ],

    // web server port
    port: 8080,

    // Start these browsers, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera
    // - Safari (only Mac)
    // - PhantomJS
    // - IE (only Windows)
    browsers: [
      'PhantomJS'
    ],

    // Which plugins to enable
    plugins: [
      'karma-phantomjs-launcher',
      'karma-jasmine'
    ],

    // Continuous Integration mode
    // if true, it capture browsers, run tests and exit
    singleRun: false,

    colors: true,

    // level of logging
    // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
    logLevel: config.LOG_INFO,

    // Uncomment the following lines if you are using grunt's server to run the tests
    // proxies: {
    //   '/': 'http://localhost:9000/'
    // },
    // URL root prevent conflicts with the site root
    // urlRoot: '_karma_'
  });
};
<commit_msg>Add missing map module to test conf<commit_after>// Karma configuration
// http://karma-runner.github.io/0.12/config/configuration-file.html
// Generated on 2015-06-23 using
// generator-karma 1.0.0

module.exports = function(config) {
  'use strict';

  config.set({
    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // base path, that will be used to resolve files and exclude
    basePath: '../',

    // testing framework to use (jasmine/mocha/qunit/...)
    // as well as any additional frameworks (requirejs/chai/sinon/...)
    frameworks: [
      'jasmine'
    ],

    // list of files / patterns to load in the browser
    files: [
      // bower:js
      'bower_components/jquery/dist/jquery.js',
      'bower_components/angular/angular.js',
      'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap.js',
      'bower_components/angular-animate/angular-animate.js',
      'bower_components/angular-ui-router/release/angular-ui-router.js',
      'bower_components/angular-bootstrap/ui-bootstrap-tpls.js',
      'bower_components/leaflet-dist/leaflet.js',
      'bower_components/leaflet-draw/dist/leaflet.draw-src.js',
      'bower_components/angular-mocks/angular-mocks.js',
      // endbower
      'test/mock/**/*.js',
      'app/scripts/config.js',
      'app/scripts/affix/module.js',
      'app/scripts/affix/action-bar-affix-directive.js',
      'app/scripts/brand/module.js',
      'app/scripts/brand/brand-directive.js',
      'app/scripts/map/module.js',
      'app/scripts/map/cartodb-vis-directive.js',
      'app/scripts/views/footer/module.js',
      'app/scripts/views/footer/footer-directive.js',
      'app/scripts/views/home/module.js',
      'app/scripts/views/home/home-controller.js',
      'app/scripts/views/about/module.js',
      'app/scripts/views/about/about-controller.js',
      'app/scripts/views/contact/module.js',
      'app/scripts/views/contact/contact-controller.js',
      'app/scripts/views/museum/module.js',
      'app/scripts/views/museum/museum-controller.js',
      'app/scripts/app.js',
      'test/spec/**/*.js'
    ],

    // list of files / patterns to exclude
    exclude: [
    ],

    // web server port
    port: 8080,

    // Start these browsers, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera
    // - Safari (only Mac)
    // - PhantomJS
    // - IE (only Windows)
    browsers: [
      'PhantomJS'
    ],

    // Which plugins to enable
    plugins: [
      'karma-phantomjs-launcher',
      'karma-jasmine'
    ],

    // Continuous Integration mode
    // if true, it capture browsers, run tests and exit
    singleRun: false,

    colors: true,

    // level of logging
    // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
    logLevel: config.LOG_INFO,

    // Uncomment the following lines if you are using grunt's server to run the tests
    // proxies: {
    //   '/': 'http://localhost:9000/'
    // },
    // URL root prevent conflicts with the site root
    // urlRoot: '_karma_'
  });
};
<|endoftext|>


<commit_before>$(window).load(function(){
	$("#runcode").on("click",function(){
		runsacode();
	});
		$("#resetcode").on("click",function(){
	$("#seqinput").val("");
	});

});

var runsacode = function(){
var characterlength = 0;
var inptxt = $("#seqinput").val().trim();
var inplength = inptxt.length;

var sttxt = "Total Length:" + inptxt.length;
var sequences = inptxt.match(/>/g);
var nazeefa = 0;
var invalid = 0;
debughtml = "";
var maxlength = 0;
var maxseqlength = 0;
var extraspace=2;
var sequences_list = [];

for (i = 0; i < sequences.length; i++) {
    var firstg = inptxt.indexOf(">");
    var secondg = inptxt.indexOf(">", firstg + 1);
    var seqtext = inptxt.substr(firstg, secondg - firstg);
    var capstart = seqtext.search("[A-Z-*]{10}");
    //separate title
    var seqtitle = seqtext.substr(0, capstart);
    seqtitle = seqtitle.substr(1);
    if(seqtitle.length+extraspace>maxlength)
    {
        maxlength=seqtitle.length+extraspace;
    }
    // Without Spaces
    var cleanseq = seqtext.substr(capstart);
    var cleanseqwithoutspaces = cleanseq.split(" ").join("").split(" ").join("");
    //Insert in array
    sequences_list.push({
        titlelength: seqtitle.length,
        title: seqtitle,
        sequence: cleanseqwithoutspaces,
        seqlength: cleanseqwithoutspaces.length
    });
    maxseqlength=cleanseqwithoutspaces.length>maxseqlength?cleanseqwithoutspaces.length:maxseqlength;

    inptxt = inptxt.substr(secondg);
}
//prepare SVG
var svgContainer = d3.select("#svgcontainer").append("svg").attr("width", (maxseqlength*10)+40).attr("height", (sequences_list.length*20)+40);
for(i=0;i<maxseqlength;i++)
{
	svgContainer.append("circle").attr('cx',20+(i*10)).attr('cy',20).attr('fill','#ccc').attr('r',3);
}
//End of SVG Test
$("#seqoutput").html("");
for (i = 0; i < sequences_list.length; i++) {
    var newtitle= sequences_list[i].title;
    diff_in_length=maxlength-sequences_list[i].titlelength;
    if(diff_in_length>0)
    {
        for(j=0;j<diff_in_length;j++){
            newtitle+=" ";
        }
    }
	//SVG Added
		svgContainer.append("circle").attr('cx',20).attr('cy',20+(i*10)).attr('r',2);
	//SVG End
    if(sequences_list[i].seqlength>0){
        characterlength=sequences_list[i].seqlength;
		if($("#seqoutput").html()==""){
			$("#seqoutput").text(sequences_list.length-1+" "+characterlength);
			$("#seqoutput").html($("#seqoutput").text()+"
");
		}
        var outtxt = $("#seqoutput").html();
        $("#seqoutput").html(outtxt + newtitle + sequences_list[i].sequence + "
");
        nazeefa++;
    }

    //debug
    debughtml += "S:" + i +
        " Length (Seq:" + sequences_list[i].titlelength +
        ",CleanNoSpace:" + sequences_list[i].seqlength + ")" +
        "
";
}
$("#debug").html(debughtml);
sttxt += ", Sequences:" + sequences.length;
sttxt += ", Processed:" + nazeefa + ", MaxLength:" + maxlength;
$("#stats").text(sttxt);
$("#headtext").text(sequences_list.length-1+" "+characterlength);
}

function selectText(containerid) {
    if (document.selection) {
        var range = document.body.createTextRange();
        range.moveToElementText(document.getElementById(containerid));
        range.select();
    } else if (window.getSelection()) {
        var range = document.createRange();
        range.selectNode(document.getElementById(containerid));
        window.getSelection().removeAllRanges();
        window.getSelection().addRange(range);
    }
}
<commit_msg>Stats Example Updated with Simple Colours<commit_after>$(window).load(function(){
	$("#runcode").on("click",function(){
		runsacode();
	});
		$("#resetcode").on("click",function(){
	$("#seqinput").val("");
	});

});

var runsacode = function(){
var characterlength = 0;
var inptxt = $("#seqinput").val().trim();
var inplength = inptxt.length;

var sttxt = "Total Length:" + inptxt.length;
var sequences = inptxt.match(/>/g);
var nazeefa = 0;
var invalid = 0;
debughtml = "";
var maxlength = 0;
var maxseqlength = 0;
var extraspace=2;
var sequences_list = [];

for (i = 0; i < sequences.length; i++) {
    var firstg = inptxt.indexOf(">");
    var secondg = inptxt.indexOf(">", firstg + 1);
    var seqtext = inptxt.substr(firstg, secondg - firstg);
    var capstart = seqtext.search("[A-Z-*]{10}");
    //separate title
    var seqtitle = seqtext.substr(0, capstart);
    seqtitle = seqtitle.substr(1);
    if(seqtitle.length+extraspace>maxlength)
    {
        maxlength=seqtitle.length+extraspace;
    }
    // Without Spaces
    var cleanseq = seqtext.substr(capstart);
    var cleanseqwithoutspaces = cleanseq.split(" ").join("").split(" ").join("");
    //Insert in array
    sequences_list.push({
        titlelength: seqtitle.length,
        title: seqtitle,
        sequence: cleanseqwithoutspaces,
        seqlength: cleanseqwithoutspaces.length
    });
    maxseqlength=cleanseqwithoutspaces.length>maxseqlength?cleanseqwithoutspaces.length:maxseqlength;

    inptxt = inptxt.substr(secondg);
}
//prepare SVG
var svgContainer = d3.select("#svgcontainer").append("svg").attr("width", (maxseqlength*15)+40).attr("height", (sequences_list.length*20)+40);
for(i=0;i<=maxseqlength;i++)
{
	svgContainer.append("circle").attr('data-col','c'+i).attr('data-row','rh').attr('class','r0c'+i).attr('cx',20+(i*15)).attr('cy',20).attr('fill','#ccc').attr('fill-opacity','1.0').attr('r',4);
}
//End of SVG Test
$("#seqoutput").html("");
var svgarr = [];
for (i = 0; i < sequences_list.length; i++) {
    var newtitle= sequences_list[i].title;
    diff_in_length=maxlength-sequences_list[i].titlelength;
    if(diff_in_length>0)
    {
        for(j=0;j<diff_in_length;j++){
            newtitle+=" ";
        }
    }
	//SVG Added
		svgContainer.append("circle").attr('data-col','c0').attr('data-row','r'+i+1).attr('cx',20).attr('cy',20+(i*15)).attr('r',4).attr('fill','blue');
		for(k=0;k<sequences_list[i].seqlength;k++)
		{
			var svgc= svgContainer.append("text").attr('data-col','c'+(k+1)).attr('data-row','r'+(i+1)).attr('x',33+(k*15)).attr('y',40+(i*15)).attr('fill','green').text(sequences_list[i].sequence[k]);
			if(sequences_list[i].sequence[k]=='-')
			{
				svgc.attr('fill','red');
			}
		}
	//SVG End
    if(sequences_list[i].seqlength>0){
        characterlength=sequences_list[i].seqlength;
		if($("#seqoutput").html()==""){
			$("#seqoutput").text(sequences_list.length-1+" "+characterlength);
			$("#seqoutput").html($("#seqoutput").text()+"
");
		}
        var outtxt = $("#seqoutput").html();
        $("#seqoutput").html(outtxt + newtitle + sequences_list[i].sequence + "
");
        nazeefa++;
		svgarr.push(
		{
			title:newtitle,
			seq:sequences_list[i].sequence,
			seqlength:sequences_list[i].sequence
		});
    }

    //debug
    debughtml += "S:" + i +
        " Length (Seq:" + sequences_list[i].titlelength +
        ",CleanNoSpace:" + sequences_list[i].seqlength + ")" +
        "
";
}
//Get colour range for 1-100;
var percentagecolour=d3.scale.linear().domain([0,50,100]).range(["green","orange","red"]);
//update column headers
for (i=0;i<maxseqlength;i++)
	{
		//for each column set to 0%
		totalhyphen=0;
		for(j=0;j<svgarr.length;j++)
		{
			if(svgarr[j].seq[i]=='-')
			{
				totalhyphen++;
			}
		}
		var percentagehyphen = Math.round((totalhyphen/svgarr.length)*100);
		$('circle.r0c'+(i+1)).attr('fill',percentagecolour(percentagehyphen)).attr('data-num',totalhyphen).attr('data-perc',percentagehyphen);
		$('circle.r0c'+(i+1)).on('click',function(){
			currentopacity = parseFloat($(this).attr('fill-opacity'));
			if(currentopacity==1.0){
				$(this).attr('fill-opacity','0.5');
				$(this).attr('stroke','black');
				$(this).attr('stroke-width','2');
			}
			else{
				$(this).attr('fill-opacity','1.0');
				$(this).attr('stroke','');
				$(this).attr('stroke-width','0');
			}
		});
		//console.log('circle.r0c'+(i+1)+": "+totalhyphen);
	}

$("#debug").html(debughtml);
sttxt += ", Sequences:" + sequences.length;
sttxt += ", Processed:" + nazeefa + ", MaxLength:" + maxlength;
$("#stats").text(sttxt);
$("#headtext").text(sequences_list.length-1+" "+characterlength);
}

function selectText(containerid) {
    if (document.selection) {
        var range = document.body.createTextRange();
        range.moveToElementText(document.getElementById(containerid));
        range.select();
    } else if (window.getSelection()) {
        var range = document.createRange();
        range.selectNode(document.getElementById(containerid));
        window.getSelection().removeAllRanges();
        window.getSelection().addRange(range);
    }
}
<|endoftext|>


<commit_before>'use strict';

var s = require('./support');
var expect = s.expect;
var lexor = require("../");
var Lexor = lexor.Lexor;

describe("Lexor Library", function () {
  it("should expose its official API", function () {
    var tokenizer = new Lexor();
    expect(tokenizer).to.be.a("object");
    expect(tokenizer).to.respondTo("input");
    expect(tokenizer).to.respondTo("rule");
    expect(tokenizer).to.respondTo("token");
  });

  it("should have the expected functionality", function () {
    var lexor = new Lexor();
    lexor.rule("default", /[a-zA-Z]+/, function (ctx /*, m */) {
      ctx.accept("symbol")
    });

    lexor.rule("default", /[0-9]+/, function (ctx, m) {
      ctx.accept("number", parseInt(m[0]))
    });

    lexor.rule("default", /"((?:\\"|[^\r\n]+)+)"/, function (ctx, m) {
      ctx.accept("string", m[1].replace(/\\"/g, "\""))
    });

    lexor.rule("default", /\/\*/, function (ctx /*, m */) {
      ctx.push("comment");
      ctx.tag("bar");
      ctx.ignore();
    });

    lexor.rule("comment #foo #bar", /\*\//, function (/* ctx, m */) {
      throw new Error("should never enter")
    });

    lexor.rule("comment #bar", /\*\//, function (ctx /*, m */) {
      ctx.untag("bar");
      ctx.pop();
      ctx.ignore();
    });

    lexor.rule("comment #bar", /./, function (ctx /*, m */) {
      ctx.ignore();
    });

    lexor.rule("default", /\s*,\s*/, function (ctx /*, m */) {
      ctx.ignore();
    });

    lexor.input("foo42,\n \"bar baz\",\n quux/* */");

    lexor.debug(true);
    var tokens;
    try {
      tokens = lexor.tokens();
    } catch (ex) {
      console.log(ex.toString());
      throw ex;
    }

    expect(tokens).to.be.a("array");
    expect(tokens).to.have.length(4);
    expect(tokens[0]).to.be.a("object");
    deepEqual(tokens[0], {type: "symbol", value: "foo", text: "foo", pos: 0, line: 1, column: 1});
    expect(tokens[1]).to.be.a("object");
    deepEqual(tokens[1], {type: "number", value: 42, text: "42", pos: 3, line: 1, column: 4});
    expect(tokens[2]).to.be.a("object");
    deepEqual(tokens[2], {type: "string", value: "bar baz", text: "\"bar baz\"", pos: 8, line: 2, column: 2});
    expect(tokens[3]).to.be.a("object");
    deepEqual(tokens[3], {type: "symbol", value: "quux", text: "quux", pos: 20, line: 3, column: 2});
  });

  it("should throw error if not matched", function () {
    var tokenizer = new Lexor();
    tokenizer.input('hello');
    expect(function () {
      tokenizer.tokens();
    }).to.throw(lexor.ParsingError);
  });
});

function deepEqual(object, expected) {
  expect(Object.keys(object)).deep.equal(Object.keys(expected));
  Object.keys(expected).forEach(function (key) {
    expect(object[key]).deep.equal(expected[key]);
  });
}
<commit_msg>Update<commit_after>'use strict';

var s = require('./support');
var expect = s.expect;
var lexor = require("../");
var Lexor = lexor.Lexor;

describe("Lexor Library", function () {
  it("should expose its official API", function () {
    var lexor = new Lexor();
    expect(lexor).to.be.a("object");
    expect(lexor).to.respondTo("input");
    expect(lexor).to.respondTo("rule");
    expect(lexor).to.respondTo("token");
  });

  it("should have the expected functionality", function () {
    var lexor = new Lexor();
    lexor.rule("default", /[a-zA-Z]+/, function (ctx /*, m */) {
      ctx.accept("symbol")
    });

    lexor.rule("default", /[0-9]+/, function (ctx, m) {
      ctx.accept("number", parseInt(m[0]))
    });

    lexor.rule("default", /"((?:\\"|[^\r\n]+)+)"/, function (ctx, m) {
      ctx.accept("string", m[1].replace(/\\"/g, "\""))
    });

    lexor.rule("default", /\/\*/, function (ctx /*, m */) {
      ctx.push("comment");
      ctx.tag("bar");
      ctx.ignore();
    });

    lexor.rule("comment #foo #bar", /\*\//, function (/* ctx, m */) {
      throw new Error("should never enter")
    });

    lexor.rule("comment #bar", /\*\//, function (ctx /*, m */) {
      ctx.untag("bar");
      ctx.pop();
      ctx.ignore();
    });

    lexor.rule("comment #bar", /./, function (ctx /*, m */) {
      ctx.ignore();
    });

    lexor.rule("default", /\s*,\s*/, function (ctx /*, m */) {
      ctx.ignore();
    });

    lexor.input("foo42,\n \"bar baz\",\n quux/* */");

    lexor.debug(true);
    var tokens;
    try {
      tokens = lexor.tokens();
    } catch (ex) {
      console.log(ex.toString());
      throw ex;
    }

    expect(tokens).to.be.a("array");
    expect(tokens).to.have.length(4);
    expect(tokens[0]).to.be.a("object");
    deepEqual(tokens[0], {type: "symbol", value: "foo", text: "foo", pos: 0, line: 1, column: 1});
    expect(tokens[1]).to.be.a("object");
    deepEqual(tokens[1], {type: "number", value: 42, text: "42", pos: 3, line: 1, column: 4});
    expect(tokens[2]).to.be.a("object");
    deepEqual(tokens[2], {type: "string", value: "bar baz", text: "\"bar baz\"", pos: 8, line: 2, column: 2});
    expect(tokens[3]).to.be.a("object");
    deepEqual(tokens[3], {type: "symbol", value: "quux", text: "quux", pos: 20, line: 3, column: 2});
  });

  it("should throw error if not matched", function () {
    var lexor = new Lexor();
    lexor.input('hello');
    expect(function () {
      lexor.tokens();
    }).to.throw(lexor.ParsingError);
  });
});

function deepEqual(object, expected) {
  expect(Object.keys(object)).deep.equal(Object.keys(expected));
  Object.keys(expected).forEach(function (key) {
    expect(object[key]).deep.equal(expected[key]);
  });
}
<|endoftext|>


<commit_before>!function($) {

"use strict";

var FOUNDATION_VERSION = '6.0.0-alpha.1';

// Global Foundation object
// This is attached to the window, or used as a module for AMD/Browserify
var Foundation = {
  version: FOUNDATION_VERSION,

  /**
   * Stores initialized plugins.
   */
  _plugins: {},

  /**
   * Stores generated unique ids for plugin instances
   */
  _uuids: [],
  /**
   * Stores currently active plugins.
   */
  _activePlugins: {},

  /**
   * Returns a boolean for RTL support
   */
  rtl: function(){
    return $('html').attr('dir') === 'rtl';
  },
  /**
   * Defines a Foundation plugin, adding it to the `Foundation` namespace and the list of plugins to initialize when reflowing.
   * @param {Object} plugin - The constructor of the plugin.
   */
  plugin: function(plugin) {
    // Object key to use when adding to global Foundation object
    // Examples: Foundation.Reveal, Foundation.OffCanvas
    var className = functionName(plugin);
    // Object key to use when storing the plugin, also used to create the identifying data attribute for the plugin
    // Examples: data-reveal, data-off-canvas
    var attrName  = hyphenate(className);

    // Add to the Foundation object and the plugins list (for reflowing)
    this._plugins[attrName] = this[className] = plugin;
  },
  /**
   * @function
   * Creates a pointer to an instance of a Plugin within the Foundation._activePlugins object.
   * Sets the `[data-pluginName="uniqueIdHere"]`, allowing easy access to any plugin's internal methods.
   * Also fires the initialization event for each plugin, consolidating repeditive code.
   * @param {Object} plugin - an instance of a plugin, usually `this` in context.
   */
  registerPlugin: function(plugin){
    var pluginName = functionName(plugin.constructor).toLowerCase();

    plugin.uuid = this.GetYoDigits(6, pluginName);
    plugin.$element.attr('data-' + pluginName, plugin.uuid).trigger('init.zf.' + pluginName);

    this._activePlugins[plugin.uuid] = plugin;

    return;
  },
  /**
   * @function
   * Removes the pointer for an instance of a Plugin from the Foundation._activePlugins obj.
   * Also fires the destroyed event for the plugin, consolidating repeditive code.
   * @param {Object} plugin - an instance of a plugin, usually `this` in context.
   */
  unregisterPlugin: function(plugin){
    var pluginName = functionName(plugin.constructor).toLowerCase();

    delete this._activePlugins[plugin.uuid];

    plugin.$element.trigger('destroyed.zf.' + pluginName);

    return;
  },

  /**
   * @function
   * Causes one or more active plugins to reflow, resetting event listeners, recalculating positions, etc.
   * @param {String} plugins - optional string of an individual plugin key, attained by calling `$(element).data('pluginName')`, or string of a plugin class i.e. `'dropdown'`
   * @default If no argument is passed, reflow all currently active plugins.
   */
  _reflow: function(plugins){
    var actvPlugins = Object.keys(this._activePlugins);
    var _this = this;

    if(!plugins){
      actvPlugins.forEach(function(p){
        _this._activePlugins[p]._init();
      });

    }else if(typeof plugins === 'string'){
      var namespace = plugins.split('-')[1];

      if(namespace){

        this._activePlugins[plugins]._init();

      }else{
        namespace = new RegExp(plugins, 'i');

        actvPlugins.filter(function(p){
          return namespace.test(p);
        }).forEach(function(p){
          _this._activePlugins[p]._init();
        });
      }
    }

  },

  /**
   * returns a random base-36 uid with namespacing
   * @function
   * @param {Number} length - number of random base-36 digits desired. Increase for more random strings.
   * @param {String} namespace - name of plugin to be incorporated in uid, optional.
   * @default {String} '' - if no plugin name is provided, nothing is appended to the uid.
   * @returns {String} - unique id
   */
  GetYoDigits: function(length, namespace){
    return Math.round((Math.pow(36, length + 1) - Math.random() * Math.pow(36, length))).toString(36).slice(1) + (namespace ? '-' + namespace : '');
  },
  /**
   * Initialize plugins on any elements within `elem` (and `elem` itself) that aren't already initialized.
   * @param {Object} elem - jQuery object containing the element to check inside. Also checks the element itself, unless it's the `document` object.
   * @param {String|Array} plugins - A list of plugins to initialize. Leave this out to initialize everything.
   */
  reflow: function(elem, plugins) {
    // If plugins is undefined, just grab everything
    if (typeof plugins === 'undefined') {
      plugins = Object.keys(this._plugins);
    }
    // If plugins is a string, convert it to an array with one item
    else if (typeof plugins === 'string') {
      plugins = [plugins];
    }

    var _this = this;

    // Iterate through each plugin
    $.each(plugins, function(i, name) {
      // Get the current plugin
      var plugin = _this._plugins[name];

      // Localize the search to all elements inside elem, as well as elem itself, unless elem === document
      var $elem = $(elem).find('[data-'+name+']').addBack('*');

      // For each plugin found, initialize it
      $elem.each(function() {
        // Don't double-dip on plugins
        if ($(this).attr('zf-plugin')) {
          console.warn("Tried to initialize "+name+" on an element that already has a Foundation plugin.");
          return;
        }
        $(this).data('zf-plugin', new plugin($(this)));
      });
    });
  },
  getFnName: functionName,
  transitionend: (function() {
    var transitions = {
      'transition': 'transitionend',
      'WebkitTransition': 'webkitTransitionEnd',
      'MozTransition': 'transitionend',
      'OTransition': 'otransitionend'
    };
    var elem = document.createElement('div');

    for (var t in transitions){
      if (typeof elem.style[t] !== 'undefined'){
        return transitions[t];
      }
    }
  })()
};

Foundation.util = {
  throttle: function (func, delay) {
    var timer = null;

    return function () {
      var context = this, args = arguments;

      if (timer === null) {
        timer = setTimeout(function () {
          func.apply(context, args);
          timer = null;
        }, delay);
      }
    };
  }
}

// TODO: consider not making this a jQuery function
// TODO: need way to reflow vs. re-initialize
/**
 * The Foundation jQuery method.
 * @param {String|Array} method - An action to perform on the current jQuery object.
 */
var foundation = function(method) {
  var type = typeof method;
  var $meta = $('meta.foundation-mq');

  if(!$meta.length){
    $('<meta class="foundation-mq">').appendTo(document.head);
  }

  if (type === 'undefined') {
    Foundation.MediaQuery._init();
    Foundation.reflow(this);
  } else if (type === 'object') {
    Foundation.reflow(this);
  } else if (type === 'string' || type === 'array') {
    Foundation.reflow(this, method);
  }

  return this;
};

window.Foundation = Foundation;
$.fn.foundation = foundation;

// Polyfill for requestAnimationFrame
(function() {
  if (!Date.now)
    Date.now = function() { return new Date().getTime(); };

  var vendors = ['webkit', 'moz'];
  for (var i = 0; i < vendors.length && !window.requestAnimationFrame; ++i) {
      var vp = vendors[i];
      window.requestAnimationFrame = window[vp+'RequestAnimationFrame'];
      window.cancelAnimationFrame = (window[vp+'CancelAnimationFrame']
                                 || window[vp+'CancelRequestAnimationFrame']);
  }
  if (/iP(ad|hone|od).*OS 6/.test(window.navigator.userAgent)
    || !window.requestAnimationFrame || !window.cancelAnimationFrame) {
    var lastTime = 0;
    window.requestAnimationFrame = function(callback) {
        var now = Date.now();
        var nextTime = Math.max(lastTime + 16, now);
        return setTimeout(function() { callback(lastTime = nextTime); },
                          nextTime - now);
    };
    window.cancelAnimationFrame = clearTimeout;
  }
  window.performance = (window.performance || {
    start: Date.now(),
    now: function(){
        return Date.now() - this.start;
    }
  });
})();

// Polyfill to get the name of a function in IE9
function functionName(fn) {
  if (Function.prototype.name === undefined) {
    var funcNameRegex = /function\s([^(]{1,})\(/;
    var results = (funcNameRegex).exec((fn).toString());
    return (results && results.length > 1) ? results[1].trim() : "";
  }
  else if (fn.prototype === undefined) {
    return fn.constructor.name;
  }
  else {
    return fn.prototype.constructor.name;
  }
}

// Convert PascalCase to kebab-case
// Thank you: http://stackoverflow.com/a/8955580
function hyphenate(str) {
  return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
}

}(jQuery);
<commit_msg>removes data-pluginName attr from elements on Foundation.unregisterPlugin<commit_after>!function($) {

"use strict";

var FOUNDATION_VERSION = '6.0.0-alpha.1';

// Global Foundation object
// This is attached to the window, or used as a module for AMD/Browserify
var Foundation = {
  version: FOUNDATION_VERSION,

  /**
   * Stores initialized plugins.
   */
  _plugins: {},

  /**
   * Stores generated unique ids for plugin instances
   */
  _uuids: [],
  /**
   * Stores currently active plugins.
   */
  _activePlugins: {},

  /**
   * Returns a boolean for RTL support
   */
  rtl: function(){
    return $('html').attr('dir') === 'rtl';
  },
  /**
   * Defines a Foundation plugin, adding it to the `Foundation` namespace and the list of plugins to initialize when reflowing.
   * @param {Object} plugin - The constructor of the plugin.
   */
  plugin: function(plugin) {
    // Object key to use when adding to global Foundation object
    // Examples: Foundation.Reveal, Foundation.OffCanvas
    var className = functionName(plugin);
    // Object key to use when storing the plugin, also used to create the identifying data attribute for the plugin
    // Examples: data-reveal, data-off-canvas
    var attrName  = hyphenate(className);

    // Add to the Foundation object and the plugins list (for reflowing)
    this._plugins[attrName] = this[className] = plugin;
  },
  /**
   * @function
   * Creates a pointer to an instance of a Plugin within the Foundation._activePlugins object.
   * Sets the `[data-pluginName="uniqueIdHere"]`, allowing easy access to any plugin's internal methods.
   * Also fires the initialization event for each plugin, consolidating repeditive code.
   * @param {Object} plugin - an instance of a plugin, usually `this` in context.
   */
  registerPlugin: function(plugin){
    var pluginName = functionName(plugin.constructor).toLowerCase();

    plugin.uuid = this.GetYoDigits(6, pluginName);
    plugin.$element.attr('data-' + pluginName, plugin.uuid).trigger('init.zf.' + pluginName);

    this._activePlugins[plugin.uuid] = plugin;

    return;
  },
  /**
   * @function
   * Removes the pointer for an instance of a Plugin from the Foundation._activePlugins obj.
   * Also fires the destroyed event for the plugin, consolidating repeditive code.
   * @param {Object} plugin - an instance of a plugin, usually `this` in context.
   */
  unregisterPlugin: function(plugin){
    var pluginName = functionName(plugin.constructor).toLowerCase();

    delete this._activePlugins[plugin.uuid];
    plugin.$element.removeAttr('data-' + pluginName).trigger('destroyed.zf.' + pluginName);

    return;
  },

  /**
   * @function
   * Causes one or more active plugins to reflow, resetting event listeners, recalculating positions, etc.
   * @param {String} plugins - optional string of an individual plugin key, attained by calling `$(element).data('pluginName')`, or string of a plugin class i.e. `'dropdown'`
   * @default If no argument is passed, reflow all currently active plugins.
   */
  _reflow: function(plugins){
    var actvPlugins = Object.keys(this._activePlugins);
    var _this = this;

    if(!plugins){
      actvPlugins.forEach(function(p){
        _this._activePlugins[p]._init();
      });

    }else if(typeof plugins === 'string'){
      var namespace = plugins.split('-')[1];

      if(namespace){

        this._activePlugins[plugins]._init();

      }else{
        namespace = new RegExp(plugins, 'i');

        actvPlugins.filter(function(p){
          return namespace.test(p);
        }).forEach(function(p){
          _this._activePlugins[p]._init();
        });
      }
    }

  },

  /**
   * returns a random base-36 uid with namespacing
   * @function
   * @param {Number} length - number of random base-36 digits desired. Increase for more random strings.
   * @param {String} namespace - name of plugin to be incorporated in uid, optional.
   * @default {String} '' - if no plugin name is provided, nothing is appended to the uid.
   * @returns {String} - unique id
   */
  GetYoDigits: function(length, namespace){
    return Math.round((Math.pow(36, length + 1) - Math.random() * Math.pow(36, length))).toString(36).slice(1) + (namespace ? '-' + namespace : '');
  },
  /**
   * Initialize plugins on any elements within `elem` (and `elem` itself) that aren't already initialized.
   * @param {Object} elem - jQuery object containing the element to check inside. Also checks the element itself, unless it's the `document` object.
   * @param {String|Array} plugins - A list of plugins to initialize. Leave this out to initialize everything.
   */
  reflow: function(elem, plugins) {
    // If plugins is undefined, just grab everything
    if (typeof plugins === 'undefined') {
      plugins = Object.keys(this._plugins);
    }
    // If plugins is a string, convert it to an array with one item
    else if (typeof plugins === 'string') {
      plugins = [plugins];
    }

    var _this = this;

    // Iterate through each plugin
    $.each(plugins, function(i, name) {
      // Get the current plugin
      var plugin = _this._plugins[name];

      // Localize the search to all elements inside elem, as well as elem itself, unless elem === document
      var $elem = $(elem).find('[data-'+name+']').addBack('*');

      // For each plugin found, initialize it
      $elem.each(function() {
        // Don't double-dip on plugins
        if ($(this).attr('zf-plugin')) {
          console.warn("Tried to initialize "+name+" on an element that already has a Foundation plugin.");
          return;
        }
        $(this).data('zf-plugin', new plugin($(this)));
      });
    });
  },
  getFnName: functionName,
  transitionend: (function() {
    var transitions = {
      'transition': 'transitionend',
      'WebkitTransition': 'webkitTransitionEnd',
      'MozTransition': 'transitionend',
      'OTransition': 'otransitionend'
    };
    var elem = document.createElement('div');

    for (var t in transitions){
      if (typeof elem.style[t] !== 'undefined'){
        return transitions[t];
      }
    }
  })()
};

Foundation.util = {
  throttle: function (func, delay) {
    var timer = null;

    return function () {
      var context = this, args = arguments;

      if (timer === null) {
        timer = setTimeout(function () {
          func.apply(context, args);
          timer = null;
        }, delay);
      }
    };
  }
}

// TODO: consider not making this a jQuery function
// TODO: need way to reflow vs. re-initialize
/**
 * The Foundation jQuery method.
 * @param {String|Array} method - An action to perform on the current jQuery object.
 */
var foundation = function(method) {
  var type = typeof method;
  var $meta = $('meta.foundation-mq');

  if(!$meta.length){
    $('<meta class="foundation-mq">').appendTo(document.head);
  }

  if (type === 'undefined') {
    Foundation.MediaQuery._init();
    Foundation.reflow(this);
  } else if (type === 'object') {
    Foundation.reflow(this);
  } else if (type === 'string' || type === 'array') {
    Foundation.reflow(this, method);
  }

  return this;
};

window.Foundation = Foundation;
$.fn.foundation = foundation;

// Polyfill for requestAnimationFrame
(function() {
  if (!Date.now)
    Date.now = function() { return new Date().getTime(); };

  var vendors = ['webkit', 'moz'];
  for (var i = 0; i < vendors.length && !window.requestAnimationFrame; ++i) {
      var vp = vendors[i];
      window.requestAnimationFrame = window[vp+'RequestAnimationFrame'];
      window.cancelAnimationFrame = (window[vp+'CancelAnimationFrame']
                                 || window[vp+'CancelRequestAnimationFrame']);
  }
  if (/iP(ad|hone|od).*OS 6/.test(window.navigator.userAgent)
    || !window.requestAnimationFrame || !window.cancelAnimationFrame) {
    var lastTime = 0;
    window.requestAnimationFrame = function(callback) {
        var now = Date.now();
        var nextTime = Math.max(lastTime + 16, now);
        return setTimeout(function() { callback(lastTime = nextTime); },
                          nextTime - now);
    };
    window.cancelAnimationFrame = clearTimeout;
  }
  window.performance = (window.performance || {
    start: Date.now(),
    now: function(){
        return Date.now() - this.start;
    }
  });
})();

// Polyfill to get the name of a function in IE9
function functionName(fn) {
  if (Function.prototype.name === undefined) {
    var funcNameRegex = /function\s([^(]{1,})\(/;
    var results = (funcNameRegex).exec((fn).toString());
    return (results && results.length > 1) ? results[1].trim() : "";
  }
  else if (fn.prototype === undefined) {
    return fn.constructor.name;
  }
  else {
    return fn.prototype.constructor.name;
  }
}

// Convert PascalCase to kebab-case
// Thank you: http://stackoverflow.com/a/8955580
function hyphenate(str) {
  return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
}

}(jQuery);
<|endoftext|>


<commit_before>iD.modes.Select = function(context, selection, initial) {
    var mode = {
        id: 'select',
        button: 'browse'
    };

    // Selecting non-multipolygon relations is not supported
    selection = selection.filter(function(d) {
        return context.entity(d).geometry(context.graph()) !== 'relation';
    });

    if (!selection.length) return iD.modes.Browse(context);

    var inspector = singular() && iD.ui.Inspector(context, singular()),
        keybinding = d3.keybinding('select'),
        timeout = null,
        behaviors = [
            iD.behavior.Hover(),
            iD.behavior.Select(context),
            iD.behavior.Lasso(context),
            iD.modes.DragNode(context).behavior],
        radialMenu;

    var wrap = context.container()
        .select('.inspector-wrap');

    function singular() {
        if (selection.length === 1) {
            return context.entity(selection[0]);
        }
    }

    function positionMenu() {
        var entity = singular();

        if (entity && entity.type === 'node') {
            radialMenu.center(context.projection(entity.loc));
        } else {
            radialMenu.center(d3.mouse(context.surface().node()));
        }
    }

    function showMenu() {
        context.surface()
            .call(radialMenu.close)
            .call(radialMenu);
    }

    mode.selection = function() {
        return selection;
    };

    mode.reselect = function() {
        positionMenu();
        showMenu();
    };

    mode.enter = function() {
        behaviors.forEach(function(behavior) {
            context.install(behavior);
        });

        var operations = _.without(d3.values(iD.operations), iD.operations.Delete)
            .map(function(o) { return o(selection, context); })
            .filter(function(o) { return o.available(); });
        operations.unshift(iD.operations.Delete(selection, context));

        keybinding.on('⎋', function() {
            context.enter(iD.modes.Browse(context));
        }, true);

        operations.forEach(function(operation) {
            operation.keys.forEach(function(key) {
                keybinding.on(key, function() {
                    if (!operation.disabled()) {
                        operation();
                    }
                });
            });
        });

        var q = iD.util.stringQs(location.hash.substring(1));
        location.replace('#' + iD.util.qsString(_.assign(q, {
            id: selection.join(',')
        }), true));

        if (singular()) {
            wrap.call(inspector);
        }

        context.history()
            .on('undone.select', update)
            .on('redone.select', update);

        function update() {
            context.surface().call(radialMenu.close);

            if (_.any(selection, function(id) { return !context.entity(id); })) {
                // Exit mode if selected entity gets undone
                context.enter(iD.modes.Browse(context));
            }
        }

        context.map().on('move.select', function() {
            context.surface().call(radialMenu.close);
        });

        function dblclick() {
            var target = d3.select(d3.event.target),
                datum = target.datum();

            if (datum instanceof iD.Way && !target.classed('fill')) {
                var choice = iD.geo.chooseIndex(datum,
                        d3.mouse(context.surface().node()), context),
                    node = iD.Node();

                var prev = datum.nodes[choice.index - 1],
                    next = datum.nodes[choice.index];

                context.perform(
                    iD.actions.AddMidpoint({loc: choice.loc, edge: [prev, next]}, node),
                    t('operations.add.annotation.vertex'));

                d3.event.preventDefault();
                d3.event.stopPropagation();
            }
        }

        function selected(entity) {
            if (!entity) return false;
            if (selection.indexOf(entity.id) >= 0) return true;
            return d3.select(this) &&
                _.any(context.graph().parentRelations(entity), function(parent) {
                    return selection.indexOf(parent.id) >= 0;
                });
        }

        d3.select(document)
            .call(keybinding);

        function selectElements() {
            context.surface()
                .selectAll("*")
                .filter(selected)
                .classed('selected', true);
        }

        context.map().on('drawn.select', selectElements);
        selectElements();

        radialMenu = iD.ui.RadialMenu(operations);
        var show = d3.event && !initial;

        if (show) {
            positionMenu();
        }

        timeout = window.setTimeout(function() {
            if (show) {
                showMenu();
            }

            context.surface()
                .on('dblclick.select', dblclick);
        }, 200);
    };

    mode.exit = function() {
        if (timeout) window.clearTimeout(timeout);

        if (inspector) wrap.call(inspector.close);

        behaviors.forEach(function(behavior) {
            context.uninstall(behavior);
        });

        var q = iD.util.stringQs(location.hash.substring(1));
        location.replace('#' + iD.util.qsString(_.omit(q, 'id'), true));

        keybinding.off();

        context.history()
            .on('undone.select', null)
            .on('redone.select', null);

        context.surface()
            .call(radialMenu.close)
            .on('dblclick.select', null)
            .selectAll(".selected")
            .classed('selected', false);

        context.map().on('drawn.select', null);
    };

    return mode;
};
<commit_msg>simplify<commit_after>iD.modes.Select = function(context, selection, initial) {
    var mode = {
        id: 'select',
        button: 'browse'
    };

    // Selecting non-multipolygon relations is not supported
    selection = selection.filter(function(d) {
        return context.entity(d).geometry(context.graph()) !== 'relation';
    });

    if (!selection.length) return iD.modes.Browse(context);

    var inspector = singular() && iD.ui.Inspector(context, singular()),
        keybinding = d3.keybinding('select'),
        timeout = null,
        behaviors = [
            iD.behavior.Hover(),
            iD.behavior.Select(context),
            iD.behavior.Lasso(context),
            iD.modes.DragNode(context).behavior],
        radialMenu;

    var wrap = context.container()
        .select('.inspector-wrap');

    function singular() {
        if (selection.length === 1) {
            return context.entity(selection[0]);
        }
    }

    function positionMenu() {
        var entity = singular();

        if (entity && entity.type === 'node') {
            radialMenu.center(context.projection(entity.loc));
        } else {
            radialMenu.center(d3.mouse(context.surface().node()));
        }
    }

    function showMenu() {
        context.surface()
            .call(radialMenu.close)
            .call(radialMenu);
    }

    mode.selection = function() {
        return selection;
    };

    mode.reselect = function() {
        positionMenu();
        showMenu();
    };

    mode.enter = function() {
        behaviors.forEach(function(behavior) {
            context.install(behavior);
        });

        var operations = _.without(d3.values(iD.operations), iD.operations.Delete)
            .map(function(o) { return o(selection, context); })
            .filter(function(o) { return o.available(); });
        operations.unshift(iD.operations.Delete(selection, context));

        keybinding.on('⎋', function() {
            context.enter(iD.modes.Browse(context));
        }, true);

        operations.forEach(function(operation) {
            operation.keys.forEach(function(key) {
                keybinding.on(key, function() {
                    if (!operation.disabled()) {
                        operation();
                    }
                });
            });
        });

        var q = iD.util.stringQs(location.hash.substring(1));
        location.replace('#' + iD.util.qsString(_.assign(q, {
            id: selection.join(',')
        }), true));

        if (singular()) {
            wrap.call(inspector);
        }

        context.history()
            .on('undone.select', update)
            .on('redone.select', update);

        function update() {
            context.surface().call(radialMenu.close);

            if (_.any(selection, function(id) { return !context.entity(id); })) {
                // Exit mode if selected entity gets undone
                context.enter(iD.modes.Browse(context));
            }
        }

        context.map().on('move.select', function() {
            context.surface().call(radialMenu.close);
        });

        function dblclick() {
            var target = d3.select(d3.event.target),
                datum = target.datum();

            if (datum instanceof iD.Way && !target.classed('fill')) {
                var choice = iD.geo.chooseIndex(datum,
                        d3.mouse(context.surface().node()), context),
                    node = iD.Node();

                var prev = datum.nodes[choice.index - 1],
                    next = datum.nodes[choice.index];

                context.perform(
                    iD.actions.AddMidpoint({loc: choice.loc, edge: [prev, next]}, node),
                    t('operations.add.annotation.vertex'));

                d3.event.preventDefault();
                d3.event.stopPropagation();
            }
        }

        function selected(entity) {
            if (!entity) return false;
            if (selection.indexOf(entity.id) >= 0) return true;
            return _.any(context.graph().parentRelations(entity), function(parent) {
                    return selection.indexOf(parent.id) >= 0;
                });
        }

        d3.select(document)
            .call(keybinding);

        function selectElements() {
            context.surface()
                .selectAll("*")
                .filter(selected)
                .classed('selected', true);
        }

        context.map().on('drawn.select', selectElements);
        selectElements();

        radialMenu = iD.ui.RadialMenu(operations);
        var show = d3.event && !initial;

        if (show) {
            positionMenu();
        }

        timeout = window.setTimeout(function() {
            if (show) {
                showMenu();
            }

            context.surface()
                .on('dblclick.select', dblclick);
        }, 200);
    };

    mode.exit = function() {
        if (timeout) window.clearTimeout(timeout);

        if (inspector) wrap.call(inspector.close);

        behaviors.forEach(function(behavior) {
            context.uninstall(behavior);
        });

        var q = iD.util.stringQs(location.hash.substring(1));
        location.replace('#' + iD.util.qsString(_.omit(q, 'id'), true));

        keybinding.off();

        context.history()
            .on('undone.select', null)
            .on('redone.select', null);

        context.surface()
            .call(radialMenu.close)
            .on('dblclick.select', null)
            .selectAll(".selected")
            .classed('selected', false);

        context.map().on('drawn.select', null);
    };

    return mode;
};
<|endoftext|>


<commit_before>"use strict";
var BrowserWindow = require("browser-window");

var mainWindow = new BrowserWindow({
  width: 100,
  height: 100,
  //show: false,
  "node-integration": false,
});
mainWindow.loadUrl("file://" + __dirname + "/index.html");

module.exports = mainWindow;
<commit_msg>Hide window on test<commit_after>"use strict";
var BrowserWindow = require("browser-window");

var mainWindow = new BrowserWindow({
  width: 100,
  height: 100,
  show: false,
  "node-integration": false,
});
mainWindow.loadUrl("file://" + __dirname + "/index.html");

module.exports = mainWindow;
<|endoftext|>


<commit_before>iD.modes.Select = function(context, selection, initial) {
    var mode = {
        id: 'select',
        button: 'browse'
    };

    var showgrid = singular() && !_.without(Object.keys(singular().tags), 'area').length;

    var inspector = iD.ui.Inspector(context).initial(showgrid),
        keybinding = d3.keybinding('select'),
        timeout = null,
        behaviors = [
            iD.behavior.Hover(),
            iD.behavior.Select(context),
            iD.behavior.Lasso(context),
            iD.behavior.DragNode(context)],
        radialMenu;

    function changeTags(d, tags) {
        if (!_.isEqual(singular().tags, tags)) {
            context.perform(
                iD.actions.ChangeTags(d.id, tags),
                t('operations.change_tags.annotation'));
        }
    }

    function singular() {
        if (selection.length === 1) {
            return context.entity(selection[0]);
        }
    }

    function positionMenu() {
        var entity = singular();

        if (entity && entity.type === 'node') {
            radialMenu.center(context.projection(entity.loc));
        } else {
            radialMenu.center(d3.mouse(context.surface().node()));
        }
    }

    function showMenu() {
        context.surface()
            .call(radialMenu.close)
            .call(radialMenu);
    }

    mode.selection = function() {
        return selection;
    };

    mode.reselect = function() {
        positionMenu();
        showMenu();
    };

    mode.enter = function() {
        var entity = singular();

        behaviors.forEach(function(behavior) {
            context.install(behavior);
        });

        var operations = _.without(d3.values(iD.operations), iD.operations.Delete)
            .map(function(o) { return o(selection, context); })
            .filter(function(o) { return o.available(); });
        operations.unshift(iD.operations.Delete(selection, context));

        keybinding.on('⎋', function() {
            context.enter(iD.modes.Browse(context));
        });

        operations.forEach(function(operation) {
            operation.keys.forEach(function(key) {
                keybinding.on(key, function() {
                    if (operation.enabled()) {
                        operation();
                    }
                });
            });
        });

        var q = iD.util.stringQs(location.hash.substring(1));
        location.replace('#' + iD.util.qsString(_.assign(q, {
            id: selection.join(',')
        }), true));

        if (entity) {
            var wrap = context.container()
                .select('.inspector-wrap');

            wrap.style('display', 'block')
                .style('opacity', 1)
                .datum(entity)
                .call(inspector);

            if (d3.event) {
                // Pan the map if the clicked feature intersects with the position
                // of the inspector
                var inspectorSize = wrap.size(),
                    mapSize = context.map().size(),
                    offset = 50,
                    shiftLeft = d3.event.clientX - mapSize[0] + inspectorSize[0] + offset,
                    center = (mapSize[0] / 2) + shiftLeft + offset;

                if (shiftLeft > 0 && inspectorSize[1] > d3.event.clientY) {
                    context.map().centerEase(context.projection.invert([center, mapSize[1]/2]));
                }
            }

            inspector
                .on('changeTags', changeTags)
                .on('close', function() { context.enter(iD.modes.Browse(context)); });
        }

        context.history()
            .on('undone.select', updateInspector)
            .on('redone.select', updateInspector);

        function updateInspector() {
            context.surface().call(radialMenu.close);

            if (_.any(selection, function(id) { return !context.entity(id); })) {
                // Exit mode if selected entity gets undone
                context.enter(iD.modes.Browse(context));

            } else if (singular()) {
                inspector.tags(context.entity(selection[0]).tags);
            }
        }

        context.map().on('move.select', function() {
            context.surface().call(radialMenu.close);
        });

        function dblclick() {
            var target = d3.select(d3.event.target),
                datum = target.datum();

            if (datum instanceof iD.Way && !target.classed('fill')) {
                var choice = iD.geo.chooseIndex(datum,
                        d3.mouse(context.surface().node()), context),
                    node = iD.Node();

                var prev = datum.nodes[choice.index - 1],
                    next = datum.nodes[choice.index];

                context.perform(
                    iD.actions.AddMidpoint({loc: choice.loc, edge: [prev, next]}, node),
                    t('operations.add.annotation.vertex'));

                d3.event.preventDefault();
                d3.event.stopPropagation();
            }
        }

        function selected(entity) {
            if (!entity) return false;
            if (selection.indexOf(entity.id) >= 0) return true;
            return d3.select(this).classed('stroke') &&
                _.any(context.graph().parentRelations(entity), function(parent) {
                    return selection.indexOf(parent.id) >= 0;
                });
        }

        d3.select(document)
            .call(keybinding);

        context.surface()
            .selectAll("*")
            .filter(selected)
            .classed('selected', true);

        radialMenu = iD.ui.RadialMenu(operations);
        var show = d3.event && !initial;

        if (show) {
            positionMenu();
        }

        timeout = window.setTimeout(function() {
            if (show) {
                showMenu();
            }

            context.surface()
                .on('dblclick.select', dblclick);
        }, 200);
    };

    mode.exit = function() {
        if (timeout) window.clearTimeout(timeout);

        context.container()
            .select('.inspector-wrap')
            .style('display', 'none')
            .html('');

        // Firefox incorrectly implements blur, so typeahead elements
        // are not correctly removed. Remove any stragglers manually.
        d3.selectAll('div.typeahead').remove();

        behaviors.forEach(function(behavior) {
            context.uninstall(behavior);
        });

        var q = iD.util.stringQs(location.hash.substring(1));
        location.replace('#' + iD.util.qsString(_.omit(q, 'id'), true));

        keybinding.off();

        context.history()
            .on('undone.select', null)
            .on('redone.select', null);

        context.surface()
            .call(radialMenu.close)
            .on('dblclick.select', null)
            .selectAll(".selected")
            .classed('selected', false);
    };

    return mode;
};
<commit_msg>use capture for esc in select mode<commit_after>iD.modes.Select = function(context, selection, initial) {
    var mode = {
        id: 'select',
        button: 'browse'
    };

    var showgrid = singular() && !_.without(Object.keys(singular().tags), 'area').length;

    var inspector = iD.ui.Inspector(context).initial(showgrid),
        keybinding = d3.keybinding('select'),
        timeout = null,
        behaviors = [
            iD.behavior.Hover(),
            iD.behavior.Select(context),
            iD.behavior.Lasso(context),
            iD.behavior.DragNode(context)],
        radialMenu;

    function changeTags(d, tags) {
        if (!_.isEqual(singular().tags, tags)) {
            context.perform(
                iD.actions.ChangeTags(d.id, tags),
                t('operations.change_tags.annotation'));
        }
    }

    function singular() {
        if (selection.length === 1) {
            return context.entity(selection[0]);
        }
    }

    function positionMenu() {
        var entity = singular();

        if (entity && entity.type === 'node') {
            radialMenu.center(context.projection(entity.loc));
        } else {
            radialMenu.center(d3.mouse(context.surface().node()));
        }
    }

    function showMenu() {
        context.surface()
            .call(radialMenu.close)
            .call(radialMenu);
    }

    mode.selection = function() {
        return selection;
    };

    mode.reselect = function() {
        positionMenu();
        showMenu();
    };

    mode.enter = function() {
        var entity = singular();

        behaviors.forEach(function(behavior) {
            context.install(behavior);
        });

        var operations = _.without(d3.values(iD.operations), iD.operations.Delete)
            .map(function(o) { return o(selection, context); })
            .filter(function(o) { return o.available(); });
        operations.unshift(iD.operations.Delete(selection, context));

        keybinding.on('⎋', function() {
            context.enter(iD.modes.Browse(context));
        }, true);

        operations.forEach(function(operation) {
            operation.keys.forEach(function(key) {
                keybinding.on(key, function() {
                    if (operation.enabled()) {
                        operation();
                    }
                });
            });
        });

        var q = iD.util.stringQs(location.hash.substring(1));
        location.replace('#' + iD.util.qsString(_.assign(q, {
            id: selection.join(',')
        }), true));

        if (entity) {
            var wrap = context.container()
                .select('.inspector-wrap');

            wrap.style('display', 'block')
                .style('opacity', 1)
                .datum(entity)
                .call(inspector);

            if (d3.event) {
                // Pan the map if the clicked feature intersects with the position
                // of the inspector
                var inspectorSize = wrap.size(),
                    mapSize = context.map().size(),
                    offset = 50,
                    shiftLeft = d3.event.clientX - mapSize[0] + inspectorSize[0] + offset,
                    center = (mapSize[0] / 2) + shiftLeft + offset;

                if (shiftLeft > 0 && inspectorSize[1] > d3.event.clientY) {
                    context.map().centerEase(context.projection.invert([center, mapSize[1]/2]));
                }
            }

            inspector
                .on('changeTags', changeTags)
                .on('close', function() { context.enter(iD.modes.Browse(context)); });
        }

        context.history()
            .on('undone.select', updateInspector)
            .on('redone.select', updateInspector);

        function updateInspector() {
            context.surface().call(radialMenu.close);

            if (_.any(selection, function(id) { return !context.entity(id); })) {
                // Exit mode if selected entity gets undone
                context.enter(iD.modes.Browse(context));

            } else if (singular()) {
                inspector.tags(context.entity(selection[0]).tags);
            }
        }

        context.map().on('move.select', function() {
            context.surface().call(radialMenu.close);
        });

        function dblclick() {
            var target = d3.select(d3.event.target),
                datum = target.datum();

            if (datum instanceof iD.Way && !target.classed('fill')) {
                var choice = iD.geo.chooseIndex(datum,
                        d3.mouse(context.surface().node()), context),
                    node = iD.Node();

                var prev = datum.nodes[choice.index - 1],
                    next = datum.nodes[choice.index];

                context.perform(
                    iD.actions.AddMidpoint({loc: choice.loc, edge: [prev, next]}, node),
                    t('operations.add.annotation.vertex'));

                d3.event.preventDefault();
                d3.event.stopPropagation();
            }
        }

        function selected(entity) {
            if (!entity) return false;
            if (selection.indexOf(entity.id) >= 0) return true;
            return d3.select(this).classed('stroke') &&
                _.any(context.graph().parentRelations(entity), function(parent) {
                    return selection.indexOf(parent.id) >= 0;
                });
        }

        d3.select(document)
            .call(keybinding);

        context.surface()
            .selectAll("*")
            .filter(selected)
            .classed('selected', true);

        radialMenu = iD.ui.RadialMenu(operations);
        var show = d3.event && !initial;

        if (show) {
            positionMenu();
        }

        timeout = window.setTimeout(function() {
            if (show) {
                showMenu();
            }

            context.surface()
                .on('dblclick.select', dblclick);
        }, 200);
    };

    mode.exit = function() {
        if (timeout) window.clearTimeout(timeout);

        context.container()
            .select('.inspector-wrap')
            .style('display', 'none')
            .html('');

        // Firefox incorrectly implements blur, so typeahead elements
        // are not correctly removed. Remove any stragglers manually.
        d3.selectAll('div.typeahead').remove();

        behaviors.forEach(function(behavior) {
            context.uninstall(behavior);
        });

        var q = iD.util.stringQs(location.hash.substring(1));
        location.replace('#' + iD.util.qsString(_.omit(q, 'id'), true));

        keybinding.off();

        context.history()
            .on('undone.select', null)
            .on('redone.select', null);

        context.surface()
            .call(radialMenu.close)
            .on('dblclick.select', null)
            .selectAll(".selected")
            .classed('selected', false);
    };

    return mode;
};
<|endoftext|>


<commit_before>var test = require('tap').test;
var makeActive = require('../lib/makeActive.js');

test('it can listen to actived objects', function(t) {
  var obj = makeActive({ name: 'John' });

  obj.connect('name', onNameChanged);
  obj.name = 'Bob';

  function onNameChanged(model) {
    t.ok(model === obj, 'model is the same as source object');
    t.equals(model.name, 'Bob', 'Name is changed');
    t.end();
  }
});

test('it can unsubscribe from activated objects', function(t) {
  var obj = makeActive({ name: 'John' });
  var calledCount = 0;

  obj.connect('name', onNameChanged);
  obj.name = 'Bob';
  obj.disconnect('name', onNameChanged);
  obj.name = 'Shmob';
  t.equals(calledCount, 1, 'Called exactly once');
  t.end();

  function onNameChanged() {
    calledCount += 1;
    t.equals(calledCount, 1, 'Called once!');
  }
});

test('it can listen to nested objects', function(t) {
  var obj = makeActive({ user: {name: 'John' }});
  obj.connect('user.name', onNameChanged);
  obj.user.name = 'Bob';

  function onNameChanged(model) {
    t.ok(model === obj, 'model is the same as source object');
    t.equals(model.user.name, 'Bob', 'Name is changed');
    t.end();
  }
});

test('it can listen to nested object parents', function(t) {
  var obj = makeActive({ user: {name: 'John' }});
  obj.connect('user', onNameChanged);
  obj.user = {
    name: 'Bob'
  };

  function onNameChanged(model) {
    t.ok(model === obj, 'model is the same as source object');
    t.equals(model.user.name, 'Bob', 'Name is changed');
    t.end();
  }
});

test('it can unsubscribe from nested objects', function(t) {
  var calledCount = 0;
  var obj = makeActive({ user: {name: 'John' }});
  obj.connect('user.name', onNameChanged);
  obj.user.name = 'Bob';
  obj.disconnect('user.name', onNameChanged);
  obj.user.name = 'Shmob';
  t.equals(calledCount, 1, 'Called exactly once');
  t.end();

  function onNameChanged() {
    calledCount += 1;
    t.equals(calledCount, 1, 'Called once!');
  }
});
<commit_msg>Added more coposite changes<commit_after>var test = require('tap').test;
var makeActive = require('../lib/makeActive.js');

test('it can listen to actived objects', function(t) {
  var obj = makeActive({ name: 'John' });

  obj.connect('name', onNameChanged);
  obj.name = 'Bob';

  function onNameChanged(model) {
    t.ok(model === obj, 'model is the same as source object');
    t.equals(model.name, 'Bob', 'Name is changed');
    t.end();
  }
});

test('it can unsubscribe from activated objects', function(t) {
  var obj = makeActive({ name: 'John' });
  var calledCount = 0;

  obj.connect('name', onNameChanged);
  obj.name = 'Bob';
  obj.disconnect('name', onNameChanged);
  obj.name = 'Shmob';
  t.equals(calledCount, 1, 'Called exactly once');
  t.end();

  function onNameChanged() {
    calledCount += 1;
    t.equals(calledCount, 1, 'Called once!');
  }
});

test('it can listen to nested objects', function(t) {
  var obj = makeActive({ user: {name: 'John' }});
  obj.connect('user.name', onNameChanged);
  obj.user.name = 'Bob';

  function onNameChanged(model) {
    t.ok(model === obj, 'model is the same as source object');
    t.equals(model.user.name, 'Bob', 'Name is changed');
    t.end();
  }
});

test('it can listen to nested object parents', function(t) {
  var obj = makeActive({ user: {name: 'John' }});
  obj.connect('user', onNameChanged);
  obj.user = {
    name: 'Bob'
  };

  function onNameChanged(model) {
    t.ok(model === obj, 'model is the same as source object');
    t.equals(model.user.name, 'Bob', 'Name is changed');
    t.end();
  }
});

test('it can unsubscribe from nested objects', function(t) {
  var calledCount = 0;
  var obj = makeActive({ user: {name: 'John' }});
  obj.connect('user.name', onNameChanged);
  obj.user.name = 'Bob';
  obj.disconnect('user.name', onNameChanged);
  obj.user.name = 'Shmob';
  t.equals(calledCount, 1, 'Called exactly once');
  t.end();

  function onNameChanged() {
    calledCount += 1;
    t.equals(calledCount, 1, 'Called once!');
  }
});

test('it can listen to both nested and parent objects', function(t) {
  var bobChanged = 0;
  var userChanged = 0;
  var obj = makeActive({ user: {name: 'John' }});
  obj.connect({
    'user.name': onBobChanged,
    user: onUserChanged
  });

  obj.user.name = 'Bob';
  obj.user = 'oops!'

  t.equals(bobChanged, 1, 'bob called exactly once');
  t.equals(userChanged, 1, 'user called exactly once');
  t.end();

  function onBobChanged() {
    bobChanged += 1;
    t.equals(bobChanged, 1, 'bob changed once');
  }

  function onUserChanged() {
    userChanged += 1;
    t.equals(userChanged, 1, 'user changed once');
  }
  t.end();
});
<|endoftext|>


<commit_before>/**
 * The MIT License (MIT)
 * Copyright (c) 2014 Andreas Tscheinig
 * See LICENSE file in ImageLoader.js repository for the full text of license.
 */
ImageLoader=(function(){var g=[],d=[];var a=function(){};function f(){var j,h,k=true;for(j=0;j<g.length;j++){h=g[j];if(!h.ready){k=false}}return k}function e(j){var h,i;if(c(j.key)){return}h=document.createElement("img");j.ready=false;g.push({key:j.key,ready:false});h.onload=function(){b(j.key,h,false)};h.onerror=function(){b(j.key,h,true)};h.src=j.url}function b(l,h,j){res=c(l);if(res){res.ready=true;res.image=j?null:h}if(f()){for(var k=0;k<d.length;k++){d[k]()}}}function c(k){var l=null,j;for(var h=0;h<g.length;h++){j=g[h];if(j.key===k){l=j;break}}return l}a.prototype.startQueue=function(h){if(h instanceof Array){for(var j=0;j<h.length;j++){e(h[j])}}else{e(h)}};a.prototype.onReady=function(h){d.push(h)};a.prototype.get=function(h){return c(h)};return a})();
<commit_msg>Update imageLoader-min.js<commit_after>/**
 * The MIT License (MIT)
 * Copyright (c) 2014 Andreas Tscheinig
 * See LICENSE file in ImageLoader.js repository for the full text of license.
 */
ImageLoader=(function(){var g=[],d=[];var a=function(h){this.onReady(h)};function f(){var j,h,k=true;for(j=0;j<g.length;j++){h=g[j];if(!h.ready){k=false}}return k}function e(j){var h,i;if(c(j.key)){return}h=document.createElement("img");j.ready=false;g.push({key:j.key,ready:false});h.onload=function(){b(j.key,h,false)};h.onerror=function(){b(j.key,h,true)};h.src=j.url}function b(l,h,j){res=c(l);if(res){res.ready=true;res.image=j?null:h}if(f()){for(var k=0;k<d.length;k++){d[k]()}}}function c(k){var l=null,j;for(var h=0;h<g.length;h++){j=g[h];if(j.key===k){l=j;break}}return l}a.prototype.startQueue=function(h){if(h instanceof Array){for(var j=0;j<h.length;j++){e(h[j])}}else{e(h)}};a.prototype.onReady=function(h){if(h instanceof Array){d=d.concat(h)}else{if(typeof h==="function"){d.push(h)}}};a.prototype.get=function(h){return c(h)};return a})();
<|endoftext|>


<commit_before>const test = require('tape');
const Mark = require('./../mark.js');
const selector = require('./../lib/mark.query.js');

test('Mark Select', function(assert) {
	let vtree = Mark.parse("{div {span class:'bold', width:'100px' 'text' {b 'bold'}} {br}}");
	assert.equal(selector(vtree).find("span.bold").length, 1, "Match span.bold");
	assert.equal(vtree.find("span.bold").length, 1, "Match span.bold");
	assert.equal(vtree.find("span[width='100px']").length, 1, "Match span[width='100px']");
	assert.equal(vtree.find("div > span.bold").length, 1, "Match div > span.bold");
	assert.equal(vtree.find("div").length, 0, "Find should not match on div itself");

	assert.equal(vtree.matches("div"), true, "vtree should match div");
	assert.equal(vtree[0].matches("div span"), true, "span should match 'div span'");
	assert.equal(vtree[0].matches("div >> span"), true, "span should match 'div >> span'");
	assert.equal(vtree[0].matches("div > span"), true, "span should match 'div > span'");
	assert.equal(vtree[0][1].matches("div >> b"), true, "b should match 'div >> v'");
	assert.end();
});<commit_msg>Add test.<commit_after>const test = require('tape');
const Mark = require('./../mark.js');
const selector = require('./../lib/mark.query.js');

test('Mark Select', function(assert) {
	let vtree = Mark.parse("{div {span class:'bold', width:'100px' 'text' {b 'bold'}} {br}}");
	assert.equal(selector(vtree).find("span.bold").length, 1, "Match span.bold");
	assert.equal(vtree.find("span.bold").length, 1, "Match span.bold");
	assert.equal(vtree.find("span[width='100px']").length, 1, "Match span[width='100px']");
	assert.equal(vtree.find("div > span.bold").length, 1, "Match div > span.bold");
	assert.equal(vtree.find("div").length, 0, "Find should not match on div itself");
	assert.equal(vtree.find("[width]").length, 1, "Find [width] should have 1 match");

	assert.equal(vtree.matches("div"), true, "vtree should match div");
	assert.equal(vtree[0].matches("div span"), true, "span should match 'div span'");
	assert.equal(vtree[0].matches("div >> span"), true, "span should match 'div >> span'");
	assert.equal(vtree[0].matches("div > span"), true, "span should match 'div > span'");
	assert.equal(vtree[0][1].matches("div >> b"), true, "b should match 'div >> v'");
	assert.end();
});<|endoftext|>


<commit_before>$(function() {

	var postURLs,
      isFetchingPosts = false,
			shouldFetchPosts = true,
			postsToLoad = $(".posts").children().length,
			loadNewPostsThreshold = 3000;

  // Load the JSON file containing all URLs
	$.getJSON('/all-posts.json', function(data) {
		postURLs = data["posts"];
	});

	// If there's no spinner, it's not a page where posts should be fetched
	if ($(".infinite-spinner").length < 1)
		shouldFetchPosts = false;

	// Are we close to the end of the page? If we are, load more posts
	$(window).scroll(function(e){
		if (!shouldFetchPosts || isFetchingPosts) return;

		var windowHeight = $(window).height();
		var windowScrollPosition = $(window).scrollTop();
		var bottomScrollPosition = windowHeight + windowScrollPosition;
		var documentHeight = $(document).height();

    // If we've scrolled past the loadNewPostsThreshold, fetch posts
		if ((documentHeight - loadNewPostsThreshold) < bottomScrollPosition) {
			fetchPosts();
		}
	});

  // Fetch a chunk of posts
	function fetchPosts() {
    // Exit if postURLs haven't been loaded
    if (!postURLs) return;

		isFetchingPosts = true;

    // Load as many posts as there were present on the page when it loaded
    // After successfully loading a post, load the next one
		var loadedPosts = 0,
				postCount = $(".posts").children().length,
				callback = function() {
					loadedPosts++;
					var postIndex = postCount + loadedPosts;

					if (postIndex > postURLs.length-1) {
						disableFetching();
						return;
					}

					if (loadedPosts < postsToLoad) {
						fetchPostWithIndex(postIndex, callback);
					} else {
						isFetchingPosts = false;
					}
				};

		fetchPostWithIndex(postCount + loadedPosts, callback);
	}

	function fetchPostWithIndex(index, callback) {
		var postURL = postURLs[index];

		$.get(postURL, function(data) {
			$(data).find(".post").appendTo(".blog-posts");
			callback();
		});
	}

	function disableFetching() {
		shouldFetchPosts = false;
		isFetchingPosts = false;
		$(".infinite-spinner").fadeOut();
	}

});
<commit_msg>:lipstick: formatting<commit_after>$(function() {

  var postURLs,
      isFetchingPosts = false,
      shouldFetchPosts = true,
      postsToLoad = $(".posts").children().length,
      loadNewPostsThreshold = 3000;

  // Load the JSON file containing all URLs
  $.getJSON('/all-posts.json', function(data) {
    postURLs = data["posts"];
  });

  // If there's no spinner, it's not a page where posts should be fetched
  if ($(".infinite-spinner").length < 1)
    shouldFetchPosts = false;

  // Are we close to the end of the page? If we are, load more posts
  $(window).scroll(function(e){
    if (!shouldFetchPosts || isFetchingPosts) return;

    var windowHeight = $(window).height();
    var windowScrollPosition = $(window).scrollTop();
    var bottomScrollPosition = windowHeight + windowScrollPosition;
    var documentHeight = $(document).height();

    // If we've scrolled past the loadNewPostsThreshold, fetch posts
    if ((documentHeight - loadNewPostsThreshold) < bottomScrollPosition) {
      fetchPosts();
    }
  });

  // Fetch a chunk of posts
  function fetchPosts() {
    // Exit if postURLs haven't been loaded
    if (!postURLs) return;

    isFetchingPosts = true;

    // Load as many posts as there were present on the page when it loaded
    // After successfully loading a post, load the next one
    var loadedPosts = 0,
        postCount = $(".posts").children().length,
        callback = function() {
          loadedPosts++;
          var postIndex = postCount + loadedPosts;

          if (postIndex > postURLs.length-1) {
            disableFetching();
            return;
          }

          if (loadedPosts < postsToLoad) {
            fetchPostWithIndex(postIndex, callback);
          } else {
            isFetchingPosts = false;
          }
        };

    fetchPostWithIndex(postCount + loadedPosts, callback);
  }

  function fetchPostWithIndex(index, callback) {
    var postURL = postURLs[index];

    $.get(postURL, function(data) {
      $(data).find(".post").appendTo(".blog-posts");
      callback();
    });
  }

  function disableFetching() {
    shouldFetchPosts = false;
    isFetchingPosts = false;
    $(".infinite-spinner").fadeOut();
  }

});
<|endoftext|>