<commit_before>
try {

	require( 'puppeteer' );

} catch {

	console.log( 'Error: Can\'t find Puppeteer. Run `npm install --prefix test`.' );
	process.exit( 0 );

}

const puppeteer = require( 'puppeteer' );
const handler = require( 'serve-handler' );
const http = require( 'http' );
const pixelmatch = require( 'pixelmatch' );
const jimp = require( 'jimp' );
const fs = require( 'fs' );

const port = 1234;
const pixelThreshold = 0.1; // threshold error in one pixel
const maxFailedPixels = 0.05; // total failed pixels

const networkTimeout = 600;
const networkTax = 2000; // additional timeout for resources size
const pageSizeMinTax = 1.0; // in mb, when networkTax = 0
const pageSizeMaxTax = 5.0; // in mb, when networkTax = networkTax
const renderTimeout = 1200;
const maxAttemptId = 3; // progresseve attempts
const progressFunc = n => 1 + n;

const width = 400;
const height = 250;
const viewScale = 2;
const jpgQuality = 95;

const exceptionList = [

	'index',
	'css3d_youtube', // video tag not deterministic enough
	'webaudio_visualizer', // audio can't be analyzed without proper audio hook
	'webgl_loader_texture_lottie', // not sure why this fails
	'webgl_loader_texture_pvrtc', // not supported in CI, useless
	'webgl_materials_envmaps_parallax', // empty for some reason
	'webgl_raymarching_reflect', // exception for Github Actions
	'webgl_test_memory2', // gives fatal error in puppeteer
	'webgl_tiled_forward', // exception for Github Actions
	'webgl_video_kinect', // video tag not deterministic enough
	'webgl_worker_offscreencanvas', // in a worker, not robust
	// webxr
	'webxr_ar_lighting',
	// webgpu
	'webgpu_compute',
	'webgpu_instance_uniform',
	'webgpu_lights_selective',
	'webgpu_materials',
	'webgpu_rtt',
	'webgpu_sandbox'
].concat( ( process.platform === 'win32' ) ? [

	'webgl_effects_ascii' // windows fonts not supported

] : [] );

console.green = ( msg ) => console.log( `\x1b[32m${ msg }\x1b[37m` );
console.red = ( msg ) => console.log( `\x1b[31m${ msg }\x1b[37m` );
console.null = () => {};

/* Launch server */

const server = http.createServer( ( req, resp ) => handler( req, resp ) );
server.listen( port, async () => await pup );
server.on( 'SIGINT', () => process.exit( 1 ) );

/* Launch browser */

const pup = puppeteer.launch( {
	headless: ! process.env.VISIBLE,
	args: [
		'--use-gl=swiftshader',
		'--no-sandbox',
		'--enable-surface-synchronization'
	]
} ).then( async browser => {

	/* Prepare page */

	const page = ( await browser.pages() )[ 0 ];
	await page.setViewport( { width: width * viewScale, height: height * viewScale } );

	const cleanPage = fs.readFileSync( 'test/e2e/clean-page.js', 'utf8' );
	const injection = fs.readFileSync( 'test/e2e/deterministic-injection.js', 'utf8' );
	await page.evaluateOnNewDocument( injection );

	const threeJsBuild = fs.readFileSync( 'build/three.module.js', 'utf8' )
		.replace( /Math\.random\(\) \* 0xffffffff/g, 'Math._random() * 0xffffffff' );
	await page.setRequestInterception( true );

	page.on( 'console', msg => ( msg.text().slice( 0, 8 ) === 'Warning.' ) ? console.null( msg.text() ) : {} );
	page.on( 'request', async ( request ) => {

		if ( request.url() === 'http://localhost:1234/build/three.module.js' ) {

			await request.respond( {
				status: 200,
				contentType: 'application/javascript; charset=utf-8',
				body: threeJsBuild
			} );

		} else {

			await request.continue();

		}

	} );
	page.on( 'response', async ( response ) => {

		try {

			await response.buffer().then( buffer => pageSize += buffer.length );

		} catch ( e ) {

			console.null( `Warning. Wrong request. \n${ e }` );

		}

	} );

	/* Find files */

	const isMakeScreenshot = process.argv[ 2 ] == '--make';
	const isExactList = process.argv.length > ( 2 + isMakeScreenshot );

	const exactList = process.argv.slice( isMakeScreenshot ? 3 : 2 )
		.map( f => f.replace( '.html', '' ) );

	const files = fs.readdirSync( './examples' )
		.filter( s => s.slice( - 5 ) === '.html' )
		.map( s => s.slice( 0, s.length - 5 ) )
		.filter( f => isExactList ? exactList.includes( f ) : ! exceptionList.includes( f ) );

	/* Loop for each file, with CI parallelism */

	let pageSize, file, attemptProgress;
	const failedScreenshots = [];
	const isParallel = 'CI' in process.env;
	const beginId = isParallel ? Math.floor( parseInt( process.env.CI.slice( 0, 1 ) ) * files.length / 4 ) : 0;
	const endId = isParallel ? Math.floor( ( parseInt( process.env.CI.slice( - 1 ) ) + 1 ) * files.length / 4 ) : files.length;

	for ( let id = beginId; id < endId; ++ id ) {

		/* At least 3 attempts before fail */

		let attemptId = isMakeScreenshot ? 1.5 : 0;

		while ( attemptId < maxAttemptId ) {

			/* Load target page */

			file = files[ id ];
			attemptProgress = progressFunc( attemptId );
			pageSize = 0;

			try {

				await page.goto( `http://localhost:${ port }/examples/${ file }.html`, {
					waitUntil: 'networkidle2',
					timeout: networkTimeout * attemptProgress
				} );

			} catch {

				console.null( 'Warning. Network timeout exceeded...' );

			}

			try {

				/* Render page */

				await page.evaluate( cleanPage );

				await page.evaluate( async ( pageSize, pageSizeMinTax, pageSizeMaxTax, networkTax, renderTimeout, attemptProgress ) => {

					/* Resource timeout */

					const resourcesSize = Math.min( 1, ( pageSize / 1024 / 1024 - pageSizeMinTax ) / pageSizeMaxTax );
					await new Promise( resolve => setTimeout( resolve, networkTax * resourcesSize * attemptProgress ) );

					/* Resolve render promise */

					window._renderStarted = true;

					await new Promise( function ( resolve ) {

						performance._now = performance._now || performance.now;

						const renderStart = performance._now();

						const waitingLoop = setInterval( function () {

							const renderEcceded = ( performance._now() - renderStart > renderTimeout * attemptProgress );
							if ( window._renderFinished || renderEcceded ) {

								if ( renderEcceded ) {

									console.log( 'Warning. Render timeout exceeded...' );

								}

								clearInterval( waitingLoop );
								resolve();

							}

						}, 0 );

					} );

				}, pageSize, pageSizeMinTax, pageSizeMaxTax, networkTax, renderTimeout, attemptProgress );

			} catch ( e ) {

				if ( ++ attemptId === maxAttemptId ) {

					console.red( `Something completely wrong. 'Network timeout' is small for your machine. file: ${ file } \n${ e }` );
					failedScreenshots.push( file );
					continue;

				} else {

					console.log( 'Another attempt..' );
					await new Promise( resolve => setTimeout( resolve, networkTimeout * attemptProgress ) );

				}

			}

			if ( isMakeScreenshot ) {

				/* Make screenshots */

				attemptId = maxAttemptId;
				( await jimp.read( await page.screenshot() ) )
					.scale( 1 / viewScale ).quality( jpgQuality )
					.write( `./examples/screenshots/${ file }.jpg` );

				console.green( `file: ${ file } generated` );

			} else if ( fs.existsSync( `./examples/screenshots/${ file }.jpg` ) ) {

				/* Diff screenshots */

				const actual = ( await jimp.read( await page.screenshot() ) ).scale( 1 / viewScale ).quality( jpgQuality ).bitmap;
				const expected = ( await jimp.read( fs.readFileSync( `./examples/screenshots/${ file }.jpg` ) ) ).bitmap;
				const diff = actual;

				let numFailedPixels;

				try {

					numFailedPixels = pixelmatch( expected.data, actual.data, diff.data, actual.width, actual.height, {
						threshold: pixelThreshold,
						alpha: 0.2,
						diffMask: process.env.FORCE_COLOR === '0',
						diffColor: process.env.FORCE_COLOR === '0' ? [ 255, 255, 255 ] : [ 255, 0, 0 ]
					} );

				} catch {

					attemptId = maxAttemptId;
					console.red( `Something completely wrong. Image sizes does not match in file: ${ file }` );
					failedScreenshots.push( file );
					continue;

				}

				numFailedPixels /= actual.width * actual.height;

				/* Print results */

				if ( numFailedPixels < maxFailedPixels ) {

					attemptId = maxAttemptId;
					console.green( `diff: ${ numFailedPixels.toFixed( 3 ) }, file: ${ file }` );

				} else {

					if ( ++ attemptId === maxAttemptId ) {

						console.red( `ERROR! Diff wrong in ${ numFailedPixels.toFixed( 3 ) } of pixels in file: ${ file }` );
						failedScreenshots.push( file );
						continue;

					} else {

						console.log( 'Another attempt...' );

					}

				}

			} else {

				attemptId = maxAttemptId;
				console.log( `Warning! Screenshot not exists: ${ file }` );
				continue;

			}

		}

	}

	/* Finish */

	if ( failedScreenshots.length ) {

		if ( failedScreenshots.length > 1 ) {

			console.red( 'List of failed screenshots: ' + failedScreenshots.join( ' ' ) );

		} else {

			console.red( `If you sure that all is right, try to run \`npm run make-screenshot ${ failedScreenshots[ 0 ] }\`` );

		}

		console.red( `TEST FAILED! ${ failedScreenshots.length } from ${ endId - beginId } screenshots not pass.` );

	} else if ( ! isMakeScreenshot ) {

		console.green( `TEST PASSED! ${ endId - beginId } screenshots correctly rendered.` );

	}

	setTimeout( () => {

		server.close();
		browser.close();
		process.exit( failedScreenshots.length );

	}, 300 );

} );
<commit_msg>Avoid testing webgl_materials_standard_nodes for now<commit_after>
try {

	require( 'puppeteer' );

} catch {

	console.log( 'Error: Can\'t find Puppeteer. Run `npm install --prefix test`.' );
	process.exit( 0 );

}

const puppeteer = require( 'puppeteer' );
const handler = require( 'serve-handler' );
const http = require( 'http' );
const pixelmatch = require( 'pixelmatch' );
const jimp = require( 'jimp' );
const fs = require( 'fs' );

const port = 1234;
const pixelThreshold = 0.1; // threshold error in one pixel
const maxFailedPixels = 0.05; // total failed pixels

const networkTimeout = 600;
const networkTax = 2000; // additional timeout for resources size
const pageSizeMinTax = 1.0; // in mb, when networkTax = 0
const pageSizeMaxTax = 5.0; // in mb, when networkTax = networkTax
const renderTimeout = 1200;
const maxAttemptId = 3; // progresseve attempts
const progressFunc = n => 1 + n;

const width = 400;
const height = 250;
const viewScale = 2;
const jpgQuality = 95;

