<commit_before>#!/usr/bin/env node

/* global require, module */

// require()s
var path = require('path');
var fs = require('fs');

var _ = require('lodash');

var opts = require('minimist')(process.argv.slice(2));

// opt parsing
if (opts.help) {
  console.log('Usage: bowcat [<input-dir>] [-o <output-dir>] [--min | -m]');
  process.exit(0);
}

var includeMins = opts.min || opts.m;
var inputDir = opts._[0] || '.';
var outputDir = opts.o || path.join('.', 'build');

inputDir = path.resolve(inputDir);
outputDir = path.resolve(outputDir);

var pkgs = fs.readdirSync(path.join(inputDir, 'bower_components'));

pkgs = _.map(pkgs, function (p) {
  return path.join(inputDir, 'bower_components', p);
});

var concatedPkgs = [];

// constructFileList: create a list of files to concat for a particular
// package. 'dir' is the path to the package, 'mains' is the 'main' field
// in the package's bower.json, 'minified' is whether or not to include
// minified files
function constructFileList (dir, mains, minified) {
  var files = fs.readdirSync(dir);

  files = _.map(files, function (f) {
    return path.join(dir, f);
  });

  _.each(files, function (f, i, l) {
    if (! f) return;

    if (fs.statSync(f).isDirectory()) {
      files.splice(i, 1);
      files = files.concat(constructFileList(f, mains, minified));
    }
  });

  files = _.filter(files, function (f) {
    f = path.basename(f).split('.').slice(0, -1).join('.');

    var include = _.some(mains, function (m) {
      m = path.basename(m).split('.').slice(0, -1).join('.');
      return m === f;
    });

    if (typeof mains === 'string') {
      mains = path.basename(mains).split('.').slice(0, -1).join('.');
      include = (mains === f);
    }

    if (minified) include = include
                         || f.indexOf('.min.js') === (f.length - 7)
                         || f.indexOf('.min.css') === (f.length - 8);

    return include;
  });

  return files;
}

// concatPackage: concatenate a single package. 'package' is the full path to
// the package directory, 'outDir' is the output directory, 'minified'
// is whether or not to include minified files
function concatPackage (package, outDir, minified) {
  if (_.contains(concatedPkgs, path.basename(package))) return;

  var bowerJSON = JSON.parse(fs.readFileSync(path.join(package, 'bower.json')));
  var deps = bowerJSON.dependencies || {};
  var mains = bowerJSON.main || [];

  concatedPkgs.push(path.basename(package));

  _.each(Object.keys(deps), function (pkg, i, l) {
    var components = package.split(path.sep);
    var pkgpath = components.slice(0, -1).join(path.sep);
    concatPackage(path.join(pkgpath, pkg));
  });

  var files = constructFileList(package, mains, minified);
  var concatJS = '', concatCSS = '';

  _.each(files, function (filepath, i, l) {
    var contents = fs.readFileSync(filepath) + '\n';
    var ext = filepath.split('.')[filepath.split('.').length - 1];

    if (ext === 'js')
      concatJS += contents;
    else if (ext === 'css')
      concatCSS += contents;
  });

  if (concatJS !== '')
    fs.appendFileSync(path.join(outDir, 'build.js'), concatJS);

  if (concatCSS !== '')
    fs.appendFileSync(path.join(outDir, 'build.css'), concatCSS);
}

// concatPackages: concatenate a list of packages ('packages'). 'outDir'
// is the output directory, 'minified' is whether or not to include
// minified files.
function concatPackages (packages, outDir, minified) {
  if (! outDir) outDir = path.join('.', 'build');

  if (! fs.existsSync(outDir)) fs.mkdirSync(outDir);

  _.each(packages, function (package, i, l) {
    concatPackage(package, outDir, minified);
  });
}

module.exports = {
  concatPackage: concatPackage,
  concatPackages: concatPackages,
  constructFileList: constructFileList
};

if (require.main === module)
  concatPackages(pkgs, outputDir, includeMins);
<commit_msg>Don't reassign 'mains'<commit_after>#!/usr/bin/env node

/* global require, module */

// require()s
var path = require('path');
var fs = require('fs');

var _ = require('lodash');

var opts = require('minimist')(process.argv.slice(2));

// opt parsing
if (opts.help) {
  console.log('Usage: bowcat [<input-dir>] [-o <output-dir>] [--min | -m]');
  process.exit(0);
}

var includeMins = opts.min || opts.m;
var inputDir = opts._[0] || '.';
var outputDir = opts.o || path.join('.', 'build');

inputDir = path.resolve(inputDir);
outputDir = path.resolve(outputDir);

var pkgs = fs.readdirSync(path.join(inputDir, 'bower_components'));

pkgs = _.map(pkgs, function (p) {
  return path.join(inputDir, 'bower_components', p);
});

var concatedPkgs = [];

// constructFileList: create a list of files to concat for a particular
// package. 'dir' is the path to the package, 'mains' is the 'main' field
// in the package's bower.json, 'minified' is whether or not to include
// minified files
function constructFileList (dir, mains, minified) {
  var files = fs.readdirSync(dir);

  files = _.map(files, function (f) {
    return path.join(dir, f);
  });

  _.each(files, function (f, i, l) {
    if (fs.statSync(f).isDirectory())
      files = files.concat(constructFileList(f, mains, minified));
  });

  files = _.filter(files, function (f) {
    if (fs.statSync(f).isDirectory()) return false;

    var fname = path.basename(f).split('.').slice(0, -1).join('.');

    var include = _.some(mains, function (m) {
      m = path.basename(m).split('.').slice(0, -1).join('.');
      return m === fname;
    });

    if (typeof mains === 'string') {
      var mainsName = path.basename(mains).split('.').slice(0, -1).join('.');
      include = (mainsName === fname);
    }

    if (minified) include = include
                         || f.indexOf('.min.js') === (f.length - 7)
                         || f.indexOf('.min.css') === (f.length - 8);

    return include;
  });

  return files;
}

// concatPackage: concatenate a single package. 'package' is the full path to
// the package directory, 'outDir' is the output directory, 'minified'
// is whether or not to include minified files
function concatPackage (package, outDir, minified) {
  if (_.contains(concatedPkgs, path.basename(package))) return;

  var bowerJSON = JSON.parse(fs.readFileSync(path.join(package, 'bower.json')));
  var deps = bowerJSON.dependencies || {};
  var mains = bowerJSON.main || [];

  concatedPkgs.push(path.basename(package));

  _.each(Object.keys(deps), function (pkg, i, l) {
    var components = package.split(path.sep);
    var pkgpath = components.slice(0, -1).join(path.sep);
    concatPackage(path.join(pkgpath, pkg));
  });

  var files = constructFileList(package, mains, minified);
  var concatJS = '', concatCSS = '';

  _.each(files, function (filepath, i, l) {
    var contents = fs.readFileSync(filepath) + '\n';
    var ext = filepath.split('.')[filepath.split('.').length - 1];

    if (ext === 'js')
      concatJS += contents;
    else if (ext === 'css')
      concatCSS += contents;
  });

  if (concatJS !== '')
    fs.appendFileSync(path.join(outDir, 'build.js'), concatJS);

  if (concatCSS !== '')
    fs.appendFileSync(path.join(outDir, 'build.css'), concatCSS);
}

// concatPackages: concatenate a list of packages ('packages'). 'outDir'
// is the output directory, 'minified' is whether or not to include
// minified files.
function concatPackages (packages, outDir, minified) {
  if (! outDir) outDir = path.join('.', 'build');

  if (! fs.existsSync(outDir)) fs.mkdirSync(outDir);

  _.each(packages, function (package, i, l) {
    concatPackage(package, outDir, minified);
  });
}

module.exports = {
  concatPackage: concatPackage,
  concatPackages: concatPackages,
  constructFileList: constructFileList
};

if (require.main === module)
  concatPackages(pkgs, outputDir, includeMins);
<|endoftext|>


<commit_before>/**
 * Component to display the optional fields (description, images, ...)
 * of a need.
 * Created by ksinger on 10.04.2017.
 */

import angular from 'angular';
import 'ng-redux';
import extendedGalleryModule from '../components/extended-gallery';
import { actionCreators }  from '../actions/actions';
import {
    attach,
} from '../utils.js'
import {
    connect2Redux,
} from '../won-utils'

const serviceDependencies = ['$ngRedux', '$scope'];
function genComponentConf() {
    let template = `

            {{ self.need.getIn(['location', 's:name']) }}

            {{ self.need.get('description') }}

            {{ self.textMessage }}

    `;

    class Controller {
        constructor() {
            attach(this, serviceDependencies, arguments);
            window.pc4dbg = this;
            const selectFromState = (state) => {
                return {
                    need: state.getIn(['needs', this.needUri]),
                }
            };
            /*
            const disconnect = this.$ngRedux.connect(selectFromState, actionCreators)(this);
            this.$scope.$on('$destroy', disconnect);
            */
            connect2Redux(selectFromState, actionCreators, ['self.needUri'], this);
        }
    }
    Controller.$inject = serviceDependencies;
    return {
        restrict: 'E',
        controller: Controller,
        controllerAs: 'self',
        bindToController: true, //scope-bindings -> ctrl
        scope: {
            needUri: '=',
            /**
             * one of:
             * - "fullpage" (NOT_YET_IMPLEMENTED) (used in post-info page)
             * - "medium" (NOT_YET_IMPLEMENTED) (used in incoming/outgoing requests and matches-tiles)
             * - "small" (NOT_YET_IMPLEMENTED) (in matches-list)
             */
            //size: '=',

            /**
             * Additional text-message that is shown. Use this e.g. when displaying
             * an incoming request.
             */
            textMessage: '=',
        },
        template: template
    }
}

export default angular.module('won.owner.components.postContent', [
    extendedGalleryModule,
])
    .directive('wonPostContent', genComponentConf)
    .name;
<commit_msg>adds element to show address of need if the location is present<commit_after>/**
 * Component to display the optional fields (description, images, ...)
 * of a need.
 * Created by ksinger on 10.04.2017.
 */

import angular from 'angular';
import 'ng-redux';
import extendedGalleryModule from '../components/extended-gallery';
import { actionCreators }  from '../actions/actions';
import {
    attach,
} from '../utils.js'
import {
    connect2Redux,
} from '../won-utils'

