<commit_before>// Copyright 2017-2019, University of Colorado Boulder

/**
 * Deploys a decaf simulation after incrementing the test version number.  This file ported from dev.js
 *
 * @author Sam Reid (PhET Interactive Simulations)
 */

'use strict';

const execute = require( '../../common/execute' );
const copyFile = require( '../../common/copyFile' );
const getPreloads = require( './getPreloads' );
const SimVersion = require( '../../common/SimVersion' );
const gitRevParse = require( '../../common/gitRevParse' );
const loadJSON = require( '../../common/loadJSON' );
const writeJSON = require( '../../common/writeJSON' );
const fs = require( 'fs' );
const _ = require( 'lodash' ); // eslint-disable-line

const TRUNK = '/Users/samreid/phet-svn-trunk-2020';
/**
 * Deploys a dev version after incrementing the test version number.
 * @public
 *
 * @param {string} project
 * @returns {Promise}
 */
module.exports = async function( project ) {

  console.log( 'building project: ' + project );

  // // // Command obtained from running in IntelliJ IDEA with the given .project.
  await execute( '/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/bin/java', [
      '-Dfile.encoding=UTF-8',
      '-classpath',
      '/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/jre/lib/charsets.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/jre/lib/deploy.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/jre/lib/ext/cldrdata.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/jre/lib/ext/dnsns.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/jre/lib/ext/jaccess.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/jre/lib/ext/jfxrt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/jre/lib/ext/localedata.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/jre/lib/ext/nashorn.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/jre/lib/ext/sunec.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/jre/lib/ext/sunjce_provider.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/jre/lib/ext/sunpkcs11.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/jre/lib/ext/zipfs.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/jre/lib/javaws.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/jre/lib/jce.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/jre/lib/jfr.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/jre/lib/jfxswt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/jre/lib/jsse.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/jre/lib/management-agent.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/jre/lib/plugin.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/jre/lib/resources.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/jre/lib/rt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/lib/ant-javafx.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/lib/dt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/lib/javafx-mx.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/lib/jconsole.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/lib/packager.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/lib/sa-jdi.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/lib/tools.jar:/Users/samreid/phet-svn-trunk-2020-output/production/build-tools:/Users/samreid/phet-svn-trunk-2020-output/production/flash-launcher:/Users/samreid/phet-svn-trunk-2020/simulations-flash/flash-launcher/data:/Users/samreid/phet-svn-trunk-2020-output/production/phetcommon:/Users/samreid/phet-svn-trunk-2020/simulations-java/common/phetcommon/data:/Users/samreid/phet-svn-trunk-2020/simulations-java/contrib/junit/junit.jar:/Users/samreid/phet-svn-trunk-2020/simulations-java/contrib/javaws/jnlp.jar:/Users/samreid/phet-svn-trunk-2020-output/production/think-tank-maths:/Users/samreid/phet-svn-trunk-2020/simulations-java/contrib/mongodb/mongo-2.7.2.jar:/Users/samreid/phet-svn-trunk-2020/simulations-java/contrib/lombok/lombok.jar:/Users/samreid/phet-svn-trunk-2020/simulations-java/contrib/functionaljava/functionaljava-3.1.jar:/Users/samreid/phet-svn-trunk-2020/build-tools/contrib/jsch/jsch.jar:/Users/samreid/phet-svn-trunk-2020/build-tools/contrib/apache-ant/lib/ant.jar:/Users/samreid/phet-svn-trunk-2020/build-tools/contrib/proguard/lib/proguard.jar:/Users/samreid/phet-svn-trunk-2020/build-tools/contrib/yuicompressor/yuicompressor-2.4.4.jar:/Users/samreid/phet-svn-trunk-2020/build-tools/contrib/scala/scala-library.jar:/Users/samreid/phet-svn-trunk-2020/build-tools/contrib/scala/scala-compiler.jar:/Users/samreid/phet-svn-trunk-2020/build-tools/contrib/apache-ant/lib/ant-launcher.jar:/Users/samreid/phet-svn-trunk-2020/build-tools/contrib/commons-lang/commons-lang.jar:/Users/samreid/phet-svn-trunk-2020/build-tools/contrib/jgit/org.eclipse.jgit-1.1.0.201109151100-r.jar:/Users/samreid/phet-svn-trunk-2020/build-tools/contrib/closure-compiler/compiler.jar',
      'edu.colorado.phet.buildtools.BuildScript',
      TRUNK,
      project
    ]
  );
  console.log( 'Java build complete' );

  const allJar = `/Users/samreid/apache-document-root/main/decaf/projects/${project}/build/${project}_all.jar`;
  await copyFile( `${TRUNK}/simulations-java/simulations/${project}/deploy/${project}_all.jar`, allJar );
  console.log( 'copied' );

  await execute( '/Applications/cheerpj/cheerpjfy.py', [ allJar ] );
  console.log( 'cheerpjed' );

  const url = `http://localhost/main/decaf/html?project=${project}`;
  console.log( `awaiting preloads via puppeteer at url = ${url}` );
  const preloadResources = await getPreloads( url );
  console.log( 'We have the preloads!\n' + preloadResources );

  const packageFileRelative = `projects/${project}/package.json`;
  const packageFile = `../decaf/${packageFileRelative}`;
  const packageObject = await loadJSON( packageFile );
  const previousVersion = SimVersion.parse( packageObject.version );

  // Bump the version
  const version = new SimVersion( previousVersion.major, previousVersion.minor, previousVersion.maintenance, {
    testType: 'dev',
    testNumber: previousVersion.testNumber + 1
  } );
  packageObject.version = version.toString();
  await writeJSON( packageFile, packageObject );

  const versionString = version.toString();

  let html = fs.readFileSync( '../decaf/html/index.html', 'utf-8' );
  html = html.split( '{{PROJECT}}' ).join( project );
  html = html.split( '{{VERSION}}' ).join( versionString );
  html = html.split( '{{IS_BUILT}}' ).join( 'true' );
  html = html.split( '\'{{PRELOAD_RESOURCES}}\'' ).join( preloadResources );
  const buildDir = `../decaf/projects/${project}/build/`;
  try {
    fs.mkdirSync( buildDir );
  }
  catch( e ) {
    console.log( 'perhaps the build directory exists' );
  }
  fs.writeFileSync( `${buildDir}/${project}.html`, html );

  await copyFile( '../decaf/html/style.css', `${buildDir}/style.css` );
  await copyFile( '../decaf/html/splash.gif', `${buildDir}/splash.gif` );

  const decafSHA = await gitRevParse( 'decaf', 'HEAD' );
  const chipperSHA = await gitRevParse( 'chipper', 'HEAD' );

  const svnInfo = await execute( 'svn', [ 'info' ], '/Users/samreid/phet-svn-trunk-2020' );

  const dependencies = {
    version: versionString,
    decaf: decafSHA,
    notes: 'The decaf sha is from before the version commit.',
    chipper: chipperSHA,
    svnInfo: svnInfo
  };
  console.log( dependencies );
  await writeJSON( `${buildDir}/dependencies.json`, dependencies );

  console.log( `build and ready for local testing: http://localhost/main/decaf/projects/${project}/build/${project}.html?testLocalBuild=true` );
};
<commit_msg>Clean up output, see https://github.com/phetsims/decaf/issues/76<commit_after>// Copyright 2017-2019, University of Colorado Boulder

/**
 * Deploys a decaf simulation after incrementing the test version number.  This file ported from dev.js
 *
 * @author Sam Reid (PhET Interactive Simulations)
 */

'use strict';

const execute = require( '../../common/execute' );
const copyFile = require( '../../common/copyFile' );
const getPreloads = require( './getPreloads' );
const SimVersion = require( '../../common/SimVersion' );
const gitRevParse = require( '../../common/gitRevParse' );
const loadJSON = require( '../../common/loadJSON' );
const writeJSON = require( '../../common/writeJSON' );
const fs = require( 'fs' );
const _ = require( 'lodash' ); // eslint-disable-line

const TRUNK = '/Users/samreid/phet-svn-trunk-2020';
/**
 * Deploys a dev version after incrementing the test version number.
 * @public
 *
 * @param {string} project
 * @returns {Promise}
 */
module.exports = async function( project ) {

  console.log( 'building project: ' + project );

  // // // Command obtained from running in IntelliJ IDEA with the given .project.
  await execute( '/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/bin/java', [
      '-Dfile.encoding=UTF-8',
      '-classpath',
      '/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/jre/lib/charsets.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/jre/lib/deploy.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/jre/lib/ext/cldrdata.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/jre/lib/ext/dnsns.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/jre/lib/ext/jaccess.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/jre/lib/ext/jfxrt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/jre/lib/ext/localedata.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/jre/lib/ext/nashorn.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/jre/lib/ext/sunec.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/jre/lib/ext/sunjce_provider.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/jre/lib/ext/sunpkcs11.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/jre/lib/ext/zipfs.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/jre/lib/javaws.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/jre/lib/jce.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/jre/lib/jfr.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/jre/lib/jfxswt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/jre/lib/jsse.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/jre/lib/management-agent.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/jre/lib/plugin.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/jre/lib/resources.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/jre/lib/rt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/lib/ant-javafx.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/lib/dt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/lib/javafx-mx.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/lib/jconsole.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/lib/packager.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/lib/sa-jdi.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/lib/tools.jar:/Users/samreid/phet-svn-trunk-2020-output/production/build-tools:/Users/samreid/phet-svn-trunk-2020-output/production/flash-launcher:/Users/samreid/phet-svn-trunk-2020/simulations-flash/flash-launcher/data:/Users/samreid/phet-svn-trunk-2020-output/production/phetcommon:/Users/samreid/phet-svn-trunk-2020/simulations-java/common/phetcommon/data:/Users/samreid/phet-svn-trunk-2020/simulations-java/contrib/junit/junit.jar:/Users/samreid/phet-svn-trunk-2020/simulations-java/contrib/javaws/jnlp.jar:/Users/samreid/phet-svn-trunk-2020-output/production/think-tank-maths:/Users/samreid/phet-svn-trunk-2020/simulations-java/contrib/mongodb/mongo-2.7.2.jar:/Users/samreid/phet-svn-trunk-2020/simulations-java/contrib/lombok/lombok.jar:/Users/samreid/phet-svn-trunk-2020/simulations-java/contrib/functionaljava/functionaljava-3.1.jar:/Users/samreid/phet-svn-trunk-2020/build-tools/contrib/jsch/jsch.jar:/Users/samreid/phet-svn-trunk-2020/build-tools/contrib/apache-ant/lib/ant.jar:/Users/samreid/phet-svn-trunk-2020/build-tools/contrib/proguard/lib/proguard.jar:/Users/samreid/phet-svn-trunk-2020/build-tools/contrib/yuicompressor/yuicompressor-2.4.4.jar:/Users/samreid/phet-svn-trunk-2020/build-tools/contrib/scala/scala-library.jar:/Users/samreid/phet-svn-trunk-2020/build-tools/contrib/scala/scala-compiler.jar:/Users/samreid/phet-svn-trunk-2020/build-tools/contrib/apache-ant/lib/ant-launcher.jar:/Users/samreid/phet-svn-trunk-2020/build-tools/contrib/commons-lang/commons-lang.jar:/Users/samreid/phet-svn-trunk-2020/build-tools/contrib/jgit/org.eclipse.jgit-1.1.0.201109151100-r.jar:/Users/samreid/phet-svn-trunk-2020/build-tools/contrib/closure-compiler/compiler.jar',
      'edu.colorado.phet.buildtools.BuildScript',
      TRUNK,
      project
    ]
  );
  console.log( 'Java build complete' );

  const allJar = `/Users/samreid/apache-document-root/main/decaf/projects/${project}/build/${project}_all.jar`;
  await copyFile( `${TRUNK}/simulations-java/simulations/${project}/deploy/${project}_all.jar`, allJar );
  console.log( 'copied' );

  await execute( '/Applications/cheerpj/cheerpjfy.py', [ allJar ] );
  console.log( 'cheerpjed' );

  const url = `http://localhost/main/decaf/html?project=${project}`;
  console.log( `awaiting preloads via puppeteer at url = ${url}` );
  const preloadResources = await getPreloads( url );
  console.log( 'We have the preloads!\n' + preloadResources );

  const packageFileRelative = `projects/${project}/package.json`;
  const packageFile = `../decaf/${packageFileRelative}`;
  const packageObject = await loadJSON( packageFile );
  const previousVersion = SimVersion.parse( packageObject.version );

  // Bump the version
  const version = new SimVersion( previousVersion.major, previousVersion.minor, previousVersion.maintenance, {
    testType: 'dev',
    testNumber: previousVersion.testNumber + 1
  } );
  packageObject.version = version.toString();
  await writeJSON( packageFile, packageObject );

  const versionString = version.toString();

  let html = fs.readFileSync( '../decaf/html/index.html', 'utf-8' );
  html = html.split( '{{PROJECT}}' ).join( project );
  html = html.split( '{{VERSION}}' ).join( versionString );
  html = html.split( '{{IS_BUILT}}' ).join( 'true' );
  html = html.split( '\'{{PRELOAD_RESOURCES}}\'' ).join( preloadResources );
  const buildDir = `../decaf/projects/${project}/build/`;
  try {
    fs.mkdirSync( buildDir );
  }
  catch( e ) {
    console.log( 'perhaps the build directory exists' );
  }
  fs.writeFileSync( `${buildDir}/${project}.html`, html );

  await copyFile( '../decaf/html/style.css', `${buildDir}/style.css` );
  await copyFile( '../decaf/html/splash.gif', `${buildDir}/splash.gif` );

  const decafSHA = await gitRevParse( 'decaf', 'HEAD' );
  const chipperSHA = await gitRevParse( 'chipper', 'HEAD' );

  const svnInfo = await execute( 'svn', [ 'info' ], '/Users/samreid/phet-svn-trunk-2020' );

  const dependencies = {
    version: versionString,
    decaf: decafSHA,
    notes: 'The decaf sha is from before the version commit.',
    chipper: chipperSHA,
    svnInfo: svnInfo
  };
  console.log( dependencies );
  await writeJSON( `${buildDir}/dependencies.json`, dependencies );

  console.log( `build and ready for local testing: http://localhost/main/decaf/projects/${project}/build/${project}.html` );
};
<|endoftext|>