const exceptionList = [

	'index',
	'css3d_youtube', // video tag not deterministic enough
	'webaudio_visualizer', // audio can't be analyzed without proper audio hook
	'webgl_loader_texture_lottie', // not sure why this fails
	'webgl_loader_texture_pvrtc', // not supported in CI, useless
	'webgl_materials_envmaps_parallax', // empty for some reason
	'webgl_materials_standard_nodes', // puppeteer does not support import maps yet
	'webgl_raymarching_reflect', // exception for Github Actions
	'webgl_test_memory2', // gives fatal error in puppeteer
	'webgl_tiled_forward', // exception for Github Actions
	'webgl_video_kinect', // video tag not deterministic enough
	'webgl_worker_offscreencanvas', // in a worker, not robust
	// webxr
	'webxr_ar_lighting',
	// webgpu
	'webgpu_compute',
	'webgpu_instance_uniform',
	'webgpu_lights_selective',
	'webgpu_materials',
	'webgpu_rtt',
	'webgpu_sandbox'
].concat( ( process.platform === 'win32' ) ? [

	'webgl_effects_ascii' // windows fonts not supported

] : [] );

console.green = ( msg ) => console.log( `\x1b[32m${ msg }\x1b[37m` );
console.red = ( msg ) => console.log( `\x1b[31m${ msg }\x1b[37m` );
console.null = () => {};

/* Launch server */

const server = http.createServer( ( req, resp ) => handler( req, resp ) );
server.listen( port, async () => await pup );
server.on( 'SIGINT', () => process.exit( 1 ) );

/* Launch browser */

const pup = puppeteer.launch( {
	headless: ! process.env.VISIBLE,
	args: [
		'--use-gl=swiftshader',
		'--no-sandbox',
		'--enable-surface-synchronization'
	]
} ).then( async browser => {

	/* Prepare page */

	const page = ( await browser.pages() )[ 0 ];
	await page.setViewport( { width: width * viewScale, height: height * viewScale } );

	const cleanPage = fs.readFileSync( 'test/e2e/clean-page.js', 'utf8' );
	const injection = fs.readFileSync( 'test/e2e/deterministic-injection.js', 'utf8' );
	await page.evaluateOnNewDocument( injection );

	const threeJsBuild = fs.readFileSync( 'build/three.module.js', 'utf8' )
		.replace( /Math\.random\(\) \* 0xffffffff/g, 'Math._random() * 0xffffffff' );
	await page.setRequestInterception( true );

	page.on( 'console', msg => ( msg.text().slice( 0, 8 ) === 'Warning.' ) ? console.null( msg.text() ) : {} );
	page.on( 'request', async ( request ) => {

		if ( request.url() === 'http://localhost:1234/build/three.module.js' ) {

			await request.respond( {
				status: 200,
				contentType: 'application/javascript; charset=utf-8',
				body: threeJsBuild
			} );

		} else {

			await request.continue();

		}

	} );
	page.on( 'response', async ( response ) => {

		try {

			await response.buffer().then( buffer => pageSize += buffer.length );

		} catch ( e ) {

			console.null( `Warning. Wrong request. \n${ e }` );

		}

	} );

	/* Find files */

	const isMakeScreenshot = process.argv[ 2 ] == '--make';
	const isExactList = process.argv.length > ( 2 + isMakeScreenshot );

	const exactList = process.argv.slice( isMakeScreenshot ? 3 : 2 )
		.map( f => f.replace( '.html', '' ) );

	const files = fs.readdirSync( './examples' )
		.filter( s => s.slice( - 5 ) === '.html' )
		.map( s => s.slice( 0, s.length - 5 ) )
		.filter( f => isExactList ? exactList.includes( f ) : ! exceptionList.includes( f ) );

	/* Loop for each file, with CI parallelism */

	let pageSize, file, attemptProgress;
	const failedScreenshots = [];
	const isParallel = 'CI' in process.env;
	const beginId = isParallel ? Math.floor( parseInt( process.env.CI.slice( 0, 1 ) ) * files.length / 4 ) : 0;
	const endId = isParallel ? Math.floor( ( parseInt( process.env.CI.slice( - 1 ) ) + 1 ) * files.length / 4 ) : files.length;

	for ( let id = beginId; id < endId; ++ id ) {

		/* At least 3 attempts before fail */

		let attemptId = isMakeScreenshot ? 1.5 : 0;

		while ( attemptId < maxAttemptId ) {

			/* Load target page */

			file = files[ id ];
			attemptProgress = progressFunc( attemptId );
			pageSize = 0;

			try {

				await page.goto( `http://localhost:${ port }/examples/${ file }.html`, {
					waitUntil: 'networkidle2',
					timeout: networkTimeout * attemptProgress
				} );

			} catch {

				console.null( 'Warning. Network timeout exceeded...' );

			}

			try {

				/* Render page */

				await page.evaluate( cleanPage );

				await page.evaluate( async ( pageSize, pageSizeMinTax, pageSizeMaxTax, networkTax, renderTimeout, attemptProgress ) => {

					/* Resource timeout */

					const resourcesSize = Math.min( 1, ( pageSize / 1024 / 1024 - pageSizeMinTax ) / pageSizeMaxTax );
					await new Promise( resolve => setTimeout( resolve, networkTax * resourcesSize * attemptProgress ) );

					/* Resolve render promise */

					window._renderStarted = true;

					await new Promise( function ( resolve ) {

						performance._now = performance._now || performance.now;

						const renderStart = performance._now();

						const waitingLoop = setInterval( function () {

							const renderEcceded = ( performance._now() - renderStart > renderTimeout * attemptProgress );
							if ( window._renderFinished || renderEcceded ) {

								if ( renderEcceded ) {

									console.log( 'Warning. Render timeout exceeded...' );

								}

								clearInterval( waitingLoop );
								resolve();

							}

						}, 0 );

					} );

				}, pageSize, pageSizeMinTax, pageSizeMaxTax, networkTax, renderTimeout, attemptProgress );

			} catch ( e ) {

				if ( ++ attemptId === maxAttemptId ) {

					console.red( `Something completely wrong. 'Network timeout' is small for your machine. file: ${ file } \n${ e }` );
					failedScreenshots.push( file );
					continue;

				} else {

					console.log( 'Another attempt..' );
					await new Promise( resolve => setTimeout( resolve, networkTimeout * attemptProgress ) );

				}

			}

			if ( isMakeScreenshot ) {

				/* Make screenshots */

				attemptId = maxAttemptId;
				( await jimp.read( await page.screenshot() ) )
					.scale( 1 / viewScale ).quality( jpgQuality )
					.write( `./examples/screenshots/${ file }.jpg` );

				console.green( `file: ${ file } generated` );

			} else if ( fs.existsSync( `./examples/screenshots/${ file }.jpg` ) ) {

				/* Diff screenshots */

				const actual = ( await jimp.read( await page.screenshot() ) ).scale( 1 / viewScale ).quality( jpgQuality ).bitmap;
				const expected = ( await jimp.read( fs.readFileSync( `./examples/screenshots/${ file }.jpg` ) ) ).bitmap;
				const diff = actual;

				let numFailedPixels;

				try {

					numFailedPixels = pixelmatch( expected.data, actual.data, diff.data, actual.width, actual.height, {
						threshold: pixelThreshold,
						alpha: 0.2,
						diffMask: process.env.FORCE_COLOR === '0',
						diffColor: process.env.FORCE_COLOR === '0' ? [ 255, 255, 255 ] : [ 255, 0, 0 ]
					} );

				} catch {

					attemptId = maxAttemptId;
					console.red( `Something completely wrong. Image sizes does not match in file: ${ file }` );
					failedScreenshots.push( file );
					continue;

				}

				numFailedPixels /= actual.width * actual.height;

				/* Print results */

				if ( numFailedPixels < maxFailedPixels ) {

					attemptId = maxAttemptId;
					console.green( `diff: ${ numFailedPixels.toFixed( 3 ) }, file: ${ file }` );

				} else {

					if ( ++ attemptId === maxAttemptId ) {

						console.red( `ERROR! Diff wrong in ${ numFailedPixels.toFixed( 3 ) } of pixels in file: ${ file }` );
						failedScreenshots.push( file );
						continue;

					} else {

						console.log( 'Another attempt...' );

					}

				}

			} else {

				attemptId = maxAttemptId;
				console.log( `Warning! Screenshot not exists: ${ file }` );
				continue;

			}

		}

	}

	/* Finish */

	if ( failedScreenshots.length ) {

		if ( failedScreenshots.length > 1 ) {

			console.red( 'List of failed screenshots: ' + failedScreenshots.join( ' ' ) );

		} else {

			console.red( `If you sure that all is right, try to run \`npm run make-screenshot ${ failedScreenshots[ 0 ] }\`` );

		}

		console.red( `TEST FAILED! ${ failedScreenshots.length } from ${ endId - beginId } screenshots not pass.` );

	} else if ( ! isMakeScreenshot ) {

		console.green( `TEST PASSED! ${ endId - beginId } screenshots correctly rendered.` );

	}

	setTimeout( () => {

		server.close();
		browser.close();
		process.exit( failedScreenshots.length );

	}, 300 );

} );
<|endoftext|>


<commit_before>var Transform = require('pipestream').Transform;
var util = require('../../util');
var config = util.config;
var protocolLength = 'weinre://'.length;

function getWeinreScript(name) {
	return '<script src="http://weinre.' + config.localUIHost + '/target/target-script-min.js#'
	+ name + '"></script>';
}

module.exports = function(req, res, next) {
	if (req.rules.weinre) {
		res.on('src', function(_res) {
			if (!util.supportHtmlTransform(_res)) {
				return;
			}
			var url = req.rules.weinre.url.substring(protocolLength);
			if (!url) {
				return;
			}

			var transform = new Transform();
			transform._transform = function(chunk, encoding, callback) {
				if (!chunk) {
					chunk = getWeinreScript(url);
				}
				callback(null, encoding);
			};

			res.addZipTransform(transform, false, true);

		});
	}

	next();
};<commit_msg>add weinre<commit_after>var Transform = require('pipestream').Transform;
var util = require('../../util');
var config = util.config;
var protocolLength = 'weinre://'.length;

function getWeinreScript(name) {
	return '\r\n<script src="http://weinre.' + config.localUIHost + '/target/target-script-min.js#'
	+ name + '"></script>\r\n';
}

module.exports = function(req, res, next) {
	if (req.rules.weinre) {
		res.on('src', function(_res) {
			if (!util.supportHtmlTransform(_res)) {
				return;
			}
			var url = req.rules.weinre.url.substring(protocolLength);
			if (!url) {
				return;
			}

			var transform = new Transform();
			transform._transform = function(chunk, encoding, callback) {
				if (!chunk) {
					chunk = getWeinreScript(url);
				}
				callback(null, chunk);
			};

			res.addZipTransform(transform, false, true);

		});
	}

	next();
};<|endoftext|>


<commit_before>var assert = require('assert')
var util = require('util')

var extend = require('../lib/extend-config.js')

