<commit_before>'use strict';

var diff = require('diff');
var chalk = require('chalk');
var Template = require('template');
var toVinyl = require('to-vinyl');
var Task = require('orchestrator');
var vfs = require('vinyl-fs');
var _ = require('lodash');

var session = require('./lib/session');
var stack = require('./lib/stack');
var utils = require('./lib/utils');
var init = require('./lib/init');

/**
 * Initialize `Assemble`
 *
 * @param {Object} `context`
 * @api private
 */

function Assemble() {
  Template.apply(this, arguments);
  Task.apply(this, arguments);
  this.session = session;
  init(this);
}

_.extend(Assemble.prototype, Task.prototype);
Template.extend(Assemble.prototype);

/**
 * Initialize default configuration.
 */

Assemble.prototype.defaultOptions = function() {
  Assemble.__super__.defaultOptions.apply(this, arguments);
  this.disable('default routes');
};

/**
 * Glob patterns or filepaths to source files.
 *
 * ```js
 * assemble.src('src/*.hbs', {layout: 'default'})
 * ```
 *
 * @param {String|Array} `glob` Glob patterns or file paths to source files.
 * @param {Object} `options` Options or locals to merge into the context and/or pass to `src` plugins
 * @api public
 */

Assemble.prototype.src = function (glob, opts) {
  return stack.src(this, glob, opts);
};

/**
 * Specify a destination for processed files.
 *
 * ```js
 * assemble.dest('dist')
 * ```
 *
 * @param {String|Function} `dest` File path or rename function.
 * @param {Object} `options` Options and locals to pass to `dest` plugins
 * @api public
 */

Assemble.prototype.dest = function (dest, opts) {
  return stack.dest(this, dest, opts);
};

/**
 * Copy a `glob` of files to the specified `dest`.
 *
 * ```js
 * assemble.task('assets', function() {
 *   assemble.copy('assets/**', 'dist');
 * });
 * ```
 *
 * @param  {String|Array} `glob`
 * @param  {String|Function} `dest`
 * @return {Stream} Stream, to continue processing if necessary.
 * @api public
 */

Assemble.prototype.copy = function(glob, dest, opts) {
  return vfs.src(glob, opts).pipe(vfs.dest(dest, opts));
};

/**
 * Define an Assemble task.
 *
 * ```js
 * assemble.task('default', function() {
 *   assemble.src('templates/*.hbs')
 *     .pipe(assemble.dest('dist/'));
 * });
 * ```
 *
 * @param {String} `name` Task name
 * @param {Function} `fn`
 * @api public
 */

Assemble.prototype.task = Assemble.prototype.add;

/**
 * Get the name of the currently running task from `session-cache`.
 * This may then be used to get the view collection that was dynamically
 * created for the task (by the `file` loader).
 *
 * ```js
 * var taskName = assemble.getTask();
 * var views = assemble.views[taskName];
 * ```
 *
 * @return {String} `task` If a task is running, returns the name of the task, otherwise returns `page`.
 * @api public
 */

Assemble.prototype.getTask = function() {
  var name = this.session.get('task');
  return typeof name === 'string' ? name : 'page';
};

/**
 * Get a view collection by its singular-form `name`.
 *
 * ```js
 * var collection = assemble.getCollection('page');
 * // gets the `pages` collection
 * //=> {a: {}, b: {}, ...}
 * ```
 *
 * @return {String} `name` Singular name of the collection to get
 * @api public
 */

Assemble.prototype.getCollection = function(name) {
  if (typeof name === 'undefined') {
    name = this.getTask();
  }

  if (this.views.hasOwnProperty(name)) {
    return this.views[name];
  }

  name = this.inflections[name];
  return this.views[name];
};

/**
 * Get a file from the currently running task.
 *
 * ```js
 * var file = assemble.getFile(file);
 * ```
 *
 * @return {Object} `file` Vinyl file object. Files must have an `id` property.
 * @api public
 */

Assemble.prototype.getFile = function(file, id) {
  // if (typeof file === 'object' || !file.hasOwnProperty('id')) {
  //   throw new Error('Assemble.getFile expects file objects to have an `id` property.');
  // }
  return this.getCollection(id)[file.id];
};

/**
 * Get a template from the current session, convert it to a vinyl
 * file, and push it into the stream.
 *
 * ```js
 * app.pushToStream(file);
 * ```
 *
 * @param {Stream} `stream` Vinyl stream
 * @param {String} `id` Get the session `id` using `app.getTask()`
 * @api public
 */

Assemble.prototype.pushToStream = function(id, stream) {
  return utils.pushToStream(this.getCollection(id), stream, toVinyl);
};

/**
 * Session-context-specific getter that returns the collection of
 * files for the currently running `task`.
 *
 * ```js
 * var files = assemble.files;
 * ```
 *
 * @name .files
 * @return {Object} Get the files from the current task.
 * @api public
 */

Object.defineProperty(Assemble.prototype, 'files', {
  configurable: true,
  enumerable: true,
  get: function () {
    return this.getCollection(this.getTask());
  }
});

/**
 * Display a visual representation of the
 * difference between `a` and `b`
 */

Assemble.prototype.diff = function(a, b, method) {
  method = method || 'diffJson';
  a = a || this.env;
  b = b || this.cache.data;
  diff[method](a, b).forEach(function (res) {
    var color = chalk.gray;
    if (res.added) {
      color = chalk.green;
    }
    if (res.removed) {
      color = chalk.red;
    }
    process.stderr.write(color(res.value));
  });
  console.log('\n');
};

/**
 * Run an array of tasks.
 *
 * ```js
 * assemble.run(['foo', 'bar']);
 * ```
 *
 * @param {Array} `tasks`
 * @api private
 */

Assemble.prototype.run = function() {
  var tasks = arguments.length ? arguments : ['default'];
  this.start.apply(this, tasks);
};

/**
 * Wrapper around Task._runTask to enable `sessions`
 *
 * @param  {Object} `task` Task to run
 * @api private
 */

Assemble.prototype._runTask = function(task) {
  var assemble = this;
  assemble.session.run(function () {
    assemble.session.set('task', task.name);
    Task.prototype._runTask.call(assemble, task);
  });
};

/**
 * Re-run the specified task(s) when a file changes.
 *
 * ```js
 * assemble.task('watch', function() {
 *   assemble.watch('docs/*.md', ['docs']);
 * });
 * ```
 *
 * @param  {String|Array} `glob` Filepaths or glob patterns.
 * @param  {Function} `fn` Task(s) to watch.
 * @api public
 */

Assemble.prototype.watch = function(glob, opts, fn) {
  if (Array.isArray(opts) || typeof opts === 'function') {
    fn = opts; opts = null;
  }
  if (!Array.isArray(fn)) return vfs.watch(glob, opts, fn);
  return vfs.watch(glob, opts, function () {
    this.start.apply(this, fn);
  }.bind(this));
};

/**
 * Create a new instance of `Assemble`.
 *
 * ```js
 * assemble.init();
 * ```
 *
 * @api public
 */

Assemble.prototype.init = function () {
  return new Assemble();
};

/**
 * Expose `assemble`
 */

module.exports = new Assemble();
<commit_msg>uncomment code for file error handling<commit_after>'use strict';

var diff = require('diff');
var chalk = require('chalk');
var Template = require('template');
var toVinyl = require('to-vinyl');
var Task = require('orchestrator');
var vfs = require('vinyl-fs');
var _ = require('lodash');

var session = require('./lib/session');
var stack = require('./lib/stack');
var utils = require('./lib/utils');
var init = require('./lib/init');

/**
 * Initialize `Assemble`
 *
 * @param {Object} `context`
 * @api private
 */

function Assemble() {
  Template.apply(this, arguments);
  Task.apply(this, arguments);
  this.session = session;
  init(this);
}

_.extend(Assemble.prototype, Task.prototype);
Template.extend(Assemble.prototype);

/**
 * Initialize default configuration.
 */

Assemble.prototype.defaultOptions = function() {
  Assemble.__super__.defaultOptions.apply(this, arguments);
  this.disable('default routes');
};

/**
 * Glob patterns or filepaths to source files.
 *
 * ```js
 * assemble.src('src/*.hbs', {layout: 'default'})
 * ```
 *
 * @param {String|Array} `glob` Glob patterns or file paths to source files.
 * @param {Object} `options` Options or locals to merge into the context and/or pass to `src` plugins
 * @api public
 */

Assemble.prototype.src = function (glob, opts) {
  return stack.src(this, glob, opts);
};

/**
 * Specify a destination for processed files.
 *
 * ```js
 * assemble.dest('dist')
 * ```
 *
 * @param {String|Function} `dest` File path or rename function.
 * @param {Object} `options` Options and locals to pass to `dest` plugins
 * @api public
 */

Assemble.prototype.dest = function (dest, opts) {
  return stack.dest(this, dest, opts);
};

/**
 * Copy a `glob` of files to the specified `dest`.
 *
 * ```js
 * assemble.task('assets', function() {
 *   assemble.copy('assets/**', 'dist');
 * });
 * ```
 *
 * @param  {String|Array} `glob`
 * @param  {String|Function} `dest`
 * @return {Stream} Stream, to continue processing if necessary.
 * @api public
 */