const serviceDependencies = ['$ngRedux', '$scope'];
function genComponentConf() {
    let template = `

            {{ self.need.getIn(['location', 's:name']) }}

            {{ self.need.get('description') }}

            {{ self.need.getIn(['location','address']) }}

            {{ self.textMessage }}

    `;

    class Controller {
        constructor() {
            attach(this, serviceDependencies, arguments);
            window.pc4dbg = this;
            const selectFromState = (state) => {
                return {
                    need: state.getIn(['needs', this.needUri]),
                }
            };
            /*
            const disconnect = this.$ngRedux.connect(selectFromState, actionCreators)(this);
            this.$scope.$on('$destroy', disconnect);
            */
            connect2Redux(selectFromState, actionCreators, ['self.needUri'], this);
        }
    }
    Controller.$inject = serviceDependencies;
    return {
        restrict: 'E',
        controller: Controller,
        controllerAs: 'self',
        bindToController: true, //scope-bindings -> ctrl
        scope: {
            needUri: '=',
            /**
             * one of:
             * - "fullpage" (NOT_YET_IMPLEMENTED) (used in post-info page)
             * - "medium" (NOT_YET_IMPLEMENTED) (used in incoming/outgoing requests and matches-tiles)
             * - "small" (NOT_YET_IMPLEMENTED) (in matches-list)
             */
            //size: '=',

            /**
             * Additional text-message that is shown. Use this e.g. when displaying
             * an incoming request.
             */
            textMessage: '=',
        },
        template: template
    }
}

export default angular.module('won.owner.components.postContent', [
    extendedGalleryModule,
])
    .directive('wonPostContent', genComponentConf)
    .name;
<|endoftext|>


<commit_before>import './Job'
import './QueryBuilder'

import Kue from 'kue'

export class Queue {
	kue = null
	app = null
	jobs = { }

	constructor(app, config) {
		if(config.isNil) {
			config = app.config.get('queue.default')
		}

		if(typeof config === 'string') {
			config = app.config.get(`queue.connections.${config}`)

			if(config.isNil) {
				throw new Error('Invalid config')
			}
		}

		this.app = app
		this.kue = Kue.createQueue(config)
	}

	register(jobClass) {
		if(jobClass.jobName.isNil) {
			throw new Error('Invalid Job, must have jobName set.')
		} else if(!(jobClass.prototype instanceof Job)) {
			throw new Error('All job classes must inherit from Job')
		}

		this.jobs[jobClass.jobName] = jobClass
	}

	findJobs(job) {
		if(typeof job === 'string') {
			job = this.jobs[job]
		}

		if(job.isNil || !(job.prototype instanceof Job)) {
			throw new Error('Invalid Job')
		}
	}

	query() {
		return new QueryBuilder(this)
	}

	fetchJob(id) {
		return new Promise((resolve, reject) => {
			Kue.Job.get(id, (err, job) => {
				if(!err.isNil) {
					return reject(err)
				}

				const jobClass = this.jobs[job.type]

				if(jobClass.isNil) {
					return reject(new Error(`Unable to fetch job of unknown type: ${job.type}`))
				}

				resolve(new jobClass(job.data, job))
			})
		})
	}

	dispatch(job) {
		return job.$save(this)
	}

	process(jobNames) {
		let jobs = Object.keys(this.jobs)

		if(!jobNames.isNil && jobs.length > 0) {
			jobs = jobs.filter(name => jobNames.indexOf(name) >= 0)
		}

		return Promise.all(jobs.map(
			key => this._process(this.jobs[key])
		))
	}

	_process(jobClass) {
		return new Promise(() => {
			this.kue.process(jobClass.jobName, jobClass.concurrency, async (kueJob, ctx, done) => {
				let result = null

				try {
					const job = new jobClass(kueJob.data, kueJob)
					result = job.$handle(this.app, this)
				} catch(err) {
					return done(this.handleError(err, done))
				}

				if(result.isNil || typeof result.then !== 'function') {
					return done()
				}

				result.then(() => done()).catch(err => this.handleError(err, done))
			})
		})
	}

	handleError(error, done) {
		return done(error)
	}

}
<commit_msg>Added a dummy Queue.destroy method<commit_after>import './Job'
import './QueryBuilder'

import Kue from 'kue'

export class Queue {
	kue = null
	app = null
	jobs = { }

	constructor(app, config) {
		if(config.isNil) {
			config = app.config.get('queue.default')
		}

		if(typeof config === 'string') {
			config = app.config.get(`queue.connections.${config}`)

			if(config.isNil) {
				throw new Error('Invalid config')
			}
		}

		this.app = app
		this.kue = Kue.createQueue(config)
	}

	register(jobClass) {
		if(jobClass.jobName.isNil) {
			throw new Error('Invalid Job, must have jobName set.')
		} else if(!(jobClass.prototype instanceof Job)) {
			throw new Error('All job classes must inherit from Job')
		}

		this.jobs[jobClass.jobName] = jobClass
	}

	findJobs(job) {
		if(typeof job === 'string') {
			job = this.jobs[job]
		}

		if(job.isNil || !(job.prototype instanceof Job)) {
			throw new Error('Invalid Job')
		}
	}

	query() {
		return new QueryBuilder(this)
	}

	fetchJob(id) {
		return new Promise((resolve, reject) => {
			Kue.Job.get(id, (err, job) => {
				if(!err.isNil) {
					return reject(err)
				}

				const jobClass = this.jobs[job.type]

				if(jobClass.isNil) {
					return reject(new Error(`Unable to fetch job of unknown type: ${job.type}`))
				}

				resolve(new jobClass(job.data, job))
			})
		})
	}

	dispatch(job) {
		return job.$save(this)
	}

	process(jobNames) {
		let jobs = Object.keys(this.jobs)

		if(!jobNames.isNil && jobs.length > 0) {
			jobs = jobs.filter(name => jobNames.indexOf(name) >= 0)
		}

		return Promise.all(jobs.map(
			key => this._process(this.jobs[key])
		))
	}

	_process(jobClass) {
		return new Promise(() => {
			this.kue.process(jobClass.jobName, jobClass.concurrency, async (kueJob, ctx, done) => {
				let result = null

				try {
					const job = new jobClass(kueJob.data, kueJob)
					result = job.$handle(this.app, this)
				} catch(err) {
					return done(this.handleError(err, done))
				}

				if(result.isNil || typeof result.then !== 'function') {
					return done()
				}

				result.then(() => done()).catch(err => this.handleError(err, done))
			})
		})
	}

	handleError(error, done) {
		return done(error)
	}

	destroy() {
		// TODO
	}

}
<|endoftext|>


<commit_before>
// This file sets up boxing of javascript native objects into squeak objects
// All relevant classes are enhanced by that functionality and there are
// Several global functions to box or unbox objects.

// Some objects are boxing primitive js-values. Unboxing these values is polymorphic.
// The real version of this method is below. This could alternatively throw an error,
// but we try to be tolerant.
_Object._addInstanceMethods({
	__giveError: function(methodname) {
		var msg = "We have an obsolete " + methodname + "()-call! Fix it.";
		alert(msg);
		throw msg;
	},
	// TODO if we're sure everything is fixed, remove these warnings.
	js: function() {
		this.__giveError("js");
	},
	jsNew_: function() {
		this.__giveError("jsNew:");
	},
	js_: function() {
		this.__giveError("js:");
	},
	slot_be_: function() {
		this.__giveError("slot:be:");
	},
	slot_: function() {
		this.__giveError("slot:");
	},
	slot_apply_: function() {
		this.__giveError("slot:apply:");
	},

	_unbox: function() {
		return this;
	},
	// This never gets called, we just need a true-ish slot in each box-instance
	_isBoxedObject: function() { throw "just access this slot without calling."; }
});

// Class, that will wrap native javascript-objects to implement the Object-interface.
// Additionally, it adds accessor-methods for all fields to provide a squeak-API to
// set slots on javascript-objects.
Class("_Box", { superclass: _Object });

// Functions to bootstrap primitive values and wrap them into 'squeak'-objects
// Most functions are used in translated code directly, to avoid switch-statement in _boxObject()
// (Instead of bool(), compiled code uses _true/_false directly. bool() is used in kernel_primitives.js etc.)
var bool = function(aBool) { if (aBool) { return _true; } else { return _false; } }
var character = function(aString) { return Character._wrapping(aString); }
var string = function(aString) { return ByteString._wrapping(aString); }
var number = function(aNumber) { return Float._wrapping(aNumber); }
var array = function(anArray) { return _Array._wrapping(anArray); }
var object = function(anObject) { return _Box._wrapping(anObject); }
// if we box a javascript function into a smalltalk block we must bind it on creation
// Non-local-return handling is not required here
var boundBlock = function(func, that) {
	var b = BlockClosure._newInstance();
	// This block is unboxed to func, but additional things happen on evaluation
	b.original$ = func;
	b.evaluated$ = function() {
		return _boxObject(func.apply(that, _unboxIterable(arguments)));
	}
	b.constructorArguments$ = function(argumentCollection) {
		// When using a library-function as constructor, unpack the arguments
		return _unboxIterable(argumentCollection);
	}
	return b;
}

// There are multiple js-'classes', that will be wrapped into a Squeak-Array
var arrayConstructors = [Array, NodeList];
var isArrayObject = function(anObject) {
	var constructor = anObject.constructor;
	for (index in arrayConstructors) {
		if (arrayConstructors[index] == constructor) {
			return true;
		}
	}
	return false;
};

// This static unboxing-function is added to avoid adding an _unbox method to native js-objects
var _unboxObject = function(anyObject) {
	if (anyObject._isBoxedObject) {
		return anyObject._unbox();
	}
	return anyObject;
};
var _unboxIterable = function(iterable) {
	var unboxed = [];
	for (index in iterable) {
		unboxed.push(_unboxObject(iterable[index]));
	}
	return unboxed;
}
// The 'that' parameter is optional and will be undefined otherwise
// It is relevant for functions, to bind them to their containing object when invoking them.
var _boxObject = function(nativeObject, that) {
	if (nativeObject === null || nativeObject === undefined) {
		return nil;
	}
	if (!nativeObject._isBoxedObject) {
		switch( typeof(nativeObject) ) {
			case "number": return number(nativeObject); break;
			case "string": return string(nativeObject); break;
			case "boolean": return bool(nativeObject); break;
			case "function": return boundBlock(nativeObject, that); break;
			case "object":
				if (isArrayObject(nativeObject)) {
					return array(nativeObject);
				} else {
					return object(nativeObject);
				}
				break;
			default:
				alert("Could not box creepy object: " + nativeObject);
		}
    }
	// nativeObject is already boxed!
	return nativeObject;
};

// These boxing classes box fixed, immutable values
False._addInstanceMethods( { _unbox: function() { return false; } } );
True._addInstanceMethods( { _unbox: function() { return true; } } );
UndefinedObject._addInstanceMethods( { _unbox: function() { return null; } } );