describe('extend-config', function () {
	it('should create needed objects if passed undefined', function () {
		assert.equal(typeof extend(), typeof {})
		assert.equal(typeof extend().rethinkdb, typeof {})
	})
	it('should create needed objects if passed a blank object', function () {
		assert.equal(typeof extend({}), typeof {})
		assert.equal(typeof extend().rethinkdb, typeof {})
	})
	describe('non-blank objects passed to extend-config', function () {
		var config = extend({rethinkdb: {port: 'hi'}}) // This should overwrite the returned object's rethinkdb.port to "hi"
		var config2 = extend({rethinkdb2: {port: 'hi'}}) // This should not overwrite anything, but rethinkdb2 should be preserved
		it('should create needed objects', function () {
			assert.equal(typeof config, typeof {}, 'config should be an object')
			assert.equal(typeof config.rethinkdb, typeof {}, 'config.rethinkdb should be an object')
			assert.equal(typeof config2, typeof {}, 'config2 should be an object')
			assert.equal(typeof config2.rethinkdb, typeof {}, 'config2.rethinkdb should be an object')
		})
		it('should preserve options it doesn\'t understand', function () {
			assert.equal(typeof config2.rethinkdb2, typeof {})
		})
		it('should not overwrite things', function () {
			assert.equal(config.rethinkdb.port, 'hi')
		})
	})
})
<commit_msg>Remove unnecessary require()ment in config test<commit_after>var assert = require('assert')

var extend = require('../lib/extend-config.js')

describe('extend-config', function () {
	it('should create needed objects if passed undefined', function () {
		assert.equal(typeof extend(), typeof {})
		assert.equal(typeof extend().rethinkdb, typeof {})
	})
	it('should create needed objects if passed a blank object', function () {
		assert.equal(typeof extend({}), typeof {})
		assert.equal(typeof extend().rethinkdb, typeof {})
	})
	describe('non-blank objects passed to extend-config', function () {
		var config = extend({rethinkdb: {port: 'hi'}}) // This should overwrite the returned object's rethinkdb.port to "hi"
		var config2 = extend({rethinkdb2: {port: 'hi'}}) // This should not overwrite anything, but rethinkdb2 should be preserved
		it('should create needed objects', function () {
			assert.equal(typeof config, typeof {}, 'config should be an object')
			assert.equal(typeof config.rethinkdb, typeof {}, 'config.rethinkdb should be an object')
			assert.equal(typeof config2, typeof {}, 'config2 should be an object')
			assert.equal(typeof config2.rethinkdb, typeof {}, 'config2.rethinkdb should be an object')
		})
		it('should preserve options it doesn\'t understand', function () {
			assert.equal(typeof config2.rethinkdb2, typeof {})
		})
		it('should not overwrite things', function () {
			assert.equal(config.rethinkdb.port, 'hi')
		})
	})
})
<|endoftext|>


<commit_before>// Webflow code to submit form

const verification = (t, e, n, i) => {
	let r = null, k = /e(-)?mail/i, _ = /^\S+@\S+$/;
	return e === 'password' ? r = 'Passwords cannot be submitted.' : getAttribute(t,'required') && (i ? (k.test(n) || k.test(getAttribute(t,'type'))) && (_.test(i) || (r = 'Please enter a valid email address for: ' + n)) : r = 'Please fill out the required field: ' + n), r
}

const conversion = (e, n) => {
	let i = null
	for (r=0; r<e[0].elements.length; r++) {
		console.log('test #1')
		const o = e[0].elements[r]
		console.log(o)
		let a = getElementById(o),
			s = getAttribute(a,'type'),
			u = getAttribute(a,'data-name') || getAttribute(a,'name') || 'Field ' + (r + 1),
			l = getValue(a)
		console.log('test #2')
		if (s === 'checkbox' && (l = isChecked(a)), s === 'radio') {
			if (n[u] === null || typeof n[u] == 'string' || s == 'submit') return;
			l = getValue(e.find('input[name="' + getAttribute(a,'name') + '"]:checked')) || null
		}
		console.log('test #3')
		typeof l == 'string' && (l = l.trim()), n[u] = l, i = i || verification(a, s, u, l)
		console.log('test #4')
	}
	return n = n || {}, i
}

const createForm = () => {
	let formData = {
		name: page() === 'Event' ? 'Event Registration' : 'Custom Charge',
		source: window.location.href,
		test: false,
		fields: {},
		dolphin: false
	}
	let error = conversion(page() === 'Event' ? getElementById(eventForm) : getElementById(customForm), formData.fields)
	if (error) {
		throw error
	}
	console.log(formData)
	return formData
}<commit_msg>Update.<commit_after>// Webflow code to submit form

const verification = (t, e, n, i) => {
	let r = null, k = /e(-)?mail/i, _ = /^\S+@\S+$/;
	return e === 'password' ? r = 'Passwords cannot be submitted.' : getAttribute(t,'required') && (i ? (k.test(n) || k.test(getAttribute(t,'type'))) && (_.test(i) || (r = 'Please enter a valid email address for: ' + n)) : r = 'Please fill out the required field: ' + n), r
}

const conversion = (e, n) => {
	let i = null
	for (r=0; r<e[0].elements.length; r++) {
		console.log('test #1')
		const o = e[0].elements[r][0]
		console.log(o)
		let a = getElementById(o),
			s = getAttribute(a,'type'),
			u = getAttribute(a,'data-name') || getAttribute(a,'name') || 'Field ' + (r + 1),
			l = getValue(a)
		console.log('test #2')
		if (s === 'checkbox' && (l = isChecked(a)), s === 'radio') {
			if (n[u] === null || typeof n[u] == 'string' || s == 'submit') return;
			l = getValue(e.find('input[name="' + getAttribute(a,'name') + '"]:checked')) || null
		}
		console.log('test #3')
		typeof l == 'string' && (l = l.trim()), n[u] = l, i = i || verification(a, s, u, l)
		console.log('test #4')
	}
	return n = n || {}, i
}

const createForm = () => {
	let formData = {
		name: page() === 'Event' ? 'Event Registration' : 'Custom Charge',
		source: window.location.href,
		test: false,
		fields: {},
		dolphin: false
	}
	let error = conversion(page() === 'Event' ? getElementById(eventForm) : getElementById(customForm), formData.fields)
	if (error) {
		throw error
	}
	console.log(formData)
	return formData
}<|endoftext|>


<commit_before>if(!window.belay) window.belay = {};
window.belay.belayInit = (function() {
  var callbacks = [];
  console.log('initializing...');

  function frameInfo(frameMaker, frameAdder, email) {
    function connect() {
      var frameWindow = frame[0].contentWindow;

      frame.unbind('load', connect);

      window.belay.port = makePostMessagePort(frameWindow, "belay");

      // TODO(joe): check args order of postMessage cross browser, use
      // $.pm() here if necessary
      var loc = window.location;
      var location = {
        hash: loc.hash,
        hostname: loc.hostname,
        port: loc.port,
        pathname: loc.pathname,
        href: loc.href
      };
      $.pm({
        target: frameWindow,
        type: 'init',
        data: {
          clientLocation: location,
          email: email
        }
      });

      // Clear the has ASAP
      window.location.hash = "";

      window.belay.portReady();
    }

    var frame = frameMaker();
    frame.load(connect);
    frameAdder(frame);
  }

  return Object.freeze(frameInfo);
})();

<commit_msg>save the launchcap in window.name for refreshes<commit_after>if(!window.belay) window.belay = {};
window.belay.belayInit = (function() {
  var callbacks = [];
  console.log('initializing...');

  function frameInfo(frameMaker, frameAdder, email) {
    function connect() {
      var frameWindow = frame[0].contentWindow;

      frame.unbind('load', connect);

      window.belay.port = makePostMessagePort(frameWindow, "belay");

      // TODO(joe): check args order of postMessage cross browser, use
      // $.pm() here if necessary
      var loc = window.location;
      var hash = window.location.hash;
      if (loc.hash === "" || loc.hash === "#") {
        hash = window.name;
      }
      var location = {
        hash: hash,
        hostname: loc.hostname,
        port: loc.port,
        pathname: loc.pathname,
        href: loc.href
      };
      $.pm({
        target: frameWindow,
        type: 'init',
        data: {
          clientLocation: location,
          email: email
        }
      });

      // Clear the hash ASAP
      window.location.hash = "";

      window.name = hash;
      window.belay.portReady();
    }

    var frame = frameMaker();
    frame.load(connect);
    frameAdder(frame);
  }

  return Object.freeze(frameInfo);
})();

<|endoftext|>


<commit_before>var core = require("../level2/core").dom.level2.core;

/*
  valuetype DOMString sequence<unsigned short>;
  typedef   unsigned long long DOMTimeStamp;
  typedef   any DOMUserData;
  typedef   Object DOMObject;

*/
  // ExceptionCode
  core.VALIDATION_ERR                 = 16;
  core.TYPE_MISMATCH_ERR              = 17;

/*
  // Introduced in DOM Level 3:
  interface DOMStringList {
    DOMString          item(in unsigned long index);
    readonly attribute unsigned long   length;
    boolean            contains(in DOMString str);
  };

  // Introduced in DOM Level 3:
  interface NameList {
    DOMString          getName(in unsigned long index);
    DOMString          getNamespaceURI(in unsigned long index);
    readonly attribute unsigned long   length;
    boolean            contains(in DOMString str);
    boolean            containsNS(in DOMString namespaceURI,
                                  in DOMString name);
  };

  // Introduced in DOM Level 3:
  interface DOMImplementationList {
    DOMImplementation  item(in unsigned long index);
    readonly attribute unsigned long   length;
  };

  // Introduced in DOM Level 3:
  interface DOMImplementationSource {
    DOMImplementation  getDOMImplementation(in DOMString features);
    DOMImplementationList getDOMImplementationList(in DOMString features);
  };

  interface DOMImplementation {
    boolean            hasFeature(in DOMString feature,
                                  in DOMString version);
    // Introduced in DOM Level 2:
    DocumentType       createDocumentType(in DOMString qualifiedName,
                                          in DOMString publicId,
                                          in DOMString systemId)
                                        raises(DOMException);
    // Introduced in DOM Level 2:
    Document           createDocument(in DOMString namespaceURI,
                                      in DOMString qualifiedName,
                                      in DocumentType doctype)
                                        raises(DOMException);
    // Introduced in DOM Level 3:
    DOMObject          getFeature(in DOMString feature,
                                  in DOMString version);
  };

  interface Node {
    // Modified in DOM Level 3:
    Node               insertBefore(in Node newChild,
                                    in Node refChild)
                                        raises(DOMException);
    // Modified in DOM Level 3:
    Node               replaceChild(in Node newChild,
                                    in Node oldChild)
                                        raises(DOMException);
    // Modified in DOM Level 3:
    Node               removeChild(in Node oldChild)
                                        raises(DOMException);
    // Modified in DOM Level 3:
    Node               appendChild(in Node newChild)
                                        raises(DOMException);
    boolean            hasChildNodes();
    Node               cloneNode(in boolean deep);
    // Modified in DOM Level 3:
    void               normalize();
    // Introduced in DOM Level 3:
    readonly attribute DOMString       baseURI;
*/