<commit_before>import { request } from './utils'
import store from './store'
import { bindActionCreators } from 'redux'
import config from './config'
import * as Modal from './components/Modal/actions'
import { notify, NOTIFY_TYPE } from './components/Notification/actions'
import { addComToSideBar } from './components/Panel/actions'

export default class {
  // app data
  constructor (config = {}) {
    this.subscribeDataArray = config.subscribeDataArray || []
    this.pkgId = config.pkgId || ''
  }
  getData () {
    const currentStore = store.getState()
    return this.subscribeDataArray.reduce((p, v) => {
      p[v] = currentStore[v] || {}
      return p
    }, {})
  }
  subscribeStore (func) {
    if (!func) return
    store.subscribe(func(this.getData()))
  }
  get utils () {
    return ({
      request,
    })
  }

  get injectComponent () {
    return ({
      addComToSideBar
    })
  }
  get config () {
    return config
  }
  get Modal () {
    return bindActionCreators(Modal, store.dispatch)
  }
  get Notify () {
    return ({
      notify: bindActionCreators(notify, store.dispatch),
      NOTIFY_TYPE
    })
  }
}
<commit_msg>修改 sdk modal 和 notify的方法<commit_after>import { request } from './utils'
import store from './store'
import { bindActionCreators } from 'redux'
import config from './config'
import * as Modal from './components/Modal/actions'
import { notify, NOTIFY_TYPE } from './components/Notification/actions'
import { addComToSideBar } from './components/Panel/actions'

export default class {
  // app data
  constructor (config = {}) {
    this.subscribeDataArray = config.subscribeDataArray || []
    this.pkgId = config.pkgId || ''
  }
  getData () {
    const currentStore = store.getState()
    return this.subscribeDataArray.reduce((p, v) => {
      p[v] = currentStore[v] || {}
      return p
    }, {})
  }
  subscribeStore (func) {
    if (!func) return
    store.subscribe(func(this.getData()))
  }
  get utils () {
    return ({
      request,
    })
  }

  get injectComponent () {
    return ({
      addComToSideBar
    })
  }
  get config () {
    return config
  }
  get Modal () {
    return Modal
  }
  get Notify () {
    return ({
      notify,
      NOTIFY_TYPE
    })
  }
}
<|endoftext|>


<commit_before>L.BingLayer = L.TileLayer.extend({
	options: {
		subdomains: [0, 1, 2, 3],
		type: 'Aerial',
		attribution: 'Bing',
		culture: ''
	},

	initialize: function(key, options) {
		L.Util.setOptions(this, options);

		this._key = key;
		this._url = null;
		this.meta = {};
		this.loadMetadata();
	},

	tile2quad: function(x, y, z) {
		var quad = '';
		for (var i = z; i > 0; i--) {
			var digit = 0;
			var mask = 1 << (i - 1);
			if ((x & mask) != 0) digit += 1;
			if ((y & mask) != 0) digit += 2;
			quad = quad + digit;
		}
		return quad;
	},

	getTileUrl: function(p, z) {
		var z = this._getZoomForUrl();
		var subdomains = this.options.subdomains,
			s = this.options.subdomains[Math.abs((p.x + p.y) % subdomains.length)];
		return this._url.replace('{subdomain}', s)
				.replace('{quadkey}', this.tile2quad(p.x, p.y, z))
				.replace('{culture}', this.options.culture);
	},

	loadMetadata: function() {
		var _this = this;
		var cbid = '_bing_metadata_' + L.Util.stamp(this);
		window[cbid] = function (meta) {
			_this.meta = meta;
			window[cbid] = undefined;
			var e = document.getElementById(cbid);
			e.parentNode.removeChild(e);
			if (meta.errorDetails) {
				alert("Got metadata" + meta.errorDetails);
				return;
			}
			_this.initMetadata();
		};
		var url = "http://dev.virtualearth.net/REST/v1/Imagery/Metadata/" + this.options.type + "?include=ImageryProviders&jsonp=" + cbid + "&key=" + this._key;
		var script = document.createElement("script");
		script.type = "text/javascript";
		script.src = url;
		script.id = cbid;
		document.getElementsByTagName("head")[0].appendChild(script);
	},

	initMetadata: function() {
		var r = this.meta.resourceSets[0].resources[0];
		this.options.subdomains = r.imageUrlSubdomains;
		this._url = r.imageUrl;
		this._providers = [];
		for (var i = 0; i < r.imageryProviders.length; i++) {
			var p = r.imageryProviders[i];
			for (var j = 0; j < p.coverageAreas.length; j++) {
				var c = p.coverageAreas[j];
				var coverage = {zoomMin: c.zoomMin, zoomMax: c.zoomMax, active: false};
				var bounds = new L.LatLngBounds(
						new L.LatLng(c.bbox[0]+0.01, c.bbox[1]+0.01),
						new L.LatLng(c.bbox[2]-0.01, c.bbox[3]-0.01)
				);
				coverage.bounds = bounds;
				coverage.attrib = p.attribution;
				this._providers.push(coverage);
			}
		}
		this._update();
	},

	_update: function() {
		if (this._url == null || !this._map) return;
		this._update_attribution();
		L.TileLayer.prototype._update.apply(this, []);
	},

	_update_attribution: function() {
		var bounds = this._map.getBounds();
		var zoom = this._map.getZoom();
		for (var i = 0; i < this._providers.length; i++) {
			var p = this._providers[i];
			if ((zoom <= p.zoomMax && zoom >= p.zoomMin) &&
					bounds.intersects(p.bounds)) {
				if (!p.active)
					this._map.attributionControl.addAttribution(p.attrib);
				p.active = true;
			} else {
				if (p.active)
					this._map.attributionControl.removeAttribution(p.attrib);
				p.active = false;
			}
		}
	},

	onRemove: function(map) {
		for (var i = 0; i < this._providers.length; i++) {
			var p = this._providers[i];
			if (p.active) {
				this._map.attributionControl.removeAttribution(p.attrib);
				p.active = false;
			}
		}
        	L.TileLayer.prototype.onRemove.apply(this, [map]);
	}
});
<commit_msg>Allow https<commit_after>L.BingLayer = L.TileLayer.extend({
	options: {
		subdomains: [0, 1, 2, 3],
		type: 'Aerial',
		attribution: 'Bing',
		culture: ''
	},

	initialize: function(key, options) {
		L.Util.setOptions(this, options);

		this._key = key;
		this._url = null;
		this.meta = {};
		this.loadMetadata();
	},

	tile2quad: function(x, y, z) {
		var quad = '';
		for (var i = z; i > 0; i--) {
			var digit = 0;
			var mask = 1 << (i - 1);
			if ((x & mask) != 0) digit += 1;
			if ((y & mask) != 0) digit += 2;
			quad = quad + digit;
		}
		return quad;
	},

	getTileUrl: function(p, z) {
		var z = this._getZoomForUrl();
		var subdomains = this.options.subdomains,
			s = this.options.subdomains[Math.abs((p.x + p.y) % subdomains.length)];
		return this._url.replace('{subdomain}', s)
				.replace('{quadkey}', this.tile2quad(p.x, p.y, z))
				.replace('{culture}', this.options.culture)
				.replace('http://', '//');
	},

	loadMetadata: function() {
		var _this = this;
		var cbid = '_bing_metadata_' + L.Util.stamp(this);
		window[cbid] = function (meta) {
			_this.meta = meta;
			window[cbid] = undefined;
			var e = document.getElementById(cbid);
			e.parentNode.removeChild(e);
			if (meta.errorDetails) {
				alert("Got metadata" + meta.errorDetails);
				return;
			}
			_this.initMetadata();
		};
		var url = "//dev.virtualearth.net/REST/v1/Imagery/Metadata/" + this.options.type + "?include=ImageryProviders&jsonp=" + cbid + "&key=" + this._key;
		var script = document.createElement("script");
		script.type = "text/javascript";
		script.src = url;
		script.id = cbid;
		document.getElementsByTagName("head")[0].appendChild(script);
	},

	initMetadata: function() {
		var r = this.meta.resourceSets[0].resources[0];
		this.options.subdomains = r.imageUrlSubdomains;
		this._url = r.imageUrl;
		this._providers = [];
		for (var i = 0; i < r.imageryProviders.length; i++) {
			var p = r.imageryProviders[i];
			for (var j = 0; j < p.coverageAreas.length; j++) {
				var c = p.coverageAreas[j];
				var coverage = {zoomMin: c.zoomMin, zoomMax: c.zoomMax, active: false};
				var bounds = new L.LatLngBounds(
						new L.LatLng(c.bbox[0]+0.01, c.bbox[1]+0.01),
						new L.LatLng(c.bbox[2]-0.01, c.bbox[3]-0.01)
				);
				coverage.bounds = bounds;
				coverage.attrib = p.attribution;
				this._providers.push(coverage);
			}
		}
		this._update();
	},

	_update: function() {
		if (this._url == null || !this._map) return;
		this._update_attribution();
		L.TileLayer.prototype._update.apply(this, []);
	},

	_update_attribution: function() {
		var bounds = this._map.getBounds();
		var zoom = this._map.getZoom();
		for (var i = 0; i < this._providers.length; i++) {
			var p = this._providers[i];
			if ((zoom <= p.zoomMax && zoom >= p.zoomMin) &&
					bounds.intersects(p.bounds)) {
				if (!p.active)
					this._map.attributionControl.addAttribution(p.attrib);
				p.active = true;
			} else {
				if (p.active)
					this._map.attributionControl.removeAttribution(p.attrib);
				p.active = false;
			}
		}
	},

	onRemove: function(map) {
		for (var i = 0; i < this._providers.length; i++) {
			var p = this._providers[i];
			if (p.active) {
				this._map.attributionControl.removeAttribution(p.attrib);
				p.active = false;
			}
		}
        	L.TileLayer.prototype.onRemove.apply(this, [map]);
	}
});
<|endoftext|>