// These boxing classes box variable values and are all added the same functionality.
var boxingClasses = [_Box, ByteString, _Number, Character, BlockClosure, _Array, OrderedCollection];
for (index in boxingClasses) {
	var aClass = boxingClasses[index];
	aClass._addClassMethods({
		_wrapping: function(originalObject) {
			var result = this._newInstance(); // Polymorphic for different kinds of boxes
			result.original$ = originalObject;
			return result;
		}
	});
	aClass._addInstanceMethods({
		doesNotUnderstand_: function(aMessage) {
			var methodName = _unboxObject(aMessage.selector());
			if (methodName[methodName.length-1] == ':') {
				// setter. Set the unboxed, native-js, value.
				var value;
				if ((aMessage._arguments().length ) == 1 )
					value = aMessage._arguments()[0];
				else
					value = aMessage._arguments();

				this.original$[methodName.substring(0, methodName.length - 1)] = _unboxObject(value);
				return value;
			} else {
				// getter. Second parameter relevant, if slot contains a function.
				return _boxObject(this.original$[methodName], this.original$);
			}
		},
		_unbox: function() {
			return this.original$;
		}
	});
}

BlockClosure._addInstanceMethods ( {
	_unbox: function() {
		var originalBlock = this.original$;
		return function () {
			var boxedArguments = new Array(arguments.length);
			for (var i=0; i <arguments.length ; i++) {
				boxedArguments[i] = _boxObject(arguments[i]);
			}
			return originalBlock.apply(this, boxedArguments )  }
	}
});<commit_msg>added value function for boxed object to make the implementation of the original value more important<commit_after>
// This file sets up boxing of javascript native objects into squeak objects
// All relevant classes are enhanced by that functionality and there are
// Several global functions to box or unbox objects.

// Some objects are boxing primitive js-values. Unboxing these values is polymorphic.
// The real version of this method is below. This could alternatively throw an error,
// but we try to be tolerant.
_Object._addInstanceMethods({
	__giveError: function(methodname) {
		var msg = "We have an obsolete " + methodname + "()-call! Fix it.";
		alert(msg);
		throw msg;
	},
	// TODO if we're sure everything is fixed, remove these warnings.
	js: function() {
		this.__giveError("js");
	},
	jsNew_: function() {
		this.__giveError("jsNew:");
	},
	js_: function() {
		this.__giveError("js:");
	},
	slot_be_: function() {
		this.__giveError("slot:be:");
	},
	slot_: function() {
		this.__giveError("slot:");
	},
	slot_apply_: function() {
		this.__giveError("slot:apply:");
	},

	_unbox: function() {
		return this;
	},
	// This never gets called, we just need a true-ish slot in each box-instance
	_isBoxedObject: function() { throw "just access this slot without calling."; }
});

// Class, that will wrap native javascript-objects to implement the Object-interface.
// Additionally, it adds accessor-methods for all fields to provide a squeak-API to
// set slots on javascript-objects.
Class("_Box", { superclass: _Object });

_Box._addInstanceMethods ( {
	value : function() {
		// if the original object has an attribute value or function value it is more important to use this instead
		if(this.original$.value) {
			if(typeof(this.original$.value) == "function") {
				return this.original$.value();
			}else {
				return this.original$.value;
			}

		} else {
			return _super.value();
		}
	}
}

	)

// Functions to bootstrap primitive values and wrap them into 'squeak'-objects
// Most functions are used in translated code directly, to avoid switch-statement in _boxObject()
// (Instead of bool(), compiled code uses _true/_false directly. bool() is used in kernel_primitives.js etc.)
var bool = function(aBool) { if (aBool) { return _true; } else { return _false; } }
var character = function(aString) { return Character._wrapping(aString); }
var string = function(aString) { return ByteString._wrapping(aString); }
var number = function(aNumber) { return Float._wrapping(aNumber); }
var array = function(anArray) { return _Array._wrapping(anArray); }
var object = function(anObject) { return _Box._wrapping(anObject); }
// if we box a javascript function into a smalltalk block we must bind it on creation
// Non-local-return handling is not required here
var boundBlock = function(func, that) {
	var b = BlockClosure._newInstance();
	// This block is unboxed to func, but additional things happen on evaluation
	b.original$ = func;
	b.evaluated$ = function() {
		return _boxObject(func.apply(that, _unboxIterable(arguments)));
	}
	b.constructorArguments$ = function(argumentCollection) {
		// When using a library-function as constructor, unpack the arguments
		return _unboxIterable(argumentCollection);
	}
	return b;
}

// There are multiple js-'classes', that will be wrapped into a Squeak-Array
var arrayConstructors = [Array, NodeList];
var isArrayObject = function(anObject) {
	var constructor = anObject.constructor;
	for (index in arrayConstructors) {
		if (arrayConstructors[index] == constructor) {
			return true;
		}
	}
	return false;
};

// This static unboxing-function is added to avoid adding an _unbox method to native js-objects
var _unboxObject = function(anyObject) {
	if (anyObject._isBoxedObject) {
		return anyObject._unbox();
	}
	return anyObject;
};
var _unboxIterable = function(iterable) {
	var unboxed = [];
	for (index in iterable) {
		unboxed.push(_unboxObject(iterable[index]));
	}
	return unboxed;
}
// The 'that' parameter is optional and will be undefined otherwise
// It is relevant for functions, to bind them to their containing object when invoking them.
var _boxObject = function(nativeObject, that) {
	if (nativeObject === null || nativeObject === undefined) {
		return nil;
	}
	if (!nativeObject._isBoxedObject) {
		switch( typeof(nativeObject) ) {
			case "number": return number(nativeObject); break;
			case "string": return string(nativeObject); break;
			case "boolean": return bool(nativeObject); break;
			case "function": return boundBlock(nativeObject, that); break;
			case "object":
				if (isArrayObject(nativeObject)) {
					return array(nativeObject);
				} else {
					return object(nativeObject);
				}
				break;
			default:
				alert("Could not box creepy object: " + nativeObject);
		}
    }
	// nativeObject is already boxed!
	return nativeObject;
};

// These boxing classes box fixed, immutable values
False._addInstanceMethods( { _unbox: function() { return false; } } );
True._addInstanceMethods( { _unbox: function() { return true; } } );
UndefinedObject._addInstanceMethods( { _unbox: function() { return null; } } );

// These boxing classes box variable values and are all added the same functionality.
var boxingClasses = [_Box, ByteString, _Number, Character, BlockClosure, _Array, OrderedCollection];
for (index in boxingClasses) {
	var aClass = boxingClasses[index];
	aClass._addClassMethods({
		_wrapping: function(originalObject) {
			var result = this._newInstance(); // Polymorphic for different kinds of boxes
			result.original$ = originalObject;
			return result;
		}
	});
	aClass._addInstanceMethods({
		doesNotUnderstand_: function(aMessage) {
			var methodName = _unboxObject(aMessage.selector());
			if (methodName[methodName.length-1] == ':') {
				// setter. Set the unboxed, native-js, value.
				var value;
				if ((aMessage._arguments().length ) == 1 )
					value = aMessage._arguments()[0];
				else
					value = aMessage._arguments();

				this.original$[methodName.substring(0, methodName.length - 1)] = _unboxObject(value);
				return value;
			} else {
				// getter. Second parameter relevant, if slot contains a function.
				return _boxObject(this.original$[methodName], this.original$);
			}
		},
		_unbox: function() {
			return this.original$;
		}
	});
}

BlockClosure._addInstanceMethods ( {
	_unbox: function() {
		var originalBlock = this.original$;
		return function () {
			var boxedArguments = new Array(arguments.length);
			for (var i=0; i <arguments.length ; i++) {
				boxedArguments[i] = _boxObject(arguments[i]);
			}
			return originalBlock.apply(this, boxedArguments )  }
	}
});<|endoftext|>


<commit_before>function getProcessGraphWidgetConfig(widgetId, bagName) {
  var widgetdataname = document.getElementById('widgetdata' + widgetId);
  var widgetdatawait = document.getElementById('widgetdatawait' + widgetId);

  Element.hide($(widgetdataname));
  Element.show($(widgetdatawait));
  var extraAttr;
  if($("widgetselect" + widgetId)!=null) {
    extraAttr = $("widgetselect" + widgetId).value;
  }

  if($("pValue" + widgetId)!=null) {
    extraAttr = $("pValue" + widgetId).value;
  }
  AjaxServices.getProcessGraphWidget(widgetId,bagName,extraAttr,handleGraphWidget);
}

function handleGraphWidget(widget) {

  calcNotAnalysed(widget);

  Element.hide($('widgetdatanoresults' + widget.configId));
  if(widget.hasResults) {
    var widgetdataname = document.getElementById('widgetdata' + widget.configId);
    var widgetdatawait = document.getElementById('widgetdatawait' + widget.configId);

    Element.update($(widgetdataname),widget.html);
    Element.hide($(widgetdatawait));
    Element.show($(widgetdataname));
  } else {
    Element.hide($('widgetdatawait' + widget.configId));
    Element.hide($('widgetdata' + widget.configId));
    Element.show($('widgetdatanoresults' + widget.configId));
    //toggleWidget('widgetcontainer' + widget.configId, 'togglelink' + widget.configId);
  }
}

function getProcessHTMLWidgetConfig(widgetId, bagName) {
	AjaxServices.getProcessHTMLWidget(widgetId, bagName, handleHTMLWidget);
}

function handleHTMLWidget(widget) {
	var widgetdataname = document.getElementById('widgetdata' + widget.configId);
	var widgetdatawait = document.getElementById('widgetdatawait' + widget.configId);
	var widgetdatacontent = document.getElementById('widgetdatacontent' + widget.configId);

	Element.hide($(widgetdatawait));
	Element.hide($(widgetdataname));
	Element.show($(widgetdatacontent));
}

function getProcessTableWidgetConfig(widgetId, bagName) {
  AjaxServices.getProcessTableWidget(widgetId,bagName,handleTableWidget);
}

function handleTableWidget(widget) {

  calcNotAnalysed(widget);

  Element.hide($('widgetdatanoresults' + widget.configId));

  if(widget.hasResults) {
    removeChildren($("tablewidget"+widget.configId+"head"));
    removeChildren($("tablewidget"+widget.configId+"body"));
    var widgetdataname = document.getElementById('widgetdata' + widget.configId);
    var widgetdatawait = document.getElementById('widgetdatawait' + widget.configId);

    var row = document.createElement("tr");

    // checkbox
    var checkboxCell = document.createElement("th");
    var formName = "widgetaction" + widget.configId;
    var checky = "<input type=\"checkbox\" name=\"select_all\" id=\"selected_all" + widget.configId + "\"";
          checky += " onclick=\"toggleAllChecks('" + formName + "','" + widget.configId + "')\">";
    checkboxCell.innerHTML = checky;
    row.appendChild(checkboxCell);

      // column names
    for(var i = 0; i < widget.columns.length ; i++){
      var cell = document.createElement("th");
      cell.innerHTML = widget.columns[i];
      row.appendChild(cell);
    }

    $("tablewidget"+widget.configId+"head").appendChild(row);

  var bagContent;
  if(widget.title == "Protein Interactions") {
     bagContent = widget.elementInList;
   }

  for(var i = 0; i < widget.flattenedResults.length ; i++){
    row = document.createElement("tr");
      var columns = widget.flattenedResults[i];
      for(var j = 0; j < columns.length ; j++){
      var cell = document.createElement("td");
         if(columns[j]!=null) {
             if(columns[j][1] != null) {
               var link = document.createElement("a");
               link.setAttribute("href",columns[j][1]);
               link.innerHTML = columns[j][0];
               cell.appendChild(link);
             } else {
              cell.innerHTML = columns[j][0];
             }
         }
         row.appendChild(cell);
    }
      $("tablewidget"+widget.configId+"body").appendChild(row);
    }
    Element.hide($(widgetdatawait));
     Element.show($(widgetdataname));
  } else {
    Element.hide($('widgetdatawait' + widget.configId));
    Element.hide($('widgetdata' + widget.configId));
    Element.show($('widgetdatanoresults' + widget.configId));
    //toggleWidget('widgetcontainer' + widget.configId, 'togglelink' + widget.configId);
  }
}

