<commit_before>/* -*- javascript -*- */
"use strict";

import {constants} from './constants';
import {inject, LogManager} from 'aurelia-framework';

function dashify( string ) {
	return string.toString().
		replace( /([a-z])([A-Z])/, (_,a,b) => `${a}-${b.toLowerCase()}` );
}

function splitIntoClasses( name ) {
	if ( !name ) return [];
	let dashified = dashify( name );
	return dashified.split( /[ ]+/ );
}

/**
 * Expand all of the values in {cssClasses} so that `'equalWidth'`, `'equal width'`, and
 * `'equal-width'` all result in `['equal', 'width']`. Also removes classes prefixed with
 * 'au-' to avoid messing with Aurelia's classes.
 * @return {Array[String]} the flattened list of CSS classes.
 */
function expandCssClasses( ...cssClasses ) {
	let expanded = cssClasses.
		map( (cl) => {
			if ( Array.isArray(cl) ) {
				return expandCssClasses( ...cl );
			} else {
				return splitIntoClasses( cl );
			}
		});
	let flattened = [].concat.apply( [], expanded );

	return flattened;
}

/**
 * Expand the classes in {cssClasses} with expandCssClasses() and then filter out
 * non-classes and Aurelia-internal classes.
 */
function normalizeCssClasses( ...cssClasses ) {
	let classList = expandCssClasses( ...cssClasses );
	return classList.
		filter( (cl) => {
			return cl !== '' &&
				cl !== 'true' &&
				cl !== 'false' &&
				!cl.startsWith( 'au-' )
		});
}

/**
 * SemanticUIElement -- base class for Semantic UI custom elements
 */
@inject( Element )
export class SemanticUIElement {

	element;
	semanticElement;

	/**
	 * Get the component name set by the uiElement() decorator on the class.
	 */
	get component() {
		let metadata = this.constructor[ constants.metadataProperty ];
		return metadata.component;
	}

	constructor( el ) {
		this.logger = LogManager.getLogger( this.constructor.name );
		this.element = el;
	}

	created( owningView, myView ) {
		this.semanticElement = this.getSemanticElement( this.element );
		this.addCssClasses( this.element.classList );
	}

	/**
	 * Add one or more {cssClasses} to the Semantic UI element.
	 */
	addCssClasses( ...cssClasses ) {
		let expandedClasses = normalizeCssClasses( cssClasses );
		if ( expandedClasses.length ) {
			this.semanticElement.classList.add( ...expandedClasses );
		}
	}

	/**
	 * Remove one or more {cssClasses} from the Semantic UI element.
	 */
	removeCssClasses( ...cssClasses ) {
		let expandedClasses = normalizeCssClasses( cssClasses ).
			filter( (cl) => cl !== '' && !cl.startsWith('au-') );
		if ( expandedClasses.length ) {
			this.semanticElement.classList.remove( ...expandedClasses );
		}
	}

	/**
	 * Get the element which should receive SemanticUI classes relative to the
	 * {parentEl}ement.
	 * @return {Element} the element to add CSS classes to.
	 */
	getSemanticElement( parentEl ) {
		// this.logger.debug( "Fetching inner semantic element for parent element: ", parentEl );

		// Containerless elements get passed a comment anchor element
		if ( parentEl.nodeType === 8 ) {
			// this.logger.debug( "  Containerless element; using previous sibling." );
			return parentEl.previousElementSibling;
		}

		else if ( parentEl.nodeType === 1 ) {
			// this.logger.debug( "  HTML element; using first element child: ", parentEl.firstElementChild );
			return parentEl.firstElementChild;
		}

		else {
			console.error( "Can't find the semantic element of: ", parentEl );
			throw new Error( `Can't find the semantic element of: ${parentEl}` );
		}
	}

}

/**
 * SemanticUIAttribute -- base class for Semantic UI custom attributes
 */
@inject( Element )
export class SemanticUIAttribute {

	element;
	semanticElement;

	/**
	 * Get the component name set by the uiAttribute() decorator on the class.
	 */
	get component() {
		let metadata = this.constructor[ constants.metadataProperty ];
		return metadata.component;
	}

	constructor( element ) {
		this.logger = LogManager.getLogger( this.constructor.name );
		this.element = element;
	}

	created( owningView, myView ) {
		this.semanticElement = this.getSemanticElement( this.element );
	}

	bind( ...args ) {
		let componentName = this.component;
		let cssClasses = componentName.split( /-/ ).filter( cssClass => cssClass !== 'ui' );
		this.addCssClasses( 'ui', ...cssClasses );
	}

	/**
	 * Add one or more {cssClasses} to the Semantic UI element. The values in {cssClasses}
	 * will be expanded by normalizeCssClasses().
	 */
	addCssClasses( ...cssClasses ) {
		let expandedClasses = normalizeCssClasses( cssClasses );
		this.semanticElement.classList.add( ...expandedClasses );
	}

	/**
	 * Remove one or more {cssClasses} from the Semantic UI element.
	 */
	removeCssClasses( ...cssClasses ) {
		let expandedClasses = normalizeCssClasses( cssClasses );
		this.semanticElement.classList.remove( ...expandedClasses );
	}

	/**
	 * Get the element which should receive SemanticUI classes relative to the specified
	 * {el}ement. Defaults to the element with the attribute.
	 * @return {Element} the element to add CSS classes to.
	 */
	getSemanticElement( el ) {
		// If this is an attribute of a Semantic UI element, use its semantic element.
		if (
			el.au &&
			el.au.controller &&
			el.au.controller.viewModel &&
			el.au.controller.viewModel instanceof SemanticUIElement
		) {
			let container = el.au.controller.viewModel;
			if ( container instanceof SemanticUIElement ) {
				this.logger.debug( "Decorating another Semantic element: ", container );
				let semEl = container.getSemanticElement( el );
				this.logger.debug( "Other element's semantic element is: ", semEl );
				return semEl;
			}
			return el;
		} else {
			this.logger.debug( "Decorating a plain HTML element: ", el );
			return el;
		}
	}

}

<commit_msg>Squelch some spammy debugging<commit_after>/* -*- javascript -*- */
"use strict";

import {constants} from './constants';
import {inject, LogManager} from 'aurelia-framework';

function dashify( string ) {
	return string.toString().
		replace( /([a-z])([A-Z])/, (_,a,b) => `${a}-${b.toLowerCase()}` );
}

function splitIntoClasses( name ) {
	if ( !name ) return [];
	let dashified = dashify( name );
	return dashified.split( /[ ]+/ );
}

/**
 * Expand all of the values in {cssClasses} so that `'equalWidth'`, `'equal width'`, and
 * `'equal-width'` all result in `['equal', 'width']`. Also removes classes prefixed with
 * 'au-' to avoid messing with Aurelia's classes.
 * @return {Array[String]} the flattened list of CSS classes.
 */
function expandCssClasses( ...cssClasses ) {
	let expanded = cssClasses.
		map( (cl) => {
			if ( Array.isArray(cl) ) {
				return expandCssClasses( ...cl );
			} else {
				return splitIntoClasses( cl );
			}
		});
	let flattened = [].concat.apply( [], expanded );

	return flattened;
}

/**
 * Expand the classes in {cssClasses} with expandCssClasses() and then filter out
 * non-classes and Aurelia-internal classes.
 */
function normalizeCssClasses( ...cssClasses ) {
	let classList = expandCssClasses( ...cssClasses );
	return classList.
		filter( (cl) => {
			return cl !== '' &&
				cl !== 'true' &&
				cl !== 'false' &&
				!cl.startsWith( 'au-' )
		});
}

/**
 * SemanticUIElement -- base class for Semantic UI custom elements
 */
@inject( Element )
export class SemanticUIElement {

	element;
	semanticElement;

	/**
	 * Get the component name set by the uiElement() decorator on the class.
	 */
	get component() {
		let metadata = this.constructor[ constants.metadataProperty ];
		return metadata.component;
	}

	constructor( el ) {
		this.logger = LogManager.getLogger( this.constructor.name );
		this.element = el;
	}

	created( owningView, myView ) {
		this.semanticElement = this.getSemanticElement( this.element );
		this.addCssClasses( this.element.classList );
	}

	/**
	 * Add one or more {cssClasses} to the Semantic UI element.
	 */
	addCssClasses( ...cssClasses ) {
		let expandedClasses = normalizeCssClasses( cssClasses );
		if ( expandedClasses.length ) {
			this.semanticElement.classList.add( ...expandedClasses );
		}
	}

	/**
	 * Remove one or more {cssClasses} from the Semantic UI element.
	 */
	removeCssClasses( ...cssClasses ) {
		let expandedClasses = normalizeCssClasses( cssClasses ).
			filter( (cl) => cl !== '' && !cl.startsWith('au-') );
		if ( expandedClasses.length ) {
			this.semanticElement.classList.remove( ...expandedClasses );
		}
	}

	/**
	 * Get the element which should receive SemanticUI classes relative to the
	 * {parentEl}ement.
	 * @return {Element} the element to add CSS classes to.
	 */
	getSemanticElement( parentEl ) {
		// this.logger.debug( "Fetching inner semantic element for parent element: ", parentEl );

		// Containerless elements get passed a comment anchor element
		if ( parentEl.nodeType === 8 ) {
			// this.logger.debug( "  Containerless element; using previous sibling." );
			return parentEl.previousElementSibling;
		}

		else if ( parentEl.nodeType === 1 ) {
			// this.logger.debug( "  HTML element; using first element child: ", parentEl.firstElementChild );
			return parentEl.firstElementChild;
		}

		else {
			console.error( "Can't find the semantic element of: ", parentEl );
			throw new Error( `Can't find the semantic element of: ${parentEl}` );
		}
	}

}

/**
 * SemanticUIAttribute -- base class for Semantic UI custom attributes
 */
@inject( Element )
export class SemanticUIAttribute {

	element;
	semanticElement;

	/**
	 * Get the component name set by the uiAttribute() decorator on the class.
	 */
	get component() {
		let metadata = this.constructor[ constants.metadataProperty ];
		return metadata.component;
	}

	constructor( element ) {
		this.logger = LogManager.getLogger( this.constructor.name );
		this.element = element;
	}

	created( owningView, myView ) {
		this.semanticElement = this.getSemanticElement( this.element );
	}

	bind( ...args ) {
		let componentName = this.component;
		let cssClasses = componentName.split( /-/ ).filter( cssClass => cssClass !== 'ui' );
		this.addCssClasses( 'ui', ...cssClasses );
	}

	/**
	 * Add one or more {cssClasses} to the Semantic UI element. The values in {cssClasses}
	 * will be expanded by normalizeCssClasses().
	 */
	addCssClasses( ...cssClasses ) {
		let expandedClasses = normalizeCssClasses( cssClasses );
		this.semanticElement.classList.add( ...expandedClasses );
	}

	/**
	 * Remove one or more {cssClasses} from the Semantic UI element.
	 */
	removeCssClasses( ...cssClasses ) {
		let expandedClasses = normalizeCssClasses( cssClasses );
		this.semanticElement.classList.remove( ...expandedClasses );
	}

	/**
	 * Get the element which should receive SemanticUI classes relative to the specified
	 * {el}ement. Defaults to the element with the attribute.
	 * @return {Element} the element to add CSS classes to.
	 */
	getSemanticElement( el ) {
		// If this is an attribute of a Semantic UI element, use its semantic element.
		if (
			el.au &&
			el.au.controller &&
			el.au.controller.viewModel &&
			el.au.controller.viewModel instanceof SemanticUIElement
		) {
			let container = el.au.controller.viewModel;
			if ( container instanceof SemanticUIElement ) {
				// this.logger.debug( "Decorating another Semantic element: ", container );
				let semEl = container.getSemanticElement( el );
				// this.logger.debug( "Other element's semantic element is: ", semEl );
				return semEl;
			}
			return el;
		} else {
			// this.logger.debug( "Decorating a plain HTML element: ", el );
			return el;
		}
	}

}

<|endoftext|>