// Compare Document Position
var DOCUMENT_POSITION_DISCONNECTED = core.Node.prototype.DOCUMENT_POSITION_DISCONNECTED = 0x01;
var DOCUMENT_POSITION_PRECEDING    = core.Node.prototype.DOCUMENT_POSITION_PRECEDING    = 0x02;
var DOCUMENT_POSITION_FOLLOWING    = core.Node.prototype.DOCUMENT_POSITION_FOLLOWING    = 0x04;
var DOCUMENT_POSITION_CONTAINS     = core.Node.prototype.DOCUMENT_POSITION_CONTAINS     = 0x08;
var DOCUMENT_POSITION_CONTAINED_BY = core.Node.prototype.DOCUMENT_POSITION_CONTAINED_BY = 0x10;
var DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC = core.Node.prototype.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC = 0x20;

core.Node.prototype.compareDocumentPosition = function compareDocumentPosition( otherNode ) {
  if( !(otherNode instanceof core.Node) ) {
    throw Error("Comparing position against non-Node values is not allowed")
  }
  if( this === otherNode ) return 0
  if( this.ownerDocument !== otherNode.ownerDocument ) {
    return DOCUMENT_POSITION_DISCONNECTED
  }
  var point = this
  var parents = [ ]
  while( point ) {
    if( point == otherNode ) return DOCUMENT_POSITION_CONTAINS
    parents.push( point )
    point = point.parentNode
  }
  point = otherNode
  while( point ) {
    if( point == this ) return DOCUMENT_POSITION_CONTAINED_BY
    var location_index = parents.indexOf( point )
    if( location_index !== -1) {
     var smallest_common_ancestor = parents[ location_index ]
     var this_index = smallest_common_ancestor.childNodes.indexOf( this )
     var other_index = smallest_common_ancestor.childNodes.indexOf( otherNode )
     if( this_index > other_index ) {
           return DOCUMENT_POSITION_PRECEDING
     }
     else {
       return DOCUMENT_POSITION_FOLLOWING
     }
    }
    point = point.parentNode
  }
  return DOCUMENT_POSITION_DISCONNECTED
};
/*
    // Introduced in DOM Level 3:
             attribute DOMString       textContent;
                                        // raises(DOMException) on setting
                                        // raises(DOMException) on retrieval
*/
core.Node.prototype.isSameNode = function(other) {
  return (other === this);
};

/*
    // Introduced in DOM Level 3:
    DOMString          lookupPrefix(in DOMString namespaceURI);
    // Introduced in DOM Level 3:
    boolean            isDefaultNamespace(in DOMString namespaceURI);
    // Introduced in DOM Level 3:
    DOMString          lookupNamespaceURI(in DOMString prefix);
    // Introduced in DOM Level 3:
    boolean            isEqualNode(in Node arg);
    // Introduced in DOM Level 3:
    DOMObject          getFeature(in DOMString feature,
                                  in DOMString version);
    // Introduced in DOM Level 3:
    DOMUserData        setUserData(in DOMString key,
                                   in DOMUserData data,
                                   in UserDataHandler handler);
    // Introduced in DOM Level 3:
    DOMUserData        getUserData(in DOMString key);
  };

  interface NodeList {
    Node               item(in unsigned long index);
    readonly attribute unsigned long   length;
  };

  interface NamedNodeMap {
    Node               getNamedItem(in DOMString name);
    Node               setNamedItem(in Node arg)
                                        raises(DOMException);
    Node               removeNamedItem(in DOMString name)
                                        raises(DOMException);
    Node               item(in unsigned long index);
    readonly attribute unsigned long   length;
    // Introduced in DOM Level 2:
    Node               getNamedItemNS(in DOMString namespaceURI,
                                      in DOMString localName)
                                        raises(DOMException);
    // Introduced in DOM Level 2:
    Node               setNamedItemNS(in Node arg)
                                        raises(DOMException);
    // Introduced in DOM Level 2:
    Node               removeNamedItemNS(in DOMString namespaceURI,
                                         in DOMString localName)
                                        raises(DOMException);
  };

  interface CharacterData : Node {
             attribute DOMString       data;
                                        // raises(DOMException) on setting
                                        // raises(DOMException) on retrieval

    readonly attribute unsigned long   length;
    DOMString          substringData(in unsigned long offset,
                                     in unsigned long count)
                                        raises(DOMException);
    void               appendData(in DOMString arg)
                                        raises(DOMException);
    void               insertData(in unsigned long offset,
                                  in DOMString arg)
                                        raises(DOMException);
    void               deleteData(in unsigned long offset,
                                  in unsigned long count)
                                        raises(DOMException);
    void               replaceData(in unsigned long offset,
                                   in unsigned long count,
                                   in DOMString arg)
                                        raises(DOMException);
  };

  interface Attr : Node {
    readonly attribute DOMString       name;
    readonly attribute boolean         specified;
             attribute DOMString       value;
                                        // raises(DOMException) on setting

    // Introduced in DOM Level 2:
    readonly attribute Element         ownerElement;
    // Introduced in DOM Level 3:
    readonly attribute TypeInfo        schemaTypeInfo;

*/
    // Introduced in DOM Level 3:
core.Attr.prototype.__defineGetter__('isId', function() {
  return (this.name.toLowerCase() === 'id');
});
/*
  };

  interface Element : Node {
    readonly attribute DOMString       tagName;
    DOMString          getAttribute(in DOMString name);
    void               setAttribute(in DOMString name,
                                    in DOMString value)
                                        raises(DOMException);
    void               removeAttribute(in DOMString name)
                                        raises(DOMException);
    Attr               getAttributeNode(in DOMString name);
    Attr               setAttributeNode(in Attr newAttr)
                                        raises(DOMException);
    Attr               removeAttributeNode(in Attr oldAttr)
                                        raises(DOMException);
    NodeList           getElementsByTagName(in DOMString name);
    // Introduced in DOM Level 2:
    DOMString          getAttributeNS(in DOMString namespaceURI,
                                      in DOMString localName)
                                        raises(DOMException);
    // Introduced in DOM Level 2:
    void               setAttributeNS(in DOMString namespaceURI,
                                      in DOMString qualifiedName,
                                      in DOMString value)
                                        raises(DOMException);
    // Introduced in DOM Level 2:
    void               removeAttributeNS(in DOMString namespaceURI,
                                         in DOMString localName)
                                        raises(DOMException);
    // Introduced in DOM Level 2:
    Attr               getAttributeNodeNS(in DOMString namespaceURI,
                                          in DOMString localName)
                                        raises(DOMException);
    // Introduced in DOM Level 2:
    Attr               setAttributeNodeNS(in Attr newAttr)
                                        raises(DOMException);
    // Introduced in DOM Level 2:
    NodeList           getElementsByTagNameNS(in DOMString namespaceURI,
                                              in DOMString localName)
                                        raises(DOMException);
    // Introduced in DOM Level 2:
    boolean            hasAttribute(in DOMString name);
    // Introduced in DOM Level 2:
    boolean            hasAttributeNS(in DOMString namespaceURI,
                                      in DOMString localName)
                                        raises(DOMException);
    // Introduced in DOM Level 3:
    readonly attribute TypeInfo        schemaTypeInfo;
    // Introduced in DOM Level 3:
    void               setIdAttribute(in DOMString name,
                                      in boolean isId)
                                        raises(DOMException);
    // Introduced in DOM Level 3:
    void               setIdAttributeNS(in DOMString namespaceURI,
                                        in DOMString localName,
                                        in boolean isId)
                                        raises(DOMException);
    // Introduced in DOM Level 3:
    void               setIdAttributeNode(in Attr idAttr,
                                          in boolean isId)
                                        raises(DOMException);
  };

  interface Text : CharacterData {
    Text               splitText(in unsigned long offset)
                                        raises(DOMException);
    // Introduced in DOM Level 3:
    readonly attribute boolean         isElementContentWhitespace;
    // Introduced in DOM Level 3:
    readonly attribute DOMString       wholeText;
    // Introduced in DOM Level 3:
    Text               replaceWholeText(in DOMString content)
                                        raises(DOMException);
  };

  interface Comment : CharacterData {
  };

  // Introduced in DOM Level 3:
  interface TypeInfo {
    readonly attribute DOMString       typeName;
    readonly attribute DOMString       typeNamespace;

    // DerivationMethods
    const unsigned long       DERIVATION_RESTRICTION         = 0x00000001;
    const unsigned long       DERIVATION_EXTENSION           = 0x00000002;
    const unsigned long       DERIVATION_UNION               = 0x00000004;
    const unsigned long       DERIVATION_LIST                = 0x00000008;

    boolean            isDerivedFrom(in DOMString typeNamespaceArg,
                                     in DOMString typeNameArg,
                                     in unsigned long derivationMethod);
  };

  // Introduced in DOM Level 3:
  interface UserDataHandler {

    // OperationType
    const unsigned short      NODE_CLONED                    = 1;
    const unsigned short      NODE_IMPORTED                  = 2;
    const unsigned short      NODE_DELETED                   = 3;
    const unsigned short      NODE_RENAMED                   = 4;
    const unsigned short      NODE_ADOPTED                   = 5;

    void               handle(in unsigned short operation,
                              in DOMString key,
                              in DOMUserData data,
                              in Node src,
                              in Node dst);
  };
*/
  // Introduced in DOM Level 3:
core.DOMError = function(severity, message, type, relatedException, relatedData, location) {
  this._severity         = severity;
  this._message          = message;
  this._type             = type;
  this._relatedException = relatedException;
  this._relatedData      = relatedData;
  this._location         = location;
};
core.DOMError.prototype = {};
core.DOMError.prototype.SEVERITY_WARNING     = 1;
core.DOMError.prototype.SEVERITY_ERROR       = 2;
core.DOMError.prototype.SEVERITY_FATAL_ERROR = 3;
core.DOMError.prototype.__defineGetter__('severity', function() {
  return this._severity;
});
core.DOMError.prototype.__defineGetter__('message', function() {
  return this._message;
});
core.DOMError.prototype.__defineGetter__('type', function() {
  return this._type;
});
core.DOMError.prototype.__defineGetter__('relatedException', function() {
  return this._relatedException;
});
core.DOMError.prototype.__defineGetter__('relatedData', function() {
  return this._relatedData;
});
core.DOMError.prototype.__defineGetter__('location', function() {
  return this._location;
});