function getProcessGridWidgetConfig(widgetId, bagName) {
  var widgetdataname = document.getElementById('widgetdata' + widgetId);
  var widgetdatawait = document.getElementById('widgetdatawait' + widgetId);

  Element.hide($(widgetdataname));
  Element.show($(widgetdatawait));

  var externalLink;
  if($("externalLink" + widgetId)!=null) {
    externalLink = $("externalLink" + widgetId).value;
  }

  var externalLinkLabel;
  if($("externalLinkLabel" + widgetId)!=null) {
    externalLinkLabel = $("externalLinkLabel" + widgetId).value;
  }

  var highlight;
  if($("highlight" + widgetId)!=null) {
    highlight = $("highlight" + widgetId).value;
  }

  var numberOpt;
  if($("numberOpt" + widgetId)!=null) {
    numberOpt = $("numberOpt" + widgetId).value;
  }

  var pValue;
  if($("pValue" + widgetId)!=null) {
    pValue = $("pValue" + widgetId).value;
  }
  AjaxServices.getProcessGridWidget(widgetId,bagName,highlight,pValue,numberOpt,externalLink,externalLinkLabel,handleGridWidget);
}

function handleGridWidget(widget) {

  calcNotAnalysed(widget);

    Element.hide($('widgetdatanoresults' + widget.configId));

  if(widget.hasResults) {
    removeChildren($("tablewidget"+widget.configId+"head"));
    removeChildren($("tablewidget"+widget.configId+"body"));
    var widgetdataname = document.getElementById('widgetdata' + widget.configId);
    var widgetdatawait = document.getElementById('widgetdatawait' + widget.configId);

    var row = document.createElement("tr");
    var cell = document.createElement("th");
    cell.width = "40";
    cell.innerHTML = "/";
      row.appendChild(cell);
      // column names
    for(var i = 0; i < widget.columns.length ; i++){
      cell = document.createElement("th");
      cell.width = "40";
      if(widget.columns[i].length <= 5) {
        cell.innerHTML = '' + widget.columns[i] + '';
      } else {
        cell.innerHTML = '' + widget.columns[i].substring(0,5) + "..." + '';
        cell.title = widget.columns[i];
      }
      row.appendChild(cell);
    }

     $("tablewidget"+widget.configId+"head").appendChild(row);
     //for display
     var counter = 1;
     var display = 0;
     //for special table
     var specialtable = widget.columns.length + 1;
     var specialTableCounter = 1;
    // column names
    for(var i = 0; i < widget.columns.length ; i++){

      var results = widget.flattenedResults[i];
      var resultsDown = 0;
      if (widget.elementInList.length > 0) {
        resultsDown = widget.elementInList[i];
      }

      row = document.createElement("tr");
      var cell = document.createElement("th");
      if(widget.columns[i].length <= 5) {
        cell.innerHTML = '' +  widget.columns[i] + '';
      } else {
        cell.innerHTML ='' +  widget.columns[i].substring(0,5) + "..." + '';
        cell.title = widget.columns[i];
      }
      row.appendChild(cell);

      for(var k = 0; k < widget.columns.length ; k++){

       cell = document.createElement("td");
       if (resultsDown.length > 0) {
        if(specialTableCounter%specialtable == 1) {
             var newTable = document.createElement("table");
             var newrow = document.createElement("tr");
             var newCell = document.createElement("td");
             newrow.appendChild(newCell)
             newCell = document.createElement("td");
             var link = document.createElement("a");
              link.setAttribute("href", results[k][1]);
              link.innerHTML ='' +  results[k][0] + '';
              link.title = (results[k][3]);
               newCell.appendChild(link);
               var rgb = "#" + results[k][2];
               newCell.style.background = rgb;
             newrow.appendChild(newCell)
             newTable.appendChild(newrow);
             newrow = document.createElement("tr");
             newCell = document.createElement("td");
             var link = document.createElement("a");
               link.setAttribute("href", resultsDown[k][1]);
              link.innerHTML ='' +  resultsDown[k][0] + '';
              link.title = (resultsDown[k][3]);
               newCell.appendChild(link);
               var rgb = "#" + resultsDown[k][2];
               newCell.style.background = rgb;
             newrow.appendChild(newCell);
             newCell = document.createElement("td");
             newrow.appendChild(newCell);
             newTable.appendChild(newrow);
             newTable.width = "100%";
             cell.appendChild(newTable);
         } else if(counter > display) {
                 var link = document.createElement("a");
                 link.setAttribute("href", results[k][1]);
                link.innerHTML ='' +  results[k][0] + '';
                link.title = (results[k][3]);
                 cell.appendChild(link);
                 var rgb = "#" + results[k][2];
                 cell.style.background = rgb;
             } else {
               var link = document.createElement("a");
                 link.setAttribute("href", resultsDown[k][1]);
                link.innerHTML ='' +  resultsDown[k][0] + '';
                link.title = (resultsDown[k][3]);
                 cell.appendChild(link);
                 var rgb = "#" + resultsDown[k][2];
                 cell.style.background = rgb;
             }
       } else {
         if(counter > display) {
                 var link = document.createElement("a");
                 link.setAttribute("href", results[k][1]);
                link.innerHTML ='' +   results[k][0] + '';
                link.title = (results[k][3]);
                 cell.appendChild(link);
                 var rgb = "#" + results[k][2];
                 cell.style.background = rgb;
             }
           }
           counter++;
           specialTableCounter++;
         row.appendChild(cell);

      }
      counter = 1;
      display++;
      $("tablewidget"+widget.configId+"head").appendChild(row);
    }

    Element.hide($(widgetdatawait));
      Element.show($(widgetdataname));

  } else {
    Element.hide($('widgetdatawait' + widget.configId));
    Element.hide($('widgetdata' + widget.configId));
    Element.show($('widgetdatanoresults' + widget.configId));
  }
}

function getProcessEnrichmentWidgetConfig(widgetId, bagName) {
  var widgetdataname = document.getElementById('widgetdata' + widgetId);
  var widgetdatawait = document.getElementById('widgetdatawait' + widgetId);

  Element.hide($(widgetdataname));
  Element.show($(widgetdatawait));
  var errorCorrection;
  if($("errorCorrection" + widgetId)!=null) {
    errorCorrection = $("errorCorrection" + widgetId).value;
  }
  var max;
  if($("max" + widgetId)!=null) {
    max = $("max" + widgetId).value;
  }
  var extraAttr;
  if($("widgetselect" + widgetId)!=null) {
    extraAttr = $("widgetselect" + widgetId).value;
  }
  var externalLink;
  if($("externalLink" + widgetId)!=null) {
    externalLink = $("externalLink" + widgetId).value;
  }

  var externalLinkLabel;
  if($("externalLinkLabel" + widgetId)!=null) {
    externalLinkLabel = $("externalLinkLabel" + widgetId).value;
  }
  AjaxServices.getProcessEnrichmentWidget(widgetId,bagName,errorCorrection,max,extraAttr,externalLink,externalLinkLabel,handleTableWidget);
}

function removeChildren(node) {
  while(node.childNodes.length > 0) {
    node.removeChild(node.childNodes[0]);
  }
}

function checkSelected(formName) {
  var elts = Form.getElements(formName);
  for(var i=0;i<elts.length;i++) {
    if( $(elts[i]).name=='selected' && $(elts[i]).checked ) {
     return true;
    }
  }
  alert("Please select some items")
  return false;
}

function submitWidgetForm(widgetId,type,extra) {
  if(type == 'displayAll' || checkSelected('widgetaction'+widgetId)) {
    $('action'+widgetId).value=type;
    $('export' + widgetId).value=extra;
    $('widgetaction' + widgetId).submit();
  }
}

function displayNotAnalysed(widgetId,type,extra) {
    $('action'+widgetId).value='notAnalysed';
    $('widgetaction' + widgetId).submit();
}

function calcNotAnalysed(widget) {
    $('widgetnotanalysed' + widget.configId).update(widget.notAnalysed);
}

function toggleAllChecks(formName, widgetId) {
  var checked = document.getElementById('selected_all' + widgetId).checked;
  var elts = Form.getElements(formName);
  for(var i=0;i<elts.length;i++) {
    if( $(elts[i]).name=='selected') {
        $(elts[i]).checked=checked;
    }
  }
}<commit_msg>fix for broken jQuery<commit_after>function getProcessGraphWidgetConfig(widgetId, bagName) {
  var widgetdataname = document.getElementById('widgetdata' + widgetId);
  var widgetdatawait = document.getElementById('widgetdatawait' + widgetId);

  Element.hide($(widgetdataname));
  Element.show($(widgetdatawait));
  var extraAttr;
  if($("widgetselect" + widgetId)!=null) {
    extraAttr = $("widgetselect" + widgetId).value;
  }

  if($("pValue" + widgetId)!=null) {
    extraAttr = $("pValue" + widgetId).value;
  }
  AjaxServices.getProcessGraphWidget(widgetId,bagName,extraAttr,handleGraphWidget);
}

function handleGraphWidget(widget) {

  calcNotAnalysed(widget);

  Element.hide($('widgetdatanoresults' + widget.configId));
  if(widget.hasResults) {
    var widgetdataname = document.getElementById('widgetdata' + widget.configId);
    var widgetdatawait = document.getElementById('widgetdatawait' + widget.configId);

    Element.update($(widgetdataname),widget.html);
    Element.hide($(widgetdatawait));
    Element.show($(widgetdataname));
  } else {
    Element.hide($('widgetdatawait' + widget.configId));
    Element.hide($('widgetdata' + widget.configId));
    Element.show($('widgetdatanoresults' + widget.configId));
    //toggleWidget('widgetcontainer' + widget.configId, 'togglelink' + widget.configId);
  }
}

function getProcessHTMLWidgetConfig(widgetId, bagName) {
	AjaxServices.getProcessHTMLWidget(widgetId, bagName, handleHTMLWidget);
}