Assemble.prototype.copy = function(glob, dest, opts) {
  return vfs.src(glob, opts).pipe(vfs.dest(dest, opts));
};

/**
 * Define an Assemble task.
 *
 * ```js
 * assemble.task('default', function() {
 *   assemble.src('templates/*.hbs')
 *     .pipe(assemble.dest('dist/'));
 * });
 * ```
 *
 * @param {String} `name` Task name
 * @param {Function} `fn`
 * @api public
 */

Assemble.prototype.task = Assemble.prototype.add;

/**
 * Get the name of the currently running task from `session-cache`.
 * This may then be used to get the view collection that was dynamically
 * created for the task (by the `file` loader).
 *
 * ```js
 * var taskName = assemble.getTask();
 * var views = assemble.views[taskName];
 * ```
 *
 * @return {String} `task` If a task is running, returns the name of the task, otherwise returns `page`.
 * @api public
 */

Assemble.prototype.getTask = function() {
  var name = this.session.get('task');
  return typeof name === 'string' ? name : 'page';
};

/**
 * Get a view collection by its singular-form `name`.
 *
 * ```js
 * var collection = assemble.getCollection('page');
 * // gets the `pages` collection
 * //=> {a: {}, b: {}, ...}
 * ```
 *
 * @return {String} `name` Singular name of the collection to get
 * @api public
 */

Assemble.prototype.getCollection = function(name) {
  if (typeof name === 'undefined') {
    name = this.getTask();
  }

  if (this.views.hasOwnProperty(name)) {
    return this.views[name];
  }

  name = this.inflections[name];
  return this.views[name];
};

/**
 * Get a file from the currently running task.
 *
 * ```js
 * var file = assemble.getFile(file);
 * ```
 *
 * @return {Object} `file` Vinyl file object. Files must have an `id` property.
 * @api public
 */

Assemble.prototype.getFile = function(file, id) {
  if (typeof file === 'object' || !file.hasOwnProperty('id')) {
    throw new Error('Assemble.getFile expects file objects to have an `id` property.');
  }
  return this.getCollection(id)[file.id];
};

/**
 * Get a template from the current session, convert it to a vinyl
 * file, and push it into the stream.
 *
 * ```js
 * app.pushToStream(file);
 * ```
 *
 * @param {Stream} `stream` Vinyl stream
 * @param {String} `id` Get the session `id` using `app.getTask()`
 * @api public
 */

Assemble.prototype.pushToStream = function(id, stream) {
  return utils.pushToStream(this.getCollection(id), stream, toVinyl);
};

/**
 * Session-context-specific getter that returns the collection of
 * files for the currently running `task`.
 *
 * ```js
 * var files = assemble.files;
 * ```
 *
 * @name .files
 * @return {Object} Get the files from the current task.
 * @api public
 */

Object.defineProperty(Assemble.prototype, 'files', {
  configurable: true,
  enumerable: true,
  get: function () {
    return this.getCollection(this.getTask());
  }
});

/**
 * Display a visual representation of the
 * difference between `a` and `b`
 */

Assemble.prototype.diff = function(a, b, method) {
  method = method || 'diffJson';
  a = a || this.env;
  b = b || this.cache.data;
  diff[method](a, b).forEach(function (res) {
    var color = chalk.gray;
    if (res.added) {
      color = chalk.green;
    }
    if (res.removed) {
      color = chalk.red;
    }
    process.stderr.write(color(res.value));
  });
  console.log('\n');
};

/**
 * Run an array of tasks.
 *
 * ```js
 * assemble.run(['foo', 'bar']);
 * ```
 *
 * @param {Array} `tasks`
 * @api private
 */

Assemble.prototype.run = function() {
  var tasks = arguments.length ? arguments : ['default'];
  this.start.apply(this, tasks);
};

/**
 * Wrapper around Task._runTask to enable `sessions`
 *
 * @param  {Object} `task` Task to run
 * @api private
 */

Assemble.prototype._runTask = function(task) {
  var assemble = this;
  assemble.session.run(function () {
    assemble.session.set('task', task.name);
    Task.prototype._runTask.call(assemble, task);
  });
};

/**
 * Re-run the specified task(s) when a file changes.
 *
 * ```js
 * assemble.task('watch', function() {
 *   assemble.watch('docs/*.md', ['docs']);
 * });
 * ```
 *
 * @param  {String|Array} `glob` Filepaths or glob patterns.
 * @param  {Function} `fn` Task(s) to watch.
 * @api public
 */

Assemble.prototype.watch = function(glob, opts, fn) {
  if (Array.isArray(opts) || typeof opts === 'function') {
    fn = opts; opts = null;
  }
  if (!Array.isArray(fn)) return vfs.watch(glob, opts, fn);
  return vfs.watch(glob, opts, function () {
    this.start.apply(this, fn);
  }.bind(this));
};

/**
 * Create a new instance of `Assemble`.
 *
 * ```js
 * assemble.init();
 * ```
 *
 * @api public
 */

Assemble.prototype.init = function () {
  return new Assemble();
};

/**
 * Expose `assemble`
 */

module.exports = new Assemble();
<|endoftext|>


<commit_before>module.exports = function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');

    if (req.query.name || (req.body && req.body.name)) {
        res = {
            // status: 200, /* Defaults to 200 */
            body: "Hello " + (req.query.name || req.body.name)
        };
    }
    else {
        res = {
            status: 400,
            body: "Please  pass a name on the query string or in the request body"
        };
    }
    context.done(null, res);
};
<commit_msg>Add AI<commit_after>module.exports = function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');

    if (req.query.name || (req.body && req.body.name)) {
        res = {
            // status: 200, /* Defaults to 200 */
            body: "Hello " + (req.query.name || req.body.name) + ". You know how to call an API!"
        };
    }
    else {
        res = {
            status: 400,
            body: "Please  pass a name on the query string or in the request body"
        };
    }
    context.done(null, res);
};
<|endoftext|>


<commit_before>function updateAllocationTotal(id, count, required) {

    $('#allocation-total-'+id).html(count);

    var el = $("#allocation-panel-" + id);
    el.removeClass('part-allocation-pass part-allocation-underallocated part-allocation-overallocated');

    if (count < required) {
        el.addClass('part-allocation-underallocated');
    } else if (count > required) {
        el.addClass('part-allocation-overallocated');
    } else {
        el.addClass('part-allocation-pass');
    }
}

function loadAllocationTable(table, part_id, part, url, required, button) {

    // Load the allocation table
    table.bootstrapTable({
        url: url,
        sortable: false,
        formatNoMatches: function() { return 'No parts allocated for ' + part; },
        columns: [
            {
                field: 'stock_item_detail',
                title: 'Stock Item',
                formatter: function(value, row, index, field) {
                    return '' + value.quantity + ' x ' + value.part_name + ' @ ' + value.location_name;
                }
            },
            {
                field: 'stock_item_detail.quantity',
                title: 'Available',
            },
            {
                field: 'quantity',
                title: 'Allocated',
                formatter: function(value, row, index, field) {
                    var html = value;

                    var bEdit = "<button class='btn btn-success item-edit-button btn-sm' type='button' url='/build/item/" + row.pk + "/edit/'>Edit</button>";
                    var bDel = "<button class='btn btn-danger item-del-button btn-sm' type='button' url='/build/item/" + row.pk + "/delete/'>Delete</button>";

                    html += "
" + bEdit + bDel + "
";

                    return html;
                }
            }
        ],
    });

    // Callback for 'new-item' button
    button.click(function() {
        launchModalForm(button.attr('url'), {
            success: function() {
                table.bootstrapTable('refresh');
            }
        });
    });

    table.on('load-success.bs.table', function(data) {
        // Extract table data
        var results = table.bootstrapTable('getData');

        var count = 0;

        for (var i = 0; i < results.length; i++) {
            count += results[i].quantity;
        }

        updateAllocationTotal(part_id, count, required);
    });

    // Button callbacks for editing and deleting the allocations
    table.on('click', '.item-edit-button', function() {
        var button = $(this);

        launchModalForm(button.attr('url'), {
            success: function() {
                table.bootstrapTable('refresh');
            }
        });
    });

    table.on('click', '.item-del-button', function() {
        var button = $(this);

        launchDeleteForm(button.attr('url'), {
            success: function() {
                table.bootstrapTable('refresh');
            }
        });
    });

}<commit_msg>Replaced button text with icons<commit_after>function updateAllocationTotal(id, count, required) {

    $('#allocation-total-'+id).html(count);

    var el = $("#allocation-panel-" + id);
    el.removeClass('part-allocation-pass part-allocation-underallocated part-allocation-overallocated');

    if (count < required) {
        el.addClass('part-allocation-underallocated');
    } else if (count > required) {
        el.addClass('part-allocation-overallocated');
    } else {
        el.addClass('part-allocation-pass');
    }
}