<commit_before>// Copyright 2002-2015, University of Colorado Boulder

/**
 * Deploy a simulation by sending a request to our build-server.
 *
 * @author Aaron Davis
 */

// The following comment permits node-specific globals (such as process.cwd()) to pass jshint
/* jslint node: true */
'use strict';

// modules
var querystring = require( 'querystring' );
var request = require( 'request' );
var ChipperConstants = require( '../../../chipper/js/common/ChipperConstants' );
var getDeployConfig = require( '../../../chipper/js/common/getDeployConfig' );

/**
 * @param grunt - the grunt instance
 * @param callback - optional callback to run when finished, defaults to grunt.task.current.async()
 */
module.exports = function( grunt, callback ) {

  // configuration info from external files
  var deployConfig = getDeployConfig( global.phet.chipper.fs );

  var locales = grunt.option( 'locales' ) || ChipperConstants.FALLBACK_LOCALE;

  // read dependencies.json (required)
  var dependenciesJSON = grunt.file.readJSON( 'build/dependencies.json' );

  var query = querystring.stringify( {
    'repos': JSON.stringify( dependenciesJSON ),
    'locales': locales,
    'simName': deployConfig.name,
    'version': deployConfig.version,
    'serverName': deployConfig.productionServerName,
    'authorizationCode': deployConfig.buildServerAuthorizationCode
  } );

  var productionServerURL = deployConfig.productionServerURL;
  var url = productionServerURL + '/deploy-html-simulation?' + query;

  var done = callback || grunt.task.current.async();

  request( url, function( error, response, body ) {
    if ( error ) {
      grunt.log.writeln( 'error: deploy failed with error ' + error );
    }
    else if ( response.statusCode !== 200 ) {
      grunt.log.writeln( 'error: deploy failed with status code ' + response.statusCode );
    }
    else {
      grunt.log.writeln( 'sending request to: ' + url );
    }
    done();
  } );
};
<commit_msg>add rc option for deploy, see #343<commit_after>// Copyright 2002-2015, University of Colorado Boulder

/**
 * Deploy a simulation by sending a request to our build-server.
 *
 * @author Aaron Davis
 */

// The following comment permits node-specific globals (such as process.cwd()) to pass jshint
/* jslint node: true */
'use strict';

// modules
var querystring = require( 'querystring' );
var request = require( 'request' );
var ChipperConstants = require( '../../../chipper/js/common/ChipperConstants' );
var getDeployConfig = require( '../../../chipper/js/common/getDeployConfig' );

/**
 * @param grunt - the grunt instance
 * @param callback - optional callback to run when finished, defaults to grunt.task.current.async()
 */
module.exports = function( grunt, callback ) {

  // configuration info from external files
  var deployConfig = getDeployConfig( global.phet.chipper.fs );

  var locales = grunt.option( 'locales' ) || ChipperConstants.FALLBACK_LOCALE;

  // read dependencies.json (required)
  var dependenciesJSON = grunt.file.readJSON( 'build/dependencies.json' );

  var params = {
    'repos': JSON.stringify( dependenciesJSON ),
    'locales': locales,
    'simName': deployConfig.name,
    'version': deployConfig.version,
    'serverName': deployConfig.productionServerName,
    'authorizationCode': deployConfig.buildServerAuthorizationCode
  };

  if ( grunt.option( 'option' ) === 'rc' ) {
    params.option = 'rc';
  }

  var query = querystring.stringify( params );

  var productionServerURL = deployConfig.productionServerURL;
  var url = productionServerURL + '/deploy-html-simulation?' + query;

  var done = callback || grunt.task.current.async();

  request( url, function( error, response, body ) {
    if ( error ) {
      grunt.log.writeln( 'error: deploy failed with error ' + error );
    }
    else if ( response.statusCode !== 200 ) {
      grunt.log.writeln( 'error: deploy failed with status code ' + response.statusCode );
    }
    else {
      grunt.log.writeln( 'sending request to: ' + url );
    }
    done();
  } );
};
<|endoftext|>


<commit_before>import axios from 'axios';
import config from '../configs/;

export default class Api {
  constructor(){
    this.apiKey = config.apiKey;
    this.apiBaseUrl = 'https://api.darksky.net/forecast'
  }
  constructApiUrl(lat, long) {
    return `${this.apiBaseUrl}/${this.apiKey}/${lat},${long}?units=ca`;
  }

  getFromMyLocation() {
    return axios.get(this.constructApiUrl(45.561050,-73.474612));
  }

  getCurrentWeather({latitude, longitude}) {
    return axios.get(this.constructApiUrl(latitude,longitude));
  }

}
<commit_msg>Update index.js<commit_after>import axios from 'axios';
import config from '../configs/';

export default class Api {
  constructor(){
    this.apiKey = config.apiKey;
    this.apiBaseUrl = 'https://api.darksky.net/forecast'
  }
  constructApiUrl(lat, long) {
    return `${this.apiBaseUrl}/${this.apiKey}/${lat},${long}?units=ca`;
  }

  getFromMyLocation() {
    return axios.get(this.constructApiUrl(45.561050,-73.474612));
  }

  getCurrentWeather({latitude, longitude}) {
    return axios.get(this.constructApiUrl(latitude,longitude));
  }

}
<|endoftext|>