function handleHTMLWidget(widget) {
	var widgetdataname = document.getElementById('widgetdata' + widget.configId);
	var widgetdatawait = document.getElementById('widgetdatawait' + widget.configId);
	var widgetdatacontent = document.getElementById('widgetdatacontent' + widget.configId);

	Element.hide($(widgetdatawait));
	Element.hide($(widgetdataname));
	Element.show($(widgetdatacontent));
}

function getProcessTableWidgetConfig(widgetId, bagName) {
  AjaxServices.getProcessTableWidget(widgetId,bagName,handleTableWidget);
}

function handleTableWidget(widget) {

  calcNotAnalysed(widget);

  Element.hide($('widgetdatanoresults' + widget.configId));

  if(widget.hasResults) {
    removeChildren($("tablewidget"+widget.configId+"head"));
    removeChildren($("tablewidget"+widget.configId+"body"));
    var widgetdataname = document.getElementById('widgetdata' + widget.configId);
    var widgetdatawait = document.getElementById('widgetdatawait' + widget.configId);

    var row = document.createElement("tr");

    // checkbox
    var checkboxCell = document.createElement("th");
    var formName = "widgetaction" + widget.configId;
    var checky = "<input type=\"checkbox\" name=\"select_all\" id=\"selected_all" + widget.configId + "\"";
          checky += " onclick=\"toggleAllChecks('" + formName + "','" + widget.configId + "')\">";
    checkboxCell.innerHTML = checky;
    row.appendChild(checkboxCell);

      // column names
    for(var i = 0; i < widget.columns.length ; i++){
      var cell = document.createElement("th");
      cell.innerHTML = widget.columns[i];
      row.appendChild(cell);
    }

    $("tablewidget"+widget.configId+"head").appendChild(row);

  var bagContent;
  if(widget.title == "Protein Interactions") {
     bagContent = widget.elementInList;
   }

  for(var i = 0; i < widget.flattenedResults.length ; i++){
    row = document.createElement("tr");
      var columns = widget.flattenedResults[i];
      for(var j = 0; j < columns.length ; j++){
      var cell = document.createElement("td");
         if(columns[j]!=null) {
             if(columns[j][1] != null) {
               var link = document.createElement("a");
               link.setAttribute("href",columns[j][1]);
               link.innerHTML = columns[j][0];
               cell.appendChild(link);
             } else {
              cell.innerHTML = columns[j][0];
             }
         }
         row.appendChild(cell);
    }
      $("tablewidget"+widget.configId+"body").appendChild(row);
    }
    Element.hide($(widgetdatawait));
     Element.show($(widgetdataname));
  } else {
    Element.hide($('widgetdatawait' + widget.configId));
    Element.hide($('widgetdata' + widget.configId));
    Element.show($('widgetdatanoresults' + widget.configId));
    //toggleWidget('widgetcontainer' + widget.configId, 'togglelink' + widget.configId);
  }
}

function getProcessGridWidgetConfig(widgetId, bagName) {
  var widgetdataname = document.getElementById('widgetdata' + widgetId);
  var widgetdatawait = document.getElementById('widgetdatawait' + widgetId);

  Element.hide($(widgetdataname));
  Element.show($(widgetdatawait));

  var externalLink;
  if($("externalLink" + widgetId)!=null) {
    externalLink = $("externalLink" + widgetId).value;
  }

  var externalLinkLabel;
  if($("externalLinkLabel" + widgetId)!=null) {
    externalLinkLabel = $("externalLinkLabel" + widgetId).value;
  }

  var highlight;
  if($("highlight" + widgetId)!=null) {
    highlight = $("highlight" + widgetId).value;
  }

  var numberOpt;
  if($("numberOpt" + widgetId)!=null) {
    numberOpt = $("numberOpt" + widgetId).value;
  }

  var pValue;
  if($("pValue" + widgetId)!=null) {
    pValue = $("pValue" + widgetId).value;
  }
  AjaxServices.getProcessGridWidget(widgetId,bagName,highlight,pValue,numberOpt,externalLink,externalLinkLabel,handleGridWidget);
}

function handleGridWidget(widget) {

  calcNotAnalysed(widget);

    Element.hide($('widgetdatanoresults' + widget.configId));

  if(widget.hasResults) {
    removeChildren($("tablewidget"+widget.configId+"head"));
    removeChildren($("tablewidget"+widget.configId+"body"));
    var widgetdataname = document.getElementById('widgetdata' + widget.configId);
    var widgetdatawait = document.getElementById('widgetdatawait' + widget.configId);

    var row = document.createElement("tr");
    var cell = document.createElement("th");
    cell.width = "40";
    cell.innerHTML = "/";
      row.appendChild(cell);
      // column names
    for(var i = 0; i < widget.columns.length ; i++){
      cell = document.createElement("th");
      cell.width = "40";
      if(widget.columns[i].length <= 5) {
        cell.innerHTML = '' + widget.columns[i] + '';
      } else {
        cell.innerHTML = '' + widget.columns[i].substring(0,5) + "..." + '';
        cell.title = widget.columns[i];
      }
      row.appendChild(cell);
    }

     $("tablewidget"+widget.configId+"head").appendChild(row);
     //for display
     var counter = 1;
     var display = 0;
     //for special table
     var specialtable = widget.columns.length + 1;
     var specialTableCounter = 1;
    // column names
    for(var i = 0; i < widget.columns.length ; i++){

      var results = widget.flattenedResults[i];
      var resultsDown = 0;
      if (widget.elementInList.length > 0) {
        resultsDown = widget.elementInList[i];
      }

      row = document.createElement("tr");
      var cell = document.createElement("th");
      if(widget.columns[i].length <= 5) {
        cell.innerHTML = '' +  widget.columns[i] + '';
      } else {
        cell.innerHTML ='' +  widget.columns[i].substring(0,5) + "..." + '';
        cell.title = widget.columns[i];
      }
      row.appendChild(cell);

      for(var k = 0; k < widget.columns.length ; k++){

       cell = document.createElement("td");
       if (resultsDown.length > 0) {
        if(specialTableCounter%specialtable == 1) {
             var newTable = document.createElement("table");
             var newrow = document.createElement("tr");
             var newCell = document.createElement("td");
             newrow.appendChild(newCell)
             newCell = document.createElement("td");
             var link = document.createElement("a");
              link.setAttribute("href", results[k][1]);
              link.innerHTML ='' +  results[k][0] + '';
              link.title = (results[k][3]);
               newCell.appendChild(link);
               var rgb = "#" + results[k][2];
               newCell.style.background = rgb;
             newrow.appendChild(newCell)
             newTable.appendChild(newrow);
             newrow = document.createElement("tr");
             newCell = document.createElement("td");
             var link = document.createElement("a");
               link.setAttribute("href", resultsDown[k][1]);
              link.innerHTML ='' +  resultsDown[k][0] + '';
              link.title = (resultsDown[k][3]);
               newCell.appendChild(link);
               var rgb = "#" + resultsDown[k][2];
               newCell.style.background = rgb;
             newrow.appendChild(newCell);
             newCell = document.createElement("td");
             newrow.appendChild(newCell);
             newTable.appendChild(newrow);
             newTable.width = "100%";
             cell.appendChild(newTable);
         } else if(counter > display) {
                 var link = document.createElement("a");
                 link.setAttribute("href", results[k][1]);
                link.innerHTML ='' +  results[k][0] + '';
                link.title = (results[k][3]);
                 cell.appendChild(link);
                 var rgb = "#" + results[k][2];
                 cell.style.background = rgb;
             } else {
               var link = document.createElement("a");
                 link.setAttribute("href", resultsDown[k][1]);
                link.innerHTML ='' +  resultsDown[k][0] + '';
                link.title = (resultsDown[k][3]);
                 cell.appendChild(link);
                 var rgb = "#" + resultsDown[k][2];
                 cell.style.background = rgb;
             }
       } else {
         if(counter > display) {
                 var link = document.createElement("a");
                 link.setAttribute("href", results[k][1]);
                link.innerHTML ='' +   results[k][0] + '';
                link.title = (results[k][3]);
                 cell.appendChild(link);
                 var rgb = "#" + results[k][2];
                 cell.style.background = rgb;
             }
           }
           counter++;
           specialTableCounter++;
         row.appendChild(cell);

      }
      counter = 1;
      display++;
      $("tablewidget"+widget.configId+"head").appendChild(row);
    }

    Element.hide($(widgetdatawait));
      Element.show($(widgetdataname));

  } else {
    Element.hide($('widgetdatawait' + widget.configId));
    Element.hide($('widgetdata' + widget.configId));
    Element.show($('widgetdatanoresults' + widget.configId));
  }
}

function getProcessEnrichmentWidgetConfig(widgetId, bagName) {
  var widgetdataname = document.getElementById('widgetdata' + widgetId);
  var widgetdatawait = document.getElementById('widgetdatawait' + widgetId);

  Element.hide($(widgetdataname));
  Element.show($(widgetdatawait));
  var errorCorrection;
  if($("errorCorrection" + widgetId)!=null) {
    errorCorrection = $("errorCorrection" + widgetId).value;
  }
  var max;
  if($("max" + widgetId)!=null) {
    max = $("max" + widgetId).value;
  }
  var extraAttr;
  if($("widgetselect" + widgetId)!=null) {
    extraAttr = $("widgetselect" + widgetId).value;
  }
  var externalLink;
  if($("externalLink" + widgetId)!=null) {
    externalLink = $("externalLink" + widgetId).value;
  }

  var externalLinkLabel;
  if($("externalLinkLabel" + widgetId)!=null) {
    externalLinkLabel = $("externalLinkLabel" + widgetId).value;
  }
  AjaxServices.getProcessEnrichmentWidget(widgetId,bagName,errorCorrection,max,extraAttr,externalLink,externalLinkLabel,handleTableWidget);
}

function removeChildren(node) {
  while(node.childNodes.length > 0) {
    node.removeChild(node.childNodes[0]);
  }
}

function checkSelected(formName) {
  var elts = Form.getElements(formName);
  for(var i=0;i<elts.length;i++) {
    if( $(elts[i]).name=='selected' && $(elts[i]).checked ) {
     return true;
    }
  }
  alert("Please select some items")
  return false;
}

function submitWidgetForm(widgetId,type,extra) {
  if(type == 'displayAll' || checkSelected('widgetaction'+widgetId)) {
    $('action'+widgetId).value=type;
    $('export' + widgetId).value=extra;
    $('widgetaction' + widgetId).submit();
  }
}

function displayNotAnalysed(widgetId,type,extra) {
    $('action'+widgetId).value='notAnalysed';
    $('widgetaction' + widgetId).submit();
}

function calcNotAnalysed(widget) {
	document.getElementById('widgetnotanalysed' + widget.configId).innerHTML=widget.notAnalysed;
	// this was broken in 21.0 when we upgraded jQuery
    //$('widgetnotanalysed' + widget.configId).update(widget.notAnalysed);
}