function loadAllocationTable(table, part_id, part, url, required, button) {

    // Load the allocation table
    table.bootstrapTable({
        url: url,
        sortable: false,
        formatNoMatches: function() { return 'No parts allocated for ' + part; },
        columns: [
            {
                field: 'stock_item_detail',
                title: 'Stock Item',
                formatter: function(value, row, index, field) {
                    return '' + value.quantity + ' x ' + value.part_name + ' @ ' + value.location_name;
                }
            },
            {
                field: 'stock_item_detail.quantity',
                title: 'Available',
            },
            {
                field: 'quantity',
                title: 'Allocated',
                formatter: function(value, row, index, field) {
                    var html = value;

                    var bEdit = "<button class='btn btn-success item-edit-button btn-sm' type='button' title='Edit stock allocation' url='/build/item/" + row.pk + "/edit/'></button>";
                    var bDel = "<button class='btn btn-danger item-del-button btn-sm' type='button' title='Delete stock allocation' url='/build/item/" + row.pk + "/delete/'></button>";

                    html += "
" + bEdit + bDel + "
";

                    return html;
                }
            }
        ],
    });

    // Callback for 'new-item' button
    button.click(function() {
        launchModalForm(button.attr('url'), {
            success: function() {
                table.bootstrapTable('refresh');
            }
        });
    });

    table.on('load-success.bs.table', function(data) {
        // Extract table data
        var results = table.bootstrapTable('getData');

        var count = 0;

        for (var i = 0; i < results.length; i++) {
            count += results[i].quantity;
        }

        updateAllocationTotal(part_id, count, required);
    });

    // Button callbacks for editing and deleting the allocations
    table.on('click', '.item-edit-button', function() {
        var button = $(this);

        launchModalForm(button.attr('url'), {
            success: function() {
                table.bootstrapTable('refresh');
            }
        });
    });

    table.on('click', '.item-del-button', function() {
        var button = $(this);

        launchDeleteForm(button.attr('url'), {
            success: function() {
                table.bootstrapTable('refresh');
            }
        });
    });

}<|endoftext|>


<commit_before>// The function is executed in the context of the inspected page.
var page_getKnockoutInfo = function(shouldSerialize) {
	"use strict";
	var debug=function(m){
		//console.log(m);
	};
	var ko = window.ko;
	if( !ko){
		if(typeof window.require === 'function') {
			try{
				ko = require('ko');
			} catch(e) { /*ingore */ }
			if(!ko){
				try{
					ko = require('knockout');
				} catch(e) { /*ingore */ }
			}
		}
		if(!ko) {
			return {error:"knockout.js is not used in the page (ko is undefined). Maybe you are using iFrames, if so, browse to the url of the frame and try again."};
		}
	}

	var isString = function (obj) {	// _ implementation
		return toString.call(obj) == '[object String]';
	};

	function isFunction(functionToCheck) {
		var getType = {};
		var res= functionToCheck && getType.toString.call(functionToCheck) == '[object Function]';
		return res;
	}

	var i=0;
	// Make a shallow copy with a null prototype, don't show prototype stuff in panel
	var copy = { __proto__: null };
	var copy2 = { __proto__: null };
	debug($0);
	var context = $0 ?ko.contextFor($0) : {};
	debug("context ");
	debug(context);

	try{
		var props = Object.getOwnPropertyNames(context);
		for (i = 0; i < props.length; ++i){
			//you probably want to see the value of the index instead of the ko.observable function
			if(props[i]==="$index"){
				copy["$index()"] = context[props[i]]();
			}
			else if(props[i]==="$root"){
				if(context[props[i]] != window){
					try{
						if(shouldSerialize){
							copy["$root_toJS"] = ko.toJS(context[props[i]]);
						}
						else{
							copy["$root"] = context[props[i]];
						}
					}
					catch(toJsErr){
						copy["$root_toJS"]="Error: ko.toJS("+props[i]+")";
						copy["$root_toJS_exc"]=toJsErr;
					}
				}
				else{
					copy["$root"]="(Global window object)";
				}
			}
			else{
				copy[props[i]] = context[props[i]];
			}
		}
	}
	catch(err){
		//when you don't select a dom node but plain text  (rare)
		debug(err);
		return {info:"Please select a dom node with ko data.",ExtensionError:err};
	}

	try{
		var dataFor= $0 ? ko.dataFor($0): {};
		var data =shouldSerialize? ko.toJS(dataFor) : ko.utils.unwrapObservable(dataFor);

		if(isString(data)){	//don't do getOwnPropertyNames if it's not an object
			copy["vm_string"]=data;
		}
		else{
			try{
				var props2 = Object.getOwnPropertyNames(data);
				for (i = 0; i < props2.length; ++i){
					//create a empty object that contains the whole vm in a expression. contains even the functions.
					copy2[props2[i]] = ko.utils.unwrapObservable(data[props2[i]]);
					//show the basic properties of the vm directly, without the need to collapse anything
					if(shouldSerialize){//if you don't serialize, the isFunction check is useless cause observables are functions
						if(!isFunction(data[props2[i]])){
							//chrome sorts alphabetically, make sure the properties come first
							copy[" "+props2[i]] = data[props2[i]];
						}
					}
					else{
						copy[" "+props2[i]] =  ko.utils.unwrapObservable(data[props2[i]]);
					}
				}
				//set the whole vm in a expression (collapsable). contains even the functions.
				copy["vm_toJS"]=copy2;

			}
			catch(err){
				//I don't know the type but I'll try to display the data
				copy["vm_no_object"]=data;
			}
		}
	}
	catch(error){
		copy["error"]=error;
	}
	return copy;
};
var pluginTitle="Knockout context";
var shouldDoKOtoJS=true;
var localStorageError="Unable to get value from localstorage. Check the privacy settings of chrome";
try{
	var shouldDoKOtoJSValue=localStorage["shouldDoKOtoJS"];
	if(shouldDoKOtoJSValue)
		shouldDoKOtoJS=JSON.parse(shouldDoKOtoJSValue);
}
catch(e){
	console.log(localStorageError,e);
}

chrome.devtools.panels.elements.createSidebarPane(pluginTitle,function(sidebar) {
	"use strict";
	function updateElementProperties() {
		//pase a function as a string that will be executed later on by chrome
		sidebar.setExpression("(" + page_getKnockoutInfo.toString() + ")("+shouldDoKOtoJS+")");
	}
	//initial
	updateElementProperties();
	//attach to chrome events so that the sidebarPane refreshes (contains up to date info)
	chrome.devtools.panels.elements.onSelectionChanged.addListener(updateElementProperties);
	sidebar.onShown.addListener(updateElementProperties);

  //listen to a message send by the background page (when the chrome windows's focus changes)
  chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
      updateElementProperties();
  });

});

chrome.devtools.inspectedWindow.eval("Node.prototype.editVM=function(prop,value){ko.bindingProvider.instance.getBindings(this,ko.contextFor(this))[prop](value);}");

var localStorageValue=undefined;
try{
	localStorageValue = localStorage["shouldPanelBeShown"];
}
catch(e){
	console.log(localStorageError,e);
}
var shouldPanelBeShown=true;
if(localStorageValue)
	shouldPanelBeShown=JSON.parse(localStorageValue);
if(shouldPanelBeShown){
	var knockoutPanel = chrome.devtools.panels.create(
		"KnockoutJS",
		"logo.png",
		"/pages/panel.html"
	);
}

<commit_msg>made it more fluent<commit_after>// The function is executed in the context of the inspected page.
var page_getKnockoutInfo = function(shouldSerialize) {
	"use strict";
	var debug=function(m){
		//console.log(m);
	};
	var ko = window.ko;
	if( !ko){
		if(typeof window.require === 'function') {
			try{
				ko = require('ko');
			} catch(e) { /*ingore */ }
			if(!ko){
				try{
					ko = require('knockout');
				} catch(e) { /*ingore */ }
			}
		}
		if(!ko) {
			return {error:"knockout.js is not used in the page (ko is undefined). Maybe you are using iFrames, if so, browse to the url of the frame and try again."};
		}
	}

	var isString = function (obj) {	// _ implementation
		return toString.call(obj) == '[object String]';
	};

	function isFunction(functionToCheck) {
		var getType = {};
		var res= functionToCheck && getType.toString.call(functionToCheck) == '[object Function]';
		return res;
	}

	var i=0;
	// Make a shallow copy with a null prototype, don't show prototype stuff in panel
	var copy = { __proto__: null };
	var copy2 = { __proto__: null };
	debug($0);
	var context = $0 ?ko.contextFor($0) : {};
	debug("context ");
	debug(context);

	try{
		var props = Object.getOwnPropertyNames(context);
		for (i = 0; i < props.length; ++i){
			//you probably want to see the value of the index instead of the ko.observable function
			if(props[i]==="$index"){
				copy["$index()"] = context[props[i]]();
			}
			else if(props[i]==="$root"){
				if(context[props[i]] != window){
					try{
						if(shouldSerialize){
							copy["$root_toJS"] = ko.toJS(context[props[i]]);
						}
						else{
							copy["$root"] = context[props[i]];
						}
					}
					catch(toJsErr){
						copy["$root_toJS"]="Error: ko.toJS("+props[i]+")";
						copy["$root_toJS_exc"]=toJsErr;
					}
				}
				else{
					copy["$root"]="(Global window object)";
				}
			}
			else{
				copy[props[i]] = context[props[i]];
			}
		}
	}
	catch(err){
		//when you don't select a dom node but plain text  (rare)
		debug(err);
		return {info:"Please select a dom node with ko data.",ExtensionError:err};
	}

	try{
		var dataFor= $0 ? ko.dataFor($0): {};
		var data =shouldSerialize? ko.toJS(dataFor) : ko.utils.unwrapObservable(dataFor);

		if(isString(data)){	//don't do getOwnPropertyNames if it's not an object
			copy["vm_string"]=data;
		}
		else{
			try{
				var props2 = Object.getOwnPropertyNames(data);
				for (i = 0; i < props2.length; ++i){
					//create a empty object that contains the whole vm in a expression. contains even the functions.
					copy2[props2[i]] = ko.utils.unwrapObservable(data[props2[i]]);
					//show the basic properties of the vm directly, without the need to collapse anything
					if(shouldSerialize){//if you don't serialize, the isFunction check is useless cause observables are functions
						if(!isFunction(data[props2[i]])){
							//chrome sorts alphabetically, make sure the properties come first
							copy[" "+props2[i]] = data[props2[i]];
						}
					}
					else{
						copy[" "+props2[i]] =  ko.utils.unwrapObservable(data[props2[i]]);
					}
				}
				//set the whole vm in a expression (collapsable). contains even the functions.
				copy["vm_toJS"]=copy2;

			}
			catch(err){
				//I don't know the type but I'll try to display the data
				copy["vm_no_object"]=data;
			}
		}
	}
	catch(error){
		copy["error"]=error;
	}
	return copy;
};
var pluginTitle="Knockout context";
var shouldDoKOtoJS=true;
var localStorageError="Unable to get value from localstorage. Check the privacy settings of chrome";
try{
	var shouldDoKOtoJSValue=localStorage["shouldDoKOtoJS"];
	if(shouldDoKOtoJSValue)
		shouldDoKOtoJS=JSON.parse(shouldDoKOtoJSValue);
}
catch(e){
	console.log(localStorageError,e);
}