<commit_before>(function() {

	// loadFile('jQuery URL', 'js', function() {
	// 	loadFile('Your Plugin', 'js', function() {
	// 		// initialize
	// 	});
	// });

	/**
	 * Load File
	 * @param  {string} file   file url
	 * @param  {string} type   file type (css or js)
	 * @param  {function} handle file loaded callback
	 */
	function loadFile (file, type, handle) {
		var head = document.getElementsByTagName('head')[0],
			res;

		// avoid load more times
		if ( !window.loadedFiles ) {
			window.loadedFiles = [];
		}
		for (var i = 0; i < window.loadedFiles.length; i++) {
			if( file === window.loadedFiles[i] )
				return;
		}
		window.loadedFiles.push(file);

		// load res
		if ( type === 'js' ) {
			res = document.createElement('script');
			res.src = file;
		}else if ( type === 'css' ) {
			res = document.createElement('link');
			res.rel = 'stylesheet';
			res.type = 'text/css';
			res.href = file;
		}
		head.appendChild(res);

		// callback
		if (handle) {
			if ( type === 'js' && document.all ) {
				res.onreadystatechange = function() {
					if ( js.readyState === 'loaded' || js.readyState === 'complete' ) {
						handle();
					}
				};
			} else {
				res.onload = function() {
					handle();
				};
			}
		}
	}

})();<commit_msg>Fix: typos<commit_after>(function() {

	// loadFile('jQuery URL', 'js', function() {
	// 	loadFile('Your Plugin', 'js', function() {
	// 		// initialize
	// 	});
	// });

	/**
	 * Load File
	 * @param  {string} file   file url
	 * @param  {string} type   file type (css or js)
	 * @param  {function} handle file loaded callback
	 */
	function loadFile (file, type, handle) {
		var head = document.getElementsByTagName('head')[0],
			res;

		// avoid load more times
		if ( !window.loadedFiles ) {
			window.loadedFiles = [];
		}
		for (var i = 0; i < window.loadedFiles.length; i++) {
			if( file === window.loadedFiles[i] )
				return;
		}
		window.loadedFiles.push(file);

		// load res
		if ( type === 'js' ) {
			res = document.createElement('script');
			res.src = file;
		}else if ( type === 'css' ) {
			res = document.createElement('link');
			res.rel = 'stylesheet';
			res.type = 'text/css';
			res.href = file;
		}
		head.appendChild(res);

		// callback
		if (handle) {
			if ( type === 'js' && document.all ) {
				res.onreadystatechange = function() {
					if ( res.readyState === 'loaded' || res.readyState === 'complete' ) {
						handle();
					}
				};
			} else {
				res.onload = function() {
					handle();
				};
			}
		}
	}

})();<|endoftext|>


<commit_before>var fs = require('fs'),
    path = require('path'),
    os = require('os'),
    win32 = os.platform() === 'win32',
    argv = nw.App.argv,
    bookmarkletOnly = argv.length > 0 && argv[0] === 'b',
    start_str = 'jni rpc: ',
    pdb_started = false,
    hide_backup = false,
    pdb,
    wnd,
    rpc_host

function println(str) {
    process.stdout.write(str + '\n')
}

function getChildArgs(initial_args, extra_args, child_cwd) {
    return initial_args.concat(extra_args, [
        '-Djava.class.path=' + path.join(child_cwd, 'bookmarks-all/target/bookmarks-all-jarjar.jar'),
        'bookmarks.all.Main',
        child_cwd
    ])
}

function isDir(dir) {
    return fs.statSync(dir).isDirectory()
}

function findSubDir(baseDir, subDirPrefix) {
    var dirs = fs.readdirSync(baseDir), dir, f
    for (var i = 0, len = dirs.length; i < len; i++) {
        if (isDir(dir=path.join(baseDir, f=dirs[i])) && 0 === f.indexOf(subDirPrefix))
            return dir
    }
    return null
}

function startProtostuffdb() {
    var spawn = require('child_process').spawn,
        child_cwd = path.join(__dirname, '..'),
        bin = path.join(child_cwd, 'target/protostuffdb'),
        port = fs.readFileSync(path.join(child_cwd, 'PORT.txt'), 'utf8').trim(),
        raw_args = fs.readFileSync(path.join(child_cwd, 'ARGS.txt'), 'utf8').trim(),
        extra_args = raw_args.split(' '),
        child_args = getChildArgs([port, path.join(__dirname, 'g/user/UserServices.json')], extra_args, child_cwd),
        target_cwd,
        p

    hide_backup = raw_args.indexOf('-Dprotostuffdb.with_backup=true') === -1
    if (!win32) {
        target_cwd = child_cwd
    } else if (isDir(target_cwd = 'C:/Program Files/Java/jdk1.7.0_79/jre/bin/server')) {
        bin += '.exe'
    } else if (fs.existsSync(p = path.join(child_cwd, 'JDK_DIR.txt'))) {
        if (!isDir(target_cwd = path.join(fs.readFileSync(p, 'utf8').trim(), 'jre/bin/server'))) {
            println('JDK_DIR.txt did not contain a valid jdk path.')
            process.exit(1)
            return
        }
        bin += '.exe'
    } else if (!isDir('C:/Program Files/Java') ||
            !(p = findSubDir('C:/Program Files/Java', 'jdk1.7')) ||
            !isDir(target_cwd = path.join(p, 'jre/bin/server'))) {
        println('Please create JDK_DIR.txt in the root dir of the project that contains the full path to your jdk.')
        println('E.g.\nC:/path/to/jdk1.7.0_79')
        process.exit(1)
        return
    } else {
        bin += '.exe'
    }

    pdb = spawn(bin, child_args, { cwd: target_cwd })
    pdb.stdout.on('data', onChildOut)
    pdb.on('close', onChildClose)
    rpc_host = 'http://127.0.0.1:' + port
}

function isStart(data) {
    return data.length > start_str.length && start_str === String(data.slice(0, start_str.length))
}

function onChildOut(data) {
    if (pdb_started || !isStart(data))
        return
    pdb_started = true
    openWindow()
}

function onChildClose(code) {
    if (code)
        println('child process exited with code ' + code)
    if (wnd)
        wnd.close(true)
    pdb = undefined
}

function onClose() {
    this.hide()
    wnd = undefined
    if (pdb)
        pdb.kill()
    this.close(true)
}

function onOpen(w) {
    wnd = w
    if (bookmarkletOnly) {
        w.resizeTo(340, 70)
    } else {
        w.resizeTo(767, 715)
    }

    w.moveTo(430, 0)
    if (pdb)
        w.on('close', onClose)
    w.show()
}

function openWindow() {
    global.rpc_host = rpc_host
    global.hide_backup = hide_backup
    nw.Window.open(bookmarkletOnly ? 'nw/bookmarklet.html' : 'index.html', { show: false }, onOpen)

    require('./dist/bookmarklet-nw')
}

startProtostuffdb()

<commit_msg>adjust window width<commit_after>var fs = require('fs'),
    path = require('path'),
    os = require('os'),
    win32 = os.platform() === 'win32',
    argv = nw.App.argv,
    bookmarkletOnly = argv.length > 0 && argv[0] === 'b',
    start_str = 'jni rpc: ',
    pdb_started = false,
    hide_backup = false,
    pdb,
    wnd,
    rpc_host

function println(str) {
    process.stdout.write(str + '\n')
}

function getChildArgs(initial_args, extra_args, child_cwd) {
    return initial_args.concat(extra_args, [
        '-Djava.class.path=' + path.join(child_cwd, 'bookmarks-all/target/bookmarks-all-jarjar.jar'),
        'bookmarks.all.Main',
        child_cwd
    ])
}

function isDir(dir) {
    return fs.statSync(dir).isDirectory()
}

function findSubDir(baseDir, subDirPrefix) {
    var dirs = fs.readdirSync(baseDir), dir, f
    for (var i = 0, len = dirs.length; i < len; i++) {
        if (isDir(dir=path.join(baseDir, f=dirs[i])) && 0 === f.indexOf(subDirPrefix))
            return dir
    }
    return null
}

function startProtostuffdb() {
    var spawn = require('child_process').spawn,
        child_cwd = path.join(__dirname, '..'),
        bin = path.join(child_cwd, 'target/protostuffdb'),
        port = fs.readFileSync(path.join(child_cwd, 'PORT.txt'), 'utf8').trim(),
        raw_args = fs.readFileSync(path.join(child_cwd, 'ARGS.txt'), 'utf8').trim(),
        extra_args = raw_args.split(' '),
        child_args = getChildArgs([port, path.join(__dirname, 'g/user/UserServices.json')], extra_args, child_cwd),
        target_cwd,
        p

    hide_backup = raw_args.indexOf('-Dprotostuffdb.with_backup=true') === -1
    if (!win32) {
        target_cwd = child_cwd
    } else if (isDir(target_cwd = 'C:/Program Files/Java/jdk1.7.0_79/jre/bin/server')) {
        bin += '.exe'
    } else if (fs.existsSync(p = path.join(child_cwd, 'JDK_DIR.txt'))) {
        if (!isDir(target_cwd = path.join(fs.readFileSync(p, 'utf8').trim(), 'jre/bin/server'))) {
            println('JDK_DIR.txt did not contain a valid jdk path.')
            process.exit(1)
            return
        }
        bin += '.exe'
    } else if (!isDir('C:/Program Files/Java') ||
            !(p = findSubDir('C:/Program Files/Java', 'jdk1.7')) ||
            !isDir(target_cwd = path.join(p, 'jre/bin/server'))) {
        println('Please create JDK_DIR.txt in the root dir of the project that contains the full path to your jdk.')
        println('E.g.\nC:/path/to/jdk1.7.0_79')
        process.exit(1)
        return
    } else {
        bin += '.exe'
    }

    pdb = spawn(bin, child_args, { cwd: target_cwd })
    pdb.stdout.on('data', onChildOut)
    pdb.on('close', onChildClose)
    rpc_host = 'http://127.0.0.1:' + port
}

function isStart(data) {
    return data.length > start_str.length && start_str === String(data.slice(0, start_str.length))
}

function onChildOut(data) {
    if (pdb_started || !isStart(data))
        return
    pdb_started = true
    openWindow()
}

function onChildClose(code) {
    if (code)
        println('child process exited with code ' + code)
    if (wnd)
        wnd.close(true)
    pdb = undefined
}

function onClose() {
    this.hide()
    wnd = undefined
    if (pdb)
        pdb.kill()
    this.close(true)
}

function onOpen(w) {
    wnd = w
    if (bookmarkletOnly) {
        w.resizeTo(340, 70)
    } else {
        w.resizeTo(992, 715)
    }

    w.moveTo(360, 0)
    if (pdb)
        w.on('close', onClose)
    w.show()
}

function openWindow() {
    global.rpc_host = rpc_host
    global.hide_backup = hide_backup
    nw.Window.open(bookmarkletOnly ? 'nw/bookmarklet.html' : 'index.html', { show: false }, onOpen)

    require('./dist/bookmarklet-nw')
}

startProtostuffdb()

<|endoftext|>


<commit_before>// @flow
/* global */

import type { OfflineState, OfflineAction, ResultAction } from './types';
import {
  OFFLINE_STATUS_CHANGED,
  OFFLINE_SCHEDULE_RETRY,
  OFFLINE_COMPLETE_RETRY,
  OFFLINE_BUSY,
  PERSIST_REHYDRATE
} from './constants';

type ControlAction =
  | { type: OFFLINE_STATUS_CHANGED, payload: { online: boolean } }
  | { type: OFFLINE_SCHEDULE_RETRY };

const enqueue = (state: OfflineState, action: any): OfflineState => {
  const transaction = state.lastTransaction + 1;
  const stamped = { ...action, meta: { ...action.meta, transaction } };
  const outbox = state.outbox;
  return {
    ...state,
    lastTransaction: transaction,
    outbox: [...outbox, stamped]
  };
};

const dequeue = (state: OfflineState): OfflineState => {
  const [, ...rest] = state.outbox;
  return { ...state, outbox: rest, retryCount: 0, busy: false };
};

const initialState: OfflineState = {
  busy: false,
  lastTransaction: 0,
  online: false,
  outbox: [],
  receipts: [],
  retryToken: 0,
  retryCount: 0,
  retryScheduled: false
};

// @TODO: the typing of this is all kinds of wack

const offlineUpdater = function offlineUpdater(
  state: OfflineState = initialState,
  action: ControlAction | OfflineAction | ResultAction
): OfflineState {
  // Update online/offline status
  if (
    action.type === OFFLINE_STATUS_CHANGED &&
    action.payload &&
    typeof action.payload.online === 'boolean'
  ) {
    return { ...state, online: action.payload.online, netInfo: action.payload.netInfo };
  }

  if (action.type === PERSIST_REHYDRATE) {
    return { ...state, busy: false };
  }

  if (action.type === OFFLINE_SCHEDULE_RETRY) {
    return {
      ...state,
      busy: false,
      retryScheduled: true,
      retryCount: state.retryCount + 1,
      retryToken: state.retryToken + 1
    };
  }

  if (action.type === OFFLINE_COMPLETE_RETRY) {
    return { ...state, retryScheduled: false };
  }

  if (action.type === OFFLINE_BUSY && action.payload && typeof action.payload.busy === 'boolean') {
    return { ...state, busy: action.payload.busy };
  }

  // Add offline actions to queue
  if (action.meta && action.meta.offline) {
    return enqueue(state, action);
  }

  // Remove completed actions from queue (success or fail)
  if (action.meta != null && action.meta.completed === true) {
    return dequeue(state);
  }

  return state;
};

export const enhanceReducer = (reducer: any) =>
  (state: any, action: any) => {
    let offlineState;
    let restState;
    if (typeof state !== 'undefined') {
      const { offline, ...rest } = state;
      offlineState = offline;
      restState = rest;
    }

    return {
      ...reducer(restState, action),
      offline: offlineUpdater(offlineState, action)
    };
  };
<commit_msg>fix: includes netInfo in initialState<commit_after>// @flow
/* global */

import type { OfflineState, OfflineAction, ResultAction } from './types';
import {
  OFFLINE_STATUS_CHANGED,
  OFFLINE_SCHEDULE_RETRY,
  OFFLINE_COMPLETE_RETRY,
  OFFLINE_BUSY,
  PERSIST_REHYDRATE
} from './constants';