<commit_before>angular.module("omniFactories")
	.factory("Orderbook",["$http","DExOrder","DExOffer","Transaction","Account","Wallet","ModalManager","MIN_MINER_FEE", "WHOLE_UNIT", "SATOSHI_UNIT",
		function OrderbookFactory($http,DExOrder,DExOffer,Transaction,Account,Wallet,ModalManager,MIN_MINER_FEE,WHOLE_UNIT,SATOSHI_UNIT){
			var Orderbook = function(tradingPair){
				var self = this;

				self.initialize = function(){
					self.tradingPair=tradingPair;
					self.title = "Trade " + tradingPair.selling.name + " for " + tradingPair.desired.name;
					self.active = true;
					self.disabled = !self.active;
					self.buyOrder = {};
					self.sellOrder = {};

					self.selling = tradingPair.selling;
					self.desired = tradingPair.desired;

					// TODO:  list only addresses with balance > 0
					self.addresses = Wallet.addresses.filter(function(address){
						return ((address.privkey && address.privkey.length == 58) || address.pubkey)
					});
					self.buyAddresses = self.addresses.filter(function(address){
						return address.getBalance(self.desired.propertyid) > 0;
					});
					self.buyOrder.address = self.buyAddresses.length > 0 ? self.buyAddresses[0] : undefined;
					self.sellAddresses = self.addresses.filter(function(address){
						return address.getBalance(self.selling.propertyid) > 0;
					});
					self.sellOrder.address = self.sellAddresses.length > 0 ? self.sellAddresses[0] : undefined;

					self.buyBook = []
					self.sellBook = []

					$http.get("/v1/markets/"+tradingPair.desired.propertyid+"/"+tradingPair.selling.propertyid)
						.then(function(response){
							if(response.status != "200" || response.data.status !="OK")
								return // handle errors

							var offers = response.data.orderbook
							offers.forEach(function(offerData){
								var order = null;
								var offer = new DExOffer(offerData);
								self.buyBook.forEach(function(orderData){
									if(orderData.price.eq(offer.price)){
										order = orderData;
										order.addOffer(offer)
									}

								})

								if(order == null){
									order = new DExOrder(offer);
									self.buyBook.push(order);
								}

							});

							self.buyBook.sort(function(a, b) {
					          var priceA = a.price;
					          var priceB = b.price;
					          return priceA.gt(priceB) ? -1 : priceA.lt(priceB) ? 1 : 0;
					        });
						})
					$http.get("/v1/markets/"+tradingPair.selling.propertyid+"/"+tradingPair.desired.propertyid)
						.then(function(response){
							if(response.status != "200" || response.data.status !="OK")
								return // handle errors

							var offers = response.data.orders
							offers.forEach(function(offerData){
								var order = null;
								var offer = new DExOffer(offerData);
								self.sellBook.forEach(function(orderData){
									if(orderData.price.eq(offer.price)){
										order = orderData;
										order.addOffer(offer)
									}
								})
								if(order == null){
									order = new DExOrder(offer);
									self.sellBook.push(order);
								}

							});

							self.sellBook.sort(function(a, b) {
					          var priceA = a.price;
					          var priceB = b.price;
					          return priceA.lt(priceB) ? -1 : priceA.gt(priceB) ? 1 : 0;
					        });
						})

				};

				self.setBuyAddress = function(address){
					$scope.orderbook.buyOrder.address = address;
				};

				self.setSellAddress = function(address){
					$scope.orderbook.sellOrder.address = address;
				};

				self.updateAmount = function(offer) {
					offer.amounts.desired= offer.amounts.selling * offer.price
				}

				self.submitBuyOffer = function(){
					// TODO: Validations
					var fee = Account.settings.minerFee || MIN_MINER_FEE;
					var dexOffer = new Transaction(25,self.buyOrder.address,fee,{
							transaction_version:0,
							propertyidforsale:self.tradingPair.desired.propertyid,
							amountforsale: self.tradingPair.desired.divisible ? new Big(self.sellOrder.amounts.desired).times(SATOSHI_UNIT).valueOf() : new Big(self.sellOrder.amounts.desired).valueOf(),
							propertiddesired:self.tradingPair.selling.propertyid,
							amountdesired: self.tradingPair.selling.divisible ? new Big(self.sellOrder.amounts.selling).times(SATOSHI_UNIT).valueOf() : new Big(self.sellOrder.amounts.selling).times(SATOSHI_UNIT).valueOf()
						});
					ModalManager.openConfirmationModal({
						dataTemplate: '/views/modals/partials/dex_offer.html',
						scope: {
							title:"Confirm DEx Transaction",
							address:self.buyOrder.address,
							saleCurrency:self.tradingPair.desired.propertyid,
							saleAmount:self.buyOrder.amounts.desired,
							desiredCurrency:self.tradingPair.selling.propertyid,
							desiredAmount:self.buyOrder.amounts.selling,
							totalCost:dexOffer.totalCost,
							action:"Add",
							confirmText: "Create Transaction",
							successMessage: "Your order was placed successfully"
						},
						transaction:dexOffer
					})
				};

				self.submitSellOffer = function(){
					// TODO: Validations
					var fee = Account.settings.minerFee || MIN_MINER_FEE;
					var dexOffer = new Transaction(25,self.sellOrder.address,fee,{
							transaction_version:0,
							propertyidforsale:self.tradingPair.selling.propertyid,
							amountforsale: self.tradingPair.selling.divisible ? new Big(self.sellOrder.amounts.selling).times(SATOSHI_UNIT).valueOf() : new Big(self.sellOrder.amounts.selling).valueOf(),
							propertiddesired:self.tradingPair.desired.propertyid,
							amountdesired: self.tradingPair.desired.divisible ? new Big(self.sellOrder.amounts.desired).times(SATOSHI_UNIT).valueOf() : new Big(self.sellOrder.amounts.desired).times(SATOSHI_UNIT).valueOf()
						});
					ModalManager.openConfirmationModal({
						dataTemplate: '/views/modals/partials/dex_offer.html',
						scope: {
							title:"Confirm DEx Transaction",
							address:self.sellOrder.address,
							saleCurrency:self.tradingPair.selling.propertyid,
							saleAmount:self.sellOrder.amounts.selling,
							desiredCurrency:self.tradingPair.desired.propertyid,
							desiredAmount:self.sellOrder.amounts.desired,
							totalCost:dexOffer.totalCost,
							action:"Add",
							confirmText: "Create Transaction",
							successMessage: "Your order was placed successfully"
						},
						transaction:dexOffer
					})
				};

				self.getBalance = function(address, assetId){
					return address && address.getBalance(assetId) ? new Big(address.getBalance(assetId)).times(WHOLE_UNIT).valueOf() : 0;
				}

				self.initialize();
			}

			return Orderbook;
		}]);<commit_msg>Fix Orderbook<commit_after>angular.module("omniFactories")
	.factory("Orderbook",["$http","DExOrder","DExOffer","Transaction","Account","Wallet","ModalManager","MIN_MINER_FEE", "WHOLE_UNIT", "SATOSHI_UNIT",
		function OrderbookFactory($http,DExOrder,DExOffer,Transaction,Account,Wallet,ModalManager,MIN_MINER_FEE,WHOLE_UNIT,SATOSHI_UNIT){
			var Orderbook = function(tradingPair){
				var self = this;

				self.initialize = function(){
					self.tradingPair=tradingPair;
					self.title = "Trade " + tradingPair.selling.name + " for " + tradingPair.desired.name;
					self.active = true;
					self.disabled = !self.active;
					self.buyOrder = {};
					self.sellOrder = {};

					self.selling = tradingPair.selling;
					self.desired = tradingPair.desired;

					// TODO:  list only addresses with balance > 0
					self.addresses = Wallet.addresses.filter(function(address){
						return ((address.privkey && address.privkey.length == 58) || address.pubkey)
					});
					self.buyAddresses = self.addresses.filter(function(address){
						return address.getBalance(self.desired.propertyid) > 0;
					});
					self.buyOrder.address = self.buyAddresses.length > 0 ? self.buyAddresses[0] : undefined;
					self.sellAddresses = self.addresses.filter(function(address){
						return address.getBalance(self.selling.propertyid) > 0;
					});
					self.sellOrder.address = self.sellAddresses.length > 0 ? self.sellAddresses[0] : undefined;

					self.buyBook = []
					self.sellBook = []

					$http.get("/v1/markets/"+tradingPair.desired.propertyid+"/"+tradingPair.selling.propertyid)
						.then(function(response){
							if(response.status != 200 || response.data.status !=200)
								return // handle errors

							var offers = response.data.orderbook;
							offers.forEach(function(offerData){
								var order = null;
								var offer = new DExOffer(offerData);
								self.buyBook.forEach(function(orderData){
									if(orderData.price.eq(offer.price)){
										order = orderData;
										order.addOffer(offer)
									}

								})

								if(order == null){
									order = new DExOrder(offer);
									self.buyBook.push(order);
								}

							});

							self.buyBook.sort(function(a, b) {
					          var priceA = a.price;
					          var priceB = b.price;
					          return priceA.gt(priceB) ? -1 : priceA.lt(priceB) ? 1 : 0;
					        });
						})
					$http.get("/v1/markets/"+tradingPair.selling.propertyid+"/"+tradingPair.desired.propertyid)
						.then(function(response){
							if(response.status != 200 || response.data.status != 200)
								return // handle errors

							var offers = response.data.orderbook;
							offers.forEach(function(offerData){
								var order = null;
								var offer = new DExOffer(offerData);
								self.sellBook.forEach(function(orderData){
									if(orderData.price.eq(offer.price)){
										order = orderData;
										order.addOffer(offer)
									}
								})
								if(order == null){
									order = new DExOrder(offer);
									self.sellBook.push(order);
								}

							});

							self.sellBook.sort(function(a, b) {
					          var priceA = a.price;
					          var priceB = b.price;
					          return priceA.lt(priceB) ? -1 : priceA.gt(priceB) ? 1 : 0;
					        });
						})

				};

				self.setBuyAddress = function(address){
					$scope.orderbook.buyOrder.address = address;
				};

				self.setSellAddress = function(address){
					$scope.orderbook.sellOrder.address = address;
				};

				self.updateAmount = function(offer) {
					offer.amounts.desired= offer.amounts.selling * offer.price
				}

				self.submitBuyOffer = function(){
					// TODO: Validations
					var fee = Account.settings.minerFee || MIN_MINER_FEE;
					var dexOffer = new Transaction(25,self.buyOrder.address,fee,{
							transaction_version:0,
							propertyidforsale:self.tradingPair.desired.propertyid,
							amountforsale: self.tradingPair.desired.divisible ? new Big(self.sellOrder.amounts.desired).times(SATOSHI_UNIT).valueOf() : new Big(self.sellOrder.amounts.desired).valueOf(),
							propertiddesired:self.tradingPair.selling.propertyid,
							amountdesired: self.tradingPair.selling.divisible ? new Big(self.sellOrder.amounts.selling).times(SATOSHI_UNIT).valueOf() : new Big(self.sellOrder.amounts.selling).times(SATOSHI_UNIT).valueOf()
						});
					ModalManager.openConfirmationModal({
						dataTemplate: '/views/modals/partials/dex_offer.html',
						scope: {
							title:"Confirm DEx Transaction",
							address:self.buyOrder.address,
							saleCurrency:self.tradingPair.desired.propertyid,
							saleAmount:self.buyOrder.amounts.desired,
							desiredCurrency:self.tradingPair.selling.propertyid,
							desiredAmount:self.buyOrder.amounts.selling,
							totalCost:dexOffer.totalCost,
							action:"Add",
							confirmText: "Create Transaction",
							successMessage: "Your order was placed successfully"
						},
						transaction:dexOffer
					})
				};

				self.submitSellOffer = function(){
					// TODO: Validations
					var fee = Account.settings.minerFee || MIN_MINER_FEE;
					var dexOffer = new Transaction(25,self.sellOrder.address,fee,{
							transaction_version:0,
							propertyidforsale:self.tradingPair.selling.propertyid,
							amountforsale: self.tradingPair.selling.divisible ? new Big(self.sellOrder.amounts.selling).times(SATOSHI_UNIT).valueOf() : new Big(self.sellOrder.amounts.selling).valueOf(),
							propertiddesired:self.tradingPair.desired.propertyid,
							amountdesired: self.tradingPair.desired.divisible ? new Big(self.sellOrder.amounts.desired).times(SATOSHI_UNIT).valueOf() : new Big(self.sellOrder.amounts.desired).times(SATOSHI_UNIT).valueOf()
						});
					ModalManager.openConfirmationModal({
						dataTemplate: '/views/modals/partials/dex_offer.html',
						scope: {
							title:"Confirm DEx Transaction",
							address:self.sellOrder.address,
							saleCurrency:self.tradingPair.selling.propertyid,
							saleAmount:self.sellOrder.amounts.selling,
							desiredCurrency:self.tradingPair.desired.propertyid,
							desiredAmount:self.sellOrder.amounts.desired,
							totalCost:dexOffer.totalCost,
							action:"Add",
							confirmText: "Create Transaction",
							successMessage: "Your order was placed successfully"
						},
						transaction:dexOffer
					})
				};

				self.getBalance = function(address, assetId){
					return address && address.getBalance(assetId) ? new Big(address.getBalance(assetId)).times(WHOLE_UNIT).valueOf() : 0;
				}

				self.initialize();
			}

			return Orderbook;
		}]);<|endoftext|>


<commit_before>iD.Background = function() {

    var deviceRatio = (window.devicePixelRatio &&
        window.devicePixelRatio === 2) ? 0.5 : 1;
        // tileSize = (deviceRatio === 0.5) ? [128,128] : [256,256];
    var tileSize = [256, 256];

    var tile = d3.geo.tile(),
        projection,
        cache = {},
        offset = [0, 0],
        transformProp = iD.util.prefixCSSProperty('Transform'),
        source = d3.functor('');

    var imgstyle = 'position:absolute;transform-origin:0 0;' +
        '-ms-transform-origin:0 0;' +
        '-webkit-transform-origin:0 0;' +
        '-moz-transform-origin:0 0;' +
        '-o-transform-origin:0 0;' +
        '-webkit-user-select: none;' +
        '-webkit-user-drag: none;' +
        '-moz-user-drag: none;' +
        'opacity:0;';

    function tileSizeAtZoom(d, z) {
        return Math.ceil(tileSize[0] * Math.pow(2, z - d[2])) / tileSize[0];
    }

    function atZoom(t, distance) {
        var power = Math.pow(2, distance);
        var az = [
            Math.floor(t[0] * power),
            Math.floor(t[1] * power),
            t[2] + distance];
        return az;
    }

    function lookUp(d) {
        for (var up = -1; up > -d[2]; up--) {
            if (cache[atZoom(d, up)] !== false) return atZoom(d, up);
        }
    }

    function uniqueBy(a, n) {
        var o = [], seen = {};
        for (var i = 0; i < a.length; i++) {
            if (seen[a[i][n]] === undefined) {
                o.push(a[i]);
                seen[a[i][n]] = true;
            }
        }
        return o;
    }

    function addSource(d) {
        d.push(source(d));
        return d;
    }

    // derive the tiles onscreen, remove those offscreen and position tiles
    // correctly for the currentstate of `projection`
    function background() {
        var sel = this,
            tiles = tile
            .scale(projection.scale())
            .scaleExtent(source.scaleExtent || [1, 17])
            .translate(projection.translate())(),
            requests = [],
            scaleExtent = tile.scaleExtent(),
            z = Math.max(Math.log(projection.scale()) / Math.log(2) - 8, 0),
            rz = Math.max(scaleExtent[0],
                Math.min(scaleExtent[1], Math.floor(z))),
            ts = tileSize[0] * Math.pow(2, z - rz),
            tile_origin = [
                projection.scale() / 2 - projection.translate()[0],
                projection.scale() / 2 - projection.translate()[1]];

        tiles.forEach(function(d) {
            addSource(d);
            requests.push(d);
            if (!cache[d[3]] && lookUp(d)) {
                requests.push(addSource(lookUp(d)));
            }
        });

        requests = uniqueBy(requests, 3);

        function load(d) {
            cache[d[3]] = true;
            d3.select(this)
                .on('load', null)
                .transition()
                .style('opacity', 1);
            background.apply(sel);
        }

        function error(d) {
            cache[d[3]] = false;
            d3.select(this).on('load', null);
            d3.select(this).remove();
            background.apply(sel);
        }

        function imageTransform(d) {
            var _ts = tileSize[0] * Math.pow(2, z - d[2]);
            var scale = tileSizeAtZoom(d, z);
            return 'translate(' +
                (Math.round((d[0] * _ts) - tile_origin[0]) + offset[0]) + 'px,' +
                (Math.round((d[1] * _ts) - tile_origin[1]) + offset[1]) + 'px)' +
                'scale(' + scale + ',' + scale + ')';
        }

        var image = this
            .selectAll('img')
            .data(requests, function(d) { return d[3]; });

        image.exit()
            .style(transformProp, imageTransform)
            .transition()
            .style('opacity', 0)
            .remove();

        image.enter().append('img')
            .attr('style', imgstyle)
            .attr('src', function(d) { return d[3]; })
            .on('error', error)
            .on('load', load);

        image.style(transformProp, imageTransform);

        if (Object.keys(cache).length > 100) cache = {};
    }

    background.offset = function(_) {
        if (!arguments.length) return offset;
        offset = _;
        return background;
    };

    background.nudge = function(_) {
        offset[0] += _[0];
        offset[1] += _[1];
        return background;
    };

    background.projection = function(_) {
        if (!arguments.length) return projection;
        projection = _;
        return background;
    };

    background.size = function(_) {
        if (!arguments.length) return tile.size();
        tile.size(_);
        return background;
    };

    background.source = function(_) {
        if (!arguments.length) return source;
        source = _;
        return background;
    };

    return background;
};
<commit_msg>Fix re-requesting failed tiles. Fixes #594<commit_after>iD.Background = function() {

    var deviceRatio = (window.devicePixelRatio &&
        window.devicePixelRatio === 2) ? 0.5 : 1;
        // tileSize = (deviceRatio === 0.5) ? [128,128] : [256,256];
    var tileSize = [256, 256];

    var tile = d3.geo.tile(),
        projection,
        cache = {},
        offset = [0, 0],
        transformProp = iD.util.prefixCSSProperty('Transform'),
        source = d3.functor('');

    var imgstyle = 'position:absolute;transform-origin:0 0;' +
        '-ms-transform-origin:0 0;' +
        '-webkit-transform-origin:0 0;' +
        '-moz-transform-origin:0 0;' +
        '-o-transform-origin:0 0;' +
        '-webkit-user-select: none;' +
        '-webkit-user-drag: none;' +
        '-moz-user-drag: none;' +
        'opacity:0;';

    function tileSizeAtZoom(d, z) {
        return Math.ceil(tileSize[0] * Math.pow(2, z - d[2])) / tileSize[0];
    }

    function atZoom(t, distance) {
        var power = Math.pow(2, distance);
        var az = [
            Math.floor(t[0] * power),
            Math.floor(t[1] * power),
            t[2] + distance];
        return az;
    }

    function lookUp(d) {
        for (var up = -1; up > -d[2]; up--) {
            if (cache[atZoom(d, up)] !== false) return atZoom(d, up);
        }
    }

    function uniqueBy(a, n) {
        var o = [], seen = {};
        for (var i = 0; i < a.length; i++) {
            if (seen[a[i][n]] === undefined) {
                o.push(a[i]);
                seen[a[i][n]] = true;
            }
        }
        return o;
    }

    function addSource(d) {
        d.push(source(d));
        return d;
    }

    // derive the tiles onscreen, remove those offscreen and position tiles
    // correctly for the currentstate of `projection`
    function background() {
        var sel = this,
            tiles = tile
            .scale(projection.scale())
            .scaleExtent(source.scaleExtent || [1, 17])
            .translate(projection.translate())(),
            requests = [],
            scaleExtent = tile.scaleExtent(),
            z = Math.max(Math.log(projection.scale()) / Math.log(2) - 8, 0),
            rz = Math.max(scaleExtent[0],
                Math.min(scaleExtent[1], Math.floor(z))),
            ts = tileSize[0] * Math.pow(2, z - rz),
            tile_origin = [
                projection.scale() / 2 - projection.translate()[0],
                projection.scale() / 2 - projection.translate()[1]];

        tiles.forEach(function(d) {
            addSource(d);
            requests.push(d);
            if (!cache[d[3]] && lookUp(d)) {
                requests.push(addSource(lookUp(d)));
            }
        });

        requests = uniqueBy(requests, 3).filter(function(r) {
            // don't re-request tiles which have failed in the past
            return cache[r[3]] !== false;
        });

        function load(d) {
            cache[d[3]] = true;
            d3.select(this)
                .on('load', null)
                .transition()
                .style('opacity', 1);
            background.apply(sel);
        }

        function error(d) {
            cache[d[3]] = false;
            d3.select(this).on('load', null);
            d3.select(this).remove();
            background.apply(sel);
        }

        function imageTransform(d) {
            var _ts = tileSize[0] * Math.pow(2, z - d[2]);
            var scale = tileSizeAtZoom(d, z);
            return 'translate(' +
                (Math.round((d[0] * _ts) - tile_origin[0]) + offset[0]) + 'px,' +
                (Math.round((d[1] * _ts) - tile_origin[1]) + offset[1]) + 'px)' +
                'scale(' + scale + ',' + scale + ')';
        }

        var image = this
            .selectAll('img')
            .data(requests, function(d) { return d[3]; });

        image.exit()
            .style(transformProp, imageTransform)
            .transition()
            .style('opacity', 0)
            .remove();

        image.enter().append('img')
            .attr('style', imgstyle)
            .attr('src', function(d) { return d[3]; })
            .on('error', error)
            .on('load', load);

        image.style(transformProp, imageTransform);

        if (Object.keys(cache).length > 100) cache = {};
    }

    background.offset = function(_) {
        if (!arguments.length) return offset;
        offset = _;
        return background;
    };

    background.nudge = function(_) {
        offset[0] += _[0];
        offset[1] += _[1];
        return background;
    };

    background.projection = function(_) {
        if (!arguments.length) return projection;
        projection = _;
        return background;
    };

    background.size = function(_) {
        if (!arguments.length) return tile.size();
        tile.size(_);
        return background;
    };

    background.source = function(_) {
        if (!arguments.length) return source;
        source = _;
        return background;
    };

    return background;
};
<|endoftext|>