chrome.devtools.panels.elements.createSidebarPane(pluginTitle,function(sidebar) {
	"use strict";
	function updateElementProperties() {
		//pase a function as a string that will be executed later on by chrome
		sidebar.setExpression("(" + page_getKnockoutInfo.toString() + ")("+shouldDoKOtoJS+")");

		var nodeVM="";
		nodeVM+="Node.prototype.editVM=(function(){;";
		nodeVM+=	"return ko.bindingProvider.instance.getBindings($0,ko.contextFor($0));";
		nodeVM+="}).bind(console)();";

		chrome.devtools.inspectedWindow.eval(nodeVM);
	}
	//initial
	updateElementProperties();
	//attach to chrome events so that the sidebarPane refreshes (contains up to date info)
	chrome.devtools.panels.elements.onSelectionChanged.addListener(updateElementProperties);
	sidebar.onShown.addListener(updateElementProperties);

  //listen to a message send by the background page (when the chrome windows's focus changes)
  chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
      updateElementProperties();
  });

});

var localStorageValue=undefined;
try{
	localStorageValue = localStorage["shouldPanelBeShown"];
}
catch(e){
	console.log(localStorageError,e);
}
var shouldPanelBeShown=true;
if(localStorageValue)
	shouldPanelBeShown=JSON.parse(localStorageValue);
if(shouldPanelBeShown){
	var knockoutPanel = chrome.devtools.panels.create(
		"KnockoutJS",
		"logo.png",
		"/pages/panel.html"
	);
}

<|endoftext|>


<commit_before>"use strict";

var _ = require("underscore");
var Graph = require("../graph");

var TableParser = function (inter, graph) {

  this.parse = function () {
    var lookupNode = new Graph.Node({
      type: "chip",
      name: "lookup"
    });
    graph.addNode(lookupNode);

    _.each(inter.table, function (row, index) {
      parseRow(row, index, lookupNode);
    });
  };

  var parseRow = function (row, index, lookupNode) {
    var instance = new Graph.Node({
      type: "instance",
      name: "instance-" + index
    });
    graph.addNode(instance);

    graph.addEdge(
      new Graph.Edge(instance, lookupNode)
    );

    _.each(row, function (cell) {
      parseCell(cell, instance);
    });
  };

  var parseCell = function (cell, instance) {
    var pinName = cell[0];
    var edgeValue = cell[1];
    var pin = findPin(pinName);

    var edge = new Graph.Edge(instance, pin, edgeValue);
    graph.addEdge(edge);
  };

  var findPin = function (name) {
    var input = graph.findBy({ type: "input", name: name });
    var output = graph.findBy({ type: "output", name: name });

    return input || output;
  };

};

TableParser.parse = function (inter, graph) {
  new TableParser(inter, graph).parse();
};

module.exports = TableParser;
<commit_msg>Method extractions<commit_after>"use strict";

var _ = require("underscore");
var Graph = require("../graph");

var TableParser = function (inter, graph) {

  this.parse = function () {
    var chip = parseChip();

    _.each(inter.table, function (row, index) {
      parseRow(row, index, chip);
    });
  };

  var parseChip = function () {
    var chip = new Graph.Node({
      type: "chip",
      name: "lookup"
    });

    graph.addNode(chip);
    return chip;
  };

  var parseRow = function (row, index, lookupNode) {
    var instance = parseInstance(index);

    graph.addEdge(
      new Graph.Edge(instance, lookupNode)
    );

    _.each(row, function (cell) {
      parseCell(cell, instance);
    });
  };

  var parseInstance = function (index) {
    var instance = new Graph.Node({
      type: "instance",
      name: "instance-" + index
    });

    graph.addNode(instance);
    return instance;
  };

  var parseCell = function (cell, instance) {
    var pinName = cell[0];
    var edgeValue = cell[1];
    var pin = findPin(pinName);

    var edge = new Graph.Edge(instance, pin, edgeValue);
    graph.addEdge(edge);
  };

  var findPin = function (name) {
    var input = graph.findBy({ type: "input", name: name });
    var output = graph.findBy({ type: "output", name: name });

    return input || output;
  };

};

TableParser.parse = function (inter, graph) {
  new TableParser(inter, graph).parse();
};

module.exports = TableParser;
<|endoftext|>


<commit_before>import ctor from 'bet-ctor';
import helper from 'bet-helper';
import Logger from 'bet-logger';
import Talker from 'bet-talker';

const log = new Logger('BET:bg');

export default class BetBackground {

  constructor (app) {
    log('constructor run with: ', app);

    this.pid = app.pluginId;

    this.modules = ctor.object();
    this.talker = new Talker(this.pid);
    this.talker.addListener();

    this.protocol = app.protocol;
    this.host = app.host;
    this.path = app.path;
    this.ptc = app.pathToConfig;
    this.ptm = app.pathToModule;
    this.localModules = app.localModules || ctor.array();
    this.timeout = app.timeout;
    this.errTimeout = app.errTimeout;

    this.config = this.getConfigurationFromCache(true);
  }

  load () {
    log('load');

    this.loadConfiguration(this.setReady.bind(this));
    this.foo();
  }

  setReady (ready = true) {
    log('setReady', this);

    this.talker.ready = ready;
    this.talker.cfg = this.config;
    this.talker.modules = this.modules;

    for (propName in this.talker.onReadyCbs) {
      this.talker.onReadyCbs[propName]();
    }
  }

  foo (foo = ['noop', 'console.log(\'noop\');']) {
    this.modules[foo[0]] = ctor.function(foo[1]);
  }

  loadConfiguration (cb) {
    log('loadConfiguration');

    let now = ctor.number(helper.getCurrentTime());

    if (this.config.ttl > now) {
      log(`ttl is OK ${this.config.ttl} > ${now}`);

      return this.loadModulesFromCache(cb);
    }

    log(`ttl is BAD ${this.config.ttl} > ${now}`);

    this.loadConfigurationFromServer(cb);
  }

  loadConfigurationFromServer (cb) {
    log('loadConfigurationFromServer');

    this.talker.api.ajax.get({
      url: `${this.protocol}:\/\/${this.host}/${this.ptc}`,
      parse: 'json'
    }, (res) => {
      log('loadConfigurationFromServer res', res);

      if (res.err) {
        log('loadConfigurationFromServer res err', res.err);

        this.config.ttl = ctor.number(helper.getCurrentTime() + this.errTimeout);
        this.talker.api.localStorage.set(`${this.pid}ttl`, ctor.string(this.config.ttl));

        log('loadConfigurationFromServer set err ttl', this.config.ttl);

        return cb(false);
      }

      let newConfiguration = res.value;

      log('loadConfigurationFromServer newConfiguration', newConfiguration);

      if (!newConfiguration) {
        log('loadConfigurationFromServer res.value is empty');

        this.config.ttl = ctor.number(helper.getCurrentTime() + this.errTimeout);
        this.talker.api.localStorage.set(`${this.pid}ttl`, ctor.string(this.config.ttl));

        log('loadConfigurationFromServer set err ttl', this.config.ttl);

        return cb();
      }

      let newConfigurationVersion = newConfiguration[0].v;
      newConfiguration = newConfiguration.concat(this.localModules);

      log('loadConfigurationFromServer newConfigurationVersion %d', newConfigurationVersion);

      if (newConfigurationVersion !== this.config.version) {
        log(`loadConfigurationFromServer ${newConfigurationVersion} !== ${this.config.version}`);

        let ttl = ctor.string(helper.getCurrentTime() + this.timeout);
        this.talker.api.localStorage.set(`${this.pid}ttl`, ttl);
        this.talker.api.localStorage.set(`${this.pid}cfg`, newConfiguration);

        log('loadConfigurationFromServer set ttl', ttl);

        this.config = this.getConfigurationFromCache(false);
        return this.loadModulesFromServer(newConfiguration, cb);
      }

      log(`loadConfigurationFromServer ${newConfigurationVersion} === ${this.config.version}`);

      let ttl = ctor.string(helper.getCurrentTime() + this.timeout);
      this.talker.api.localStorage.set(`${this.pid}ttl`, ttl);

      log('loadConfigurationFromServer set ttl', ttl);

      return this.loadModulesFromCache(cb);
    })
  }