type ControlAction =
  | { type: OFFLINE_STATUS_CHANGED, payload: { online: boolean } }
  | { type: OFFLINE_SCHEDULE_RETRY };

const enqueue = (state: OfflineState, action: any): OfflineState => {
  const transaction = state.lastTransaction + 1;
  const stamped = { ...action, meta: { ...action.meta, transaction } };
  const outbox = state.outbox;
  return {
    ...state,
    lastTransaction: transaction,
    outbox: [...outbox, stamped]
  };
};

const dequeue = (state: OfflineState): OfflineState => {
  const [, ...rest] = state.outbox;
  return { ...state, outbox: rest, retryCount: 0, busy: false };
};

const initialState: OfflineState = {
  busy: false,
  lastTransaction: 0,
  online: false,
  outbox: [],
  receipts: [],
  retryToken: 0,
  retryCount: 0,
  retryScheduled: false,
  netInfo: {
    isConnectionExpensive: null,
    reach: 'NONE'
  }
};

// @TODO: the typing of this is all kinds of wack

const offlineUpdater = function offlineUpdater(
  state: OfflineState = initialState,
  action: ControlAction | OfflineAction | ResultAction
): OfflineState {
  // Update online/offline status
  if (
    action.type === OFFLINE_STATUS_CHANGED &&
    action.payload &&
    typeof action.payload.online === 'boolean'
  ) {
    return { ...state, online: action.payload.online, netInfo: action.payload.netInfo };
  }

  if (action.type === PERSIST_REHYDRATE) {
    return { ...state, busy: false };
  }

  if (action.type === OFFLINE_SCHEDULE_RETRY) {
    return {
      ...state,
      busy: false,
      retryScheduled: true,
      retryCount: state.retryCount + 1,
      retryToken: state.retryToken + 1
    };
  }

  if (action.type === OFFLINE_COMPLETE_RETRY) {
    return { ...state, retryScheduled: false };
  }

  if (action.type === OFFLINE_BUSY && action.payload && typeof action.payload.busy === 'boolean') {
    return { ...state, busy: action.payload.busy };
  }

  // Add offline actions to queue
  if (action.meta && action.meta.offline) {
    return enqueue(state, action);
  }

  // Remove completed actions from queue (success or fail)
  if (action.meta != null && action.meta.completed === true) {
    return dequeue(state);
  }

  return state;
};

export const enhanceReducer = (reducer: any) =>
  (state: any, action: any) => {
    let offlineState;
    let restState;
    if (typeof state !== 'undefined') {
      const { offline, ...rest } = state;
      offlineState = offline;
      restState = rest;
    }

    return {
      ...reducer(restState, action),
      offline: offlineUpdater(offlineState, action)
    };
  };
<|endoftext|>


<commit_before>fs = require('fs');

var corp = 'corporate.symphony.com';
var corpApi = 'corporate-api.symphony.com';
var nexus = 'nexus.symphony.com';
var nexusApi = 'nexus-api.symphony.com';
var nexus2 = 'nexus2.symphony.com';
var nexus2Api = 'nexus2-api.symphony.com';
nexus = 'nexus-dev-ause1-all.symphony.com';

function base64EncodeUrl(str){
	return str.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=+$/, '');
}

var n1CrazyThreadId = base64EncodeUrl('9FR+lyvLNttuARgs7av3D3///rCPekXbdA=='); //nexus
var n2CrazyThreadId = base64EncodeUrl('pnTN05AkpGivKFCNzEWkk3///qTgBnUtdA=='); //nexus2
var nexusThreadId = base64EncodeUrl('pnTN05AkpGivKFCNzEWkk3///qTgBnUtdA=='); //nexus2
var n2PrivateThreadId = base64EncodeUrl('DxbnV8++z3vny/SIX7NqGX///qPFMGuYdA==');
var corpTestThreadId = base64EncodeUrl('QBsRAH+GVNvyvRsK9AVufX///qOCFrt8dA==');

module.exports = {
	bots: {
/*
		'1045': {
			keyUrl: 'https://' + corpApi + ':8444/keyauth',
			sessionUrl: 'https://' + corpApi + ':8444/sessionauth',
			agentUrl: 'https://' + corp + ':443/agent',
			podUrl: 'https://' + corp + ':443/pod',

			auth: {
				cert: fs.readFileSync(__dirname + '/certs/grub.bot-cert.pem', {encoding: 'utf-8'}),
				key: fs.readFileSync(__dirname + '/certs/grub.bot-key.pem', {encoding: 'utf-8'}),
				passphrase: 'changeit',
			},
			threadId: corpTestThreadId,
		},
*/
		'130' : {
			keyUrl: 'https://' + nexus2 + ':8444/keyauth',
			sessionUrl: 'https://' + nexus2 + ':8444/sessionauth',
			agentUrl: 'https://' + nexus2 + ':443/agent',
			podUrl: 'https://' + nexus2 + ':443/pod',
			auth: {
				cert: fs.readFileSync(__dirname + '/certs/bot.user1-cert.pem', {encoding: 'utf-8'}),
				key: fs.readFileSync(__dirname + '/certs/bot.user1-key.pem', {encoding: 'utf-8'}),
				passphrase: 'changeit',
			},
			threadId: n2PrivateThreadId,
		},
/*
		'131' : {
			keyUrl: 'https://' + nexus + ':8444/keyauth',
			sessionUrl: 'https://' + nexus + ':8444/sessionauth',
			agentUrl: 'https://' + nexus + ':443/agent',
			podUrl: 'https://' + nexus + ':443/pod',
			auth: {
				cert: fs.readFileSync(__dirname + '/certs/bot.user1-cert.pem', {encoding: 'utf-8'}),
				key: fs.readFileSync(__dirname + '/certs/bot.user1-key.pem', {encoding: 'utf-8'}),
				passphrase: 'changeit',
			},
			threadId: n2PrivateThreadId,
		}
*/

	},
	menuFiles: __dirname + '/../../../menus',
}
<commit_msg>just some configurations<commit_after>fs = require('fs');

var corp = 'corporate.symphony.com';
var corpApi = 'corporate-api.symphony.com';
var nexus = 'nexus.symphony.com';
var nexusApi = 'nexus-api.symphony.com';
var nexus2 = 'nexus2.symphony.com';
var nexus2Api = 'nexus2-api.symphony.com';
nexusApi = 'nexus-dev-ause1-all.symphony.com';
//nexus = 'nexus-dev-ause1-all.symphony.com';

function base64EncodeUrl(str){
	return str.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=+$/, '');
}

var n1CrazyThreadId = base64EncodeUrl('9FR+lyvLNttuARgs7av3D3///rCPekXbdA=='); //nexus
var n2CrazyThreadId = base64EncodeUrl('pnTN05AkpGivKFCNzEWkk3///qTgBnUtdA=='); //nexus2
var nexusThreadId = base64EncodeUrl('pnTN05AkpGivKFCNzEWkk3///qTgBnUtdA=='); //nexus2
var n2PrivateThreadId = base64EncodeUrl('DxbnV8++z3vny/SIX7NqGX///qPFMGuYdA==');
var corpTestThreadId = base64EncodeUrl('QBsRAH+GVNvyvRsK9AVufX///qOCFrt8dA==');

module.exports = {
	bots: {
/*
		'1045': {
			keyUrl: 'https://' + corpApi + ':8444/keyauth',
			sessionUrl: 'https://' + corpApi + ':8444/sessionauth',
			agentUrl: 'https://' + corp + ':443/agent',
			podUrl: 'https://' + corp + ':443/pod',

			auth: {
				cert: fs.readFileSync(__dirname + '/certs/grub.bot-cert.pem', {encoding: 'utf-8'}),
				key: fs.readFileSync(__dirname + '/certs/grub.bot-key.pem', {encoding: 'utf-8'}),
				passphrase: 'changeit',
			},
			threadId: corpTestThreadId,
		},
/*
		'130' : {
			keyUrl: 'https://' + nexus2 + ':8444/keyauth',
			sessionUrl: 'https://' + nexus2 + ':8444/sessionauth',
			agentUrl: 'https://' + nexus2 + ':443/agent',
			podUrl: 'https://' + nexus2 + ':443/pod',
			auth: {
				cert: fs.readFileSync(__dirname + '/certs/bot.user1-cert.pem', {encoding: 'utf-8'}),
				key: fs.readFileSync(__dirname + '/certs/bot.user1-key.pem', {encoding: 'utf-8'}),
				passphrase: 'changeit',
			},
			threadId: n2PrivateThreadId,
		},
/**/
		'131' : {
			keyUrl: 'https://' + nexusApi + ':8444/keyauth',
			sessionUrl: 'https://' + nexusApi + ':8444/sessionauth',
			agentUrl: 'https://' + nexus + ':443/agent',
			podUrl: 'https://' + nexus + ':443/pod',
			auth: {
				cert: fs.readFileSync(__dirname + '/certs/bot.user1-cert.pem', {encoding: 'utf-8'}),
				key: fs.readFileSync(__dirname + '/certs/bot.user1-key.pem', {encoding: 'utf-8'}),
				passphrase: 'changeit',
			},
			threadId: n1CrazyThreadId,
		}
/**/

	},
	menuFiles: __dirname + '/../../../menus',
}
<|endoftext|>


<commit_before>import {getLatestRelease} from './github';
import request from 'request-promise';
import config from '../config';
import cache from './cache';
import semver from 'semver';

export async function darwin(req, res) {
  const version = req.query.version;

  if (!version || !semver.valid(version)) {
    throw new Error('400:Invalid version ${version}.');
  }

  const cacheValidity = 60 * 60 * 1000; // 1h
  const latestRelease = await cache.get('latest-release', getLatestRelease, cacheValidity);

  if (!latestRelease) {
    throw new Error('Latest release not found.');
  }

  const latestVersion = semver.clean(latestRelease.name);
  const shouldUpdate = semver.lt(version, latestVersion);

  if (shouldUpdate) {
    const asset = latestRelease.assets
      .find(a => a.name.match(config.darwinUpdateZipPattern));

    if (!asset) {
      throw new Error(`No asset found that matches ${config.darwinUpdateZipPattern}.`);
    }

    res.json({
      url: asset.browser_download_url,
      name: latestRelease.name,
      notes: latestRelease.body,
      pub_date: latestRelease.published_at
    });

    return;
  }

  res.status(204);
  res.end();
}

export async function win32_portable(req, res) {
  const cacheValidity = 60 * 60 * 1000; // 1h
  const latestRelease = await cache.get('latest-release', getLatestRelease, cacheValidity);

  if (!latestRelease) {
    throw new Error('Latest release not found.');
  }

  const zipAsset = latestRelease.assets
    .find(a => a.name.match(config.win32ZipPattern));

  if (!zipAsset) {
    throw new Error(`No asset found that matches ${config.win32ZipPattern}.`);
  }

  res.json({
    url: zipAsset.browser_download_url,
    name: latestRelease.name,
    notes: latestRelease.body,
    pub_date: latestRelease.published_at,
    version: semver.clean(latestRelease.name)
  });
}

export async function win32_releases(req, res) {
  const cacheValidity = 60 * 60 * 1000; // 1h
  const latestRelease = await cache.get('latest-release', getLatestRelease, cacheValidity);

  if (!latestRelease) {
    throw new Error('Latest release not found.');
  }

  const releasesAsset = latestRelease.assets
    .find(a => a.name == 'RELEASES');

  if (!releasesAsset) {
    throw new Error('Asset RELEASES not found.');
  }

  let releasesFile = await request(releasesAsset.browser_download_url);
  releasesFile = releasesFile
    .replace('\n\r', '\n')
    .split('\n')
    .map(line => {
      const parts = line.split(' ');
      const version = parts[1].match(/-(\d+\.\d+\.\d+)-/)[1];

      const downloadPath = releasesAsset.browser_download_url
        .replace(semver.clean(latestRelease.name), version)
        .replace('/RELEASES', '/');

      parts[1] = downloadPath + parts[1];
      return parts.join(' ');
    })
    .join('\n');

  res.header('Content-Length', releasesFile.length);
  res.attachment('RELEASES');
  res.send(releasesFile);
}

export async function linux(req, res) {
  const arch = req.query.arch || '';
  const pkg = req.query.pkg || '';

  if (['i386', 'amd64', 'x86_64'].indexOf(arch) === -1) {
    throw new Error(`400:Invalid arch ${arch}.`);
  }

  if (['deb', 'rpm'].indexOf(pkg) === -1) {
    throw new Error(`400:Invalid pkg ${pkg}.`);
  }

  const cacheValidity = 60 * 60 * 1000; // 1h
  const latestRelease = await cache.get('latest-release', getLatestRelease, cacheValidity);

  if (!latestRelease) {
    throw new Error('Latest release not found.');
  }

  const asset = latestRelease.assets
    .find(a => a.name.includes(pkg) && a.name.includes(arch));

  if (!asset) {
    throw new Error(`No asset found for pkg ${pkg} and arch ${arch}.`);
  }

  res.json({
    url: asset.browser_download_url,
    name: latestRelease.name,
    notes: latestRelease.body,
    pub_date: latestRelease.published_at,
    version: semver.clean(latestRelease.name)
  });
}
<commit_msg>Changes cache valability to 10 minutes<commit_after>import {getLatestRelease} from './github';
import request from 'request-promise';
import config from '../config';
import cache from './cache';
import semver from 'semver';