/*
  // Introduced in DOM Level 3:
  interface DOMErrorHandler {
    boolean            handleError(in DOMError error);
  };

  // Introduced in DOM Level 3:
  interface DOMLocator {
    readonly attribute long            lineNumber;
    readonly attribute long            columnNumber;
    readonly attribute long            byteOffset;
    readonly attribute long            utf16Offset;
    readonly attribute Node            relatedNode;
    readonly attribute DOMString       uri;
  };

  // Introduced in DOM Level 3:
  interface DOMConfiguration {
    void               setParameter(in DOMString name,
                                    in DOMUserData value)
                                        raises(DOMException);
    DOMUserData        getParameter(in DOMString name)
                                        raises(DOMException);
    boolean            canSetParameter(in DOMString name,
                                       in DOMUserData value);
    readonly attribute DOMStringList   parameterNames;
  };

  interface CDATASection : Text {
  };

  interface DocumentType : Node {
    readonly attribute DOMString       name;
    readonly attribute NamedNodeMap    entities;
    readonly attribute NamedNodeMap    notations;
    // Introduced in DOM Level 2:
    readonly attribute DOMString       publicId;
    // Introduced in DOM Level 2:
    readonly attribute DOMString       systemId;
    // Introduced in DOM Level 2:
    readonly attribute DOMString       internalSubset;
  };

  interface Notation : Node {
    readonly attribute DOMString       publicId;
    readonly attribute DOMString       systemId;
  };

  interface Entity : Node {
    readonly attribute DOMString       publicId;
    readonly attribute DOMString       systemId;
    readonly attribute DOMString       notationName;
    // Introduced in DOM Level 3:
    readonly attribute DOMString       inputEncoding;
    // Introduced in DOM Level 3:
    readonly attribute DOMString       xmlEncoding;
    // Introduced in DOM Level 3:
    readonly attribute DOMString       xmlVersion;
  };

  interface EntityReference : Node {
  };

  interface ProcessingInstruction : Node {
    readonly attribute DOMString       target;
             attribute DOMString       data;
                                        // raises(DOMException) on setting

  };

  interface DocumentFragment : Node {
  };

  interface Document : Node {
    // Modified in DOM Level 3:
    readonly attribute DocumentType    doctype;
    readonly attribute DOMImplementation implementation;
    readonly attribute Element         documentElement;
    Element            createElement(in DOMString tagName)
                                        raises(DOMException);
    DocumentFragment   createDocumentFragment();
    Text               createTextNode(in DOMString data);
    Comment            createComment(in DOMString data);
    CDATASection       createCDATASection(in DOMString data)
                                        raises(DOMException);
    ProcessingInstruction createProcessingInstruction(in DOMString target,
                                                      in DOMString data)
                                        raises(DOMException);
    Attr               createAttribute(in DOMString name)
                                        raises(DOMException);
    EntityReference    createEntityReference(in DOMString name)
                                        raises(DOMException);
    NodeList           getElementsByTagName(in DOMString tagname);
    // Introduced in DOM Level 2:
    Node               importNode(in Node importedNode,
                                  in boolean deep)
                                        raises(DOMException);
    // Introduced in DOM Level 2:
    Element            createElementNS(in DOMString namespaceURI,
                                       in DOMString qualifiedName)
                                        raises(DOMException);
    // Introduced in DOM Level 2:
    Attr               createAttributeNS(in DOMString namespaceURI,
                                         in DOMString qualifiedName)
                                        raises(DOMException);
    // Introduced in DOM Level 2:
    NodeList           getElementsByTagNameNS(in DOMString namespaceURI,
                                              in DOMString localName);
    // Introduced in DOM Level 2:
    Element            getElementById(in DOMString elementId);
    // Introduced in DOM Level 3:
    readonly attribute DOMString       inputEncoding;
    // Introduced in DOM Level 3:
    readonly attribute DOMString       xmlEncoding;
    // Introduced in DOM Level 3:
             attribute boolean         xmlStandalone;
                                        // raises(DOMException) on setting

    // Introduced in DOM Level 3:
             attribute DOMString       xmlVersion;
                                        // raises(DOMException) on setting

    // Introduced in DOM Level 3:
             attribute boolean         strictErrorChecking;
    // Introduced in DOM Level 3:
             attribute DOMString       documentURI;
    // Introduced in DOM Level 3:
    Node               adoptNode(in Node source)
                                        raises(DOMException);
    // Introduced in DOM Level 3:
    readonly attribute DOMConfiguration domConfig;
    // Introduced in DOM Level 3:
    void               normalizeDocument();
    // Introduced in DOM Level 3:
    Node               renameNode(in Node n,
                                  in DOMString namespaceURI,
                                  in DOMString qualifiedName)
                                        raises(DOMException);
  };
};

#endif // _DOM_IDL_
*/

exports.dom = {
  level3 : {
    core: core
  }
};
<commit_msg>Use the backing array instead of the NodeList (which has no indexOf method)<commit_after>var core = require("../level2/core").dom.level2.core;

/*
  valuetype DOMString sequence<unsigned short>;
  typedef   unsigned long long DOMTimeStamp;
  typedef   any DOMUserData;
  typedef   Object DOMObject;

*/
  // ExceptionCode
  core.VALIDATION_ERR                 = 16;
  core.TYPE_MISMATCH_ERR              = 17;

/*
  // Introduced in DOM Level 3:
  interface DOMStringList {
    DOMString          item(in unsigned long index);
    readonly attribute unsigned long   length;
    boolean            contains(in DOMString str);
  };

  // Introduced in DOM Level 3:
  interface NameList {
    DOMString          getName(in unsigned long index);
    DOMString          getNamespaceURI(in unsigned long index);
    readonly attribute unsigned long   length;
    boolean            contains(in DOMString str);
    boolean            containsNS(in DOMString namespaceURI,
                                  in DOMString name);
  };

  // Introduced in DOM Level 3:
  interface DOMImplementationList {
    DOMImplementation  item(in unsigned long index);
    readonly attribute unsigned long   length;
  };

  // Introduced in DOM Level 3:
  interface DOMImplementationSource {
    DOMImplementation  getDOMImplementation(in DOMString features);
    DOMImplementationList getDOMImplementationList(in DOMString features);
  };

  interface DOMImplementation {
    boolean            hasFeature(in DOMString feature,
                                  in DOMString version);
    // Introduced in DOM Level 2:
    DocumentType       createDocumentType(in DOMString qualifiedName,
                                          in DOMString publicId,
                                          in DOMString systemId)
                                        raises(DOMException);
    // Introduced in DOM Level 2:
    Document           createDocument(in DOMString namespaceURI,
                                      in DOMString qualifiedName,
                                      in DocumentType doctype)
                                        raises(DOMException);
    // Introduced in DOM Level 3:
    DOMObject          getFeature(in DOMString feature,
                                  in DOMString version);
  };

  interface Node {
    // Modified in DOM Level 3:
    Node               insertBefore(in Node newChild,
                                    in Node refChild)
                                        raises(DOMException);
    // Modified in DOM Level 3:
    Node               replaceChild(in Node newChild,
                                    in Node oldChild)
                                        raises(DOMException);
    // Modified in DOM Level 3:
    Node               removeChild(in Node oldChild)
                                        raises(DOMException);
    // Modified in DOM Level 3:
    Node               appendChild(in Node newChild)
                                        raises(DOMException);
    boolean            hasChildNodes();
    Node               cloneNode(in boolean deep);
    // Modified in DOM Level 3:
    void               normalize();
    // Introduced in DOM Level 3:
    readonly attribute DOMString       baseURI;
*/

// Compare Document Position
var DOCUMENT_POSITION_DISCONNECTED = core.Node.prototype.DOCUMENT_POSITION_DISCONNECTED = 0x01;
var DOCUMENT_POSITION_PRECEDING    = core.Node.prototype.DOCUMENT_POSITION_PRECEDING    = 0x02;
var DOCUMENT_POSITION_FOLLOWING    = core.Node.prototype.DOCUMENT_POSITION_FOLLOWING    = 0x04;
var DOCUMENT_POSITION_CONTAINS     = core.Node.prototype.DOCUMENT_POSITION_CONTAINS     = 0x08;
var DOCUMENT_POSITION_CONTAINED_BY = core.Node.prototype.DOCUMENT_POSITION_CONTAINED_BY = 0x10;
var DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC = core.Node.prototype.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC = 0x20;

core.Node.prototype.compareDocumentPosition = function compareDocumentPosition( otherNode ) {
  if( !(otherNode instanceof core.Node) ) {
    throw Error("Comparing position against non-Node values is not allowed")
  }
  if( this === otherNode ) return 0
  if( this.ownerDocument !== otherNode.ownerDocument ) {
    return DOCUMENT_POSITION_DISCONNECTED
  }
  var point = this
  var parents = [ ]
  while( point ) {
    if( point == otherNode ) return DOCUMENT_POSITION_CONTAINS
    parents.push( point )
    point = point.parentNode
  }
  point = otherNode
  while( point ) {
    if( point == this ) return DOCUMENT_POSITION_CONTAINED_BY
    var location_index = parents.indexOf( point )
    if( location_index !== -1) {
     var smallest_common_ancestor = parents[ location_index ]
     var this_index = smallest_common_ancestor._childNodes.indexOf( this )
     var other_index = smallest_common_ancestor._childNodes.indexOf( otherNode )
     if( this_index > other_index ) {
           return DOCUMENT_POSITION_PRECEDING
     }
     else {
       return DOCUMENT_POSITION_FOLLOWING
     }
    }
    point = point.parentNode
  }
  return DOCUMENT_POSITION_DISCONNECTED
};
/*
    // Introduced in DOM Level 3:
             attribute DOMString       textContent;
                                        // raises(DOMException) on setting
                                        // raises(DOMException) on retrieval
*/
core.Node.prototype.isSameNode = function(other) {
  return (other === this);
};

/*
    // Introduced in DOM Level 3:
    DOMString          lookupPrefix(in DOMString namespaceURI);
    // Introduced in DOM Level 3:
    boolean            isDefaultNamespace(in DOMString namespaceURI);
    // Introduced in DOM Level 3:
    DOMString          lookupNamespaceURI(in DOMString prefix);
    // Introduced in DOM Level 3:
    boolean            isEqualNode(in Node arg);
    // Introduced in DOM Level 3:
    DOMObject          getFeature(in DOMString feature,
                                  in DOMString version);
    // Introduced in DOM Level 3:
    DOMUserData        setUserData(in DOMString key,
                                   in DOMUserData data,
                                   in UserDataHandler handler);
    // Introduced in DOM Level 3:
    DOMUserData        getUserData(in DOMString key);
  };

  interface NodeList {
    Node               item(in unsigned long index);
    readonly attribute unsigned long   length;
  };

  interface NamedNodeMap {
    Node               getNamedItem(in DOMString name);
    Node               setNamedItem(in Node arg)
                                        raises(DOMException);
    Node               removeNamedItem(in DOMString name)
                                        raises(DOMException);
    Node               item(in unsigned long index);
    readonly attribute unsigned long   length;
    // Introduced in DOM Level 2:
    Node               getNamedItemNS(in DOMString namespaceURI,
                                      in DOMString localName)
                                        raises(DOMException);
    // Introduced in DOM Level 2:
    Node               setNamedItemNS(in Node arg)
                                        raises(DOMException);
    // Introduced in DOM Level 2:
    Node               removeNamedItemNS(in DOMString namespaceURI,
                                         in DOMString localName)
                                        raises(DOMException);
  };

  interface CharacterData : Node {
             attribute DOMString       data;
                                        // raises(DOMException) on setting
                                        // raises(DOMException) on retrieval

    readonly attribute unsigned long   length;
    DOMString          substringData(in unsigned long offset,
                                     in unsigned long count)
                                        raises(DOMException);
    void               appendData(in DOMString arg)
                                        raises(DOMException);
    void               insertData(in unsigned long offset,
                                  in DOMString arg)
                                        raises(DOMException);
    void               deleteData(in unsigned long offset,
                                  in unsigned long count)
                                        raises(DOMException);
    void               replaceData(in unsigned long offset,
                                   in unsigned long count,
                                   in DOMString arg)
                                        raises(DOMException);
  };

  interface Attr : Node {
    readonly attribute DOMString       name;
    readonly attribute boolean         specified;
             attribute DOMString       value;
                                        // raises(DOMException) on setting

    // Introduced in DOM Level 2:
    readonly attribute Element         ownerElement;
    // Introduced in DOM Level 3:
    readonly attribute TypeInfo        schemaTypeInfo;

*/
    // Introduced in DOM Level 3:
core.Attr.prototype.__defineGetter__('isId', function() {
  return (this.name.toLowerCase() === 'id');
});
/*
  };

  interface Element : Node {
    readonly attribute DOMString       tagName;
    DOMString          getAttribute(in DOMString name);
    void               setAttribute(in DOMString name,
                                    in DOMString value)
                                        raises(DOMException);
    void               removeAttribute(in DOMString name)
                                        raises(DOMException);
    Attr               getAttributeNode(in DOMString name);
    Attr               setAttributeNode(in Attr newAttr)
                                        raises(DOMException);
    Attr               removeAttributeNode(in Attr oldAttr)
                                        raises(DOMException);
    NodeList           getElementsByTagName(in DOMString name);
    // Introduced in DOM Level 2:
    DOMString          getAttributeNS(in DOMString namespaceURI,
                                      in DOMString localName)
                                        raises(DOMException);
    // Introduced in DOM Level 2:
    void               setAttributeNS(in DOMString namespaceURI,
                                      in DOMString qualifiedName,
                                      in DOMString value)
                                        raises(DOMException);
    // Introduced in DOM Level 2:
    void               removeAttributeNS(in DOMString namespaceURI,
                                         in DOMString localName)
                                        raises(DOMException);
    // Introduced in DOM Level 2:
    Attr               getAttributeNodeNS(in DOMString namespaceURI,
                                          in DOMString localName)
                                        raises(DOMException);
    // Introduced in DOM Level 2:
    Attr               setAttributeNodeNS(in Attr newAttr)
                                        raises(DOMException);
    // Introduced in DOM Level 2:
    NodeList           getElementsByTagNameNS(in DOMString namespaceURI,
                                              in DOMString localName)
                                        raises(DOMException);
    // Introduced in DOM Level 2:
    boolean            hasAttribute(in DOMString name);
    // Introduced in DOM Level 2:
    boolean            hasAttributeNS(in DOMString namespaceURI,
                                      in DOMString localName)
                                        raises(DOMException);
    // Introduced in DOM Level 3:
    readonly attribute TypeInfo        schemaTypeInfo;
    // Introduced in DOM Level 3:
    void               setIdAttribute(in DOMString name,
                                      in boolean isId)
                                        raises(DOMException);
    // Introduced in DOM Level 3:
    void               setIdAttributeNS(in DOMString namespaceURI,
                                        in DOMString localName,
                                        in boolean isId)
                                        raises(DOMException);
    // Introduced in DOM Level 3:
    void               setIdAttributeNode(in Attr idAttr,
                                          in boolean isId)
                                        raises(DOMException);
  };

  interface Text : CharacterData {
    Text               splitText(in unsigned long offset)
                                        raises(DOMException);
    // Introduced in DOM Level 3:
    readonly attribute boolean         isElementContentWhitespace;
    // Introduced in DOM Level 3:
    readonly attribute DOMString       wholeText;
    // Introduced in DOM Level 3:
    Text               replaceWholeText(in DOMString content)
                                        raises(DOMException);
  };

  interface Comment : CharacterData {
  };

  // Introduced in DOM Level 3:
  interface TypeInfo {
    readonly attribute DOMString       typeName;
    readonly attribute DOMString       typeNamespace;

    // DerivationMethods
    const unsigned long       DERIVATION_RESTRICTION         = 0x00000001;
    const unsigned long       DERIVATION_EXTENSION           = 0x00000002;
    const unsigned long       DERIVATION_UNION               = 0x00000004;
    const unsigned long       DERIVATION_LIST                = 0x00000008;

    boolean            isDerivedFrom(in DOMString typeNamespaceArg,
                                     in DOMString typeNameArg,
                                     in unsigned long derivationMethod);
  };

  // Introduced in DOM Level 3:
  interface UserDataHandler {

    // OperationType
    const unsigned short      NODE_CLONED                    = 1;
    const unsigned short      NODE_IMPORTED                  = 2;
    const unsigned short      NODE_DELETED                   = 3;
    const unsigned short      NODE_RENAMED                   = 4;
    const unsigned short      NODE_ADOPTED                   = 5;

    void               handle(in unsigned short operation,
                              in DOMString key,
                              in DOMUserData data,
                              in Node src,
                              in Node dst);
  };
*/
  // Introduced in DOM Level 3:
core.DOMError = function(severity, message, type, relatedException, relatedData, location) {
  this._severity         = severity;
  this._message          = message;
  this._type             = type;
  this._relatedException = relatedException;
  this._relatedData      = relatedData;
  this._location         = location;
};
core.DOMError.prototype = {};
core.DOMError.prototype.SEVERITY_WARNING     = 1;
core.DOMError.prototype.SEVERITY_ERROR       = 2;
core.DOMError.prototype.SEVERITY_FATAL_ERROR = 3;
core.DOMError.prototype.__defineGetter__('severity', function() {
  return this._severity;
});
core.DOMError.prototype.__defineGetter__('message', function() {
  return this._message;
});
core.DOMError.prototype.__defineGetter__('type', function() {
  return this._type;
});
core.DOMError.prototype.__defineGetter__('relatedException', function() {
  return this._relatedException;
});
core.DOMError.prototype.__defineGetter__('relatedData', function() {
  return this._relatedData;
});
core.DOMError.prototype.__defineGetter__('location', function() {
  return this._location;
});

/*
  // Introduced in DOM Level 3:
  interface DOMErrorHandler {
    boolean            handleError(in DOMError error);
  };

  // Introduced in DOM Level 3:
  interface DOMLocator {
    readonly attribute long            lineNumber;
    readonly attribute long            columnNumber;
    readonly attribute long            byteOffset;
    readonly attribute long            utf16Offset;
    readonly attribute Node            relatedNode;
    readonly attribute DOMString       uri;
  };

  // Introduced in DOM Level 3:
  interface DOMConfiguration {
    void               setParameter(in DOMString name,
                                    in DOMUserData value)
                                        raises(DOMException);
    DOMUserData        getParameter(in DOMString name)
                                        raises(DOMException);
    boolean            canSetParameter(in DOMString name,
                                       in DOMUserData value);
    readonly attribute DOMStringList   parameterNames;
  };

  interface CDATASection : Text {
  };

  interface DocumentType : Node {
    readonly attribute DOMString       name;
    readonly attribute NamedNodeMap    entities;
    readonly attribute NamedNodeMap    notations;
    // Introduced in DOM Level 2:
    readonly attribute DOMString       publicId;
    // Introduced in DOM Level 2:
    readonly attribute DOMString       systemId;
    // Introduced in DOM Level 2:
    readonly attribute DOMString       internalSubset;
  };

  interface Notation : Node {
    readonly attribute DOMString       publicId;
    readonly attribute DOMString       systemId;
  };

  interface Entity : Node {
    readonly attribute DOMString       publicId;
    readonly attribute DOMString       systemId;
    readonly attribute DOMString       notationName;
    // Introduced in DOM Level 3:
    readonly attribute DOMString       inputEncoding;
    // Introduced in DOM Level 3:
    readonly attribute DOMString       xmlEncoding;
    // Introduced in DOM Level 3:
    readonly attribute DOMString       xmlVersion;
  };

  interface EntityReference : Node {
  };

  interface ProcessingInstruction : Node {
    readonly attribute DOMString       target;
             attribute DOMString       data;
                                        // raises(DOMException) on setting

  };

  interface DocumentFragment : Node {
  };

  interface Document : Node {
    // Modified in DOM Level 3:
    readonly attribute DocumentType    doctype;
    readonly attribute DOMImplementation implementation;
    readonly attribute Element         documentElement;
    Element            createElement(in DOMString tagName)
                                        raises(DOMException);
    DocumentFragment   createDocumentFragment();
    Text               createTextNode(in DOMString data);
    Comment            createComment(in DOMString data);
    CDATASection       createCDATASection(in DOMString data)
                                        raises(DOMException);
    ProcessingInstruction createProcessingInstruction(in DOMString target,
                                                      in DOMString data)
                                        raises(DOMException);
    Attr               createAttribute(in DOMString name)
                                        raises(DOMException);
    EntityReference    createEntityReference(in DOMString name)
                                        raises(DOMException);
    NodeList           getElementsByTagName(in DOMString tagname);
    // Introduced in DOM Level 2:
    Node               importNode(in Node importedNode,
                                  in boolean deep)
                                        raises(DOMException);
    // Introduced in DOM Level 2:
    Element            createElementNS(in DOMString namespaceURI,
                                       in DOMString qualifiedName)
                                        raises(DOMException);
    // Introduced in DOM Level 2:
    Attr               createAttributeNS(in DOMString namespaceURI,
                                         in DOMString qualifiedName)
                                        raises(DOMException);
    // Introduced in DOM Level 2:
    NodeList           getElementsByTagNameNS(in DOMString namespaceURI,
                                              in DOMString localName);
    // Introduced in DOM Level 2:
    Element            getElementById(in DOMString elementId);
    // Introduced in DOM Level 3:
    readonly attribute DOMString       inputEncoding;
    // Introduced in DOM Level 3:
    readonly attribute DOMString       xmlEncoding;
    // Introduced in DOM Level 3:
             attribute boolean         xmlStandalone;
                                        // raises(DOMException) on setting

    // Introduced in DOM Level 3:
             attribute DOMString       xmlVersion;
                                        // raises(DOMException) on setting

    // Introduced in DOM Level 3:
             attribute boolean         strictErrorChecking;
    // Introduced in DOM Level 3:
             attribute DOMString       documentURI;
    // Introduced in DOM Level 3:
    Node               adoptNode(in Node source)
                                        raises(DOMException);
    // Introduced in DOM Level 3:
    readonly attribute DOMConfiguration domConfig;
    // Introduced in DOM Level 3:
    void               normalizeDocument();
    // Introduced in DOM Level 3:
    Node               renameNode(in Node n,
                                  in DOMString namespaceURI,
                                  in DOMString qualifiedName)
                                        raises(DOMException);
  };
};

#endif // _DOM_IDL_
*/

exports.dom = {
  level3 : {
    core: core
  }
};
<|endoftext|>