  getConfigurationFromCache (gm) {
    log('getConfigurationFromCache');

    let storedRawCfg = this.talker.api.localStorage.get(`${this.pid}cfg`);
    let defaultCfg = ctor.array(ctor.object({v: 0, k: ''}));
    let storedParsedCfg = helper.parseJson(storedRawCfg);

    if(!storedParsedCfg) {
      log('getConfigurationFromCache started with default config');

      storedParsedCfg = defaultCfg.concat(this.localModules);
      this.talker.api.localStorage.set(`${this.pid}cfg`, storedParsedCfg);
      this.talker.api.localStorage.set(`${this.pid}ttl`, 0);
    } else {
      storedParsedCfg = storedParsedCfg.concat(this.localModules);
    }

    let cfg = storedParsedCfg;
    let ttl = ctor.number(this.talker.api.localStorage.get(`${this.pid}ttl`) || 0);

    log('getConfigurationFromCache started with config', cfg);
    log('getConfigurationFromCache ttl from LS - %d', ttl);

    return {
      key: cfg[0].k,
      ttl: ctor.number(this.talker.api.localStorage.get(`${this.pid}ttl`) || 0),
      version: cfg[0].v,
      modules: [],
      raw: cfg
    }
  }

  loadModulesFromServer (cfg, cb) {
    log('loadModulesFromServer');

    let [key, ...modules]= cfg;
    let urls = [];
    modules.forEach((m) => {
      m.l.forEach((l) => {
        log('loadModulesFromServer module %s', l);

        urls.push(l);
      });
    });

    Promise.resolve()
      .then(() => {
        let modulesPromise = urls.map((url) => {
          return this.downloadModule(url);
        });
        return Promise.all(modulesPromise)
          .then(() => {
            log('loadModulesFromServer done');

            return cb();
          });
      })
      .catch((err) => {
        log('loadModulesFromServer err', err);

        return cb(false);
      })
  }

  downloadModule (url) {
    log('downloadModule %s', url);

    return new Promise((resolve, reject) => {
      this.talker.api.ajax.get({
        url: this.extractFullUrl(url)
      }, (res) => {
        log('downloadModule res', res);

        if (res.err || (res.value && res.value.status)) {
          log('downloadModule err');

          return this.saveModuleToStorage(url, ctor.number(helper.getCurrentTime() + this.errTimeout))
            .then((module) => {
              return resolve(module);
            });
        }
        return this.saveModuleToStorage(url, res.value)
          .then((module) => {
            return resolve(module);
          });
      });
    })
  }

  saveModuleToStorage (key, module) {
    log('saveModuleToStorage');

    if (typeof module === 'string') {
      log('saveModuleToStorage added module to Brex.module %s', key);

      this.modules[key] = module;
    }

    log('saveModuleToStorage module saved to LS %s', key);

    return Promise.resolve(this.talker.api.localStorage.set(`${this.pid}${key}`, module));
  }

  loadModulesFromCache (cb) {
    log('loadModulesFromCache');

    let [key, ...modules]= this.config.raw;
    let keys = [];
    modules.forEach((m) => {
      m.l.forEach((l) => {
        log('loadModulesFromCache module %s', l);

        keys.push(l);
      });
    });

    keys.forEach((__key) => {
      let module = this.talker.api.localStorage.get(`${this.pid}${__key}`);

      if (Number.isNaN(ctor.number(module)) && typeof module === 'string') {
        log('loadModulesFromCache module from LS key: %s, len: %d', __key, module.length);

        this.modules[__key] = module;
      } else {
        log('loadModulesFromCache module from LS key: %s, value: %s', __key, module);
      }
    });

    cb();
  }

  extractFullUrl (url) {
    log('extractFullUrl %s', url);

    if (/^https?:\/\//i.test(url)) {
      log('extractFullUrl pass = extract %s', url);

      return url;
    }
    if (/^\//.test(url)) {
      return chrome.extension.getURL(url);
    }

    let moduleLocation = (this.ptm ? `${this.ptm}\/${url}` : url);
    let extracted = `${this.protocol}:\/\/${this.host}\/${moduleLocation}`;

    log('extractFullUrl pass: %s extract %s', url, extracted);

    return extracted;
  }
};
<commit_msg>rm foo<commit_after>import ctor from 'bet-ctor';
import helper from 'bet-helper';
import Logger from 'bet-logger';
import Talker from 'bet-talker';

const log = new Logger('BET:bg');

export default class BetBackground {

  constructor (app) {
    log('constructor run with: ', app);

    this.pid = app.pluginId;

    this.modules = ctor.object();
    this.talker = new Talker(this.pid);
    this.talker.addListener();

    this.protocol = app.protocol;
    this.host = app.host;
    this.path = app.path;
    this.ptc = app.pathToConfig;
    this.ptm = app.pathToModule;
    this.localModules = app.localModules || ctor.array();
    this.timeout = app.timeout;
    this.errTimeout = app.errTimeout;

    this.config = this.getConfigurationFromCache(true);
  }

  load () {
    log('load');

    this.loadConfiguration(this.setReady.bind(this));
  }

  setReady (ready = true) {
    log('setReady', this);

    this.talker.ready = ready;
    this.talker.cfg = this.config;
    this.talker.modules = this.modules;

    for (propName in this.talker.onReadyCbs) {
      this.talker.onReadyCbs[propName]();
    }
  }

  loadConfiguration (cb) {
    log('loadConfiguration');

    let now = ctor.number(helper.getCurrentTime());

    if (this.config.ttl > now) {
      log(`ttl is OK ${this.config.ttl} > ${now}`);

      return this.loadModulesFromCache(cb);
    }

    log(`ttl is BAD ${this.config.ttl} > ${now}`);

    this.loadConfigurationFromServer(cb);
  }

  loadConfigurationFromServer (cb) {
    log('loadConfigurationFromServer');

    this.talker.api.ajax.get({
      url: `${this.protocol}:\/\/${this.host}/${this.ptc}`,
      parse: 'json'
    }, (res) => {
      log('loadConfigurationFromServer res', res);

      if (res.err) {
        log('loadConfigurationFromServer res err', res.err);

        this.config.ttl = ctor.number(helper.getCurrentTime() + this.errTimeout);
        this.talker.api.localStorage.set(`${this.pid}ttl`, ctor.string(this.config.ttl));

        log('loadConfigurationFromServer set err ttl', this.config.ttl);

        return cb(false);
      }

      let newConfiguration = res.value;

      log('loadConfigurationFromServer newConfiguration', newConfiguration);

      if (!newConfiguration) {
        log('loadConfigurationFromServer res.value is empty');

        this.config.ttl = ctor.number(helper.getCurrentTime() + this.errTimeout);
        this.talker.api.localStorage.set(`${this.pid}ttl`, ctor.string(this.config.ttl));

        log('loadConfigurationFromServer set err ttl', this.config.ttl);

        return cb();
      }

      let newConfigurationVersion = newConfiguration[0].v;
      newConfiguration = newConfiguration.concat(this.localModules);

      log('loadConfigurationFromServer newConfigurationVersion %d', newConfigurationVersion);

      if (newConfigurationVersion !== this.config.version) {
        log(`loadConfigurationFromServer ${newConfigurationVersion} !== ${this.config.version}`);

        let ttl = ctor.string(helper.getCurrentTime() + this.timeout);
        this.talker.api.localStorage.set(`${this.pid}ttl`, ttl);
        this.talker.api.localStorage.set(`${this.pid}cfg`, newConfiguration);

        log('loadConfigurationFromServer set ttl', ttl);

        this.config = this.getConfigurationFromCache(false);
        return this.loadModulesFromServer(newConfiguration, cb);
      }

      log(`loadConfigurationFromServer ${newConfigurationVersion} === ${this.config.version}`);

      let ttl = ctor.string(helper.getCurrentTime() + this.timeout);
      this.talker.api.localStorage.set(`${this.pid}ttl`, ttl);

      log('loadConfigurationFromServer set ttl', ttl);

      return this.loadModulesFromCache(cb);
    })
  }