export async function darwin(req, res) {
  const version = req.query.version;

  if (!version || !semver.valid(version)) {
    throw new Error('400:Invalid version ${version}.');
  }

  const cacheValidity = 10 * 60 * 1000; // 10 minutes
  const latestRelease = await cache.get('latest-release', getLatestRelease, cacheValidity);

  if (!latestRelease) {
    throw new Error('Latest release not found.');
  }

  const latestVersion = semver.clean(latestRelease.name);
  const shouldUpdate = semver.lt(version, latestVersion);

  if (shouldUpdate) {
    const asset = latestRelease.assets
      .find(a => a.name.match(config.darwinUpdateZipPattern));

    if (!asset) {
      throw new Error(`No asset found that matches ${config.darwinUpdateZipPattern}.`);
    }

    res.json({
      url: asset.browser_download_url,
      name: latestRelease.name,
      notes: latestRelease.body,
      pub_date: latestRelease.published_at
    });

    return;
  }

  res.status(204);
  res.end();
}

export async function win32_portable(req, res) {
  const cacheValidity = 10 * 60 * 1000; // 10 minutes
  const latestRelease = await cache.get('latest-release', getLatestRelease, cacheValidity);

  if (!latestRelease) {
    throw new Error('Latest release not found.');
  }

  const zipAsset = latestRelease.assets
    .find(a => a.name.match(config.win32ZipPattern));

  if (!zipAsset) {
    throw new Error(`No asset found that matches ${config.win32ZipPattern}.`);
  }

  res.json({
    url: zipAsset.browser_download_url,
    name: latestRelease.name,
    notes: latestRelease.body,
    pub_date: latestRelease.published_at,
    version: semver.clean(latestRelease.name)
  });
}

export async function win32_releases(req, res) {
  const cacheValidity = 10 * 60 * 1000; // 10 minutes
  const latestRelease = await cache.get('latest-release', getLatestRelease, cacheValidity);

  if (!latestRelease) {
    throw new Error('Latest release not found.');
  }

  const releasesAsset = latestRelease.assets
    .find(a => a.name == 'RELEASES');

  if (!releasesAsset) {
    throw new Error('Asset RELEASES not found.');
  }

  let releasesFile = await request(releasesAsset.browser_download_url);
  releasesFile = releasesFile
    .replace('\n\r', '\n')
    .split('\n')
    .map(line => {
      const parts = line.split(' ');
      const version = parts[1].match(/-(\d+\.\d+\.\d+)-/)[1];

      const downloadPath = releasesAsset.browser_download_url
        .replace(semver.clean(latestRelease.name), version)
        .replace('/RELEASES', '/');

      parts[1] = downloadPath + parts[1];
      return parts.join(' ');
    })
    .join('\n');

  res.header('Content-Length', releasesFile.length);
  res.attachment('RELEASES');
  res.send(releasesFile);
}

export async function linux(req, res) {
  const arch = req.query.arch || '';
  const pkg = req.query.pkg || '';

  if (['i386', 'amd64', 'x86_64'].indexOf(arch) === -1) {
    throw new Error(`400:Invalid arch ${arch}.`);
  }

  if (['deb', 'rpm'].indexOf(pkg) === -1) {
    throw new Error(`400:Invalid pkg ${pkg}.`);
  }

  const cacheValidity = 10 * 60 * 1000; // 10 minutes
  const latestRelease = await cache.get('latest-release', getLatestRelease, cacheValidity);

  if (!latestRelease) {
    throw new Error('Latest release not found.');
  }

  const asset = latestRelease.assets
    .find(a => a.name.includes(pkg) && a.name.includes(arch));

  if (!asset) {
    throw new Error(`No asset found for pkg ${pkg} and arch ${arch}.`);
  }

  res.json({
    url: asset.browser_download_url,
    name: latestRelease.name,
    notes: latestRelease.body,
    pub_date: latestRelease.published_at,
    version: semver.clean(latestRelease.name)
  });
}
<|endoftext|>


<commit_before>const flatten = require('lodash.flatten');

function encodeAsUrlParam(object) {
  const keyValuePairs =  Object
    .keys(object)
    .filter((key) => object[key] != null)
    .map((key) => {
      const value = object[key];

      if (value.constructor == Array) {
        return value;
      }

      return encodeKeyValuePair(key, value);
    });

  return flatten(keyValuePairs).join('&');
}

function encodeKeyValuePair(key, value) {
  // Skip keys whose value is null or undefined
  if (value == null) { return null; }
  return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`
}

/**
 * Takes an array of objects and returns an array of strings using the following format
 * `${prefix}__${arrayIndex}__${keyName}={value}`
 *
 * @param {string} prefix
 * @param {Array<Object>} arr
 * @returns {Array<String>}
 */
function encodeObjectArray(prefix, arr) {
  const encodedPrefix = encodeURIComponent(prefix);

  const nestedArrays = arr.map((obj, index) => {
    return Object.keys(obj).map((key) => {
      const value = obj[key];
      return `${encodedPrefix}__${index}__${encodeKeyValuePair(key, value)}`;
    });
  });

  return flatten(nestedArrays);
}

module.exports = {
  encodeAsUrlParam,
  encodeKeyValuePair,
  encodeObjectArray
};
<commit_msg>Bugfix for expense creation<commit_after>const lodash = require('lodash');

function encodeAsUrlParam(object) {
  const keyValuePairs =  Object
    .keys(object)
    .filter((key) => object[key] != null)
    .map((key) => {
      const value = object[key];

      if (value.constructor == Array) {
        return value;
      }

      return encodeKeyValuePair(key, value);
    });

  return lodash.flattenDeep(keyValuePairs).join('&');
}

function encodeKeyValuePair(key, value) {
  // Skip keys whose value is null or undefined
  if (value == null) { return null; }
  return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`
}

/**
 * Takes an array of objects and returns an array of strings using the following format
 * `${prefix}__${arrayIndex}__${keyName}={value}`
 *
 * @param {string} prefix
 * @param {Array<Object>} arr
 * @returns {Array<String>}
 */
function encodeObjectArray(prefix, arr) {
  const encodedPrefix = encodeURIComponent(prefix);

  const nestedArrays = arr.map((obj, index) => {
    return Object.keys(obj).map((key) => {
      const value = obj[key];
      return `${encodedPrefix}__${index}__${encodeKeyValuePair(key, value)}`;
    });
  });

  return lodash.flattenDeep(nestedArrays);
}

module.exports = {
  encodeAsUrlParam,
  encodeKeyValuePair,
  encodeObjectArray
};
<|endoftext|>


<commit_before>/*
 * jquery.closestchild 0.1.0
 *
 * Author: Andrey Mikhaylov aka lolmaus
 * Email: lolmaus@gmail.com
 *
 */

 ;(function($){
  $.fn.closestChild = function(selector) {
    var $children, $results;

    $children = this.children();

    if ($children.length === 0)
      return $();

    $results = $children.filter(selector);

    if ($results.length > 0)
      return $results;
    else
      return $children.closestChild(selector);
  };
})(window.jQuery);
<commit_msg>Version bump to 0.1.1<commit_after>/*
 * jquery.closestchild 0.1.1
 *
 * Author: Andrey Mikhaylov aka lolmaus
 * Email: lolmaus@gmail.com
 *
 */

 ;(function($){
  $.fn.closestChild = function(selector) {
    var $children, $results;

    $children = this.children();

    if ($children.length === 0)
      return $();

    $results = $children.filter(selector);

    if ($results.length > 0)
      return $results;
    else
      return $children.closestChild(selector);
  };
})(window.jQuery);
<|endoftext|>


<commit_before>/*
 * jQuery uploader
 *
 * Copyright (c) 2009 Ca-Phun Ung <caphun at yelotofu dot com>
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://yelotofu.com/labs/jquery/snippets/uploader/
 *
 * File upload using an iframe with an indeterminate progress bar.
 */