<commit_before>JustifiedColumns = (function(window) {

    var DEFAULT_THROTTLE = 25,
        WRAPPER_CLASS = 'justified-columns-wrapper',
        NEEDS_WRAPPER = document.documentElement.style.objectFit === undefined;

    function pxAsNum(px) {
        return 1 * px.split('px')[0];
    }

    function throttle(fn, threshhold, scope) {
        threshhold || (threshhold = 250);
        var last,
            deferTimer;

        return function() {
            var context = scope || this;

            var now = +new Date,
                args = arguments;

            if (last && now < last + threshhold) {
                clearTimeout(deferTimer);
                deferTimer = setTimeout(function() {
                    last = now;
                    fn.apply(context, args);
                }, threshhold);
            } else {
                last = now;
                fn.apply(context, args);
            }
        };
    }

    function Justifier(config) {
        this.setGrid(config.grid || config);
        this.stretchSelector = config.stretch || 'img';
        this.shrink = config.shrink || false; //or 'shrink' (column-justify);
        this.autoResize = config.hasOwnProperty('autoResize') ? config.autoResize : true;
        this.grid.Justifier = this;
        this.boundReset = config.throttle === 0 ? this.reset.bind(this) : throttle(this.reset.bind(this), config.throttle || DEFAULT_THROTTLE);
        this.boundJustify = config.throttle === 0 ? this.justify.bind(this) : throttle(this.justify.bind(this), config.throttle || DEFAULT_THROTTLE);
        this.enable();
    }

    Justifier.prototype.setGrid = function(grid) {
        if (typeof grid === 'string') {
            this.grid = document.querySelector(grid);
        } else {
            this.grid = grid.jquery ? grid[0] : grid;
        }
    };

    Justifier.prototype.justify = function() {
        var self = this,
            refColComparator = Math[this.shrink ? 'min' : 'max'],
            columns = [],
            currentColumn = -1,
            referenceColumn = this.shrink ? Number.POSITIVE_INFINITY : 0,
            currentOffset;

        //sort the grid into columns based on offsetLeft; cache heights
        [].slice.call(this.grid.children).forEach(function(gridItem) {
            var gridItemStyle = window.getComputedStyle(gridItem);
            var gridItemOffsetLeft = gridItem.offsetLeft; //saves like 40% of execution time to cache this
            if (gridItemOffsetLeft !== currentOffset) {
                if (currentColumn !== -1) referenceColumn = refColComparator(columns[currentColumn].height, referenceColumn);
                currentColumn++;
                currentOffset = gridItemOffsetLeft;
                columns.push({
                    items: [],
                    height: pxAsNum(gridItemStyle.getPropertyValue('margin-top')),
                    totalImagesHeight: 0
                });
            }
            gridItem.stretchable = gridItem.querySelector(self.stretchSelector);
            if (gridItem.stretchable) {
                gridItem.stretchableHeight = gridItem.stretchable.offsetHeight;
            }
            columns[currentColumn].items.push(gridItem);
            columns[currentColumn].height += (gridItem.offsetHeight + pxAsNum(gridItemStyle.getPropertyValue('margin-bottom')));
            columns[currentColumn].totalImagesHeight += (gridItem.stretchableHeight ? gridItem.stretchableHeight : 0);
        });
        referenceColumn = refColComparator(columns[currentColumn].height, referenceColumn); //last column could be reference, too

        //modify height of "stretchable" items (if present) in each of the non-reference-columns' items
        columns.forEach(function(column, colIndex) {
            if (column.height < referenceColumn || (self.shrink && column.height > referenceColumn)) {
                var columnDelta = referenceColumn - column.height;
                var stretchedImagesDelta = 0;
                column.items.forEach(function(gridItem, itemIndex) {
                    var stretchable = gridItem.querySelector(self.stretchSelector);
                    if (stretchable) {
                        var stretchablePercent = columnDelta / column.totalImagesHeight,
                            stretchableDelta = gridItem.stretchableHeight * stretchablePercent,
                            newHeight = gridItem.stretchableHeight + stretchableDelta,
                            heightProperty = (self.shrink ? 'max' : 'min') + 'Height';
                        if (stretchable.nodeName !== 'IMG') {
                            // not an image, so just set max/min-height and call it a day
                            stretchable.style[heightProperty] = newHeight + 'px';
                        } else if (!NEEDS_WRAPPER) {
                            // can rely on objectFit, so set the max/min-height, then use objectFit to handle resize + overflow
                            stretchable.style[heightProperty] = newHeight + 'px';
                            stretchable.style.objectFit = 'cover';
                            stretchable.style.objectPosition = 'center';
                        } else {
                            //it's an IMG and we're in older IE, ugh
                            if (stretchable.parentNode.className !== WRAPPER_CLASS) {
                                //create overflow wrapper
                                var wrapper = document.createElement('DIV');
                                wrapper.className = WRAPPER_CLASS;
                                wrapper.style.overflow = 'hidden';
                                wrapper.style[heightProperty] = newHeight + 'px';
                                stretchable.parentNode.replaceChild(wrapper, stretchable);
                                wrapper.appendChild(stretchable);
                            }
                            //set wrapper max/min-height, position within wrapper
                            if (self.shrink) {
                                var sOffset = 0.5 * (newHeight - gridItem.stretchableHeight);
                                stretchable.style.marginTop = sOffset + 'px';
                                stretchable.style.marginBottom = -1 * sOffset + 'px';
                            } else {
                                var sWidth = stretchable.offsetWidth,
                                    newWidth = sWidth * (newHeight / gridItem.stretchableHeight);
                                stretchable.style.minHeight = newHeight + 'px';
                                stretchable.style.minWidth = newWidth + 'px';
                                stretchable.style.marginLeft = -0.5 * (newWidth - sWidth) + 'px';
                            }
                        }
                        stretchedImagesDelta += stretchableDelta;
                    }
                });
                column.height += stretchedImagesDelta;
                column.totalImagesHeight += stretchedImagesDelta;
            }
        });

        //Fix the stupid IE10/11 interactions between column-count grid and height/max-height children
        if (NEEDS_WRAPPER) {
            var resizeHeight = referenceColumn,
                gridStyle = getComputedStyle(this.grid);
            if (gridStyle.boxSizing === 'border-box') {
                ['paddingTop', 'paddingBottom', 'borderTopWidth', 'borderBottomWidth'].forEach(function(spacer) {
                    resizeHeight += pxAsNum(gridStyle[spacer]);
                });
            }
            if (Math.abs(this.grid.offsetHeight - resizeHeight) >= 2) {
                this.grid.style.height = gridHeight + 'px';
            }
        }

    };

    Justifier.prototype.reset = function() {
        [].slice.call(this.grid.querySelectorAll(this.stretchSelector)).forEach(function(s) {
            s.style.maxHeight = '';
            s.style.minHeight = '';
            if (NEEDS_WRAPPER) {
                s.style.minWidth = '';
                s.style.marginLeft = '';
                s.style.marginTop = '';
            } else {
                s.style.objectFit = '';
                s.style.objectPosition = '';
            }
        });
        if (NEEDS_WRAPPER) {
            [].slice.call(this.grid.getElementsByClassName(WRAPPER_CLASS)).forEach(function(wrapper) {
                wrapper.parentNode.replaceChild(wrapper.firstChild, wrapper);
            });
            this.grid.style.height = '';
        }
    };

    Justifier.prototype.enable = function() {
        if (this.autoResize) {
            window.addEventListener('resize', this.boundReset);
            window.addEventListener('resize', this.boundJustify);
        }
        this.justify();
    };

    Justifier.prototype.disable = function() {
        if (this.autoResize) {
            window.removeEventListener('resize', this.boundReset);
            window.removeEventListener('resize', this.boundJustify);
        }
        this.reset();
    };

    return Justifier;

})(window);<commit_msg>wrong var<commit_after>JustifiedColumns = (function(window) {

    var DEFAULT_THROTTLE = 25,
        WRAPPER_CLASS = 'justified-columns-wrapper',
        NEEDS_WRAPPER = document.documentElement.style.objectFit === undefined;

    function pxAsNum(px) {
        return 1 * px.split('px')[0];
    }

    function throttle(fn, threshhold, scope) {
        threshhold || (threshhold = 250);
        var last,
            deferTimer;

        return function() {
            var context = scope || this;

            var now = +new Date,
                args = arguments;

            if (last && now < last + threshhold) {
                clearTimeout(deferTimer);
                deferTimer = setTimeout(function() {
                    last = now;
                    fn.apply(context, args);
                }, threshhold);
            } else {
                last = now;
                fn.apply(context, args);
            }
        };
    }

    function Justifier(config) {
        this.setGrid(config.grid || config);
        this.stretchSelector = config.stretch || 'img';
        this.shrink = config.shrink || false; //or 'shrink' (column-justify);
        this.autoResize = config.hasOwnProperty('autoResize') ? config.autoResize : true;
        this.grid.Justifier = this;
        this.boundReset = config.throttle === 0 ? this.reset.bind(this) : throttle(this.reset.bind(this), config.throttle || DEFAULT_THROTTLE);
        this.boundJustify = config.throttle === 0 ? this.justify.bind(this) : throttle(this.justify.bind(this), config.throttle || DEFAULT_THROTTLE);
        this.enable();
    }

    Justifier.prototype.setGrid = function(grid) {
        if (typeof grid === 'string') {
            this.grid = document.querySelector(grid);
        } else {
            this.grid = grid.jquery ? grid[0] : grid;
        }
    };

    Justifier.prototype.justify = function() {
        var self = this,
            refColComparator = Math[this.shrink ? 'min' : 'max'],
            columns = [],
            currentColumn = -1,
            referenceColumn = this.shrink ? Number.POSITIVE_INFINITY : 0,
            currentOffset;

        //sort the grid into columns based on offsetLeft; cache heights
        [].slice.call(this.grid.children).forEach(function(gridItem) {
            var gridItemStyle = window.getComputedStyle(gridItem);
            var gridItemOffsetLeft = gridItem.offsetLeft; //saves like 40% of execution time to cache this
            if (gridItemOffsetLeft !== currentOffset) {
                if (currentColumn !== -1) referenceColumn = refColComparator(columns[currentColumn].height, referenceColumn);
                currentColumn++;
                currentOffset = gridItemOffsetLeft;
                columns.push({
                    items: [],
                    height: pxAsNum(gridItemStyle.getPropertyValue('margin-top')),
                    totalImagesHeight: 0
                });
            }
            gridItem.stretchable = gridItem.querySelector(self.stretchSelector);
            if (gridItem.stretchable) {
                gridItem.stretchableHeight = gridItem.stretchable.offsetHeight;
            }
            columns[currentColumn].items.push(gridItem);
            columns[currentColumn].height += (gridItem.offsetHeight + pxAsNum(gridItemStyle.getPropertyValue('margin-bottom')));
            columns[currentColumn].totalImagesHeight += (gridItem.stretchableHeight ? gridItem.stretchableHeight : 0);
        });
        referenceColumn = refColComparator(columns[currentColumn].height, referenceColumn); //last column could be reference, too

        //modify height of "stretchable" items (if present) in each of the non-reference-columns' items
        columns.forEach(function(column, colIndex) {
            if (column.height < referenceColumn || (self.shrink && column.height > referenceColumn)) {
                var columnDelta = referenceColumn - column.height;
                var stretchedImagesDelta = 0;
                column.items.forEach(function(gridItem, itemIndex) {
                    var stretchable = gridItem.querySelector(self.stretchSelector);
                    if (stretchable) {
                        var stretchablePercent = columnDelta / column.totalImagesHeight,
                            stretchableDelta = gridItem.stretchableHeight * stretchablePercent,
                            newHeight = gridItem.stretchableHeight + stretchableDelta,
                            heightProperty = (self.shrink ? 'max' : 'min') + 'Height';
                        if (stretchable.nodeName !== 'IMG') {
                            // not an image, so just set max/min-height and call it a day
                            stretchable.style[heightProperty] = newHeight + 'px';
                        } else if (!NEEDS_WRAPPER) {
                            // can rely on objectFit, so set the max/min-height, then use objectFit to handle resize + overflow
                            stretchable.style[heightProperty] = newHeight + 'px';
                            stretchable.style.objectFit = 'cover';
                            stretchable.style.objectPosition = 'center';
                        } else {
                            //it's an IMG and we're in older IE, ugh
                            if (stretchable.parentNode.className !== WRAPPER_CLASS) {
                                //create overflow wrapper
                                var wrapper = document.createElement('DIV');
                                wrapper.className = WRAPPER_CLASS;
                                wrapper.style.overflow = 'hidden';
                                wrapper.style[heightProperty] = newHeight + 'px';
                                stretchable.parentNode.replaceChild(wrapper, stretchable);
                                wrapper.appendChild(stretchable);
                            }
                            //set wrapper max/min-height, position within wrapper
                            if (self.shrink) {
                                var sOffset = 0.5 * (newHeight - gridItem.stretchableHeight);
                                stretchable.style.marginTop = sOffset + 'px';
                                stretchable.style.marginBottom = -1 * sOffset + 'px';
                            } else {
                                var sWidth = stretchable.offsetWidth,
                                    newWidth = sWidth * (newHeight / gridItem.stretchableHeight);
                                stretchable.style.minHeight = newHeight + 'px';
                                stretchable.style.minWidth = newWidth + 'px';
                                stretchable.style.marginLeft = -0.5 * (newWidth - sWidth) + 'px';
                            }
                        }
                        stretchedImagesDelta += stretchableDelta;
                    }
                });
                column.height += stretchedImagesDelta;
                column.totalImagesHeight += stretchedImagesDelta;
            }
        });

        //Fix the stupid IE10/11 interactions between column-count grid and height/max-height children
        if (NEEDS_WRAPPER) {
            var resizeHeight = referenceColumn,
                gridStyle = getComputedStyle(this.grid);
            if (gridStyle.boxSizing === 'border-box') {
                ['paddingTop', 'paddingBottom', 'borderTopWidth', 'borderBottomWidth'].forEach(function(spacer) {
                    resizeHeight += pxAsNum(gridStyle[spacer]);
                });
            }
            if (Math.abs(this.grid.offsetHeight - resizeHeight) >= 2) {
                this.grid.style.height = resizeHeight + 'px';
            }
        }

    };

    Justifier.prototype.reset = function() {
        [].slice.call(this.grid.querySelectorAll(this.stretchSelector)).forEach(function(s) {
            s.style.maxHeight = '';
            s.style.minHeight = '';
            if (NEEDS_WRAPPER) {
                s.style.minWidth = '';
                s.style.marginLeft = '';
                s.style.marginTop = '';
            } else {
                s.style.objectFit = '';
                s.style.objectPosition = '';
            }
        });
        if (NEEDS_WRAPPER) {
            [].slice.call(this.grid.getElementsByClassName(WRAPPER_CLASS)).forEach(function(wrapper) {
                wrapper.parentNode.replaceChild(wrapper.firstChild, wrapper);
            });
            this.grid.style.height = '';
        }
    };

    Justifier.prototype.enable = function() {
        if (this.autoResize) {
            window.addEventListener('resize', this.boundReset);
            window.addEventListener('resize', this.boundJustify);
        }
        this.justify();
    };

    Justifier.prototype.disable = function() {
        if (this.autoResize) {
            window.removeEventListener('resize', this.boundReset);
            window.removeEventListener('resize', this.boundJustify);
        }
        this.reset();
    };

    return Justifier;

})(window);<|endoftext|>