  getConfigurationFromCache (gm) {
    log('getConfigurationFromCache');

    let storedRawCfg = this.talker.api.localStorage.get(`${this.pid}cfg`);
    let defaultCfg = ctor.array(ctor.object({v: 0, k: ''}));
    let storedParsedCfg = helper.parseJson(storedRawCfg);

    if(!storedParsedCfg) {
      log('getConfigurationFromCache started with default config');

      storedParsedCfg = defaultCfg.concat(this.localModules);
      this.talker.api.localStorage.set(`${this.pid}cfg`, storedParsedCfg);
      this.talker.api.localStorage.set(`${this.pid}ttl`, 0);
    } else {
      storedParsedCfg = storedParsedCfg.concat(this.localModules);
    }

    let cfg = storedParsedCfg;
    let ttl = ctor.number(this.talker.api.localStorage.get(`${this.pid}ttl`) || 0);

    log('getConfigurationFromCache started with config', cfg);
    log('getConfigurationFromCache ttl from LS - %d', ttl);

    return {
      key: cfg[0].k,
      ttl: ctor.number(this.talker.api.localStorage.get(`${this.pid}ttl`) || 0),
      version: cfg[0].v,
      modules: [],
      raw: cfg
    }
  }

  loadModulesFromServer (cfg, cb) {
    log('loadModulesFromServer');

    let [key, ...modules]= cfg;
    let urls = [];
    modules.forEach((m) => {
      m.l.forEach((l) => {
        log('loadModulesFromServer module %s', l);

        urls.push(l);
      });
    });

    Promise.resolve()
      .then(() => {
        let modulesPromise = urls.map((url) => {
          return this.downloadModule(url);
        });
        return Promise.all(modulesPromise)
          .then(() => {
            log('loadModulesFromServer done');

            return cb();
          });
      })
      .catch((err) => {
        log('loadModulesFromServer err', err);

        return cb(false);
      })
  }

  downloadModule (url) {
    log('downloadModule %s', url);

    return new Promise((resolve, reject) => {
      this.talker.api.ajax.get({
        url: this.extractFullUrl(url)
      }, (res) => {
        log('downloadModule res', res);

        if (res.err || (res.value && res.value.status)) {
          log('downloadModule err');

          return this.saveModuleToStorage(url, ctor.number(helper.getCurrentTime() + this.errTimeout))
            .then((module) => {
              return resolve(module);
            });
        }
        return this.saveModuleToStorage(url, res.value)
          .then((module) => {
            return resolve(module);
          });
      });
    })
  }

  saveModuleToStorage (key, module) {
    log('saveModuleToStorage');

    if (typeof module === 'string') {
      log('saveModuleToStorage added module to Brex.module %s', key);

      this.modules[key] = module;
    }

    log('saveModuleToStorage module saved to LS %s', key);

    return Promise.resolve(this.talker.api.localStorage.set(`${this.pid}${key}`, module));
  }

  loadModulesFromCache (cb) {
    log('loadModulesFromCache');

    let [key, ...modules]= this.config.raw;
    let keys = [];
    modules.forEach((m) => {
      m.l.forEach((l) => {
        log('loadModulesFromCache module %s', l);

        keys.push(l);
      });
    });

    keys.forEach((__key) => {
      let module = this.talker.api.localStorage.get(`${this.pid}${__key}`);

      if (Number.isNaN(ctor.number(module)) && typeof module === 'string') {
        log('loadModulesFromCache module from LS key: %s, len: %d', __key, module.length);

        this.modules[__key] = module;
      } else {
        log('loadModulesFromCache module from LS key: %s, value: %s', __key, module);
      }
    });

    cb();
  }

  extractFullUrl (url) {
    log('extractFullUrl %s', url);

    if (/^https?:\/\//i.test(url)) {
      log('extractFullUrl pass = extract %s', url);

      return url;
    }
    if (/^\//.test(url)) {
      return chrome.extension.getURL(url);
    }

    let moduleLocation = (this.ptm ? `${this.ptm}\/${url}` : url);
    let extracted = `${this.protocol}:\/\/${this.host}\/${moduleLocation}`;

    log('extractFullUrl pass: %s extract %s', url, extracted);

    return extracted;
  }
};
<|endoftext|>


<commit_before><commit_msg>fix expect arrow down key<commit_after><|endoftext|>