function toggleAllChecks(formName, widgetId) {
  var checked = document.getElementById('selected_all' + widgetId).checked;
  var elts = Form.getElements(formName);
  for(var i=0;i<elts.length;i++) {
    if( $(elts[i]).name=='selected') {
        $(elts[i]).checked=checked;
    }
  }
}<|endoftext|>


<commit_before>Package.describe({
  summary: "Wraps the request module from Npm in a fiber.",
  version: '0.0.0'
});

Npm.depends({request: "2.33.0"});

Package.on_use(function (api) {
  api.add_files('request-server.js', 'server');
  api.export('Request');
});
<commit_msg>Upgrade request to 2.47.0 from 2.33.0<commit_after>Package.describe({
  summary: "Wraps the request module from Npm in a fiber.",
  version: '0.0.0'
});

Npm.depends({request: "2.47.0"});

Package.on_use(function (api) {
  api.add_files('request-server.js', 'server');
  api.export('Request');
});
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { Dropdown } from 'react-bootstrap';

import { modules } from 'stripes-loader'; // eslint-disable-line

import { clearOkapiToken, clearCurrentUser } from '../../okapiActions';

import css from './MainNav.css';
import NavButton from './NavButton';
import NavDivider from './NavDivider';
import NavGroup from './NavGroup';
import Breadcrumbs from './Breadcrumbs';
import NavIcon from './NavIcon';

import NavDropdownMenu from './NavDropdownMenu';

if (!Array.isArray(modules.app) || modules.app.length < 1) {
  throw new Error('At least one module of type "app" must be enabled.');
}

class MainNav extends Component {

  static contextTypes = {
    store: PropTypes.object,
    router: PropTypes.object.isRequired,
  }

  static propTypes = {
    currentUser: PropTypes.shape({
      username: PropTypes.string,
    }),
    currentPerms: PropTypes.object, // eslint-disable-line react/forbid-prop-types
  }

  constructor(props, context) {
    super(props);
    this.state = {
      userMenuOpen: false,
    };
    this.store = context.store;
    this.toggleUserMenu = this.toggleUserMenu.bind(this);
    this.logout = this.logout.bind(this);
  }

  toggleUserMenu() {
    const isOpen = this.state.userMenuOpen;
    this.setState({
      userMenuOpen: !isOpen,
    });
  }

  logout() {
    this.store.dispatch(clearOkapiToken());
    this.store.dispatch(clearCurrentUser());
    this.toggleUserMenu();
    this.context.router.transitionTo('/');
    window.location.reload();
  }

  render() {
    const { currentUser, currentPerms } = this.props;
    const userIcon = (
      <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 26 26">
        <rect width="26" height="26" style={{ fill: '#3D9964' }} />
        <path d="M1.1 24.9c0 0 0-2.6 0.8-3.7 0.8-1 5.8-5.2 11.1-5.1s9.9 3.1 10.9 4.4 1.1 4.4 1.1 4.4L1.1 24.9z" style={{ fill: '#FFF' }} />
        <path d="M18.6 11.4c0 4.2-2.5 7.6-5.6 7.6 -3.1 0-5.6-3.4-5.6-7.6S8.4 3.8 13 3.8 18.6 7.2 18.6 11.4z" style={{ fill: '#FFF' }} />
        <path d="M13 19.5c-3.4 0-6.1-3.6-6.1-8.1 0-3.5 0.6-8.1 6.1-8.1 5.5 0 6.1 4.6 6.1 8.1C19.1 15.9 16.4 19.5 13 19.5zM13 4.3c-3.6 0-5.1 2.1-5.1 7.1 0 3.9 2.3 7.1 5.1 7.1 2.8 0 5.1-3.2 5.1-7.1C18.1 6.5 16.6 4.3 13 4.3z" style={{ fill: '#3D9964' }} />
      </svg>
    );

    const userDD = (

        <li className={`${css.nowrap} ${css.ddTextItem}`}>Logged in as { currentUser != null ? `${currentUser.first_name} ${currentUser.last_name}` : null }

Perms: {Object.keys(currentPerms || {}).sort().join(', ')}

<button className={css.ddButton} type="button" onClick={this.logout}>Log out</button>

    );

    const menuLinks = modules.app.map(entry =>
      <NavButton href={entry.home || entry.route} title={entry.displayName} key={entry.route}>
        <NavIcon color="#61f160" />

          {entry.displayName}

      </NavButton>,
    );

    let firstNav;
    let breadcrumbArray = []; // eslint-disable-line

    if (breadcrumbArray.length === 0) {
      firstNav = (
        <NavGroup md="hide">
          <NavButton href="/">
            <NavIcon color="#fdae35" />
            FOLIO
          </NavButton>
        </NavGroup>
      );
    } else {
      firstNav = (
        <NavGroup>
          <NavButton md="hide">
            <NavIcon color="#fdae35" />
          </NavButton>
          <Breadcrumbs linkArray={breadcrumbArray} />
        </NavGroup>
      );
    }

    return (

        {firstNav}
        <NavGroup>
          <NavGroup>
            {menuLinks}
            <NavDivider md="hide" />
            <NavButton md="hide" ><NavIcon color="#7eb970" /></NavButton>
            <NavButton md="hide"><NavIcon color="#b33f3f" /></NavButton>
            <NavButton md="hide"><NavIcon color="#3fb38e" /></NavButton>
            <NavButton md="hide"><NavIcon color="#3f6cb3" /></NavButton>
            <NavDivider md="hide" />
            <NavButton md="hide"><NavIcon color="#7d3fb3" /></NavButton>
          </NavGroup>
          <NavGroup className={css.smallAlignRight}>
            <Dropdown open={this.state.userMenuOpen} id="UserMenuDropDown" onToggle={this.toggleUserMenu} pullRight >
              <NavButton bsRole="toggle" title="User Menu" aria-haspopup="true" aria-expanded={this.state.userMenuOpen}><NavIcon icon={userIcon} /></NavButton>
              <NavDropdownMenu bsRole="menu" onToggle={this.toggleUserMenu} aria-label="User Menu">{userDD}</NavDropdownMenu>
            </Dropdown>
          </NavGroup>
        </NavGroup>

    );
  }
}

function mapStateToProps(state) {
  return {
    currentUser: state.okapi.currentUser,
    currentPerms: state.okapi.currentPerms,
  };
}

export default connect(mapStateToProps)(MainNav);
<commit_msg>Log out by simple location.assign<commit_after>import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { Dropdown } from 'react-bootstrap';

import { modules } from 'stripes-loader'; // eslint-disable-line

import { clearOkapiToken, clearCurrentUser } from '../../okapiActions';

import css from './MainNav.css';
import NavButton from './NavButton';
import NavDivider from './NavDivider';
import NavGroup from './NavGroup';
import Breadcrumbs from './Breadcrumbs';
import NavIcon from './NavIcon';

import NavDropdownMenu from './NavDropdownMenu';

if (!Array.isArray(modules.app) || modules.app.length < 1) {
  throw new Error('At least one module of type "app" must be enabled.');
}

class MainNav extends Component {

  static contextTypes = {
    store: PropTypes.object,
    router: PropTypes.object.isRequired,
  }

  static propTypes = {
    currentUser: PropTypes.shape({
      username: PropTypes.string,
    }),
    currentPerms: PropTypes.object, // eslint-disable-line react/forbid-prop-types
  }

  constructor(props, context) {
    super(props);
    this.state = {
      userMenuOpen: false,
    };
    this.store = context.store;
    this.toggleUserMenu = this.toggleUserMenu.bind(this);
    this.logout = this.logout.bind(this);
  }

  toggleUserMenu() {
    const isOpen = this.state.userMenuOpen;
    this.setState({
      userMenuOpen: !isOpen,
    });
  }

  logout() {
    //this.store.dispatch(clearOkapiToken());
    //this.store.dispatch(clearCurrentUser());
    window.location.assign('/');
  }

  render() {
    const { currentUser, currentPerms } = this.props;
    const userIcon = (
      <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 26 26">
        <rect width="26" height="26" style={{ fill: '#3D9964' }} />
        <path d="M1.1 24.9c0 0 0-2.6 0.8-3.7 0.8-1 5.8-5.2 11.1-5.1s9.9 3.1 10.9 4.4 1.1 4.4 1.1 4.4L1.1 24.9z" style={{ fill: '#FFF' }} />
        <path d="M18.6 11.4c0 4.2-2.5 7.6-5.6 7.6 -3.1 0-5.6-3.4-5.6-7.6S8.4 3.8 13 3.8 18.6 7.2 18.6 11.4z" style={{ fill: '#FFF' }} />
        <path d="M13 19.5c-3.4 0-6.1-3.6-6.1-8.1 0-3.5 0.6-8.1 6.1-8.1 5.5 0 6.1 4.6 6.1 8.1C19.1 15.9 16.4 19.5 13 19.5zM13 4.3c-3.6 0-5.1 2.1-5.1 7.1 0 3.9 2.3 7.1 5.1 7.1 2.8 0 5.1-3.2 5.1-7.1C18.1 6.5 16.6 4.3 13 4.3z" style={{ fill: '#3D9964' }} />
      </svg>
    );

    const userDD = (

        <li className={`${css.nowrap} ${css.ddTextItem}`}>Logged in as { currentUser != null ? `${currentUser.first_name} ${currentUser.last_name}` : null }

Perms: {Object.keys(currentPerms || {}).sort().join(', ')}

<button className={css.ddButton} type="button" onClick={this.logout}>Log out</button>

    );

    const menuLinks = modules.app.map(entry =>
      <NavButton href={entry.home || entry.route} title={entry.displayName} key={entry.route}>
        <NavIcon color="#61f160" />

          {entry.displayName}

      </NavButton>,
    );

    let firstNav;
    let breadcrumbArray = []; // eslint-disable-line

    if (breadcrumbArray.length === 0) {
      firstNav = (
        <NavGroup md="hide">
          <NavButton href="/">
            <NavIcon color="#fdae35" />
            FOLIO
          </NavButton>
        </NavGroup>
      );
    } else {
      firstNav = (
        <NavGroup>
          <NavButton md="hide">
            <NavIcon color="#fdae35" />
          </NavButton>
          <Breadcrumbs linkArray={breadcrumbArray} />
        </NavGroup>
      );
    }

    return (

        {firstNav}
        <NavGroup>
          <NavGroup>
            {menuLinks}
            <NavDivider md="hide" />
            <NavButton md="hide" ><NavIcon color="#7eb970" /></NavButton>
            <NavButton md="hide"><NavIcon color="#b33f3f" /></NavButton>
            <NavButton md="hide"><NavIcon color="#3fb38e" /></NavButton>
            <NavButton md="hide"><NavIcon color="#3f6cb3" /></NavButton>
            <NavDivider md="hide" />
            <NavButton md="hide"><NavIcon color="#7d3fb3" /></NavButton>
          </NavGroup>
          <NavGroup className={css.smallAlignRight}>
            <Dropdown open={this.state.userMenuOpen} id="UserMenuDropDown" onToggle={this.toggleUserMenu} pullRight >
              <NavButton bsRole="toggle" title="User Menu" aria-haspopup="true" aria-expanded={this.state.userMenuOpen}><NavIcon icon={userIcon} /></NavButton>
              <NavDropdownMenu bsRole="menu" onToggle={this.toggleUserMenu} aria-label="User Menu">{userDD}</NavDropdownMenu>
            </Dropdown>
          </NavGroup>
        </NavGroup>

    );
  }
}