<commit_before>const admin = require('firebase-admin')
const db = admin.database()

module.exports = (req, res) => {
	const { historyId, todo = {} } = req.body

	const promises = Object.keys(todo)
	.filter(key => todo[key].status)
	.map(key => {
		return new Promise((resolve, reject) => {
			const taskId = db.ref('kanban').push().key
			db.ref(`kanban/${taskId}`).set({
				status: 'backlog',
				task: todo[key].task,
				taskId: taskId,
				user: {
					userId: todo[key].userId,
					name: todo[key].userName
				}
			})
			.then(() => {
				db.ref(`history/${historyId}`).update({status: true})
				resolve(true)
			})
		})
	})

	Promise.all(promises)
	.then(results => {
		console.log('tes', results)
		res.send(true)
	})
	.catch(err => res.send(err))
}<commit_msg>submit review update history status<commit_after>const admin = require('firebase-admin')
const db = admin.database()

module.exports = (req, res) => {
	const { historyId, todo = {} } = req.body

	const promises = Object.keys(todo)
	.filter(key => todo[key].status)
	.map(key => {
		return new Promise((resolve, reject) => {
			const taskId = db.ref('kanban').push().key
			db.ref(`kanban/${taskId}`).set({
				status: 'backlog',
				task: todo[key].task,
				taskId: taskId,
				user: {
					userId: todo[key].userId,
					name: todo[key].userName
				}
			})
			.then(() => {
				resolve(true)
			})
		})
	})

	Promise.all(promises)
	.then(results => {
		db.ref(`history/${historyId}`).update({status: true})
		res.send(true)
	})
	.catch(err => res.send(err))
}<|endoftext|>


<commit_before>class Example extends React.Component {
  constructor(...args) {
    super(...args);

    this.attachRef = target => this.setState({ target });
    this.state = {
      show: false,
    };
  }

  render() {
    const { show, target } = this.state;
    return (
      <>
        <Button
          variant="danger"
          ref={this.attachRef}
          onClick={() => this.setState({ show: !show })}
        >
          Click me to see
        </Button>
        <Overlay target={target} show={show} placement="right">
          {({ placement, scheduleUpdate, arrowProps, ...props }) => (
            <div
              {...props}
              style={{
                backgroundColor: 'rgba(255, 100, 100, 0.85)',
                padding: '2px 10px',
                color: 'white',
                borderRadius: 3,
                ...props.style,
              }}
            >
              Simple tooltip
            </div>
          )}
        </Overlay>
      </>
    );
  }
}

render(<Example />);
<commit_msg>excluding warning messages for using "Overlay" component (#3443)<commit_after>class Example extends React.Component {
  constructor(...args) {
    super(...args);

    this.attachRef = target => this.setState({ target });
    this.state = {
      show: false,
    };
  }

  render() {
    const { show, target } = this.state;
    return (
      <>
        <Button
          variant="danger"
          ref={this.attachRef}
          onClick={() => this.setState({ show: !show })}
        >
          Click me to see
        </Button>
        <Overlay target={target} show={show} placement="right">
          {({
            placement,
            scheduleUpdate,
            arrowProps,
            outOfBoundaries,
            show: _show,
            ...props
          }) => (
            <div
              {...props}
              style={{
                backgroundColor: 'rgba(255, 100, 100, 0.85)',
                padding: '2px 10px',
                color: 'white',
                borderRadius: 3,
                ...props.style,
              }}
            >
              Simple tooltip
            </div>
          )}
        </Overlay>
      </>
    );
  }
}

render(<Example />);
<|endoftext|>