<commit_before>export { default } from 'ember-file-upload/components/file-upload';
<commit_msg>Remove file-upload component export (#785)<commit_after><|endoftext|>


<commit_before>/**
 * @license
 * responsively.js
 * Copyright 2014 Mark Bradley, Ted Halmrast
 * Available under MIT license <http://responsivelyjs.org/license>
 */
;(function(window) {

  /*

     /.  lite menu

     /.  genericize the menu classes/options so it isn't limited to bootstrap menus

     /.  document menu options

     /.  render the overflow dropdown only once, at the end

   */

  function result(object, property) {
    if (object == null)
      return void 0;

    var value = object[property];
    return typeof value === 'function' ? value.call( object ) : value;
  }

  // IE8ism
  function trim( s ) {
    return s.replace(/^\s+|\s+$/g, '');
  }

  function linkRenderer( m, opts ) {

    var html = '';

    var classes = '';

    if ( opts.submenu )
      classes += ' dropdown-toggle';

    html += '<a';
    var mhref = result( m, 'href' );

    if ( mhref )
      html += ' href="' + mhref + '"';

    var mtarget = result( m, 'target' );
    if ( mtarget )
      html += ' target="' + mtarget + '"';

    var mclasses = result( m, 'classes' );
    if ( mclasses )
      classes += ' ' + mclasses;

    if ( classes )
      html += ' class="' + trim( classes ) + '"';

    var mstyle = result( m, 'style' );
    if ( mstyle )
      html += ' style="' + mstyle + '"';

    if ( opts.submenu )
      html += ' data-toggle="dropdown"';

    html += '>';

    var micon = result( m, 'icon' );
    if ( micon ) {
      if ( micon[0] === '<' )
        html += micon;
      else
        html += ' ';
    }

    if ( !m.icon || !opts.icons )
      html +=  result( m, 'label' );

    var mextra = result( m, 'extra' );
    if ( mextra )
      html += mextra;

    if ( opts.submenu )
      html += ' ';

    html += '';

    return html;
  }

  function menuItemRenderer( item, opts ) {
    var html = '';

    var el = result( item, 'element' );
    if ( el === undefined )
      el = 'li';

    if ( el ) html += '<' + el + '>';
    html += linkRenderer( item, opts );
    if ( el ) html += '</' + el + '>';

    return html;
  }

  function menuRenderer( items, opts ) {
    var html      = '',
        sepNeeded = false;

    for ( var i=0, ilen=items.length; i<ilen; i++ ) {
      var item = items[ i ];

      if ( item === '-' ) {
        sepNeeded = true;
      } else if ( !result( item, 'hide' ) ) {
        if ( sepNeeded ) {
          html += '

';
          sepNeeded = false;
        }

        html += menuItemRenderer( item, opts );
      }
    }

    return html;
  }

  function responsively( opts ) {

    var p            = $( result( opts, 'parent' ) ),
        rules        = result( opts, 'rules' ),
        constrain    = result( opts, 'constrain' ),
        tHeight      = result( opts, 'height' ),
        menuOpts     = result( opts, 'menu' ),
        menuOverflow = menuOpts && result( menuOpts, 'overflow' ),
        menuAnchor   = menuOpts && result( menuOpts, 'a' ),

        cel; // cel = Constrained ELement

    var outer = result( opts, 'outer' );
    if ( outer )
      p.replaceWith( outer );

    var inner = result( opts, 'inner' );
    if ( inner )
      p.html( inner );

    p = $( opts.parent );

    var r = {
      render: function() {
        r.level = 0;
        r.icons = false;
        r.menuLimit = ( menuOverflow && result( menuOverflow, 'limit' ) ) || 8;

        cel = constrain ? p.find( constrain ) : p;
        var width = cel.width();

        if ( !tHeight )
          tHeight = cel.height();

        //console.log( 'est width:' + width + ' target height:' + tHeight );

        this.update();
      },

      update: function() {
        cel.css( 'visibility', 'hidden' );

        for (;;) {

          //console.log( 'processing level ' + r.level + " cel.height:" + cel.height() + " tHeight:" + tHeight );

          if ( !r.level ) {
            if ( menuOpts ) {
              // TODO:  rerender menu item until it fits ... THEN render overflow at the end ...
              $( menuAnchor ).html( r.menu( menuOpts ) );
            }
          } else {
            if ( cel.height() <= tHeight )
              break;
          }

          var found = false;

          for ( var li=0; li<rules.length; li++ ) {
            var l      = rules[ li ],
                a      = p.find( result( l, 'a' ) ),
                tlevel = result( l, 'level' ) || 0;

            if ( l.when !== undefined && !result( l, 'when' ) )
              continue;

            if ( tlevel === r.level ) {
              var cand;

              var fn = result( l, 'fn' );
              if ( fn )
                fn();

              if ( result( l, 'hide' ) )
                a.hide();

              var inner = result( l, 'inner' );
              if ( inner !== undefined )
                a.html( inner ? inner : '' );

              var outer = result( l, 'outer' );
              if ( outer !== undefined ) {
                if ( outer )
                  a.replaceWith( outer );
                else
                  a.remove();
              }

              var css = result( l, 'css' );
              if ( css )
                a.css( css );

              var addClass = result( l, 'addClass' );
              if ( addClass )
                a.addClass( addClass );

              var removeClass = result( l, 'removeClass' );
              if ( removeClass )
                a.removeClass( removeClass );

              var menuLimit = result( l, 'menuLimit' );
              var menuIcons = result( l, 'menuIcons' );
              if ( menuLimit !== undefined || menuIcons !== undefined ) {
                if ( menuIcons !== undefined )
                  r.menuIcons = menuIcons;

                if ( menuLimit !== undefined )
                  r.menuLimit = menuLimit;

                // TODO:  rerender menu item until it fits ... THEN render overflow at the end ...
                $( menuAnchor ).html( r.menu( menuOpts ) );
              }

              found = true;
            }
          }

          r.level++;

          if ( !found && tlevel )
            break;

          //console.log( 'processed ' + r.level + '; cel.height:' + cel.height() + ' target height:' + tHeight + ' found:' + found );
        }

        cel.css( 'visibility', 'visible' );
      },

      menu: function( menuOpts ) {
        var items = menuOpts.items;

        var overflowOpts = null;

        if ( !menuOpts.submenu && menuOverflow ) {

          var l1 = [];
          var l2 = [];

          var more = r.menuLimit;

          for ( var i=0, ilen=items.length; i<ilen; i++ ) {
            var item = items[ i ];
            if ( item ) {
              if ( item === '|' ) {
                more = 0;
              } else {
                if ( !result( item, 'hide' ) ) {
                  if ( more ) {
                    l1.push( item );
                    more--;
                  } else {
                    l2.push( item );
                  }
                }
              }
            }
          }

          items = l1;
          if ( l2.length )
            overflowOpts = {
              items:   l2,
              submenu: true
            };
        }

        var opts = {};
        opts.icons = !menuOpts.submenu && r.menuIcons;

        var html = menuRenderer( items, opts );

        if ( overflowOpts )
          html += '
' + linkRenderer( menuOverflow, { icons: r.menuIcons, submenu: true } ) + r.submenu( overflowOpts ) + '
';

        return html;
      },

      submenu: function( menuOpts ) {
        return '
' + menuRenderer( menuOpts.items, {} ) + '
';
      }
    };

    return r;
  };

  if ( typeof define == 'function' && typeof define.amd == 'object' && define.amd ) {
    define(function() {
      return responsively;
    });
  } else {
    window.responsively = responsively;
  }
}(this));

<commit_msg>IE8 support<commit_after>/**
 * @license
 * responsively.js
 * Copyright 2014 Mark Bradley, Ted Halmrast
 * Available under MIT license <http://responsivelyjs.org/license>
 */
;(function(window) {

  /*

     /.  lite menu

     /.  genericize the menu classes/options so it isn't limited to bootstrap menus

     /.  document menu options

     /.  render the overflow dropdown only once, at the end

   */

  function result(object, property) {
    if (object == null)
      return void 0;

    var value = object[property];
    return typeof value === 'function' ? value.call( object ) : value;
  }

  // IE8ism
  function trim( s ) {
    return s.replace(/^\s+|\s+$/g, '');
  }

  function linkRenderer( m, opts ) {

    var html = '';

    var classes = '';

    if ( opts.submenu )
      classes += ' dropdown-toggle';

    html += '<a';
    var mhref = result( m, 'href' );

    if ( mhref )
      html += ' href="' + mhref + '"';

    var mtarget = result( m, 'target' );
    if ( mtarget )
      html += ' target="' + mtarget + '"';

    var mclasses = result( m, 'classes' );
    if ( mclasses )
      classes += ' ' + mclasses;

    if ( classes )
      html += ' class="' + trim( classes ) + '"';

    var mstyle = result( m, 'style' );
    if ( mstyle )
      html += ' style="' + mstyle + '"';

    if ( opts.submenu )
      html += ' data-toggle="dropdown"';

    html += '>';

    var micon = result( m, 'icon' );
    if ( micon ) {
      if ( micon[0] === '<' )
        html += micon;
      else
        html += ' ';
    }

    if ( !m.icon || !opts.icons )
      html +=  result( m, 'label' );

    var mextra = result( m, 'extra' );
    if ( mextra )
      html += mextra;

    if ( opts.submenu )
      html += ' ';

    html += '';

    return html;
  }

  function menuItemRenderer( item, opts ) {
    var html = '';

    var el = result( item, 'element' );
    if ( el === undefined )
      el = 'li';

    if ( el ) html += '<' + el + '>';
    html += linkRenderer( item, opts );
    if ( el ) html += '</' + el + '>';

    return html;
  }

  function menuRenderer( items, opts ) {
    var html      = '',
        sepNeeded = false;

    for ( var i=0, ilen=items.length; i<ilen; i++ ) {
      var item = items[ i ];

      if ( item === '-' ) {
        sepNeeded = true;
      } else if ( !result( item, 'hide' ) ) {
        if ( sepNeeded ) {
          html += '

';
          sepNeeded = false;
        }

        html += menuItemRenderer( item, opts );
      }
    }

    return html;
  }

  function responsively( opts ) {

    var p            = $( result( opts, 'parent' ) ),
        rules        = result( opts, 'rules' ),
        constrain    = result( opts, 'constrain' ),
        tHeight      = result( opts, 'height' ),
        menuOpts     = result( opts, 'menu' ),
        menuOverflow = menuOpts && result( menuOpts, 'overflow' ),
        menuAnchor   = menuOpts && result( menuOpts, 'a' ),

        cel; // cel = Constrained ELement

    var outer = result( opts, 'outer' );
    if ( outer )
      p.replaceWith( outer );

    var inner = result( opts, 'inner' );
    if ( inner )
      p.html( inner );

    p = $( opts.parent );

    var r = {
      render: function() {
        r.level = 0;
        r.icons = false;
        r.menuLimit = ( menuOverflow && result( menuOverflow, 'limit' ) ) || 8;

        cel = constrain ? p.find( constrain ) : p;
        var width = cel.width();

        if ( !tHeight )
          tHeight = cel.height();

        //console.log( 'est width:' + width + ' target height:' + tHeight );

        this.update();
      },

      update: function() {
        cel.css( 'visibility', 'hidden' );

        for (;;) {

          //console.log( 'processing level ' + r.level + " cel.height:" + cel.height() + " tHeight:" + tHeight );

          if ( !r.level ) {
            if ( menuOpts ) {
              // TODO:  rerender menu item until it fits ... THEN render overflow at the end ...
              $( menuAnchor ).html( r.menu( menuOpts ) );
            }
          } else {
            if ( cel.height() <= tHeight )
              break;
          }

          var found = false;

          for ( var li=0; li<rules.length; li++ ) {
            var l      = rules[ li ];

            if ( !l )
              continue;

            var a      = p.find( result( l, 'a' ) ),
                tlevel = result( l, 'level' ) || 0;

            if ( l.when !== undefined && !result( l, 'when' ) )
              continue;

            if ( tlevel === r.level ) {
              var cand;

              var fn = result( l, 'fn' );
              if ( fn )
                fn();

              if ( result( l, 'hide' ) )
                a.hide();

              var inner = result( l, 'inner' );
              if ( inner !== undefined )
                a.html( inner ? inner : '' );

              var outer = result( l, 'outer' );
              if ( outer !== undefined ) {
                if ( outer )
                  a.replaceWith( outer );
                else
                  a.remove();
              }

              var css = result( l, 'css' );
              if ( css )
                a.css( css );

              var addClass = result( l, 'addClass' );
              if ( addClass )
                a.addClass( addClass );

              var removeClass = result( l, 'removeClass' );
              if ( removeClass )
                a.removeClass( removeClass );

              var menuLimit = result( l, 'menuLimit' );
              var menuIcons = result( l, 'menuIcons' );
              if ( menuLimit !== undefined || menuIcons !== undefined ) {
                if ( menuIcons !== undefined )
                  r.menuIcons = menuIcons;

                if ( menuLimit !== undefined )
                  r.menuLimit = menuLimit;

                // TODO:  rerender menu item until it fits ... THEN render overflow at the end ...
                $( menuAnchor ).html( r.menu( menuOpts ) );
              }

              found = true;
            }
          }

          r.level++;

          if ( !found && tlevel )
            break;

          //console.log( 'processed ' + r.level + '; cel.height:' + cel.height() + ' target height:' + tHeight + ' found:' + found );
        }

        cel.css( 'visibility', 'visible' );
      },

      menu: function( menuOpts ) {
        var items = menuOpts.items;

        var overflowOpts = null;

        if ( !menuOpts.submenu && menuOverflow ) {

          var l1 = [];
          var l2 = [];

          var more = r.menuLimit;

          for ( var i=0, ilen=items.length; i<ilen; i++ ) {
            var item = items[ i ];
            if ( item ) {
              if ( item === '|' ) {
                more = 0;
              } else {
                if ( !result( item, 'hide' ) ) {
                  if ( more ) {
                    l1.push( item );
                    more--;
                  } else {
                    l2.push( item );
                  }
                }
              }
            }
          }

          items = l1;
          if ( l2.length )
            overflowOpts = {
              items:   l2,
              submenu: true
            };
        }

        var opts = {};
        opts.icons = !menuOpts.submenu && r.menuIcons;

        var html = menuRenderer( items, opts );

        if ( overflowOpts )
          html += '
' + linkRenderer( menuOverflow, { icons: r.menuIcons, submenu: true } ) + r.submenu( overflowOpts ) + '
';

        return html;
      },

      submenu: function( menuOpts ) {
        return '
' + menuRenderer( menuOpts.items, {} ) + '
';
      }
    };

    return r;
  };

  if ( typeof define == 'function' && typeof define.amd == 'object' && define.amd ) {
    define(function() {
      return responsively;
    });
  } else {
    window.responsively = responsively;
  }
}(this));

<|endoftext|>


<commit_before>/**
*
* List
* params:
*  -handlei18n: bool
*   used for the buttonComponent to render label with FormattedMessage
*  - listButtonLabel: string
*  - listTitle: string
*  - noListButtonPopUp: bool
*     prevent from displaying the OldList button
*  - renderRow: function
*     overrides the default rendering of the OldList tr (we can pass customs components there)
*  - listItems: array the elements to display
*  - handleListPopButtonSave: func
*
*/

import React from 'react';
import { map, isEmpty } from 'lodash';
import { FormattedMessage } from 'react-intl';

import { Button, Modal, ModalHeader, ModalBody, ModalFooter } from 'reactstrap';
import ButtonPrimaryHotline from 'components/Button';
import PopUpForm from 'components/PopUpForm';
import styles from './styles.scss';

class List extends React.Component { // eslint-disable-line react/prefer-stateless-function
  constructor(props) {
    super(props);
    this.state = {
      modal: false,
      // isPopUpFormValid: true,
      requiredInputs: [],
      loader: false,
    };
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.error !== this.props.error) {
      if (isEmpty(nextProps.formErrors)) this.setState({ modal: false, loader: false });
    }
    if (!isEmpty(nextProps.formErrors)) this.setState({ loader: false });
  }

  toggle = () => {
    if (this.props.actionBeforeOpenPopUp && !this.state.modal) this.props.actionBeforeOpenPopUp();
    this.setState({ modal: !this.state.modal });
  }

  handleSubmit = (e) => {
    e.preventDefault();
    this.setState({ loader: true});
    this.props.handleListPopUpSubmit(e);
  }

  render() {
    const button = this.props.noListButtonPopUp ? '' :
      <ButtonPrimaryHotline
        buttonBackground={'secondaryAddType'}
        label={this.props.listButtonLabel}
        handlei18n={this.props.handlei18n}
        addShape
        onClick={this.toggle}
      />;

    const addListTitleMarginTop = this.props.addListTitleMarginTop ? styles.paddedTopList : '';
    const titleSpacer = this.props.addListTitleMarginTop ?
 : '';

    const loader = this.state.loader ?
      <Button onClick={this.handleSubmit} className={styles.primary} disabled={this.state.loader}>
...
</Button>
        : <FormattedMessage id="settings-manager.form.button.save">
          {(message) => (
            <Button onClick={this.handleSubmit} className={styles.primary}>{message}</Button>
          )}
        </FormattedMessage>;
    return (

          <div className={`${addListTitleMarginTop} ${styles.flex}`}>

              {this.props.listTitle}

              {button}

          {titleSpacer}

            {map(this.props.listItems, (listItem, key) => {
              if (this.props.renderRow) {
                return this.props.renderRow(listItem, key, styles);
              }
              return (

                    {map(listItem, (item, index) => (

{item}

                    ))}

              );
            })}

        {/*
 */}

          <Modal isOpen={this.state.modal} toggle={this.toggle} className={styles.modalPosition}>
            <ModalHeader toggle={this.toggle} className={`${styles.noBorder} ${styles.padded} ${styles.mHeader}`}>
              <FormattedMessage id={`settings-manager.${this.props.listButtonLabel}`} />
            </ModalHeader>

            <form onSubmit={this.handleSubmit}>

              <ModalBody className={styles.modalBody}>

                <PopUpForm {...this.props} />
              </ModalBody>
              <ModalFooter className={`${styles.noBorder} ${styles.modalFooter}`}>
                <FormattedMessage id="settings-manager.form.button.cancel">
                  {(message) => (
                    <Button onClick={this.toggle} className={styles.secondary}>{message}</Button>
                  )}
                </FormattedMessage>
                {loader}
              </ModalFooter>
            </form>
          </Modal>

    );
  }
}