<commit_before>'use strict';
var Graph = require('../').Structure.Graph;
var GremlinScript = require('../').GremlinScript;
var bind = require('../').bindParameter;

describe('GremlinScript', function() {
  describe('.line(String)', function() {
    it('should append a new line', function() {
      var gremlin = new GremlinScript();

      gremlin.line('g.v(1)');
      gremlin.script.should.equal('g.v(1)\n');
    });
  });

  describe('.line(String, ...parameters)', function() {
    it('should append a new line with a bound parameter', function() {
      var gremlin = new GremlinScript();

      gremlin.line('g.v(%s)', 1);
      gremlin.script.should.equal('g.v(p0)\n');
      gremlin.params.p0.should.equal(1);
    });

    it('should append a new line with multiple bound parameters', function() {
      var gremlin = new GremlinScript();

      gremlin.line('g.V(%s, %s)', 'name', 'Alice');
      gremlin.script.should.equal('g.V(p0, p1)\n');
      gremlin.params.p0.should.equal('name');
      gremlin.params.p1.should.equal('Alice');
    });
  });

  describe('.line(Helper)', function() {
    it('should append a new line', function() {
      var gremlin = new GremlinScript();
      var g = new Graph('g');

      gremlin.line(g.v(1));
      gremlin.script.should.equal('g.v(1)\n');
    });
  });

  describe('.var(Helper)', function() {
    it('should identify an object with an automatic identifier', function() {
      var gremlin = new GremlinScript();
      var g = new Graph('g');

      gremlin.var(g.v(1));
      gremlin.script.should.equal('i0=g.v(1)\n');
    });
  });

  describe('.var(Helper[, identifier])', function() {
    it('should identify an object with a custom identifier', function() {
      var gremlin = new GremlinScript();
      var g = new Graph('g');

      gremlin.var(g.v(1), 'v1');
      gremlin.script.should.equal('v1=g.v(1)\n');
    });
  });

  describe('Bound parameters with helpers', function() {
    it('should handle bound parameters', function() {
      var gremlin = new GremlinScript();
      var g = new Graph('g');

      gremlin.line(g.v(bind(1)));
      gremlin.script.should.equal('g.v(p0)\n');
      gremlin.params.p0.should.equal(1);
    });
  });
});<commit_msg>Add a test when using multiple bound parameters with helpers<commit_after>'use strict';
var Graph = require('../').Structure.Graph;
var GremlinScript = require('../').GremlinScript;
var bind = require('../').bindParameter;

describe('GremlinScript', function() {
  describe('.line(String)', function() {
    it('should append a new line', function() {
      var gremlin = new GremlinScript();

      gremlin.line('g.v(1)');
      gremlin.script.should.equal('g.v(1)\n');
    });
  });

  describe('.line(String, ...parameters)', function() {
    it('should append a new line with a bound parameter', function() {
      var gremlin = new GremlinScript();

      gremlin.line('g.v(%s)', 1);
      gremlin.script.should.equal('g.v(p0)\n');
      gremlin.params.p0.should.equal(1);
    });

    it('should append a new line with multiple bound parameters', function() {
      var gremlin = new GremlinScript();

      gremlin.line('g.V(%s, %s)', 'name', 'Alice');
      gremlin.script.should.equal('g.V(p0, p1)\n');
      gremlin.params.p0.should.equal('name');
      gremlin.params.p1.should.equal('Alice');
    });
  });

  describe('.line(Helper)', function() {
    it('should append a new line', function() {
      var gremlin = new GremlinScript();
      var g = new Graph('g');

      gremlin.line(g.v(1));
      gremlin.script.should.equal('g.v(1)\n');
    });
  });

  describe('.var(Helper)', function() {
    it('should identify an object with an automatic identifier', function() {
      var gremlin = new GremlinScript();
      var g = new Graph('g');

      gremlin.var(g.v(1));
      gremlin.script.should.equal('i0=g.v(1)\n');
    });
  });

  describe('.var(Helper[, identifier])', function() {
    it('should identify an object with a custom identifier', function() {
      var gremlin = new GremlinScript();
      var g = new Graph('g');

      gremlin.var(g.v(1), 'v1');
      gremlin.script.should.equal('v1=g.v(1)\n');
    });
  });

  describe('Bound parameters with helpers', function() {
    it('should handle a bound parameter', function() {
      var gremlin = new GremlinScript();
      var g = new Graph('g');

      gremlin.line(g.v(bind(1)));
      gremlin.script.should.equal('g.v(p0)\n');
      gremlin.params.p0.should.equal(1);
    });

    it('should handle multiple bound parameters', function() {
      var gremlin = new GremlinScript();
      var g = new Graph('g');

      gremlin.line(g.V('name', bind('Alice')).has('age', bind(28)));
      gremlin.script.should.equal("g.V('name',p0).has('age',p1)\n");
      gremlin.params.p0.should.equal('Alice');
      gremlin.params.p1.should.equal(28);
    });
  });
});<|endoftext|>


<commit_before>var test = require("testling"),
    testServer = require("test-server"),
    request = require('request'),
    nCoreStart = require("../../core"),
    server = require("../../libs/server");

nCoreStart(testServer(server, startTests));

function startTests() {
    test('session get', function (t) {
        makeRequest("/get", function (err, res, body) {
            t.equal(err, null, "error should be undefined")
            t.equal(body, undefined, "body should be undefined")
            t.end()
        })
    })

    test('session create', function (t) {
        makeRequest("/create", function (err, res, body) {
            t.equal(err, null, "error should be undefined")
            t.equal(body, undefined, "body should be undefined")
            t.end()
        })
    })

    test('session get', function (t) {
        makeRequest('/get', function (err, res, body) {
            t.equal(err, null, "error should be undefined")
            t.type(body, "string", "body should be a string")
            t.end()
        })
    })

    .on('end', function () {
        setTimeout(function (){
            process.exit(0)
        }, 1000)
    })
}

// TODOTB: use test-server instead.
function makeRequest(opts, cb) {
    if (typeof opts === 'string') {
        opts = "http://localhost:3000" + opts
    } else {
        opts.uri = "http://localhost:3000" + opts.uri
    }
    request(opts, cb)
}<commit_msg>damn tests not working<commit_after>var test = require("testling"),
    testServer = require("test-server"),
    request = require('request'),
    nCoreStart = require("../../core"),
    server = require("../../libs/server");

nCoreStart(testServer(server, {}, startTests));

var startTests = function(request, done) {
    test('session get', function (t) {
        request("/get", function (err, res, body) {
            t.equal(err, null, "error should be undefined")
            t.equal(body, undefined, "body should be undefined")
            t.end()
        })
    })

    test('session create', function (t) {
        request("/create", function (err, res, body) {
            t.equal(err, null, "error should be undefined")
            t.equal(body, undefined, "body should be undefined")
            t.end()
        })
    })

    test('session get', function (t) {
        request('/get', function (err, res, body) {
            t.equal(err, null, "error should be undefined")
            t.type(body, "string", "body should be a string")
            t.end()
        })
    })

    .on('end', function () {
        setTimeout(function (){
            process.exit(0)
        }, 1000)
    })

    done()
}<|endoftext|>