(function($) {

	$.fn.uploader = function(options) {

		var options = $.extend({
			'successLabel': 'OK',
			'url': './vendor/php/backend.php',
			'indicator': '',
			'trash': '',
			'data': 'w=800&h=800&tw=200&th=200&upload_dir=/fileuploader/uploads/'
		}, options);

		// append an iframe to the body for later use
		$('body').append('');

		return $.each(this, function() {
			var self = $(this),
				form = self.wrap('<form enctype="multipart/form-data" method="post" action="'+ options.url +'" target="iframeUploadFile"></form>').parent();

			// loop through data to generate hidden data for the form submission
			var params = options.data.split('&');
			$.each(params, function(i,n) {
				var item = n.split('=');
				form.append('<input type="hidden" name="options['+item[0]+']" value="'+item[1]+'" />');
			});

			self
				.bind('change', function() {
					form.find('.spinner').show();
					form.submit();
					return false;
				})
				.closest('form')
					.append(options.indicator).find('.spinner').hide();

			$('#iframeUploadFile')
				.bind('load', function() {
					var json = eval($(this)[0].contentWindow.document.body.innerHTML);
					if (json && json.length > 0) {
						var response = json[0].response;
						if (json[0].status == options.successLabel) {

							form.hide();
							$(' '+options.trash+' <input type="hidden" />')
								.insertAfter(form)
								.find('a.remove')
									.bind('click', function() {
										$(this).parent().remove();
										$.post(options.url, response, function(data) {
											// TODO: handle success or failure notification
										});
										form.show();
										return false;
									})
								.end()
								.find('a.file')
									.attr('href', response.url)
									.html(response.filename)
								.end()
								.find('input:hidden')
									.attr('name', self[0].name)
									.attr('value', response.filename)
								.end()
								.show();

						} else if ( response ) {
							$(''+ response +'
').insertBefore(form);
						}
					}
					form.find('.spinner').hide().end().find('input:file').val('');
				});
		});
	}

})(jQuery);<commit_msg>added support for passing parameters via hidden form elements<commit_after>/*
 * jQuery uploader
 *
 * Copyright (c) 2009 Ca-Phun Ung <caphun at yelotofu dot com>
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://yelotofu.com/labs/jquery/snippets/uploader/
 *
 * File upload using an iframe with an indeterminate progress bar.
 */

(function($) {

	$.fn.uploader = function(options) {

		var options = $.extend({
			'successLabel': 'OK',
			'url': './vendor/php/backend.php',
			'indicator': '',
			'trash': '',
			'data': 'upload_dir=/uploads/'
		}, options);

		// append an iframe to the body for later use
		$('body').append('');

		return $.each(this, function() {
			var self = $(this),
				form = self.wrap('<form enctype="multipart/form-data" method="post" action="'+ options.url +'" target="iframeUploadFile"></form>').parent();

				var params = {};

				// loop through data for params
				$.each(options.data && options.data.split('&'), function(i,n) {
					var item = n.split('=');
					params[item[0].toLowerCase()] = item[1];
				});

				// loop through hidden field params
				$('input:hidden[name]').each(function(i,n) {
					params[$(this).attr('name').toLowerCase()] = $(this).attr('value');
				});

				// generate hidden data
				for (var i in params) {
					form.append('<input type="hidden" name="options['+i+']" value="'+params[i]+'" />');
				};

			self
				.bind('change', function() {
					form.find('.spinner').show();
					form.submit();
					return false;
				})
				.closest('form')
					.append(options.indicator).find('.spinner').hide();

			$('#iframeUploadFile')
				.bind('load', function() {
					var json = eval($(this)[0].contentWindow.document.body.innerHTML);
					if (json && json.length > 0) {
						var response = json[0].response;
						if (json[0].status == options.successLabel) {

							form.hide();
							$(' '+options.trash+' <input type="hidden" />')
								.insertAfter(form)
								.find('a.remove')
									.bind('click', function() {
										$(this).parent().remove();
										$.post(options.url, response, function(data) {
											// TODO: handle success or failure notification
										});
										form.show();
										return false;
									})
								.end()
								.find('a.file')
									.attr('href', response.url)
									.html(response.filename)
								.end()
								.find('input:hidden')
									.attr('name', self[0].name)
									.attr('value', response.filename)
								.end()
								.show();

						} else if ( response ) {
							$(''+ response +'
').insertBefore(form);
						}
					}
					form.find('.spinner').hide().end().find('input:file').val('');
				});
		});
	}

})(jQuery);<|endoftext|>


<commit_before>/*!
 * jQuery imagesLoaded plugin v1.2.2
 * http://github.com/desandro/imagesloaded
 *
 * MIT License. by Paul Irish et al.
 */

(function($, undefined) {

// $('#my-container').imagesLoaded(myFunction)
// or
// $('img').imagesLoaded(myFunction)

// execute a callback when all images have loaded.
// needed because .load() doesn't work on cached images

// callback is executed when all images has fineshed loading
// callback function arguments: $all_images, $proper_images, $broken_images
// `this` is the jQuery wrapped container

// returns previous jQuery wrapped container extended with deferred object
// done method arguments: .done( function( $all_images ){ ... } )
// fail method arguments: .fail( function( $all_images, $proper_images, $broken_images ){ ... } )
// progress method arguments: .progress( function( images_count, loaded_count, proper_count, broken_count )

$.fn.imagesLoaded = function( callback ) {
	var $this = this,
		deferred = $.isFunction($.Deferred) ? $.Deferred() : 0,
		hasNotify = $.isFunction(deferred.notify),
		$images = $this.find('img').add( $this.filter('img') ),
		len = $images.length,
		blank = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==',
		loaded = [],
		proper = [],
		broken = [];

	function doneLoading() {
		var $proper = $(proper),
			$broken = $(broken);

		if ( deferred ) {
			if ( broken.length ) {
				deferred.reject( $images, $proper, $broken );
			} else {
				deferred.resolve( $images );
			}
		}

		callback.call( $this, $images, $proper, $broken );
	}

	function imgLoaded( event ) {
		// dont proceed if img src is blank or if img is already loaded
		if ( event.target.src === blank || $.inArray( this, loaded ) !== -1 ) {
			return;
		}

		// store element in loaded images array
		loaded.push( this );

		// keep track of broken and properly loaded images
		if ( event.type === 'error' ) {
			broken.push( this );
		} else {
			proper.push( this );
		}

		// cache event type in element data for future calls
		$.data( this, 'imagesLoaded', event.type );

		if ( hasNotify ) {
			deferred.notify( $images.length, loaded.length, proper.length, broken.length );
		}

		if ( --len <= 0 ){
			setTimeout( doneLoading );
			$images.unbind( '.imagesLoaded', imgLoaded );
		}
	}

	// if no images, trigger immediately
	if ( !len ) {
		doneLoading();
	}

	$images.bind( 'load.imagesLoaded error.imagesLoaded', imgLoaded ).each( function() {
		// find out if this image has been already checked for status
		var cachedEvent = $.data( this, 'imagesLoaded' );
		// if it was, trigger the corresponding event and finish
		if ( cachedEvent ) {
			$(this).triggerHandler( cachedEvent );
			return;
		}
		// cached images don't fire load sometimes, so we reset src.
		var src = this.src;
		// webkit hack from http://groups.google.com/group/jquery-dev/browse_thread/thread/eee6ab7b2da50e1f
		// data uri bypasses webkit log warning (thx doug jones)
		this.src = blank;
		this.src = src;
	});

	return deferred ? deferred.promise( $this ) : $this;
};

})(jQuery);
<commit_msg>fix of epty callback error, closes #19<commit_after>/*!
 * jQuery imagesLoaded plugin v1.2.3
 * http://github.com/desandro/imagesloaded
 *
 * MIT License. by Paul Irish et al.
 */
;(function($, undefined) {

// $('#my-container').imagesLoaded(myFunction)
// or
// $('img').imagesLoaded(myFunction)

// execute a callback when all images have loaded.
// needed because .load() doesn't work on cached images

// callback is executed when all images has fineshed loading
// callback function arguments: $all_images, $proper_images, $broken_images
// `this` is the jQuery wrapped container

// returns previous jQuery wrapped container extended with deferred object
// done method arguments: .done( function( $all_images ){ ... } )
// fail method arguments: .fail( function( $all_images, $proper_images, $broken_images ){ ... } )
// progress method arguments: .progress( function( images_count, loaded_count, proper_count, broken_count )

$.fn.imagesLoaded = function( callback ) {
	var $this = this,
		deferred = $.isFunction($.Deferred) ? $.Deferred() : 0,
		hasNotify = $.isFunction(deferred.notify),
		$images = $this.find('img').add( $this.filter('img') ),
		len = $images.length,
		blank = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==',
		loaded = [],
		proper = [],
		broken = [];

	function doneLoading() {
		var $proper = $(proper),
			$broken = $(broken);

		if ( deferred ) {
			if ( broken.length ) {
				deferred.reject( $images, $proper, $broken );
			} else {
				deferred.resolve( $images );
			}
		}

		if ( $.isFunction( callback ) ) {
			callback.call( $this, $images, $proper, $broken );
		}
	}

	function imgLoaded( event ) {
		// dont proceed if img src is blank or if img is already loaded
		if ( event.target.src === blank || $.inArray( this, loaded ) !== -1 ) {
			return;
		}

		// store element in loaded images array
		loaded.push( this );

		// keep track of broken and properly loaded images
		if ( event.type === 'error' ) {
			broken.push( this );
		} else {
			proper.push( this );
		}

		// cache event type in element data for future calls
		$.data( this, 'imagesLoaded', event.type );

		if ( hasNotify ) {
			deferred.notify( $images.length, loaded.length, proper.length, broken.length );
		}

		if ( --len <= 0 ){
			setTimeout( doneLoading );
			$images.unbind( '.imagesLoaded', imgLoaded );
		}
	}

	// if no images, trigger immediately
	if ( !len ) {
		doneLoading();
	}

	$images.bind( 'load.imagesLoaded error.imagesLoaded', imgLoaded ).each( function() {
		// find out if this image has been already checked for status
		var cachedEvent = $.data( this, 'imagesLoaded' );
		// if it was, trigger the corresponding event and finish
		if ( cachedEvent ) {
			$(this).triggerHandler( cachedEvent );
			return;
		}
		// cached images don't fire load sometimes, so we reset src.
		var src = this.src;
		// webkit hack from http://groups.google.com/group/jquery-dev/browse_thread/thread/eee6ab7b2da50e1f
		// data uri bypasses webkit log warning (thx doug jones)
		this.src = blank;
		this.src = src;
	});

	return deferred ? deferred.promise( $this ) : $this;
};

})(jQuery);
<|endoftext|>


<commit_before>'use strict';

jest.dontMock('../src/device');

describe('device detection', function() {
    it('parses chrome user agent', function() {
        let userAgent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.76 Safari/537.36';
        window.navigator.__defineGetter__('userAgent', function(){
            return userAgent;
        });
        let Device = require('../lib/device');
        let isChrome = Device.isChrome();
        expect(isChrome).toBe(true);
    });

    it('parses iphone user agent', function() {
        let userAgent = 'Mozilla/5.0(iPhone;U;CPUiPhoneOS4_0likeMacOSX;en-us)AppleWebKit/532.9(KHTML,likeGecko)Version/4.0.5Mobile/8A293Safari/6531.22.7';
        window.navigator.__defineGetter__('userAgent', function(){
            return userAgent;
        });
        let Device = require('../lib/device');
        let isIPhone = Device.isIPhone();
        expect(isIPhone).toBe(true);
    });

    it('parses ipad user agent', function() {
        let userAgent = 'Mozilla/5.0 (iPad; CPU OS 6_1_3 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B329 Safari/8536.25';
        window.navigator.__defineGetter__('userAgent', function(){
            return userAgent;
        });
        let Device = require('../lib/device');
        let isIPad = Device.isIPad();
        expect(isIPad).toBe(true);
    });

    it('parses android user agent', function() {
        let userAgent = 'Mozilla/5.0 (Linux; U; Android 2.2; fr-fr; Desire_A8181 Build/FRF91) App3leWebKit/53.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1';
        window.navigator.__defineGetter__('userAgent', function(){
            return userAgent;
        });
        let Device = require('../lib/device');
        let isAndroid = Device.isAndroid();
        expect(isAndroid).toBe(true);
    });
});
<commit_msg>test fixed<commit_after>'use strict';

jest.dontMock('../src/device');

describe('device detection', function() {
    it('parses chrome user agent', function() {
        let userAgent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.76 Safari/537.36';
        window.navigator.__defineGetter__('userAgent', function(){
            return userAgent;
        });
        let Device = require('../src/device');
        let isChrome = Device.isChrome();
        expect(isChrome).toBe(true);
    });

    it('parses iphone user agent', function() {
        let userAgent = 'Mozilla/5.0(iPhone;U;CPUiPhoneOS4_0likeMacOSX;en-us)AppleWebKit/532.9(KHTML,likeGecko)Version/4.0.5Mobile/8A293Safari/6531.22.7';
        window.navigator.__defineGetter__('userAgent', function(){
            return userAgent;
        });
        let Device = require('../src/device');
        let isIPhone = Device.isIPhone();
        expect(isIPhone).toBe(true);
    });

    it('parses ipad user agent', function() {
        let userAgent = 'Mozilla/5.0 (iPad; CPU OS 6_1_3 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B329 Safari/8536.25';
        window.navigator.__defineGetter__('userAgent', function(){
            return userAgent;
        });
        let Device = require('../src/device');
        let isIPad = Device.isIPad();
        expect(isIPad).toBe(true);
    });

    it('parses android user agent', function() {
        let userAgent = 'Mozilla/5.0 (Linux; U; Android 2.2; fr-fr; Desire_A8181 Build/FRF91) App3leWebKit/53.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1';
        window.navigator.__defineGetter__('userAgent', function(){
            return userAgent;
        });
        let Device = require('../src/device');
        let isAndroid = Device.isAndroid();
        expect(isAndroid).toBe(true);
    });
});
<|endoftext|>


<commit_before>var xtpl = require('../../');
var path = require('path');
var xtplKoa = require('../../lib/koa2');
var request = require('supertest');
var Koa=require('koa');

function normalizeSlash(path) {
    if (path.indexOf('\\') !== -1) {
        path = path.replace(/\\/g, '/');
    }
    return path;
}

describe('xtpl', function () {
    it('can get XTemplate engine', function () {
        expect(xtpl.XTemplate).not.toBe(undefined);
    });

    it('works on node', function (done) {
        xtpl.renderFile(path.resolve(__dirname, '../fixture/main.xtpl'), {
            y: '<',
            x: '>'
        }, function (err, data) {
            expect(err).toBe(null);
            expect(data).toBe('<>');
            console.log('oooo')
            done();
        });
    });

    it('works on node when cached', function (done) {
        function check(){
            if (++count === 2) {
                console.log('check');
                done();
            }
        }
        var tplPath = normalizeSlash(path.resolve(__dirname, '../fixture/main.xtpl'));
        var count = 0;
        expect(!!xtpl.getCache(tplPath).instance).toBe(false);
        xtpl.renderFile(tplPath, {
            y: '<',
            x: '>',
            cache: 1
        }, function (err, data) {
            expect(err).toBe(null);
            expect(data).toBe('<>');
            check();
        });
        //console.log(xtpl.getCaches());
        expect(xtpl.getCache(tplPath).instance.config.name).toBe(tplPath);
        xtpl.renderFile(tplPath, {
            y: '<',
            x: '>',
            cache: 1
        }, function (err, data) {
            expect(err).toBe(null);
            expect(data).toBe('<>');
            check();
        });
    });

    it('works for koa', function (done) {
        var app = xtplKoa(new Koa(), {
            views: path.resolve(__dirname, '../fixture/')
        });
        app.use(async function (ctx) {

            // test for ctx.state
            ctx.state.name = 'foo';
            ctx.state.age = 18;

            var html = await ctx.render('main', {
                y: '<',
                x: '>',
                age: 20
            });
            expect(html).toBe('<>foo20');
        });

        const server = app.listen();
        request(server)
          .get('/')
          .expect(200)
          .expect('<>foo20', ()=>{
              console.log('oooo')
              server.close();
              done();
          });
    });

    it('works for koa and absolute path', function (done) {
        var app = xtplKoa(new Koa());
        app.use(async function (ctx) {
            ctx.state.name = 'foo';
            ctx.state.age = 18;

            var html = await ctx.render(path.resolve(__dirname, '../fixture/main.xtpl'), {
                y: '<',
                x: '>',
                age: 20
            });
            expect(html).toBe('<>foo20');
        });
        const server = app.listen();
        request(server)
          .get('/')
          .expect(200)
          .expect('<>foo20', ()=>{
              console.log('oooo')
              server.close();
              done();
          });

    });
});
<commit_msg>update tc<commit_after>var xtpl = require('../../');
var path = require('path');
var xtplKoa = require('../../lib/koa2');
var request = require('supertest');
var Koa=require('koa');

function normalizeSlash(path) {
    if (path.indexOf('\\') !== -1) {
        path = path.replace(/\\/g, '/');
    }
    return path;
}

describe('xtpl', function () {
    it('can get XTemplate engine', function () {
        expect(xtpl.XTemplate).not.toBe(undefined);
    });

    it('works on node', function (done) {
        xtpl.renderFile(path.resolve(__dirname, '../fixture/main.xtpl'), {
            y: '<',
            x: '>'
        }, function (err, data) {
            expect(err).toBe(null);
            expect(data).toBe('<>');
            done();
        });
    });

    it('works on node when cached', function (done) {
        function check(){
            if (++count === 2) {
                done();
            }
        }
        var tplPath = normalizeSlash(path.resolve(__dirname, '../fixture/main.xtpl'));
        var count = 0;
        expect(!!xtpl.getCache(tplPath).instance).toBe(false);
        xtpl.renderFile(tplPath, {
            y: '<',
            x: '>',
            cache: 1
        }, function (err, data) {
            expect(err).toBe(null);
            expect(data).toBe('<>');
            check();
        });
        //console.log(xtpl.getCaches());
        expect(xtpl.getCache(tplPath).instance.config.name).toBe(tplPath);
        xtpl.renderFile(tplPath, {
            y: '<',
            x: '>',
            cache: 1
        }, function (err, data) {
            expect(err).toBe(null);
            expect(data).toBe('<>');
            check();
        });
    });

    it('works for koa', function (done) {
        var app = xtplKoa(new Koa(), {
            views: path.resolve(__dirname, '../fixture/')
        });
        app.use(async function (ctx) {

            // test for ctx.state
            ctx.state.name = 'foo';
            ctx.state.age = 18;

            var html = await ctx.render('main', {
                y: '<',
                x: '>',
                age: 20
            });
            expect(html).toBe('<>foo20');
        });

        request(app.callback())
          .get('/')
          .expect(200)
          .expect('<>foo20', done);
    });

    it('works for koa and absolute path', function (done) {
        var app = xtplKoa(new Koa());
        app.use(async function (ctx) {
            ctx.state.name = 'foo';
            ctx.state.age = 18;

            var html = await ctx.render(path.resolve(__dirname, '../fixture/main.xtpl'), {
                y: '<',
                x: '>',
                age: 20
            });
            expect(html).toBe('<>foo20');
        });
        request(app.callback())
          .get('/')
          .expect(200)
          .expect('<>foo20', done);

    });
});
<|endoftext|>


<commit_before>(function($) {
// Overlay label on top of input
$.fn.labelOverlay = function(options) {
  var opts = $.extend({}, $.fn.labelOverlay.defaults, options);

  return this.each(function() {
    var $this = $(this);

    // Support for the Metadata Plugin.
    var o = $.meta ? $.extend({}, opts, $this.data()) : opts;

	o.placeholder = $.fn.labelOverlay.support();

	if(!o.placeholder) {
		$this.data('id', $this.attr('id'));
		var $label = $('label[for=' + $this.data('id') + ']');
		$label.addClass(o.overlayedClass);
		if (!$this.val() === '') {
			label.hide();
		}
		$this
			.focus(function(e){
				var $this = $(e.target), $label = $('label[for=' + $this.data('id') + ']');
				$label.hide();
			})
			.blur(function(e){
				var $this = $(e.target), $label = $('label[for=' + $this.data('id') + ']');
				if ($this.val() == '') {
					$label.show();
				}
			})
		;
	}
  });

  // private function for debugging
  function debug($obj) {
    if (window.console && window.console.log) {
      window.console.log($obj);
    }
  }
};

$.fn.labelOverlay.support = function() {
	if (window.Modernizr) {
		return Modernizr.input.placeholder;
	} else {
	  var i = document.createElement('input');
	  return 'placeholder' in i;
	}
}

// default options
$.fn.labelOverlay.defaults = {
	placeholder: false,
	overlayedClass: 'overlayed'
};

})(jQuery);
<commit_msg>adjusted variable name to something more understandable<commit_after>(function($) {
// Overlay label on top of input
$.fn.labelOverlay = function(options) {
  var opts = $.extend({}, $.fn.labelOverlay.defaults, options);

  return this.each(function() {
    var $this = $(this);

    // Support for the Metadata Plugin.
    var o = $.meta ? $.extend({}, opts, $this.data()) : opts;

	o.placeholderSupport = $.fn.labelOverlay.support();

	if(!o.placeholderSupport) {
		$this.data('id', $this.attr('id'));
		var $label = $('label[for=' + $this.data('id') + ']');
		$label.addClass(o.overlayedClass);
		if (!$this.val() === '') {
			label.hide();
		}
		$this
			.focus(function(e){
				var $this = $(e.target), $label = $('label[for=' + $this.data('id') + ']');
				$label.hide();
			})
			.blur(function(e){
				var $this = $(e.target), $label = $('label[for=' + $this.data('id') + ']');
				if ($this.val() == '') {
					$label.show();
				}
			})
		;
	}
  });

  // private function for debugging
  function debug($obj) {
    if (window.console && window.console.log) {
      window.console.log($obj);
    }
  }
};

$.fn.labelOverlay.support = function() {
	if (window.Modernizr) {
		return Modernizr.input.placeholder;
	} else {
	  var i = document.createElement('input');
	  return 'placeholder' in i;
	}
}

// default options
$.fn.labelOverlay.defaults = {
	placeholderSupport: false,
	overlayedClass: 'overlayed'
};

})(jQuery);
<|endoftext|>


<commit_before>/*!
 * jQuery Modern Blink plugin
 * https://github.com/leonderijke/Modern-Blink
 *
 * Version: 0.1.1
 * Author: @leonderijke
 * Licensed under the MIT license
 */

;(function ( $, window, document, undefined ) {
	"use strict";

	var domPrefixes = 'Webkit Moz O ms'.split(' '),
		prefix = '',
		supportsAnimations = false,
		keyframeprefix = '',
		keyframes = '',
		defaults = {
			// Duration specified in milliseconds (integer)
			duration:       1000,

			// Number of times the element should blink ("infinite" or integer)
			iterationCount: "infinite",

			// Whether to start automatically or not (boolean)
			auto:          true
		},
		animationCss;

	if( document.documentElement.style.animationName ) {
		supportsAnimations = true;
	}

	if ( !supportsAnimations ) {
		for( var i = 0; i < domPrefixes.length; i++ ) {
			if( document.documentElement.style[ domPrefixes[i] + 'AnimationName' ] !== undefined ) {
				prefix = domPrefixes[ i ];
				keyframeprefix = '-' + prefix.toLowerCase() + '-';
				supportsAnimations = true;
				break;
			}
		}
	}

	if ( supportsAnimations ) {
		keyframes = '@' + keyframeprefix + 'keyframes modernBlink { '+
						'50% { opacity: 0; }'+
					'}';

		var styleSheet = null;
		if (document.styleSheets && document.styleSheets.length) {
			for (var i = 0; i < document.styleSheets.length; ++i) {
				if (document.styleSheets[i].href.indexOf(window.location.hostname) == -1)
					continue;

				styleSheet = document.styleSheets[i];
				break;
			}
		}

		if (styleSheet != null)
			styleSheet.insertRule(keyframes, 0);
		else {
			var s = document.createElement('style');
			s.innerHTML = keyframes;
			document.getElementsByTagName('head')[0].appendChild(s);
		}
	}

	function ModernBlink( element, options ) {
		this.el = $(element);

		this.options = $.extend( {}, defaults, options );

		this._init();
	}

	/*
	 * @function _init
	 * Wraps the element, starts the animation
	 */
	ModernBlink.prototype._init = function _init() {
		if ( this.options.auto ) {
			this.start();
		}

		this._bindEventHandlers();
	};

	/*
	 * @function start
	 * Starts the animation
	 */
	ModernBlink.prototype.start = function start( event ) {
		if ( supportsAnimations ) {
			this.el.css({
				'animation-name':            'modernBlink',
				'animation-duration':        '' + this.options.duration + 'ms',
				'animation-iteration-count': '' + this.options.iterationCount
			});
		} else {
			this._fallbackAnimation( this.options.iterationCount );
		}
	};

	/*
	 * @function stop
	 * Stops the animation
	 */
	ModernBlink.prototype.stop = function stop( event ) {
		if ( supportsAnimations ) {
			return this.el.css({
				'animation-name'            : '',
				'animation-duration'        : '',
				'animation-iteration-count' : ''
			});
		}
		return this.el.stop( true, true );
	};

	/*
	 * @function _fallbackAnimation
	 * Provides a jQuery Animation fallback for browsers not supporting CSS Animations
	 */
	ModernBlink.prototype._fallbackAnimation = function _fallbackAnimation( iterationCount ) {
		var self = this,
			duration = this.options.duration / 2;

		if ( iterationCount > 0 || iterationCount === 'infinite' ) {
			iterationCount = iterationCount === "infinite" ? "infinite" : iterationCount - 1;

			this.el.animate({ 'opacity': 0 }, duration).promise().done(function() {
				self.el.animate({ 'opacity': 1 }, duration);
				self._fallbackAnimation( iterationCount );
			});
		}
	};

	/*
	 * @function _bindEventHandlers
	 * Binds some useful event handlers to the element
	 */
	ModernBlink.prototype._bindEventHandlers = function _bindEventHandlers() {
		this.el.on( 'modernBlink.start', $.proxy( this.start, this ) );
		this.el.on( 'modernBlink.stop', $.proxy( this.stop, this ) );
	};

	/*
	 * @function modernBlink
	 * jQuery plugin wrapper around ModernBlink
	 *
	 * @param options object
	 */
	$.fn.modernBlink = function ( options ) {
		return this.each( function () {
			if (!$.data( this, "plugin_modernBlink" ) ) {
				$.data( this, "plugin_modernBlink", new ModernBlink( this, options ) );
			} else {
				options = (options || "").replace( /^_/ , "" );
				if ( $.isFunction( ModernBlink.prototype[options] ) ) {
					$.data( this, 'plugin_modernBlink' )[options]();
				}
			}
		});
	};

})( jQuery, window, document );<commit_msg>Updated code to follow coding style<commit_after>/*!
 * jQuery Modern Blink plugin
 * https://github.com/leonderijke/Modern-Blink
 *
 * Version: 0.1.1
 * Author: @leonderijke
 * Licensed under the MIT license
 */

;(function ( $, window, document, undefined ) {
	"use strict";

	var domPrefixes = 'Webkit Moz O ms'.split( ' ' ),
		prefix = '',
		supportsAnimations = false,
		keyframeprefix = '',
		keyframes = '',
		defaults = {
			// Duration specified in milliseconds (integer)
			duration:       1000,

			// Number of times the element should blink ("infinite" or integer)
			iterationCount: "infinite",

			// Whether to start automatically or not (boolean)
			auto:          true
		},
		animationCss;

	if( document.documentElement.style.animationName ) {
		supportsAnimations = true;
	}

	if ( !supportsAnimations ) {
		for( var i = 0; i < domPrefixes.length; i++ ) {
			if( document.documentElement.style[ domPrefixes[ i ] + 'AnimationName' ] !== undefined ) {
				prefix = domPrefixes[ i ];
				keyframeprefix = '-' + prefix.toLowerCase() + '-';
				supportsAnimations = true;
				break;
			}
		}
	}

	if ( supportsAnimations ) {
		keyframes = '@' + keyframeprefix + 'keyframes modernBlink { '+
						'50% { opacity: 0; }'+
					'}';

		var styleSheet = null;
		if ( document.styleSheets && document.styleSheets.length ) {
			for ( var i = 0; i < document.styleSheets.length; ++i ) {
				if ( document.styleSheets[ i ].href.indexOf( window.location.hostname ) == -1) {
					continue;
				}

				styleSheet = document.styleSheets[ i ];
				break;
			}
		}

		if ( styleSheet != null ) {
			styleSheet.insertRule( keyframes, 0 );
		}
		else {
			var s = document.createElement( 'style' );
			s.innerHTML = keyframes;
			document.getElementsByTagName( 'head' )[ 0 ].appendChild( s );
		}
	}

	function ModernBlink( element, options ) {
		this.el = $(element);

		this.options = $.extend( {}, defaults, options );

		this._init();
	}

	/*
	 * @function _init
	 * Wraps the element, starts the animation
	 */
	ModernBlink.prototype._init = function _init() {
		if ( this.options.auto ) {
			this.start();
		}

		this._bindEventHandlers();
	};

	/*
	 * @function start
	 * Starts the animation
	 */
	ModernBlink.prototype.start = function start( event ) {
		if ( supportsAnimations ) {
			this.el.css({
				'animation-name':            'modernBlink',
				'animation-duration':        '' + this.options.duration + 'ms',
				'animation-iteration-count': '' + this.options.iterationCount
			});
		} else {
			this._fallbackAnimation( this.options.iterationCount );
		}
	};

	/*
	 * @function stop
	 * Stops the animation
	 */
	ModernBlink.prototype.stop = function stop( event ) {
		if ( supportsAnimations ) {
			return this.el.css({
				'animation-name'            : '',
				'animation-duration'        : '',
				'animation-iteration-count' : ''
			});
		}
		return this.el.stop( true, true );
	};

	/*
	 * @function _fallbackAnimation
	 * Provides a jQuery Animation fallback for browsers not supporting CSS Animations
	 */
	ModernBlink.prototype._fallbackAnimation = function _fallbackAnimation( iterationCount ) {
		var self = this,
			duration = this.options.duration / 2;

		if ( iterationCount > 0 || iterationCount === 'infinite' ) {
			iterationCount = iterationCount === "infinite" ? "infinite" : iterationCount - 1;

			this.el.animate( { 'opacity': 0 }, duration ).promise().done( function() {
				self.el.animate( { 'opacity': 1 }, duration );
				self._fallbackAnimation( iterationCount );
			});
		}
	};

	/*
	 * @function _bindEventHandlers
	 * Binds some useful event handlers to the element
	 */
	ModernBlink.prototype._bindEventHandlers = function _bindEventHandlers() {
		this.el.on( 'modernBlink.start', $.proxy( this.start, this ) );
		this.el.on( 'modernBlink.stop', $.proxy( this.stop, this ) );
	};

	/*
	 * @function modernBlink
	 * jQuery plugin wrapper around ModernBlink
	 *
	 * @param options object
	 */
	$.fn.modernBlink = function ( options ) {
		return this.each( function () {
			if ( !$.data( this, "plugin_modernBlink" ) ) {
				$.data( this, "plugin_modernBlink", new ModernBlink( this, options ) );
			} else {
				options = ( options || "" ).replace( /^_/ , "" );
				if ( $.isFunction( ModernBlink.prototype[ options ] ) ) {
					$.data( this, 'plugin_modernBlink' )[ options ]();
				}
			}
		});
	};

})( jQuery, window, document );<|endoftext|>


<commit_before>/*
 jQuery PowerTip Plugin
 <https://github.com/stevenbenner/jquery-powertip>
 Copyright (c) 2012 Steven Benner, http://stevenbenner.com/
 Released under the MIT license.
 <https://raw.github.com/stevenbenner/jquery-powertip/master/LICENSE.txt>
*/
(function(c){var j,k,l,m,n,p,e,q,r;function s(c){j=c.pageX;k=c.pageY}function o(c){c.data("hoverTimer")&&(clearTimeout(c.data("hoverTimer")),c.data("hoverTimer",null))}var t=c(window),z=c("body");p=n=m=l=!1;e=null;r=q=k=j=0;c.fn.powerTip=function(y){function w(a){if(l)setTimeout(function(){w(a)},d.closeDelay);else{var f=a.data("powertip"),v=a.data("powertiptarget"),h=a.data("powertipjq"),g=v?c("#"+v):[];if(f)b.html(f);else if(0<h.length)b.empty(),h.clone(!0,!0).appendTo(b);else if(0<g.length)b.html(c("#"+
v).html());else return;e=a;l=!0;d.followMouse||(A(a),m=!0);b.data("followMouse",d.followMouse);b.data("mouseOnToPopup",d.mouseOnToPopup);b.stop(!0,!0).fadeIn(d.fadeInTime)}}function B(a){a.data("hasActiveHover",!1);b.fadeOut(d.fadeOutTime,function(){e=null;m=l=!1;b.css("left",j+d.offset+"px");b.css("top",k+d.offset+"px")})}function C(a){s(a);if(l&&!m||p&&!m&&b.data("hasMouseMove")){var f=t.scrollTop(),c=t.width(),h=t.height(),g=b.outerWidth(),x=b.outerHeight(),i=0,e=0,i=g+a.pageX+d.offset<c?a.pageX+
d.offset:c-g,e=x+a.pageY+d.offset<f+h?a.pageY+d.offset:f+h-x;b.css("left",i+"px");b.css("top",e+"px")}}function A(a){var f=a.offset(),c=a.outerWidth(),a=a.outerHeight(),h=b.outerWidth(),g=b.outerHeight(),e=0,i=0;switch(d.placement){case "n":e=f.left+c/2-h/2;i=f.top-g-d.offset;break;case "e":e=f.left+c+d.offset;i=f.top+a/2-g/2;break;case "s":e=f.left+c/2-h/2;i=f.top+a+d.offset;break;case "w":e=f.left-h-d.offset,i=f.top+a/2-g/2}b.css("left",Math.round(e)+"px");b.css("top",Math.round(i)+"px")}function u(a,
b){"show"===b?a.data("hoverTimer",setTimeout(function(){a.data("hoverTimer",null);o(a);var b=Math.abs(q-j),c=Math.abs(r-k);b+c<d.intentSensitivity?(n||a.off("mousemove",s),a.data("hasActiveHover",!0),w(a)):(q=j,r=k,u(a,"show"))},d.intentPollInterval)):"hide"===b&&a.data("hoverTimer",setTimeout(function(){a.data("hoverTimer",null);B(a)},d.closeDelay))}if(!this.length)return this;var d=c.extend({},c.fn.powerTip.defaults,y),b=c("#"+d.popupId);0===b.length&&(b=c("

",{id:d.popupId}),z.append(b));
if(d.followMouse){if(!b.data("hasMouseMove"))t.on("mousemove",C);n=!0;b.data("hasMouseMove",!0)}this.each(function(){var a=c(this),b=a.data("powertip"),d=a.data("powertipjq"),e=a.data("powertiptarget"),g=a.attr("title");if(!b&&!e&&!d&&g){a.data("powertip",g);a.removeAttr("title")}});if(d.followMouse||d.mouseOnToPopup)b.on({mouseenter:function(){(b.data("followMouse")||b.data("mouseOnToPopup"))&&o(e)},mouseleave:function(){if(b.data("mouseOnToPopup")){o(e);u(e,"hide")}}});return this.on({mouseenter:function(a){var b=
c(this);o(b);q=a.pageX;r=a.pageY;if(!n)b.on("mousemove",s);if(!b.data("hasActiveHover")){p=true;u(b,"show")}},mouseleave:function(){var a=c(this);o(a);n||a.off("mousemove",s);p=false;a.data("hasActiveHover")&&u(a,"hide")}})};c.fn.powerTip.defaults={fadeInTime:200,fadeOutTime:200,followMouse:!1,popupId:"powerTip",intentSensitivity:7,intentPollInterval:100,closeDelay:200,placement:"s",offset:10,mouseOnToPopup:!1}})(jQuery);
<commit_msg>Deleted minified version.<commit_after><|endoftext|>


<commit_before>export default '0.0.0-semantically-released';
<commit_msg>Rollback version file change<commit_after>export default '4.0.1';
<|endoftext|>


<commit_before>/*
The MIT License (MIT)

Copyright (c) 2011 Lasse Jul Nielsen

Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

var URL_DATA = '/data/'
var URL_GRAPHS = '/graph/'
var URL_GRAPH_FILES = URL_DATA+'graph/'

var E2 = {};
window.E2 = E2; // global scope so plugins can access it

E2.app = null;
E2.ui = null;	// app sets this to a VizorUI instance
E2.dom = {};
E2.plugins = {};
E2.slot_type = { input: 0, output: 1 };
E2.erase_color = '#ff3b3b';
E2.COLOR_COMPATIBLE_SLOT = '#080';

(function() {
	E2.uid = function() {
		var keys = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
		var uid = ''
		for (var i=0; i < 12; i++) {
			uid += keys[Math.floor(Math.random() * keys.length)]
		}
		return uid
	}
})()

function Delegate(delegate, dt, count)
{
	this.delegate = delegate;
	this.dt = dt;
	this.count = count;
}

function AssetTracker(core)
{
	this.core = core;
	this.started = 0;
	this.completed = 0;
	this.failed = 0;
	this.listeners = [];
}

AssetTracker.prototype.add_listener = function(listener)
{
	this.listeners.push(listener);
};

AssetTracker.prototype.remove_listener = function(listener)
{
	var listenerIdx = this.listeners.indexOf(listener)
	if (listenerIdx > -1)
		this.listeners.splice(listenerIdx, 1);
};

AssetTracker.prototype.signal_started = function()
{
	this.started++;
	this.signal_update();
};

AssetTracker.prototype.signal_completed = function()
{
	this.completed++;
	this.signal_update();
};

AssetTracker.prototype.signal_failed = function()
{
	this.failed++;
	this.signal_update();
};

AssetTracker.prototype.signal_update = function()
{
	var l = this.listeners;
	var prc = (this.completed + this.failed) / (this.started / 100);

	E2.core.emit('progress', this.started === (this.completed + this.failed) ? 100 : prc)

	for(var i = 0, len = l.length; i < len; i++)
		l[i]();
};

function Core() {
	EventEmitter.apply(this, arguments)

	E2.core = this

	E2.dt = this.datatypes = {
		FLOAT: { id: 0, name: 'Float' },
		SHADER: { id: 1, name: 'Shader' },
		TEXTURE: { id: 2, name: 'Texture' },
		COLOR: { id: 3, name: 'Color' },
		MATRIX: { id: 4, name: 'Matrix' },
		VECTOR: { id: 5, name: 'Vector' },
		CAMERA: { id: 6, name: 'Camera' },
		BOOL: { id: 7, name: 'Boolean' },
		ANY: { id: 8, name: 'Arbitrary' },
		MESH: { id: 9, name: 'Mesh' },
		AUDIO: { id: 10, name: 'Audio' },
		SCENE: { id: 11, name: 'Scene' },
		MATERIAL: { id: 12, name: 'Material' },
		LIGHT: { id: 13, name: 'Light' },
		DELEGATE: { id: 14, name: 'Delegate' },
		TEXT: { id: 15, name: 'Text' },
		VIDEO: { id: 16, name: 'Video' },
		ARRAY: { id: 17, name: 'Typed Array' },
		OBJECT: { id: 18, name: 'Object' },

		GEOMETRY: { id: 19, name: 'Geometry' },
		QUATERNION: { id: 20, name: 'Quaternion' },
		OBJECT3D: { id: 21, name: 'Object3D' },

		VECTOR4: { id: 22, name: 'Vector 4' },

		ENVIRONMENTSETTINGS: { id: 23, name: 'Environment Settings' }
	}

	this.renderer = { // compat for old plugins
		matrix_identity: new THREE.Matrix4().identity(),
		vector_origin: new THREE.Vector3(),
		material_default: new THREE.MeshBasicMaterial(),
		color_white: new THREE.Color(0xffffff),
		color_black: new THREE.Color(0x000000),
		blend_mode: {
			NORMAL: 1
		}
	}

	this._listeners = {};

	this.runtimeEvents = new EventEmitter()

	this.asset_tracker = new AssetTracker(this);

	this.active_graph_dirty = true;

	this.active_graph = this.root_graph = null
	this.graphs = []

	this.abs_t = 0.0;
	this.delta_t = 0.0;
	this.graph_uid = this.get_uid()
	this.uidCounter = 0

	this.textureCache = new TextureCache()

	this.pluginManager = new PluginManager(this, '/plugins');

	this.pluginManager.on('ready', function() {
		this.onPluginsLoaded()
	}.bind(this))

	this.aux_scripts = {};
	this.aux_styles = {};
	this.resolve_dt = []; // Table for easy reverse lookup of dt reference by id.
	this.audio_ctx = null;

	for(var i in this.datatypes) {
		var dt = this.datatypes[i];

		this.resolve_dt[dt.id] = dt;
	}

	// HTML5 audio context initialisation
	if(window.AudioContext)
		this.audio_ctx = new AudioContext();
	else if(window.webkitAudioContext)
		this.audio_ctx = new webkitAudioContext();
	else
		msg('NOTE: This host has no AudioContext support.');
}

Core.prototype = Object.create(EventEmitter.prototype)

Core.prototype.get_uid = function() {
	return E2.uid()
}

Core.prototype.update = function(abs_t, delta_t)
{
	this.abs_t = abs_t;
	this.delta_t = delta_t;

	this.root_graph.update(delta_t);

	var dirty = this.active_graph_dirty;

	this.active_graph_dirty = false;

	return dirty; // Did connection state change?
};

Core.prototype.create_dialog = function(diag, title, w, h, done_func, open_func)
{
	var modal = bootbox.dialog({
		title: title,
		message: diag,
		buttons: {'OK': function(){}}
	})

	function close()
	{
		modal.unbind();
		modal.remove();
	}

	function ok()
	{
		done_func();
		modal.modal('hide');
	}

	modal.on('show.bs.modal', function()
	{
		$('.modal-dialog', modal).css('width', w + 40).addClass('patch-inspector');
	});

	modal.on('shown.bs.modal', function()
	{
		if(open_func)
			open_func();
	});

	modal.on('hidden.bs.modal', close);
	modal.modal({ keyboard: true });

	modal.on('keypress', function(e)
	{
		if(e.keyCode === 13)
		{
			if(e.target.nodeName !== 'TEXTAREA')
				ok();
		}
	})

	$('button:last', modal).click(ok);
};

Core.prototype.get_default_value = function(dt)
{
	var dts = this.datatypes;

	if(dt === dts.FLOAT)
		return 0.0;
	else if(dt === dts.COLOR)
		return new THREE.Color(1, 1, 1, 1)
	else if(dt === dts.MATRIX) {
		return new THREE.Matrix4()
	} else if(dt === dts.VECTOR)

		return new THREE.Vector3(0, 0, 0)
	else if(dt === dts.CAMERA)
		return new THREE.PerspectiveCamera()
	else if(dt === dts.BOOL)
		return false;
	else if(dt === dts.TEXT)
		return '';
	else if(dt === dts.ARRAY) {
		var a = new ArrayBuffer(0);
		a.stride = a.datatype = 1; // Uint8
		return a;
	} else if(dt === dts.OBJECT)
		return {};

	// Shaders, textures, materials, scenes, light and delegates and ALL legally defaults to null.
	return null;
};

Core.prototype.serialise = function()
{
	var d = {};

	d.abs_t = Math.round(this.abs_t * Math.pow(10, 4)) / Math.pow(10, 4);
	d.active_graph = this.active_graph.uid;
	d.graph_uid = this.graph_uid;
	d.root = this.root_graph.serialise();

	return JSON.stringify(d, undefined, 4);
};

Core.prototype.deserialiseObject = function(d) {
	this.abs_t = d.abs_t;
	this.delta_t = 0.0;
	this.graph_uid = '' + d.graph_uid;

	this.active_graph.destroy_ui();

	this.graphs = [];

	this.root_graph = new Graph(this, null, null);
	this.root_graph.deserialise(d.root);
	this.graphs.push(this.root_graph);

	this.root_graph.patch_up(this.graphs);
	this.root_graph.initialise(this.graphs);

	this.active_graph = resolve_graph(this.graphs, ''+d.active_graph);

	if (E2.app.player.current_state === E2.app.player.state.PLAYING) {
		this.active_graph.play()
	}

	if(!this.active_graph) {
		msg('ERROR: The active graph (ID: ' + d.active_graph + ') is invalid. Using the root graph.');
		this.active_graph = this.root_graph;
	}
}

Core.prototype.deserialise = function(str) {
	return this.deserialiseObject(JSON.parse(str))
}

Core.prototype.rebuild_structure_tree = function() {
	function build(graph, name) {
		var nodes = graph.nodes;

		if (graph.parent_graph) {
			var ptn = graph.parent_graph.tree_node;
			var tnode = new TreeNode(ptn.tree, ptn, name, graph);

			ptn.children.push(tnode);
		}

		for(var i = 0, len = nodes.length; i < len; i++) {
			var n = nodes[i];

			if(n.plugin.isGraph)
				build(n.plugin.graph, n.get_disp_name());
		}
	}

	if (!E2.dom.structure)
		return;

	E2.dom.structure.tree.reset();
	this.root_graph.tree_node = E2.dom.structure.tree.root;
	E2.dom.structure.tree.root.graph = this.root_graph;
	build(this.root_graph, 'Root');
	E2.dom.structure.tree.root.rebuild_dom();
};

Core.prototype.add_aux_script = function(script_url, onload)
{
	if(this.aux_scripts.hasOwnProperty(script_url)) {
		if (onload)
			onload()
		return
	}

	load_script('/plugins/' + script_url, function() {
		this.aux_scripts[script_url] = true;
		if (onload)
			onload()
	}.bind(this));
};

Core.prototype.add_aux_style = function(style_url)
{
	if(this.aux_styles.hasOwnProperty(style_url))
		return;

	load_style('/plugins/' + style_url);
	this.aux_styles[style_url] = true;
};

Core.prototype.onPluginsLoaded = function() {
	this.emit('ready');
};

Core.prototype.on = function(kind, cb)
{
	if (!cb)
		return;

	if (!this._listeners[kind])
		this._listeners[kind] = [];

	this._listeners[kind].push(cb);
}

Core.prototype.emit = function(kind)
{
	if (!this._listeners[kind])
		return;

	this._listeners[kind].forEach(function(cb)
	{
		cb();
	});
};

if (typeof(module) !== 'undefined') {
	module.exports = Core
}
<commit_msg>lowercase E2.uid()<commit_after>/*
The MIT License (MIT)

Copyright (c) 2011 Lasse Jul Nielsen

Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

var URL_DATA = '/data/'
var URL_GRAPHS = '/graph/'
var URL_GRAPH_FILES = URL_DATA+'graph/'

var E2 = {};
window.E2 = E2; // global scope so plugins can access it

E2.app = null;
E2.ui = null;	// app sets this to a VizorUI instance
E2.dom = {};
E2.plugins = {};
E2.slot_type = { input: 0, output: 1 };
E2.erase_color = '#ff3b3b';
E2.COLOR_COMPATIBLE_SLOT = '#080';

(function() {
	E2.uid = function() {
		var keys = 'abcdefghijklmnopqrstuvwxyz0123456789'
		var uid = ''
		for (var i=0; i < 12; i++) {
			uid += keys[Math.floor(Math.random() * keys.length)]
		}
		return uid
	}
})()

function Delegate(delegate, dt, count)
{
	this.delegate = delegate;
	this.dt = dt;
	this.count = count;
}

function AssetTracker(core)
{
	this.core = core;
	this.started = 0;
	this.completed = 0;
	this.failed = 0;
	this.listeners = [];
}

AssetTracker.prototype.add_listener = function(listener)
{
	this.listeners.push(listener);
};

AssetTracker.prototype.remove_listener = function(listener)
{
	var listenerIdx = this.listeners.indexOf(listener)
	if (listenerIdx > -1)
		this.listeners.splice(listenerIdx, 1);
};

AssetTracker.prototype.signal_started = function()
{
	this.started++;
	this.signal_update();
};

AssetTracker.prototype.signal_completed = function()
{
	this.completed++;
	this.signal_update();
};

AssetTracker.prototype.signal_failed = function()
{
	this.failed++;
	this.signal_update();
};

AssetTracker.prototype.signal_update = function()
{
	var l = this.listeners;
	var prc = (this.completed + this.failed) / (this.started / 100);

	E2.core.emit('progress', this.started === (this.completed + this.failed) ? 100 : prc)

	for(var i = 0, len = l.length; i < len; i++)
		l[i]();
};

function Core() {
	EventEmitter.apply(this, arguments)

	E2.core = this

	E2.dt = this.datatypes = {
		FLOAT: { id: 0, name: 'Float' },
		SHADER: { id: 1, name: 'Shader' },
		TEXTURE: { id: 2, name: 'Texture' },
		COLOR: { id: 3, name: 'Color' },
		MATRIX: { id: 4, name: 'Matrix' },
		VECTOR: { id: 5, name: 'Vector' },
		CAMERA: { id: 6, name: 'Camera' },
		BOOL: { id: 7, name: 'Boolean' },
		ANY: { id: 8, name: 'Arbitrary' },
		MESH: { id: 9, name: 'Mesh' },
		AUDIO: { id: 10, name: 'Audio' },
		SCENE: { id: 11, name: 'Scene' },
		MATERIAL: { id: 12, name: 'Material' },
		LIGHT: { id: 13, name: 'Light' },
		DELEGATE: { id: 14, name: 'Delegate' },
		TEXT: { id: 15, name: 'Text' },
		VIDEO: { id: 16, name: 'Video' },
		ARRAY: { id: 17, name: 'Typed Array' },
		OBJECT: { id: 18, name: 'Object' },

		GEOMETRY: { id: 19, name: 'Geometry' },
		QUATERNION: { id: 20, name: 'Quaternion' },
		OBJECT3D: { id: 21, name: 'Object3D' },

		VECTOR4: { id: 22, name: 'Vector 4' },

		ENVIRONMENTSETTINGS: { id: 23, name: 'Environment Settings' }
	}

	this.renderer = { // compat for old plugins
		matrix_identity: new THREE.Matrix4().identity(),
		vector_origin: new THREE.Vector3(),
		material_default: new THREE.MeshBasicMaterial(),
		color_white: new THREE.Color(0xffffff),
		color_black: new THREE.Color(0x000000),
		blend_mode: {
			NORMAL: 1
		}
	}

	this._listeners = {};

	this.runtimeEvents = new EventEmitter()

	this.asset_tracker = new AssetTracker(this);

	this.active_graph_dirty = true;

	this.active_graph = this.root_graph = null
	this.graphs = []

	this.abs_t = 0.0;
	this.delta_t = 0.0;
	this.graph_uid = this.get_uid()
	this.uidCounter = 0

	this.textureCache = new TextureCache()

	this.pluginManager = new PluginManager(this, '/plugins');

	this.pluginManager.on('ready', function() {
		this.onPluginsLoaded()
	}.bind(this))

	this.aux_scripts = {};
	this.aux_styles = {};
	this.resolve_dt = []; // Table for easy reverse lookup of dt reference by id.
	this.audio_ctx = null;

	for(var i in this.datatypes) {
		var dt = this.datatypes[i];

		this.resolve_dt[dt.id] = dt;
	}

	// HTML5 audio context initialisation
	if(window.AudioContext)
		this.audio_ctx = new AudioContext();
	else if(window.webkitAudioContext)
		this.audio_ctx = new webkitAudioContext();
	else
		msg('NOTE: This host has no AudioContext support.');
}

Core.prototype = Object.create(EventEmitter.prototype)

Core.prototype.get_uid = function() {
	return E2.uid()
}

Core.prototype.update = function(abs_t, delta_t)
{
	this.abs_t = abs_t;
	this.delta_t = delta_t;

	this.root_graph.update(delta_t);

	var dirty = this.active_graph_dirty;

	this.active_graph_dirty = false;

	return dirty; // Did connection state change?
};

Core.prototype.create_dialog = function(diag, title, w, h, done_func, open_func)
{
	var modal = bootbox.dialog({
		title: title,
		message: diag,
		buttons: {'OK': function(){}}
	})

	function close()
	{
		modal.unbind();
		modal.remove();
	}

	function ok()
	{
		done_func();
		modal.modal('hide');
	}

	modal.on('show.bs.modal', function()
	{
		$('.modal-dialog', modal).css('width', w + 40).addClass('patch-inspector');
	});

	modal.on('shown.bs.modal', function()
	{
		if(open_func)
			open_func();
	});

	modal.on('hidden.bs.modal', close);
	modal.modal({ keyboard: true });

	modal.on('keypress', function(e)
	{
		if(e.keyCode === 13)
		{
			if(e.target.nodeName !== 'TEXTAREA')
				ok();
		}
	})

	$('button:last', modal).click(ok);
};

Core.prototype.get_default_value = function(dt)
{
	var dts = this.datatypes;

	if(dt === dts.FLOAT)
		return 0.0;
	else if(dt === dts.COLOR)
		return new THREE.Color(1, 1, 1, 1)
	else if(dt === dts.MATRIX) {
		return new THREE.Matrix4()
	} else if(dt === dts.VECTOR)

		return new THREE.Vector3(0, 0, 0)
	else if(dt === dts.CAMERA)
		return new THREE.PerspectiveCamera()
	else if(dt === dts.BOOL)
		return false;
	else if(dt === dts.TEXT)
		return '';
	else if(dt === dts.ARRAY) {
		var a = new ArrayBuffer(0);
		a.stride = a.datatype = 1; // Uint8
		return a;
	} else if(dt === dts.OBJECT)
		return {};

	// Shaders, textures, materials, scenes, light and delegates and ALL legally defaults to null.
	return null;
};

Core.prototype.serialise = function()
{
	var d = {};

	d.abs_t = Math.round(this.abs_t * Math.pow(10, 4)) / Math.pow(10, 4);
	d.active_graph = this.active_graph.uid;
	d.graph_uid = this.graph_uid;
	d.root = this.root_graph.serialise();

	return JSON.stringify(d, undefined, 4);
};

Core.prototype.deserialiseObject = function(d) {
	this.abs_t = d.abs_t;
	this.delta_t = 0.0;
	this.graph_uid = '' + d.graph_uid;

	this.active_graph.destroy_ui();

	this.graphs = [];

	this.root_graph = new Graph(this, null, null);
	this.root_graph.deserialise(d.root);
	this.graphs.push(this.root_graph);

	this.root_graph.patch_up(this.graphs);
	this.root_graph.initialise(this.graphs);

	this.active_graph = resolve_graph(this.graphs, ''+d.active_graph);

	if (E2.app.player.current_state === E2.app.player.state.PLAYING) {
		this.active_graph.play()
	}

	if(!this.active_graph) {
		msg('ERROR: The active graph (ID: ' + d.active_graph + ') is invalid. Using the root graph.');
		this.active_graph = this.root_graph;
	}
}

Core.prototype.deserialise = function(str) {
	return this.deserialiseObject(JSON.parse(str))
}

Core.prototype.rebuild_structure_tree = function() {
	function build(graph, name) {
		var nodes = graph.nodes;

		if (graph.parent_graph) {
			var ptn = graph.parent_graph.tree_node;
			var tnode = new TreeNode(ptn.tree, ptn, name, graph);

			ptn.children.push(tnode);
		}

		for(var i = 0, len = nodes.length; i < len; i++) {
			var n = nodes[i];

			if(n.plugin.isGraph)
				build(n.plugin.graph, n.get_disp_name());
		}
	}

	if (!E2.dom.structure)
		return;

	E2.dom.structure.tree.reset();
	this.root_graph.tree_node = E2.dom.structure.tree.root;
	E2.dom.structure.tree.root.graph = this.root_graph;
	build(this.root_graph, 'Root');
	E2.dom.structure.tree.root.rebuild_dom();
};

Core.prototype.add_aux_script = function(script_url, onload)
{
	if(this.aux_scripts.hasOwnProperty(script_url)) {
		if (onload)
			onload()
		return
	}

	load_script('/plugins/' + script_url, function() {
		this.aux_scripts[script_url] = true;
		if (onload)
			onload()
	}.bind(this));
};

Core.prototype.add_aux_style = function(style_url)
{
	if(this.aux_styles.hasOwnProperty(style_url))
		return;

	load_style('/plugins/' + style_url);
	this.aux_styles[style_url] = true;
};

Core.prototype.onPluginsLoaded = function() {
	this.emit('ready');
};

Core.prototype.on = function(kind, cb)
{
	if (!cb)
		return;

	if (!this._listeners[kind])
		this._listeners[kind] = [];

	this._listeners[kind].push(cb);
}

Core.prototype.emit = function(kind)
{
	if (!this._listeners[kind])
		return;

	this._listeners[kind].forEach(function(cb)
	{
		cb();
	});
};

if (typeof(module) !== 'undefined') {
	module.exports = Core
}
<|endoftext|>