function mapStateToProps(state) {
  return {
    currentUser: state.okapi.currentUser,
    currentPerms: state.okapi.currentPerms,
  };
}

export default connect(mapStateToProps)(MainNav);
<|endoftext|>


<commit_before>var isPromise = require('is-promise')

/**
 * Breeze Constructor
 *
 * Accepts a then method as the first argument.
 *
 * @param {Function} method initialization method, optional.
 */
function Breeze (method) {
  this.steps = []

  if (typeof method === 'function') {
    this.then(method)
  }
}

/**
 * Takes the next (optional) callback, and generates the done callback to be passed as the first argument.
 *
 * @private
 * @param  {Function} next Next callback in the system to be invoked.
 * @return {Function} Completion callback, first argument is error, subsequent arguments are passed down the chain.
 */
Breeze.prototype.createDoneCallback = function _breezeCreateDoneCallback () {
  var system = this

  return function (err) {
    var context = this

    function handler (err) {
      if (err) {
        if (!system.onError || !system.onDeferredError) {
          system.err = err
        } else {
          if (system.onError) system.onError(err)
          if (system.onDeferredError) system.onDeferredError(err)
        }

        return (system.steps = [] && system.check())
      }

      var args = Array.prototype.slice.call(arguments, 1)
      system.args = args
      system.context = context
      system.check(true)
    }

    if (isPromise(err)) {
      var args = Array.prototype.slice.call(arguments, 1)
      var success = function () {
        var successArgs = Array.prototype.slice.call(arguments, 0)
        args = args.concat(successArgs)
        args.unshift(null)
        handler.apply(context, args)
      }

      return typeof err.catch === 'function'
        ? err.then(success).catch(handler)
        : err.then(success, handler)
    }

    return handler.apply(context, arguments)
  }
}

/**
 * Starts the next task to be completed.
 *
 * @private
 * @return {void}
 */
Breeze.prototype.run = function _breezeRun () {
  var system = this
  var args = this.args || []
  var context = this.context || this
  var func = this.steps.shift()
  this.running = true

  try {
    if (typeof func === 'function') {
      args.unshift(this.createDoneCallback())
      return func.apply(context, args)
    }

    if (func[0] === 'none') {
      if (!this.hasSomeHappened) {
        this.hasNoneHappened = true
        func = func[1]
        args.unshift(this.createDoneCallback())
        return func.apply(context, args)
      }

      return this.check(true)
    }

    if (func[0] === 'some' && this.hasSomeHappened) {
      return this.check(true)
    }

    if ((typeof func[1] === 'function' && func[1].apply(this.context, args)) || (typeof func[1] !== 'function' && func[1])) {
      switch (func[0]) {
        case 'when': this.hasWhenHappened = true; break;
        case 'some': this.hasSomeHappened = true; break;
      }

      func = func[2]
      args.unshift(this.createDoneCallback())
      func.apply(context, args)
    } else {
      return this.check(true)
    }
  } catch (error) {
    console.error(error)
  }
}

/**
 * Checks whether the system is running, needs to be ran, or has completed
 * running.
 *
 * @private
 * @return {void}
 */
Breeze.prototype.check = function _breezeCheck (pop) {
  this.steps = this.steps || []

  if (pop && this.steps.length) {
    return this.run()
  }

  if (pop && !this.steps.length) {
    return this.running = false
  }

  if (this.steps.length && !this.running) {
    this.run()
  }
}

/**
 * Adds callback to the system stack when first argument passed is of a
 * truthy status.
 *
 * @param  {Boolean}  arg    Argument to be evaluated
 * @param  {Function} next   Callback to be pushed onto the stack
 * @return {this}
 */
Breeze.prototype.when = Breeze.prototype.maybe = function _breezeMaybeWhen (arg, next) {
  if (this.err) return this

  this.steps.push(['when', arg, next])
  this.check()
  return this
}

/**
 * Adds callback to the system when first argument is evaluated as true, and
 * no none calls have been invoked.
 *
 * @param  {Boolean}  arg    Argument to be evaluated
 * @param  {Function} next   Callback to be pushed onto stack
 * @return {this}
 */
Breeze.prototype.some = function _breezeSome (arg, next) {
  if (this.err || this.hasNoneHappened) return this

  this.hasSome = true
  this.steps.push(['some', arg, next])
  this.check()
  return this
}

/**
 * Adds callback to the system if no some callback was triggered.
 *
 * @param  {Function} next   Callback to be pushed onto stack
 * @return {this}
 */
Breeze.prototype.none = function _breezeNone (next) {
  if (this.err) return this

  if (!this.hasSome) {
    throw new Error("Cannot add .none check before adding .some checks")
  }

  if (this.hasSome) {
    this.hasNoneHappened = true
    this.steps.push(['none', next])
    this.check()
  }

  return this
}

/**
 * Adds callback to the system
 *
 * @param  {Function} next Callback to be pushed onto the stack
 * @return {this}
 */
Breeze.prototype.then = function _breezeThen (next) {
  if (this.err) return this

  this.steps.push(next)
  this.check()
  return this
}

/**
 * Checks whether system has an err and invokes callback, or saves callback for later
 * invocation.
 *
 * @param  {Function} next Callback to be invoked should err exist
 * @return {this}
 */
Breeze.prototype.catch = function _breezeCatch (next) {
  if (this.err) {
    next(this.err)

    if (this.onDeferredError) {
      this.onDeferredError(this.err)
    }

    return this
  }

  this.onError = next
  this.check()
  return this
}

/**
 * Generates a deferred promise
 *
 * @return {Function}
 */
Breeze.prototype.promise = function _breezeDeferred () {
  var system = this
  var deferred = {
    then: function (next) {
      if (system.err) return deferred

      system.steps.push(function () {
        return next.apply(this, Array.prototype.slice.call(arguments, 1))
      })

      system.check()
      return deferred
    },

    catch: function (next) {
      if (system.err) {
        return next(system.err)
      }

      system.onDeferredError = next
      return deferred
    }
  }

  return deferred
}

/**
 * Resets system
 */
Breeze.prototype.reset = function _breezeReset () {
  this.hasMaybeHappened = undefined
  this.hasNoneHappened = undefined
  this.hasSomeHappened = undefined
  this.hasSome = undefined
  this.onError = undefined
  this.running = undefined
  this.err = undefined
  this.steps = []

  return this
}

/**
 * Create new instance of Breeze
 */
module.exports = function breeze (method) {
  return new Breeze(method)
}
<commit_msg>fix(next): Fix logic in error handler<commit_after>var isPromise = require('is-promise')

/**
 * Breeze Constructor
 *
 * Accepts a then method as the first argument.
 *
 * @param {Function} method initialization method, optional.
 */
function Breeze (method) {
  this.steps = []

  if (typeof method === 'function') {
    this.then(method)
  }
}

/**
 * Takes the next (optional) callback, and generates the done callback to be passed as the first argument.
 *
 * @private
 * @param  {Function} next Next callback in the system to be invoked.
 * @return {Function} Completion callback, first argument is error, subsequent arguments are passed down the chain.
 */
Breeze.prototype.createDoneCallback = function _breezeCreateDoneCallback () {
  var system = this

  return function (err) {
    var context = this

    function handler (err) {
      if (err) {
        if (!system.onError && !system.onDeferredError) {
          system.err = err
        } else {
          if (system.onError) system.onError(err)
          if (system.onDeferredError) system.onDeferredError(err)
        }

        return (system.steps = [] && system.check())
      }

      var args = Array.prototype.slice.call(arguments, 1)
      system.args = args
      system.context = context
      system.check(true)
    }

    if (isPromise(err)) {
      var args = Array.prototype.slice.call(arguments, 1)
      var success = function () {
        var successArgs = Array.prototype.slice.call(arguments, 0)
        args = args.concat(successArgs)
        args.unshift(null)
        handler.apply(context, args)
      }

      return typeof err.catch === 'function'
        ? err.then(success).catch(handler)
        : err.then(success, handler)
    }

    return handler.apply(context, arguments)
  }
}

/**
 * Starts the next task to be completed.
 *
 * @private
 * @return {void}
 */
Breeze.prototype.run = function _breezeRun () {
  var system = this
  var args = this.args || []
  var context = this.context || this
  var func = this.steps.shift()
  this.running = true

  try {
    if (typeof func === 'function') {
      args.unshift(this.createDoneCallback())
      return func.apply(context, args)
    }

    if (func[0] === 'none') {
      if (!this.hasSomeHappened) {
        this.hasNoneHappened = true
        func = func[1]
        args.unshift(this.createDoneCallback())
        return func.apply(context, args)
      }

      return this.check(true)
    }

    if (func[0] === 'some' && this.hasSomeHappened) {
      return this.check(true)
    }

    if ((typeof func[1] === 'function' && func[1].apply(this.context, args)) || (typeof func[1] !== 'function' && func[1])) {
      switch (func[0]) {
        case 'when': this.hasWhenHappened = true; break;
        case 'some': this.hasSomeHappened = true; break;
      }

      func = func[2]
      args.unshift(this.createDoneCallback())
      func.apply(context, args)
    } else {
      return this.check(true)
    }
  } catch (error) {
    console.error(error)
  }
}

/**
 * Checks whether the system is running, needs to be ran, or has completed
 * running.
 *
 * @private
 * @return {void}
 */
Breeze.prototype.check = function _breezeCheck (pop) {
  this.steps = this.steps || []

  if (pop && this.steps.length) {
    return this.run()
  }

  if (pop && !this.steps.length) {
    return this.running = false
  }

  if (this.steps.length && !this.running) {
    this.run()
  }
}

/**
 * Adds callback to the system stack when first argument passed is of a
 * truthy status.
 *
 * @param  {Boolean}  arg    Argument to be evaluated
 * @param  {Function} next   Callback to be pushed onto the stack
 * @return {this}
 */
Breeze.prototype.when = Breeze.prototype.maybe = function _breezeMaybeWhen (arg, next) {
  if (this.err) return this

  this.steps.push(['when', arg, next])
  this.check()
  return this
}

/**
 * Adds callback to the system when first argument is evaluated as true, and
 * no none calls have been invoked.
 *
 * @param  {Boolean}  arg    Argument to be evaluated
 * @param  {Function} next   Callback to be pushed onto stack
 * @return {this}
 */
Breeze.prototype.some = function _breezeSome (arg, next) {
  if (this.err || this.hasNoneHappened) return this

  this.hasSome = true
  this.steps.push(['some', arg, next])
  this.check()
  return this
}