List.propTypes = {
  actionBeforeOpenPopUp: React.PropTypes.func,
  addListTitleMarginTop: React.PropTypes.bool,
  error: React.PropTypes.bool,
  handlei18n: React.PropTypes.bool,
  handleListPopUpSubmit: React.PropTypes.func,
  listButtonLabel: React.PropTypes.string,
  listItems: React.PropTypes.array,
  listTitle: React.PropTypes.oneOfType([
    React.PropTypes.string,
    React.PropTypes.object,
  ]),
  noListButtonPopUp: React.PropTypes.bool,
  renderRow: React.PropTypes.oneOfType([
    React.PropTypes.bool,
    React.PropTypes.func,
  ]),
}

export default List;
<commit_msg>Remove double if<commit_after>/**
*
* List
* params:
*  -handlei18n: bool
*   used for the buttonComponent to render label with FormattedMessage
*  - listButtonLabel: string
*  - listTitle: string
*  - noListButtonPopUp: bool
*     prevent from displaying the OldList button
*  - renderRow: function
*     overrides the default rendering of the OldList tr (we can pass customs components there)
*  - listItems: array the elements to display
*  - handleListPopButtonSave: func
*
*/

import React from 'react';
import { map, isEmpty } from 'lodash';
import { FormattedMessage } from 'react-intl';

import { Button, Modal, ModalHeader, ModalBody, ModalFooter } from 'reactstrap';
import ButtonPrimaryHotline from 'components/Button';
import PopUpForm from 'components/PopUpForm';
import styles from './styles.scss';

class List extends React.Component { // eslint-disable-line react/prefer-stateless-function
  constructor(props) {
    super(props);
    this.state = {
      modal: false,
      // isPopUpFormValid: true,
      requiredInputs: [],
      loader: false,
    };
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.error !== this.props.error && isEmpty(nextProps.formErrors)) {
      this.setState({ modal: false, loader: false });
    }
    if (!isEmpty(nextProps.formErrors)) this.setState({ loader: false });
  }

  toggle = () => {
    if (this.props.actionBeforeOpenPopUp && !this.state.modal) this.props.actionBeforeOpenPopUp();
    this.setState({ modal: !this.state.modal });
  }

  handleSubmit = (e) => {
    e.preventDefault();
    this.setState({ loader: true});
    this.props.handleListPopUpSubmit(e);
  }

  render() {
    const button = this.props.noListButtonPopUp ? '' :
      <ButtonPrimaryHotline
        buttonBackground={'secondaryAddType'}
        label={this.props.listButtonLabel}
        handlei18n={this.props.handlei18n}
        addShape
        onClick={this.toggle}
      />;

    const addListTitleMarginTop = this.props.addListTitleMarginTop ? styles.paddedTopList : '';
    const titleSpacer = this.props.addListTitleMarginTop ?
 : '';

    const loader = this.state.loader ?
      <Button onClick={this.handleSubmit} className={styles.primary} disabled={this.state.loader}>
...
</Button>
        : <FormattedMessage id="settings-manager.form.button.save">
          {(message) => (
            <Button onClick={this.handleSubmit} className={styles.primary}>{message}</Button>
          )}
        </FormattedMessage>;
    return (

          <div className={`${addListTitleMarginTop} ${styles.flex}`}>

              {this.props.listTitle}

              {button}

          {titleSpacer}

            {map(this.props.listItems, (listItem, key) => {
              if (this.props.renderRow) {
                return this.props.renderRow(listItem, key, styles);
              }
              return (

                    {map(listItem, (item, index) => (

{item}

                    ))}

              );
            })}

        {/*
 */}

          <Modal isOpen={this.state.modal} toggle={this.toggle} className={styles.modalPosition}>
            <ModalHeader toggle={this.toggle} className={`${styles.noBorder} ${styles.padded} ${styles.mHeader}`}>
              <FormattedMessage id={`settings-manager.${this.props.listButtonLabel}`} />
            </ModalHeader>

            <form onSubmit={this.handleSubmit}>

              <ModalBody className={styles.modalBody}>

                <PopUpForm {...this.props} />
              </ModalBody>
              <ModalFooter className={`${styles.noBorder} ${styles.modalFooter}`}>
                <FormattedMessage id="settings-manager.form.button.cancel">
                  {(message) => (
                    <Button onClick={this.toggle} className={styles.secondary}>{message}</Button>
                  )}
                </FormattedMessage>
                {loader}
              </ModalFooter>
            </form>
          </Modal>

    );
  }
}

List.propTypes = {
  actionBeforeOpenPopUp: React.PropTypes.func,
  addListTitleMarginTop: React.PropTypes.bool,
  error: React.PropTypes.bool,
  handlei18n: React.PropTypes.bool,
  handleListPopUpSubmit: React.PropTypes.func,
  listButtonLabel: React.PropTypes.string,
  listItems: React.PropTypes.array,
  listTitle: React.PropTypes.oneOfType([
    React.PropTypes.string,
    React.PropTypes.object,
  ]),
  noListButtonPopUp: React.PropTypes.bool,
  renderRow: React.PropTypes.oneOfType([
    React.PropTypes.bool,
    React.PropTypes.func,
  ]),
}

export default List;
<|endoftext|>