<commit_before>/*
* jQuery Mobile Framework : listview plugin
* Copyright (c) jQuery Project
* Dual licensed under the MIT (MIT-LICENSE.txt) and GPL (GPL-LICENSE.txt) licenses.
* Note: Code is in draft form and is subject to change
*/
(function( $ ) {

$.widget( "mobile.listview", $.mobile.widget, {
	options: {
		theme: "c",
		countTheme: "c",
		headerTheme: "b",
		dividerTheme: "b",
		splitIcon: "arrow-r"
		splitTheme: "b",
		inset: false
	},

	_create: function() {
		var o = this.options
			$list = this.element;

		this._createSubPages();

		//create listview markup
		this.element
			.addClass( "ui-listview" )
			.attr( "role", "listbox" )
			.find( "li" )
				.attr("role","option")
				.attr("tabindex","-1")
				.focus(function(){
					$(this).attr("tabindex","0");
				})
				.each(function() {
					var $li = $( this ),
						role = $li.data( "role" ),
						dividertheme = $list.data( "dividertheme" ) || o.dividerTheme;
					if ( $li.is( ":has(img)" ) ) {
						if ($li.is( ":has(img.ui-li-icon)" )){
							$li.addClass( "ui-li-has-icon" );
						}
						else{
							$li.addClass( "ui-li-has-thumb" );
						}

					}
					if ( $li.is( ":has(.ui-li-aside)" ) ) {
						var aside = $li.find('.ui-li-aside');
						aside.prependTo(aside.parent()); //shift aside to front for css float
					}
					$li.addClass( "ui-li" );

					if( $li.find('a').length ){
						$li
							.buttonMarkup({
								wrapperEls: "div",
								shadow: false,
								corners: false,
								iconpos: "right",
								icon: $(this).data("icon") || "arrow-r",
								theme: o.theme
							})
							.find( "a" ).eq( 0 )
								.addClass( "ui-link-inherit" );
					}
					else if( role == "list-divider" ){
						$li.addClass( "ui-li-divider ui-btn ui-bar-" + dividertheme ).attr( "role", "heading" );
					}
					else {
						$li.addClass( "ui-li-static ui-btn-up-" + o.theme );
					}
				})
				.eq(0)
				.attr("tabindex","0");

		//keyboard events for menu items
		this.element.keydown(function(event){
			//switch logic based on which key was pressed
			switch(event.keyCode){
				//up or left arrow keys
				case 38:
					//if there's a previous option, focus it
					if( $(event.target).closest('li').prev().length  ){
						$(event.target).blur().attr("tabindex","-1").closest('li').prev().find('a').eq(0).focus();
					}
					//prevent native scroll
					return false;
				break;
				//down or right arrow keys
				case 40:

					//if there's a next option, focus it
					if( $(event.target).closest('li').next().length ){
						$(event.target).blur().attr("tabindex","-1").closest('li').next().find('a').eq(0).focus();
					}
					//prevent native scroll
					return false;
				break;
				case 39:
					if( $(event.target).closest('li').find('a.ui-li-link-alt').length ){
						$(event.target).blur().closest('li').find('a.ui-li-link-alt').eq(0).focus();
					}
					return false;
				break;
				case 37:
					if( $(event.target).closest('li').find('a.ui-link-inherit').length ){
						$(event.target).blur().closest('li').find('a.ui-link-inherit').eq(0).focus();
					}
					return false;
				break;
				//if enter or space is pressed, trigger click
				case 13:
				case 32:
					 $(event.target).trigger('click'); //should trigger select
					 return false;
				break;
			}
		});

		if ( o.inset ) {
			this.element
				.addClass( "ui-listview-inset" )
				.controlgroup({ shadow: true });
		}

		this.element
			.find( "li" ).each(function() {
				//for split buttons
				$( this ).find( "a" ).eq( 1 ).each(function() {
					var a = $( this );
					a
						.attr( "title", $( this ).text() )
						.addClass( "ui-li-link-alt" )
						.empty()
						.buttonMarkup({
							shadow: false,
							corners: false,
							theme: o.theme,
							icon: false,
							iconpos: false
						})
						.find( ".ui-btn-inner" )
						.append( $( "" ).buttonMarkup({
							shadow: true,
							corners: true,
							theme: $list.data('splittheme') || a.data('theme') || o.splitTheme,
							iconpos: "notext",
							icon: $list.data('spliticon') || a.data('icon') ||  o.spliticon
						} ) );

					//fix corners
					if ( o.inset ) {
						var closestLi = $( this ).closest( "li" );
						if ( closestLi.is( "li:first-child" ) ) {
							$( this ).addClass( "ui-corner-tr" );
						} else if ( closestLi.is( "li:last-child" ) ) {
							$( this ).addClass( "ui-corner-br" );
						}
					}
				});
			})
			.find( "img")
				.addClass( "ui-li-thumb" );

		if ( o.inset ) {
			this.element
				.find( "img" )
					.filter( "li:first-child img" )
						.addClass( "ui-corner-tl" )
					.end()
					.filter( "li:last-child img" )
						.addClass( "ui-corner-bl" )
					.end();
		}

		this.element
			.find( ".ui-li-count" )
				.addClass( "ui-btn-up-" + ($list.data( "counttheme" ) || o.countTheme) + " ui-btn-corner-all" )
			.end()
			.find( ":header" )
				.addClass( "ui-li-heading" )
			.end()
			.find( "p,ul,dl" )
				.addClass( "ui-li-desc" );

		this._numberItems();

		//tapping the whole LI triggers ajaxClick on the first link
		this.element.find( "li:has(a)" ).live( "tap", function(event) {
			if( !$(event.target).is('a') ){
				$( this ).find( "a:first" ).ajaxClick();
				return false;
			}
		});
	},

	_createSubPages: function() {
		var parentId = this.element.closest( ".ui-page" ).attr( "id" ),
			o = this.options,
			parentList = this.element;
		$( this.element.find( "ul,ol" ).get().reverse() ).each(function( i ) {
			var list = $( this ),
				parent = list.parent(),
				title = parent.contents()[ 0 ].nodeValue.split("\n")[0],
				id = parentId + "&" + $.mobile.subPageUrlKey + "=" + $.mobile.idStringEscape(title + " " + i),
				theme = list.data( "theme" ) || o.theme,
				countTheme = list.data( "counttheme" ) || parentList.data( "counttheme" ) || o.countTheme,
				newPage = list.wrap( "

" )
							.parent()
								.before( "

" + title + "

" )
								.parent()
									.attr({
										id: id,
										"data-theme": theme,
										"data-count-theme": countTheme
									})
									.appendTo( "body" );

				newPage.page();

			parent.html( "" + title + "" );
		}).listview();
	},

	// JS fallback for auto-numbering for OL elements
	_numberItems: function() {
		if ( $.support.cssPseudoElement || !this.element.is( "ol" ) ) {
			return;
		}
		var counter = 1;
		this.element.find( ".ui-li-dec" ).remove();
		this.element.find( "li:visible" ).each(function() {
			if( $( this ).is( ".ui-li-divider" ) ) {
				//reset counter when a divider heading is encountered
				counter = 1;
			} else {
				$( this )
					.find( ".ui-link-inherit:first" )
					.addClass( "ui-li-jsnumbering" )
					.prepend( "" + (counter++) + ". " );
			}
		});
	}
});

})( jQuery );
<commit_msg>missed a comma<commit_after>/*
* jQuery Mobile Framework : listview plugin
* Copyright (c) jQuery Project
* Dual licensed under the MIT (MIT-LICENSE.txt) and GPL (GPL-LICENSE.txt) licenses.
* Note: Code is in draft form and is subject to change
*/
(function( $ ) {

$.widget( "mobile.listview", $.mobile.widget, {
	options: {
		theme: "c",
		countTheme: "c",
		headerTheme: "b",
		dividerTheme: "b",
		splitIcon: "arrow-r",
		splitTheme: "b",
		inset: false
	},

	_create: function() {
		var o = this.options
			$list = this.element;

		this._createSubPages();

		//create listview markup
		this.element
			.addClass( "ui-listview" )
			.attr( "role", "listbox" )
			.find( "li" )
				.attr("role","option")
				.attr("tabindex","-1")
				.focus(function(){
					$(this).attr("tabindex","0");
				})
				.each(function() {
					var $li = $( this ),
						role = $li.data( "role" ),
						dividertheme = $list.data( "dividertheme" ) || o.dividerTheme;
					if ( $li.is( ":has(img)" ) ) {
						if ($li.is( ":has(img.ui-li-icon)" )){
							$li.addClass( "ui-li-has-icon" );
						}
						else{
							$li.addClass( "ui-li-has-thumb" );
						}

					}
					if ( $li.is( ":has(.ui-li-aside)" ) ) {
						var aside = $li.find('.ui-li-aside');
						aside.prependTo(aside.parent()); //shift aside to front for css float
					}
					$li.addClass( "ui-li" );

					if( $li.find('a').length ){
						$li
							.buttonMarkup({
								wrapperEls: "div",
								shadow: false,
								corners: false,
								iconpos: "right",
								icon: $(this).data("icon") || "arrow-r",
								theme: o.theme
							})
							.find( "a" ).eq( 0 )
								.addClass( "ui-link-inherit" );
					}
					else if( role == "list-divider" ){
						$li.addClass( "ui-li-divider ui-btn ui-bar-" + dividertheme ).attr( "role", "heading" );
					}
					else {
						$li.addClass( "ui-li-static ui-btn-up-" + o.theme );
					}
				})
				.eq(0)
				.attr("tabindex","0");

		//keyboard events for menu items
		this.element.keydown(function(event){
			//switch logic based on which key was pressed
			switch(event.keyCode){
				//up or left arrow keys
				case 38:
					//if there's a previous option, focus it
					if( $(event.target).closest('li').prev().length  ){
						$(event.target).blur().attr("tabindex","-1").closest('li').prev().find('a').eq(0).focus();
					}
					//prevent native scroll
					return false;
				break;
				//down or right arrow keys
				case 40:

					//if there's a next option, focus it
					if( $(event.target).closest('li').next().length ){
						$(event.target).blur().attr("tabindex","-1").closest('li').next().find('a').eq(0).focus();
					}
					//prevent native scroll
					return false;
				break;
				case 39:
					if( $(event.target).closest('li').find('a.ui-li-link-alt').length ){
						$(event.target).blur().closest('li').find('a.ui-li-link-alt').eq(0).focus();
					}
					return false;
				break;
				case 37:
					if( $(event.target).closest('li').find('a.ui-link-inherit').length ){
						$(event.target).blur().closest('li').find('a.ui-link-inherit').eq(0).focus();
					}
					return false;
				break;
				//if enter or space is pressed, trigger click
				case 13:
				case 32:
					 $(event.target).trigger('click'); //should trigger select
					 return false;
				break;
			}
		});

		if ( o.inset ) {
			this.element
				.addClass( "ui-listview-inset" )
				.controlgroup({ shadow: true });
		}

		this.element
			.find( "li" ).each(function() {
				//for split buttons
				$( this ).find( "a" ).eq( 1 ).each(function() {
					var a = $( this );
					a
						.attr( "title", $( this ).text() )
						.addClass( "ui-li-link-alt" )
						.empty()
						.buttonMarkup({
							shadow: false,
							corners: false,
							theme: o.theme,
							icon: false,
							iconpos: false
						})
						.find( ".ui-btn-inner" )
						.append( $( "" ).buttonMarkup({
							shadow: true,
							corners: true,
							theme: $list.data('splittheme') || a.data('theme') || o.splitTheme,
							iconpos: "notext",
							icon: $list.data('spliticon') || a.data('icon') ||  o.spliticon
						} ) );

					//fix corners
					if ( o.inset ) {
						var closestLi = $( this ).closest( "li" );
						if ( closestLi.is( "li:first-child" ) ) {
							$( this ).addClass( "ui-corner-tr" );
						} else if ( closestLi.is( "li:last-child" ) ) {
							$( this ).addClass( "ui-corner-br" );
						}
					}
				});
			})
			.find( "img")
				.addClass( "ui-li-thumb" );

		if ( o.inset ) {
			this.element
				.find( "img" )
					.filter( "li:first-child img" )
						.addClass( "ui-corner-tl" )
					.end()
					.filter( "li:last-child img" )
						.addClass( "ui-corner-bl" )
					.end();
		}

		this.element
			.find( ".ui-li-count" )
				.addClass( "ui-btn-up-" + ($list.data( "counttheme" ) || o.countTheme) + " ui-btn-corner-all" )
			.end()
			.find( ":header" )
				.addClass( "ui-li-heading" )
			.end()
			.find( "p,ul,dl" )
				.addClass( "ui-li-desc" );

		this._numberItems();

		//tapping the whole LI triggers ajaxClick on the first link
		this.element.find( "li:has(a)" ).live( "tap", function(event) {
			if( !$(event.target).is('a') ){
				$( this ).find( "a:first" ).ajaxClick();
				return false;
			}
		});
	},

	_createSubPages: function() {
		var parentId = this.element.closest( ".ui-page" ).attr( "id" ),
			o = this.options,
			parentList = this.element;
		$( this.element.find( "ul,ol" ).get().reverse() ).each(function( i ) {
			var list = $( this ),
				parent = list.parent(),
				title = parent.contents()[ 0 ].nodeValue.split("\n")[0],
				id = parentId + "&" + $.mobile.subPageUrlKey + "=" + $.mobile.idStringEscape(title + " " + i),
				theme = list.data( "theme" ) || o.theme,
				countTheme = list.data( "counttheme" ) || parentList.data( "counttheme" ) || o.countTheme,
				newPage = list.wrap( "

" )
							.parent()
								.before( "

" + title + "

" )
								.parent()
									.attr({
										id: id,
										"data-theme": theme,
										"data-count-theme": countTheme
									})
									.appendTo( "body" );

				newPage.page();

			parent.html( "" + title + "" );
		}).listview();
	},

	// JS fallback for auto-numbering for OL elements
	_numberItems: function() {
		if ( $.support.cssPseudoElement || !this.element.is( "ol" ) ) {
			return;
		}
		var counter = 1;
		this.element.find( ".ui-li-dec" ).remove();
		this.element.find( "li:visible" ).each(function() {
			if( $( this ).is( ".ui-li-divider" ) ) {
				//reset counter when a divider heading is encountered
				counter = 1;
			} else {
				$( this )
					.find( ".ui-link-inherit:first" )
					.addClass( "ui-li-jsnumbering" )
					.prepend( "" + (counter++) + ". " );
			}
		});
	}
});

})( jQuery );
<|endoftext|>


<commit_before>//= require slideout.js/dist/slideout.min.js

var html = document.documentElement;

function isInPage(node) {
  return (node === document.body) ? false : document.body.contains(node);
}

function getWidth() {
  return window.innerWidth ||
      document.documentElement.clientWidth ||
      document.body.clientWidth;
}

// -----------------------------------------------------------------------------
// Navigation
// -----------------------------------------------------------------------------

if (isInPage(document.getElementById('menu'))) {
  html.classList.add('slideout-root');

  var navigation_settings = {
    'panel': document.getElementById('panel'),
    'menu': document.getElementById('menu'),
    'width': getWidth(),
    'tolerance': 70
  }

  var navigation_timeout = false;

  var slideout = new Slideout({
    'panel': navigation_settings.panel,
    'menu': navigation_settings.menu,
    'padding': navigation_settings.width,
    'tolerance': navigation_settings.tolerance
  });

  slideout
    .on('beforeopen', function() {
      html.classList.add('slideout-root-overlay');
    })
    .on('beforeclose', function() {
      html.classList.remove('slideout-root-overlay');
    });

  slideout.disableTouch();

  function navigation(navigation_settings) {
    if (!slideout.isOpen()) {
      slideout.destroy();

      slideout = new Slideout({
        'panel': navigation_settings.panel,
        'menu': navigation_settings.menu,
        'padding': getWidth(),
        'tolerance': navigation_settings.tolerance
      });

      slideout
        .on('beforeopen', function() {
          html.classList.add('slideout-root-overlay');
        })
        .on('beforeclose', function() {
          html.classList.remove('slideout-root-overlay');
        });

      slideout.disableTouch();
    }
  }

  // --
  // Destroy and recreate slideout menu on resize …
  // WIP: https://bencentra.com/code/2015/02/27/optimizing-window-resize.html
  // --
  window.addEventListener('resize', function() {
    //clearTimeout(navigation_timeout);
    navigation_timeout = setTimeout(navigation(navigation_settings), 1000);
  });

  // --
  // Hamburger button click behaviour
  // --

  var hamburger = document.querySelector(".hamburger");
  hamburger.addEventListener("click", function() {
    hamburger.classList.toggle("is-active");
    hamburger.classList.toggle("is-inactive");

    slideout.toggle();
  });
}
<commit_msg>Remove window resize listener on nav<commit_after>//= require slideout.js/dist/slideout.min.js

var html = document.documentElement;

function isInPage(node) {
  return (node === document.body) ? false : document.body.contains(node);
}

function getWidth() {
  return window.innerWidth ||
      document.documentElement.clientWidth ||
      document.body.clientWidth;
}

// -----------------------------------------------------------------------------
// Navigation
// -----------------------------------------------------------------------------

if (isInPage(document.getElementById('menu'))) {
  html.classList.add('slideout-root');

  var slideout = new Slideout({
    'panel': document.getElementById('panel'),
    'menu': document.getElementById('menu'),
    'padding': getWidth(),
    'tolerance': 70
  });

  slideout
    .on('beforeopen', function() {
      html.classList.add('slideout-root-overlay');
    })
    .on('beforeclose', function() {
      html.classList.remove('slideout-root-overlay');
    });

  slideout.disableTouch();

  var hamburger = document.querySelector(".hamburger");
  hamburger.addEventListener("click", function() {
    hamburger.classList.toggle("is-active");
    hamburger.classList.toggle("is-inactive");
    slideout.toggle();
  });
}
<|endoftext|>


<commit_before>/**
 * Simple JSON schema validator.
 * Version 0.1
 * Based on http://tools.ietf.org/id/draft-zyp-json-schema-03.html, current support limited to properties and additional
 * properties, only core features, array / object are not really supported.
 *
 * User: pat
 * Date: 12-05-12
 * Time: 9:33 PM
 */
define(function () {

  var sjs = {

    messages:{
      invalidNumber:' is not a number',
      mustBeGreaterThan:' must be greater than',
      mustBeSmallerThan:' must be smaller than',
      mustBeGreaterOrEqualTo:' must be greater or equal to',
      mustBeSmallerOrEqualTo:' must be smaller or equal to',
      mustBeAtLeast:' must be at least ${number} characters',
      mustBeAtMost:' cannot be more than ${number} characters',
      invalidString:' is not a valid string',
      invalidInteger:' is not a valid integer',
      invalidBoolean:' is not a valid boolean',
      invalidObject:' is not a valid object',
      invalidArray:' is not a valid array',
      mustBeNull:' must be null',
      isRequired:' cannot be empty',
      doesNotMatchProvidedRegex:' does not match the format specified by regular expression',
      doesNotMatchProvidedPattern:' does not match the pattern',
      mustBeOneOf:' value must be one of: ${choices}',
      invalidDateTime:' must be in the format YYYY-MM-DDThh:mm:ssZ',
      invalidDate:' must be in the format YYYY-MM-DD',
      invalidTime:' must be in the format hh:mm:ss',
      invalidPhoneNumber:' is not a valid phone number',
      invalidEmail:' is not a valid e-mail address',
      invalidIpAddress:' is not a valid IP address',
      invalidIpv6Address:' is not a valid IPv6 address'
    },
    regex:{
      number:/^-?[0-9]*(,.[0-9]+)?$/,
      string:/^.+$/,
      integer:/^-?[0-9]+$/,
      email:/^\S+@\S+\.\S+$/,
      'date-time':/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2,3})$/,
      date:/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/,
      time:/^([0-9]{2}):([0-9]{2}):([0-9]{2,3})$/,
      'utc-millisec':/^[0-9]+$/,
      'ip-address':/^([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4}$/,
      ipv6:/^([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4}$/,
      phone:/^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/,
    },
    validators:{
      number:function (value, prop) {
        if (typeof value === 'number') {

          if (typeof prop.minimum !== 'undefined' && prop.exclusiveMinimum && value <= prop.minimum) {
            return sjs.messages.mustBeGreaterThan;
          } else if (typeof prop.minimum !== 'undefined' && value < prop.minimum) {
            return sjs.messages.mustBeGreaterOrEqualTo;
          } else if (typeof prop.maximum !== 'undefined' && prop.exlusiveMaximum && value >= prop.maximum) {
            return sjs.messages.mustBeSmallerThan;
          } else if (typeof prop.maximum !== 'undefined' && value > prop.maximum) {
            return sjs.messages.mustBeSmallerOrEqualTo;
          } else {
            return false;
          }
        } else if (sjs && sjs instanceof String && sjs.trim().length > 0 && sjs.regex.number.exec(value)) {
          return false;
        }

        return sjs.messages.invalidNumber;
      },
      string:function (value, prop) {
        if (typeof value === 'string') {
          if (prop.pattern && !new RegExp(prop.pattern).exec(value)) {
            return sjs.messages.doesNotMatchProvidedPattern + '(' + prop.pattern + ')';
          } else if (prop.minLength && value.length < prop.minLength) {
            return sjs.messages.mustBeAtLeast.replace('${number}', prop.minLength);
          } else if (prop.maxLength && value.length > prop.maxLength) {
            return sjs.messages.mustBeAtMost.replace('${number}', prop.maxLength);
          } else if (sjs.regex.string.exec(value)) {
            return false;
          }
        }

        return sjs.messages.invalidString;
      },
      integer:function (value, prop) {
        if (typeof value === 'number') {
          if (typeof prop.minimum !== 'undefined' && prop.exclusiveMinimum && value <= prop.minimum) {
            return sjs.messages.mustBeGreaterThan;
          } else if (typeof prop.minimum !== 'undefined' && value < prop.minimum) {
            return sjs.messages.mustBeGreaterOrEqualTo;
          } else if (typeof prop.maximum !== 'undefined' && prop.exlusiveMaximum && value >= prop.maximum) {
            return sjs.messages.mustBeSmallerThan;
          } else if (typeof prop.maximum !== 'undefined' && value > prop.maximum) {
            return sjs.messages.mustBeSmallerOrEqualTo;
          } else {
            return false;
          }
        }

        return sjs.messages.invalidInteger;
      },
      'boolean':function (value, prop) {
        if (typeof value === 'boolean') {
          return false;
        } else if (value === 'true' || value === 'false'
            || value === 0 || value === 1
            || value === 't' || value === 'f') {
          return false;
        }

        return sjs.messages.invalidBoolean;
      },
      'date-time':function (value, prop) {
        if (typeof value === 'string' && value.trim().length > 0 && !sjs.regex['date-time'].exec(value)) {
          return sjs.messages.invalidDateTime;
        }
        return false;
      },
      date:function (value, prop) {
        if (typeof value === 'string' && value.trim().length > 0 && !sjs.regex.date.exec(value)) {
          return sjs.messages.invalidDate;
        }
        return false;
      },
      time:function (value, prop) {
        if (typeof value === 'string' && value.trim().length > 0 && !sjs.regex.time.exec(value)) {
          return sjs.messages.invalidTime;
        }
        return false;
      },
      phone:function (value, prop) {
        if (typeof value === 'string' && value.trim().length > 0 && !sjs.regex.phone.exec(value)) {
          return sjs.messages.invalidPhoneNumber;
        }
        return false;
      },
      email:function (value, prop) {
        if (typeof value === 'string' && value.trim().length > 0 && !sjs.regex.email.exec(value)) {
          return sjs.messages.invalidEmail;
        }
        return false;
      },
      'ip-address':function (value, prop) {
        if (typeof value === 'string' && value.trim().length > 0 && !sjs.regex['ip-address'].exec(value)) {
          return sjs.messages.invalidIpAddress;
        }
        return false;
      },
      ipv6:function (value, prop) {
        if (typeof value === 'string' && value.trim().length > 0 && !sjs.regex.ipv6.exec(value)) {
          return sjs.messages.invalidIpv6Address;
        }
        return false;
      },
      object:function (value) {
        if (typeof value === 'object') {
          return false;
        }
        return sjs.messages.invalidObject;
      },
      array:function (value) {
        if (Object.prototype.toString.call(value) === '[object Array]') {
          return false;
        }
        return sjs.messages.invalidArray;
      },
      'null':function (value) {
        if (value === null) {
          return false;
        }
        return sjs.messages.mustBeNull;
      },
      any:function (value) {
        return false;
      }
    },
    validate:function (instance, schema, partial) {

      var errors = [];

      var appendIfErrors = function (propErrors) {
        if (propErrors) {
          errors = errors.concat(propErrors);
        }
      };

      if (partial) {

        // Validate only the attributes received
        for (var key in instance) {
          appendIfErrors(sjs.validateProp(instance, schema, key, schema.additionalProperties && schema.additionalProperties[key]));
        }

      } else {
        // Validate all the schema's properties
        for (var key in schema.properties) {
          appendIfErrors(sjs.validateProp(instance, schema, key));
        }
        for (var key in schema.additionalProperties) {
          appendIfErrors(sjs.validateProp(instance, schema, key, true));
        }
      }

      return {
        isValid:errors.length == 0,
        errors:errors
      };
    },
    validateProp:function (instance, schema, key, isAdditional) {

      var value = instance[key];
      var prop;
      var errors = [];
      if (!isAdditional) {
        prop = schema.properties[key];
      } else {
        prop = schema.additionalProperties[key];
      }

      if (!prop) {
        return;
      }

      if (prop.required && (typeof value === 'undefined' || (typeof value === 'string' && value.trim().length === 0))) {
        errors.push({property:key, error:sjs.messages.isRequired});
      } else {
        // Run the format validator if any
        var errorString = false;
        if (sjs.validators[prop.format]) {
          // We have a validator for this format, run it
          errorString = sjs.validators[prop.format](value, prop);
        } else if (!errorString && sjs.validators[prop.type]) {
          errorString = sjs.validators[prop.type](value, prop);
        } else if (!errorString && prop['enum']) {

          if (prop.enum.indexOf(value) === -1) {
            errorString = sjs.messages.mustBeOneOf.replace('${choices}', prop.enum.join(', '));
          }
        } else if (!errorString && prop.regex) {
          // Run the custom regex
          if (!new RegExp(prop.regex).exec(value)) {
            errorString = sjs.messages.doesNotMatchProvidedRegex + ' (' + prop.regex + ')';
          }
        }

        if (errorString) {
          errors.push({property:key, error:errorString});
        }
      }

      if (errors.length > 0) {
        return errors;
      }

    }
  };

  return sjs;
});<commit_msg>JSON schema validator Replacing string regex with a lighter one<commit_after>/**
 * Simple JSON schema validator.
 * Version 0.1
 * Based on http://tools.ietf.org/id/draft-zyp-json-schema-03.html, current support limited to properties and additional
 * properties, only core features, array / object are not really supported.
 *
 * User: pat
 * Date: 12-05-12
 * Time: 9:33 PM
 */
define(function () {

  var sjs = {

    messages:{
      invalidNumber:' is not a number',
      mustBeGreaterThan:' must be greater than',
      mustBeSmallerThan:' must be smaller than',
      mustBeGreaterOrEqualTo:' must be greater or equal to',
      mustBeSmallerOrEqualTo:' must be smaller or equal to',
      mustBeAtLeast:' must be at least ${number} characters',
      mustBeAtMost:' cannot be more than ${number} characters',
      invalidString:' is not a valid string',
      invalidInteger:' is not a valid integer',
      invalidBoolean:' is not a valid boolean',
      invalidObject:' is not a valid object',
      invalidArray:' is not a valid array',
      mustBeNull:' must be null',
      isRequired:' cannot be empty',
      doesNotMatchProvidedRegex:' does not match the format specified by regular expression',
      doesNotMatchProvidedPattern:' does not match the pattern',
      mustBeOneOf:' value must be one of: ${choices}',
      invalidDateTime:' must be in the format YYYY-MM-DDThh:mm:ssZ',
      invalidDate:' must be in the format YYYY-MM-DD',
      invalidTime:' must be in the format hh:mm:ss',
      invalidPhoneNumber:' is not a valid phone number',
      invalidEmail:' is not a valid e-mail address',
      invalidIpAddress:' is not a valid IP address',
      invalidIpv6Address:' is not a valid IPv6 address'
    },
    regex:{
      number:/^-?[0-9]*(,.[0-9]+)?$/,
      string:/.*/,
      integer:/^-?[0-9]+$/,
      email:/^\S+@\S+\.\S+$/,
      'date-time':/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2,3})$/,
      date:/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/,
      time:/^([0-9]{2}):([0-9]{2}):([0-9]{2,3})$/,
      'utc-millisec':/^[0-9]+$/,
      'ip-address':/^([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4}$/,
      ipv6:/^([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4}$/,
      phone:/^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/,
    },
    validators:{
      number:function (value, prop) {
        if (typeof value === 'number') {

          if (typeof prop.minimum !== 'undefined' && prop.exclusiveMinimum && value <= prop.minimum) {
            return sjs.messages.mustBeGreaterThan;
          } else if (typeof prop.minimum !== 'undefined' && value < prop.minimum) {
            return sjs.messages.mustBeGreaterOrEqualTo;
          } else if (typeof prop.maximum !== 'undefined' && prop.exlusiveMaximum && value >= prop.maximum) {
            return sjs.messages.mustBeSmallerThan;
          } else if (typeof prop.maximum !== 'undefined' && value > prop.maximum) {
            return sjs.messages.mustBeSmallerOrEqualTo;
          } else {
            return false;
          }
        } else if (sjs && sjs instanceof String && sjs.trim().length > 0 && sjs.regex.number.exec(value)) {
          return false;
        }

        return sjs.messages.invalidNumber;
      },
      string:function (value, prop) {
        if (typeof value === 'string') {
          if (prop.pattern && !new RegExp(prop.pattern).exec(value)) {
            return sjs.messages.doesNotMatchProvidedPattern + '(' + prop.pattern + ')';
          } else if (prop.minLength && value.length < prop.minLength) {
            return sjs.messages.mustBeAtLeast.replace('${number}', prop.minLength);
          } else if (prop.maxLength && value.length > prop.maxLength) {
            return sjs.messages.mustBeAtMost.replace('${number}', prop.maxLength);
          } else if (sjs.regex.string.exec(value)) {
            return false;
          }
        }

        return sjs.messages.invalidString;
      },
      integer:function (value, prop) {
        if (typeof value === 'number') {
          if (typeof prop.minimum !== 'undefined' && prop.exclusiveMinimum && value <= prop.minimum) {
            return sjs.messages.mustBeGreaterThan;
          } else if (typeof prop.minimum !== 'undefined' && value < prop.minimum) {
            return sjs.messages.mustBeGreaterOrEqualTo;
          } else if (typeof prop.maximum !== 'undefined' && prop.exlusiveMaximum && value >= prop.maximum) {
            return sjs.messages.mustBeSmallerThan;
          } else if (typeof prop.maximum !== 'undefined' && value > prop.maximum) {
            return sjs.messages.mustBeSmallerOrEqualTo;
          } else {
            return false;
          }
        }

        return sjs.messages.invalidInteger;
      },
      'boolean':function (value, prop) {
        if (typeof value === 'boolean') {
          return false;
        } else if (value === 'true' || value === 'false'
            || value === 0 || value === 1
            || value === 't' || value === 'f') {
          return false;
        }

        return sjs.messages.invalidBoolean;
      },
      'date-time':function (value, prop) {
        if (typeof value === 'string' && value.trim().length > 0 && !sjs.regex['date-time'].exec(value)) {
          return sjs.messages.invalidDateTime;
        }
        return false;
      },
      date:function (value, prop) {
        if (typeof value === 'string' && value.trim().length > 0 && !sjs.regex.date.exec(value)) {
          return sjs.messages.invalidDate;
        }
        return false;
      },
      time:function (value, prop) {
        if (typeof value === 'string' && value.trim().length > 0 && !sjs.regex.time.exec(value)) {
          return sjs.messages.invalidTime;
        }
        return false;
      },
      phone:function (value, prop) {
        if (typeof value === 'string' && value.trim().length > 0 && !sjs.regex.phone.exec(value)) {
          return sjs.messages.invalidPhoneNumber;
        }
        return false;
      },
      email:function (value, prop) {
        if (typeof value === 'string' && value.trim().length > 0 && !sjs.regex.email.exec(value)) {
          return sjs.messages.invalidEmail;
        }
        return false;
      },
      'ip-address':function (value, prop) {
        if (typeof value === 'string' && value.trim().length > 0 && !sjs.regex['ip-address'].exec(value)) {
          return sjs.messages.invalidIpAddress;
        }
        return false;
      },
      ipv6:function (value, prop) {
        if (typeof value === 'string' && value.trim().length > 0 && !sjs.regex.ipv6.exec(value)) {
          return sjs.messages.invalidIpv6Address;
        }
        return false;
      },
      object:function (value) {
        if (typeof value === 'object') {
          return false;
        }
        return sjs.messages.invalidObject;
      },
      array:function (value) {
        if (Object.prototype.toString.call(value) === '[object Array]') {
          return false;
        }
        return sjs.messages.invalidArray;
      },
      'null':function (value) {
        if (value === null) {
          return false;
        }
        return sjs.messages.mustBeNull;
      },
      any:function (value) {
        return false;
      }
    },
    validate:function (instance, schema, partial) {

      var errors = [];

      var appendIfErrors = function (propErrors) {
        if (propErrors) {
          errors = errors.concat(propErrors);
        }
      };

      if (partial) {

        // Validate only the attributes received
        for (var key in instance) {
          appendIfErrors(sjs.validateProp(instance, schema, key, schema.additionalProperties && schema.additionalProperties[key]));
        }

      } else {
        // Validate all the schema's properties
        for (var key in schema.properties) {
          appendIfErrors(sjs.validateProp(instance, schema, key));
        }
        for (var key in schema.additionalProperties) {
          appendIfErrors(sjs.validateProp(instance, schema, key, true));
        }
      }

      return {
        isValid:errors.length == 0,
        errors:errors
      };
    },
    validateProp:function (instance, schema, key, isAdditional) {

      var value = instance[key];
      var prop;
      var errors = [];
      if (!isAdditional) {
        prop = schema.properties[key];
      } else {
        prop = schema.additionalProperties[key];
      }

      if (!prop) {
        return;
      }

      if (prop.required && (typeof value === 'undefined' || (typeof value === 'string' && value.trim().length === 0))) {
        errors.push({property:key, error:sjs.messages.isRequired});
      } else {
        // Run the format validator if any
        var errorString = false;
        if (sjs.validators[prop.format]) {
          // We have a validator for this format, run it
          errorString = sjs.validators[prop.format](value, prop);
        } else if (!errorString && sjs.validators[prop.type]) {
          errorString = sjs.validators[prop.type](value, prop);
        } else if (!errorString && prop['enum']) {

          if (prop.enum.indexOf(value) === -1) {
            errorString = sjs.messages.mustBeOneOf.replace('${choices}', prop.enum.join(', '));
          }
        } else if (!errorString && prop.regex) {
          // Run the custom regex
          if (!new RegExp(prop.regex).exec(value)) {
            errorString = sjs.messages.doesNotMatchProvidedRegex + ' (' + prop.regex + ')';
          }
        }

        if (errorString) {
          errors.push({property:key, error:errorString});
        }
      }

      if (errors.length > 0) {
        return errors;
      }

    }
  };

  return sjs;
});<|endoftext|>


<commit_before>import { createNewTab, getCurrentTab, getExtensionURL, sendTabMessage } from "../../shared/library/extension.js";

const CONTEXT_SHARED_ALL = {
    contexts: ["all"]
};
const CONTEXT_SHARED_EDITABLE = {
    contexts: ["editable"]
};

let __menu;

export function updateContextMenu() {
    chrome.contextMenus.removeAll();
    __menu = chrome.contextMenus.create({
        title: "Buttercup",
        ...CONTEXT_SHARED_ALL
    });
    chrome.contextMenus.create({
        title: "About",
        parentId: __menu,
        onclick: () => {
            createNewTab(getExtensionURL("setup.html#/about"));
        },
        ...CONTEXT_SHARED_ALL
    });
    // const unlockArchiveMenu = chrome.contextMenus.create({
    //     title: "Unlock archive",
    //     parentId: __menu,
    //     ...CONTEXT_SHARED_ALL
    // });
    // chrome.contextMenus.create({
    //     title: "Lock all archives",
    //     parentId: __menu,
    //     onclick: () => {
    //         createNewTab(getExtensionURL("setup.html#/lock-archives"));
    //     },
    //     ...CONTEXT_SHARED_ALL
    // });
    chrome.contextMenus.create({
        parentId: __menu,
        type: "separator",
        ...CONTEXT_SHARED_ALL
    });
    // chrome.contextMenus.create({
    //     title: "Log in using",
    //     parentId: __menu,
    //     onclick: () => {
    //         // todo
    //     },
    //     enabled: false,
    //     ...CONTEXT_SHARED_ALL
    // });
    // chrome.contextMenus.create({
    //     title: "Enter login details",
    //     parentId: __menu,
    //     onclick: () => {
    //         // todo
    //     },
    //     enabled: false,
    //     ...CONTEXT_SHARED_ALL
    // });
    chrome.contextMenus.create({
        title: "Generate password",
        parentId: __menu,
        onclick: () => {
            getCurrentTab()
                .then(tab => tab.id)
                .then(tabID => {
                    sendTabMessage(tabID, {
                        type: "open-generator"
                    });
                });
        },
        ...CONTEXT_SHARED_EDITABLE
    });
}
<commit_msg>Add password to editable items<commit_after>import { createNewTab, getCurrentTab, getExtensionURL, sendTabMessage } from "../../shared/library/extension.js";

const CONTEXT_SHARED_ALL = {
    contexts: ["all"]
};
const CONTEXT_SHARED_EDITABLE = {
    contexts: ["editable", "password"]
};

let __menu;

export function updateContextMenu() {
    chrome.contextMenus.removeAll();
    __menu = chrome.contextMenus.create({
        title: "Buttercup",
        ...CONTEXT_SHARED_ALL
    });
    chrome.contextMenus.create({
        title: "About",
        parentId: __menu,
        onclick: () => {
            createNewTab(getExtensionURL("setup.html#/about"));
        },
        ...CONTEXT_SHARED_ALL
    });
    // const unlockArchiveMenu = chrome.contextMenus.create({
    //     title: "Unlock archive",
    //     parentId: __menu,
    //     ...CONTEXT_SHARED_ALL
    // });
    // chrome.contextMenus.create({
    //     title: "Lock all archives",
    //     parentId: __menu,
    //     onclick: () => {
    //         createNewTab(getExtensionURL("setup.html#/lock-archives"));
    //     },
    //     ...CONTEXT_SHARED_ALL
    // });
    chrome.contextMenus.create({
        parentId: __menu,
        type: "separator",
        ...CONTEXT_SHARED_ALL
    });
    // chrome.contextMenus.create({
    //     title: "Log in using",
    //     parentId: __menu,
    //     onclick: () => {
    //         // todo
    //     },
    //     enabled: false,
    //     ...CONTEXT_SHARED_ALL
    // });
    // chrome.contextMenus.create({
    //     title: "Enter login details",
    //     parentId: __menu,
    //     onclick: () => {
    //         // todo
    //     },
    //     enabled: false,
    //     ...CONTEXT_SHARED_ALL
    // });
    chrome.contextMenus.create({
        title: "Generate password",
        parentId: __menu,
        onclick: () => {
            getCurrentTab()
                .then(tab => tab.id)
                .then(tabID => {
                    sendTabMessage(tabID, {
                        type: "open-generator"
                    });
                });
        },
        ...CONTEXT_SHARED_EDITABLE
    });
}
<|endoftext|>