/**
 * Adds callback to the system if no some callback was triggered.
 *
 * @param  {Function} next   Callback to be pushed onto stack
 * @return {this}
 */
Breeze.prototype.none = function _breezeNone (next) {
  if (this.err) return this

  if (!this.hasSome) {
    throw new Error("Cannot add .none check before adding .some checks")
  }

  if (this.hasSome) {
    this.hasNoneHappened = true
    this.steps.push(['none', next])
    this.check()
  }

  return this
}

/**
 * Adds callback to the system
 *
 * @param  {Function} next Callback to be pushed onto the stack
 * @return {this}
 */
Breeze.prototype.then = function _breezeThen (next) {
  if (this.err) return this

  this.steps.push(next)
  this.check()
  return this
}

/**
 * Checks whether system has an err and invokes callback, or saves callback for later
 * invocation.
 *
 * @param  {Function} next Callback to be invoked should err exist
 * @return {this}
 */
Breeze.prototype.catch = function _breezeCatch (next) {
  if (this.err) {
    next(this.err)

    if (this.onDeferredError) {
      this.onDeferredError(this.err)
    }

    return this
  }

  this.onError = next
  this.check()
  return this
}

/**
 * Generates a deferred promise
 *
 * @return {Function}
 */
Breeze.prototype.promise = function _breezeDeferred () {
  var system = this
  var deferred = {
    then: function (next) {
      if (system.err) return deferred

      system.steps.push(function () {
        return next.apply(this, Array.prototype.slice.call(arguments, 1))
      })

      system.check()
      return deferred
    },

    catch: function (next) {
      if (system.err) {
        return next(system.err)
      }

      system.onDeferredError = next
      return deferred
    }
  }

  return deferred
}

/**
 * Resets system
 */
Breeze.prototype.reset = function _breezeReset () {
  this.hasMaybeHappened = undefined
  this.hasNoneHappened = undefined
  this.hasSomeHappened = undefined
  this.hasSome = undefined
  this.onError = undefined
  this.running = undefined
  this.err = undefined
  this.steps = []

  return this
}

/**
 * Create new instance of Breeze
 */
module.exports = function breeze (method) {
  return new Breeze(method)
}
<|endoftext|>


<commit_before>import _ from 'lodash'; // eslint-disable-line
import React, { Component, PropTypes } from 'react' // eslint-disable-line
import { connect } from 'stripes-connect'; // eslint-disable-line
import Pane from '@folio/stripes-components/lib/Pane' // eslint-disable-line
import PaneMenu from '@folio/stripes-components/lib/PaneMenu' // eslint-disable-line
import Button from '@folio/stripes-components/lib/Button' // eslint-disable-line
import KeyValue from '@folio/stripes-components/lib/KeyValue' // eslint-disable-line
import {Row, Col} from 'react-bootstrap' // eslint-disable-line
import TextField from '@folio/stripes-components/lib/TextField' // eslint-disable-line
import MultiColumnList from '@folio/stripes-components/lib/MultiColumnList' // eslint-disable-line
import Icon from '@folio/stripes-components/lib/Icon' // eslint-disable-line
import Layer from '@folio/stripes-components/lib/Layer'; // eslint-disable-line

import UserForm from './UserForm';

class ViewUser extends Component {
  static propTypes = {
    data: PropTypes.shape({
      user: PropTypes.arrayOf(PropTypes.object),
    }),
    mutator: React.PropTypes.shape({
      user: React.PropTypes.shape({
        PUT: React.PropTypes.func.isRequired,
      }),
    }),
  };

  static manifest = Object.freeze({
    user: {
      type: 'okapi',
      path: 'users/:{userid}',
    },
  });

  constructor(props) {
    super(props);
    this.state = {
      editUserMode: false,
    };
    this.onClickEditUser = this.onClickEditUser.bind(this);
    this.onClickCloseEditUser = this.onClickCloseEditUser.bind(this);
  }

  // EditUser Handlers
  onClickEditUser(e) {
    if (e) e.preventDefault();
    this.setState({
      editUserMode: true,
    });
  }

  onClickCloseEditUser(e) {
    if (e) e.preventDefault();
    this.setState({
      editUserMode: false,
    });
  }

  update(data) {
    this.props.mutator.user.PUT(data).then(() => {
      this.onClickCloseEditUser();
    });
  }

  render() {
    const fineHistory = [{ 'Due Date': '11/12/2014', 'Amount': '34.23', 'Status': 'Unpaid' }]; // eslint-disable-line quote-props

    const detailMenu = <PaneMenu><button onClick={this.onClickEditUser} title="Edit User"><Icon icon="edit" />Edit</button></PaneMenu>;

    const { data: { user } } = this.props;
    if (!user || user.length === 0) return
;
    return (
      <Pane defaultWidth="fill" paneTitle="User Details" lastMenu={detailMenu}>
        <Row>
          <Col xs={8} >
            <Row>
              <Col xs={12}>

{_.get(user[0], ['personal', 'last_name'], '')}, {_.get(user[0], ['personal', 'first_name'], '')}

              </Col>
            </Row>
            <Row>
              <Col xs={12}>
                <KeyValue label="Email" value={_.get(user[0], ['personal', 'email'], '')} />
              </Col>
            </Row>
          </Col>
          <Col xs={4} >

          </Col>
        </Row>

        <Row>
          <Col xs={3}>

Fines

          </Col>
          <Col xs={4} sm={3}>
            <TextField
              rounded
              endControl={<Button buttonStyle="fieldControl"><Icon icon="clearX" /></Button>}
              startControl={<Icon icon="search" />}
              placeholder="Search"
              fullWidth
            />
          </Col>
          <Col xs={5} sm={6}>
            <Button align="end" bottomMargin0 >View Full History</Button>
          </Col>
        </Row>
        <MultiColumnList fullWidth contentData={fineHistory} />
        <Layer isOpen={this.state.editUserMode} label="Edit User Dialog">
          <UserForm
            onSubmit={(record) => { this.update(record); }}
            initialValues={user[0]}
            onCancel={this.onClickCloseEditUser}
          />
        </Layer>
      </Pane>
    );
  }
}

export default connect(ViewUser, 'users');
<commit_msg>LIBAPP-23: add username, status, password, and patron group to user detail display.<commit_after>import _ from 'lodash'; // eslint-disable-line
import React, { Component, PropTypes } from 'react' // eslint-disable-line
import { connect } from 'stripes-connect'; // eslint-disable-line
import Pane from '@folio/stripes-components/lib/Pane' // eslint-disable-line
import PaneMenu from '@folio/stripes-components/lib/PaneMenu' // eslint-disable-line
import Button from '@folio/stripes-components/lib/Button' // eslint-disable-line
import KeyValue from '@folio/stripes-components/lib/KeyValue' // eslint-disable-line
import {Row, Col} from 'react-bootstrap' // eslint-disable-line
import TextField from '@folio/stripes-components/lib/TextField' // eslint-disable-line
import MultiColumnList from '@folio/stripes-components/lib/MultiColumnList' // eslint-disable-line
import Icon from '@folio/stripes-components/lib/Icon' // eslint-disable-line
import Layer from '@folio/stripes-components/lib/Layer'; // eslint-disable-line

import UserForm from './UserForm';

class ViewUser extends Component {
  static propTypes = {
    data: PropTypes.shape({
      user: PropTypes.arrayOf(PropTypes.object),
    }),
    mutator: React.PropTypes.shape({
      user: React.PropTypes.shape({
        PUT: React.PropTypes.func.isRequired,
      }),
    }),
  };

  static manifest = Object.freeze({
    user: {
      type: 'okapi',
      path: 'users/:{userid}',
    },
  });

  constructor(props) {
    super(props);
    this.state = {
      editUserMode: false,
    };
    this.onClickEditUser = this.onClickEditUser.bind(this);
    this.onClickCloseEditUser = this.onClickCloseEditUser.bind(this);
  }

  // EditUser Handlers
  onClickEditUser(e) {
    if (e) e.preventDefault();
    this.setState({
      editUserMode: true,
    });
  }

  onClickCloseEditUser(e) {
    if (e) e.preventDefault();
    this.setState({
      editUserMode: false,
    });
  }

  update(data) {
    this.props.mutator.user.PUT(data).then(() => {
      this.onClickCloseEditUser();
    });
  }

  render() {
    const fineHistory = [{ 'Due Date': '11/12/2014', 'Amount': '34.23', 'Status': 'Unpaid' }]; // eslint-disable-line quote-props

    const detailMenu = <PaneMenu><button onClick={this.onClickEditUser} title="Edit User"><Icon icon="edit" />Edit</button></PaneMenu>;

    const { data: { user } } = this.props;
    if (!user || user.length === 0) return
;
    const userStatus = (_.get(user[0], ['active'], '') ? 'active' : 'inactive');
    return (
      <Pane defaultWidth="fill" paneTitle="User Details" lastMenu={detailMenu}>
        <Row>
          <Col xs={8} >
            <Row>
              <Col xs={12}>

{_.get(user[0], ['personal', 'last_name'], '')}, {_.get(user[0], ['personal', 'first_name'], '')}

              </Col>
            </Row>
            <Row>
              <Col xs={12}>
                <KeyValue label="Username" value={_.get(user[0], ['username'], '')} />
              </Col>
            </Row>

            <Row>
              <Col xs={12}>
                <KeyValue label="Status" value={userStatus} />
              </Col>
            </Row>

            <Row>
              <Col xs={12}>
                <KeyValue label="Password" value={'PASSWORD'} />
              </Col>
            </Row>

            <Row>
              <Col xs={12}>
                <KeyValue label="Email" value={_.get(user[0], ['personal', 'email'], '')} />
              </Col>
            </Row>

            <Row>
              <Col xs={12}>
                <KeyValue label="Patron group" value={_.get(user[0], ['patron_group'], '')} />
              </Col>
            </Row>
          </Col>
          <Col xs={4} >

          </Col>
        </Row>

        <Row>
          <Col xs={3}>

Fines

          </Col>
          <Col xs={4} sm={3}>
            <TextField
              rounded
              endControl={<Button buttonStyle="fieldControl"><Icon icon="clearX" /></Button>}
              startControl={<Icon icon="search" />}
              placeholder="Search"
              fullWidth
            />
          </Col>
          <Col xs={5} sm={6}>
            <Button align="end" bottomMargin0 >View Full History</Button>
          </Col>
        </Row>
        <MultiColumnList fullWidth contentData={fineHistory} />
        <Layer isOpen={this.state.editUserMode} label="Edit User Dialog">
          <UserForm
            onSubmit={(record) => { this.update(record); }}
            initialValues={user[0]}
            onCancel={this.onClickCloseEditUser}
          />
        </Layer>
      </Pane>
    );
  }
}

export default connect(ViewUser, 'users');
<|endoftext|>