<commit_before>/**
 * The ParseContent Utility - Parse the content of a Node so that all of the
 * javascript contained in that Node will be executed according to the order
 * that it appears.
 *
 * @module aui-parse-content
 */

/*
* NOTE: The inspiration of ParseContent cames from the "Caridy Patino" Node Dispatcher Plugin
* 		http://github.com/caridy/yui3-gallery/blob/master/src/gallery-dispatcher/
*/

var L = A.Lang,
	isString = L.isString,

	APPEND = 'append',
	CREATE_DOCUMENT_FRAGMENT = 'createDocumentFragment',
	DOCUMENT_ELEMENT = 'documentElement',
	FIRST_CHILD = 'firstChild',
	HEAD = 'head',
	HOST = 'host',
	INNER_HTML = 'innerHTML',
	PARSE_CONTENT = 'ParseContent',
	QUEUE = 'queue',
	SCRIPT = 'script',
	SRC = 'src';

/**
 * A base class for ParseContent, providing:
 *

 *
After plug ParseContent on a A.Node instance the javascript chunks will be executed (remote and inline scripts)

 *
All the javascripts within a content will be executed according to the order of apparition

 *

 *
 *
NOTE: For performance reasons on DOM manipulation,
 * ParseContent only parses the content passed to the
 * setContent,
 * prepend and
 * append methods.

 *
 * Quick Example:

 *
 *
node.plug(A.Plugin.ParseContent);

 *
 * Check the list of Configuration Attributes available for
 * ParseContent.
 *
 * @param config {Object} Object literal specifying widget configuration properties.
 *
 * @class ParseContent
 * @constructor
 * @extends Plugin.Base
 */
var ParseContent = A.Component.create(
	{
		/**
		 * Static property provides a string to identify the class.
		 *
		 * @property ParseContent.NAME
		 * @type String
		 * @static
		 */
		NAME: PARSE_CONTENT,

		/**
		 * Static property provides a string to identify the namespace.
		 *
		 * @property ParseContent.NS
		 * @type String
		 * @static
		 */
		NS: PARSE_CONTENT,

		/**
		 * Static property used to define the default attribute
		 * configuration for the ParseContent.
		 *
		 * @property ParseContent.ATTRS
		 * @type Object
		 * @static
		 */
		ATTRS: {
			queue: {
				value: null
			}
		},

		EXTENDS: A.Plugin.Base,

		prototype: {
			/**
			 * Construction logic executed during ParseContent instantiation. Lifecycle.
			 *
			 * @method initializer
			 * @protected
			 */
			initializer: function() {
				var instance = this;

				ParseContent.superclass.initializer.apply(this, arguments);

				instance.set(
					QUEUE,
					new A.AsyncQueue()
				);

				instance._bindAOP();
			},

			/**
			 * Global eval the <data>data</data> passed.
			 *
			 * @method globalEval
			 * @param {String} data JavaScript String.
			 */
			globalEval: function(data) {
				var doc = A.getDoc();
				var head = doc.one(HEAD) || doc.get(DOCUMENT_ELEMENT);

				// NOTE: A.Node.create('') doesn't work correctly on Opera
				var newScript = document.createElement(SCRIPT);

				newScript.type = 'text/javascript';

				if (data) {
					// NOTE: newScript.set(TEXT, data) breaks on IE, YUI BUG.
					newScript.text = L.trim(data);
				}

				head.appendChild(newScript).remove(); //removes the script node immediately after executing it
			},

			/**
			 * Extract the script tags from the string content and
			 * evaluate the chunks.
			 *
			 * @method parseContent
			 * @param {String} content HTML string
			 * @return {String}
			 */
			parseContent: function(content) {
				var instance = this;
				var output = instance._clean(content);

				instance._dispatch(output);

				return output;
			},

			/**
			 * Bind listeners on the insert and setContent
		     * methods of the Node instance where you are plugging the ParseContent.
		     * These listeners are responsible for intercept the HTML passed and parse
		     * them.
			 *
			 * @method _bindAOP
			 * @protected
			 */
			_bindAOP: function() {
				var instance = this;

				// overloading node.insert() arguments, affects append/prepend methods
				this.doBefore('insert', function(content) {
					var args = Array.prototype.slice.call(arguments);
					var output = instance.parseContent(content);

					// replace the first argument with the clean fragment
					args.splice(0, 1, output.fragment);

					return new A.Do.AlterArgs(null, args);
				});

				// overloading node.setContent() arguments
				this.doBefore('setContent', function(content) {
					var output = instance.parseContent(content);

					return new A.Do.AlterArgs(null, [output.fragment]);
				});
			},

			/**
			 * Create an HTML fragment with the String passed, extract all the script
		     * tags and return an Object with a reference for the extracted scripts and
		     * the fragment.
			 *
			 * @method clean
			 * @param {String} content HTML content.
			 * @protected
			 * @return {Object}
			 */
			_clean: function(content) {
				var output = {};
				var fragment = A.getDoc().invoke(CREATE_DOCUMENT_FRAGMENT);

				// instead of fix all tags to "XHTML"-style, make the firstChild be a valid non-empty tag
				fragment.append('
_
');

				if (isString(content)) {
					// create fragment from {String}
					A.DOM.addHTML(fragment, content, APPEND);
				}
				else {
					// create fragment from {Y.Node | HTMLElement}
					fragment.append(content);
				}

				output.js = fragment.all(SCRIPT).each(
					function(node, i) {
						node.remove();
					}
				);

				// remove padding node
				fragment.get(FIRST_CHILD).remove();

				output.fragment = fragment;

				return output;
			},

			/**
			 * Loop trough all extracted script tags and evaluate them.
			 *
			 * @method _dispatch
			 * @param {Object} output Object containing the reference for the fragment and the extracted script tags.
			 * @protected
			 * @return {String}
			 */
			_dispatch: function(output) {
				var instance = this;
				var queue = instance.get(QUEUE);

				output.js.each(function(node, i) {
					var src = node.get(SRC);

					if (src) {
						queue.add({
							autoContinue: false,
							fn: function () {
								A.Get.script(src, {
									onEnd: function (o) {
										o.purge(); //removes the script node immediately after executing it
										queue.run();
									}
								});
							},
							timeout: 0
						});
					}
					else {
						queue.add({
							fn: function () {
								var dom = node._node;

								instance.globalEval(
									dom.text || dom.textContent || dom.innerHTML || ''
								);
							},
							timeout: 0
						});
					}
				});

				queue.run();
			}
		}
	}
);

A.namespace('Plugin').ParseContent = ParseContent;<commit_msg>AUI-243 - Firefox 3.0.x throws error with ParseContent plugin<commit_after>/**
 * The ParseContent Utility - Parse the content of a Node so that all of the
 * javascript contained in that Node will be executed according to the order
 * that it appears.
 *
 * @module aui-parse-content
 */

/*
* NOTE: The inspiration of ParseContent cames from the "Caridy Patino" Node Dispatcher Plugin
* 		http://github.com/caridy/yui3-gallery/blob/master/src/gallery-dispatcher/
*/

var L = A.Lang,
	isString = L.isString,

	APPEND = 'append',
	DOCUMENT_ELEMENT = 'documentElement',
	FIRST_CHILD = 'firstChild',
	HEAD = 'head',
	HOST = 'host',
	INNER_HTML = 'innerHTML',
	PARSE_CONTENT = 'ParseContent',
	QUEUE = 'queue',
	SCRIPT = 'script',
	SRC = 'src';

/**
 * A base class for ParseContent, providing:
 *

 *
After plug ParseContent on a A.Node instance the javascript chunks will be executed (remote and inline scripts)

 *
All the javascripts within a content will be executed according to the order of apparition

 *

 *
 *
NOTE: For performance reasons on DOM manipulation,
 * ParseContent only parses the content passed to the
 * setContent,
 * prepend and
 * append methods.

 *
 * Quick Example:

 *
 *
node.plug(A.Plugin.ParseContent);

 *
 * Check the list of Configuration Attributes available for
 * ParseContent.
 *
 * @param config {Object} Object literal specifying widget configuration properties.
 *
 * @class ParseContent
 * @constructor
 * @extends Plugin.Base
 */
var ParseContent = A.Component.create(
	{
		/**
		 * Static property provides a string to identify the class.
		 *
		 * @property ParseContent.NAME
		 * @type String
		 * @static
		 */
		NAME: PARSE_CONTENT,

		/**
		 * Static property provides a string to identify the namespace.
		 *
		 * @property ParseContent.NS
		 * @type String
		 * @static
		 */
		NS: PARSE_CONTENT,

		/**
		 * Static property used to define the default attribute
		 * configuration for the ParseContent.
		 *
		 * @property ParseContent.ATTRS
		 * @type Object
		 * @static
		 */
		ATTRS: {
			queue: {
				value: null
			}
		},

		EXTENDS: A.Plugin.Base,

		prototype: {
			/**
			 * Construction logic executed during ParseContent instantiation. Lifecycle.
			 *
			 * @method initializer
			 * @protected
			 */
			initializer: function() {
				var instance = this;

				ParseContent.superclass.initializer.apply(this, arguments);

				instance.set(
					QUEUE,
					new A.AsyncQueue()
				);

				instance._bindAOP();
			},

			/**
			 * Global eval the <data>data</data> passed.
			 *
			 * @method globalEval
			 * @param {String} data JavaScript String.
			 */
			globalEval: function(data) {
				var doc = A.getDoc();
				var head = doc.one(HEAD) || doc.get(DOCUMENT_ELEMENT);

				// NOTE: A.Node.create('') doesn't work correctly on Opera
				var newScript = document.createElement(SCRIPT);

				newScript.type = 'text/javascript';

				if (data) {
					// NOTE: newScript.set(TEXT, data) breaks on IE, YUI BUG.
					newScript.text = L.trim(data);
				}

				head.appendChild(newScript).remove(); //removes the script node immediately after executing it
			},

			/**
			 * Extract the script tags from the string content and
			 * evaluate the chunks.
			 *
			 * @method parseContent
			 * @param {String} content HTML string
			 * @return {String}
			 */
			parseContent: function(content) {
				var instance = this;
				var output = instance._clean(content);

				instance._dispatch(output);

				return output;
			},

			/**
			 * Bind listeners on the insert and setContent
		     * methods of the Node instance where you are plugging the ParseContent.
		     * These listeners are responsible for intercept the HTML passed and parse
		     * them.
			 *
			 * @method _bindAOP
			 * @protected
			 */
			_bindAOP: function() {
				var instance = this;

				// overloading node.insert() arguments, affects append/prepend methods
				this.doBefore('insert', function(content) {
					var args = Array.prototype.slice.call(arguments);
					var output = instance.parseContent(content);

					// replace the first argument with the clean fragment
					args.splice(0, 1, output.fragment);

					return new A.Do.AlterArgs(null, args);
				});

				// overloading node.setContent() arguments
				this.doBefore('setContent', function(content) {
					var output = instance.parseContent(content);

					return new A.Do.AlterArgs(null, [output.fragment]);
				});
			},

			/**
			 * Create an HTML fragment with the String passed, extract all the script
		     * tags and return an Object with a reference for the extracted scripts and
		     * the fragment.
			 *
			 * @method clean
			 * @param {String} content HTML content.
			 * @protected
			 * @return {Object}
			 */
			_clean: function(content) {
				var output = {};
				var fragment = A.Node.create('

');

				// instead of fix all tags to "XHTML"-style, make the firstChild be a valid non-empty tag
				fragment.append('
_
');

				if (isString(content)) {
					// create fragment from {String}
					A.DOM.addHTML(fragment, content, APPEND);
				}
				else {
					// create fragment from {Y.Node | HTMLElement}
					fragment.append(content);
				}

				output.js = fragment.all(SCRIPT).each(
					function(node, i) {
						node.remove();
					}
				);

				// remove padding node
				fragment.get(FIRST_CHILD).remove();

				output.fragment = fragment.get('childNodes').toFrag();

				return output;
			},

			/**
			 * Loop trough all extracted script tags and evaluate them.
			 *
			 * @method _dispatch
			 * @param {Object} output Object containing the reference for the fragment and the extracted script tags.
			 * @protected
			 * @return {String}
			 */
			_dispatch: function(output) {
				var instance = this;
				var queue = instance.get(QUEUE);

				output.js.each(function(node, i) {
					var src = node.get(SRC);

					if (src) {
						queue.add({
							autoContinue: false,
							fn: function () {
								A.Get.script(src, {
									onEnd: function (o) {
										o.purge(); //removes the script node immediately after executing it
										queue.run();
									}
								});
							},
							timeout: 0
						});
					}
					else {
						queue.add({
							fn: function () {
								var dom = node._node;

								instance.globalEval(
									dom.text || dom.textContent || dom.innerHTML || ''
								);
							},
							timeout: 0
						});
					}
				});

				queue.run();
			}
		}
	}
);

A.namespace('Plugin').ParseContent = ParseContent;<|endoftext|>


<commit_before>/*

*/

kb_define('kbasePlantsNetworkNarrative',
    [
        'jquery',
        'kbasePlantsNetworkTable',
        'kbaseForcedNetwork',
        'kbaseTable',
        'KbaseNetworkServiceClient',
        'CDMI_API',
        'IdMapClient',
        'OntologyServiceClient',
    ],
    function ($) {
        $.KBWidget(
        {

            name: "kbasePlantsNetworkNarrative",
            parent: 'kbaseIrisWidget',

            version: "1.0.0",

            _accessors : [
                'networkTable',
                'networkGraph',
                'networkClient',
                //'idMapClient',
                'cdmiClient',
                'ontologyClient',
                'idmapClient',
                'tabularData',
            ],

            options: {

            },

            setInput : function(newInput) {

                if (newInput.data) {
                    newInput = newInput.data;
                };

                var colorCats = d3.scale.category20();

                this.setValueForKey('input', newInput);

                var records = {};
                var datasets = [];
                $.each(
                    newInput.datasets,
                    function (idx, rec) {
                        datasets.push(rec.id);
                        records[rec.id] =
                            {
                                nodes       : [],
                                edges       : [],
                                nodesByName : {},
                                edgesByName : {},
                                dataset     : rec.id,
                                type        : rec.network_type,
                                source      : rec.source_ref,
                                description : rec.name + ' (' + rec.description + ')',
                            }
                        ;
                    }
                );

                var linkScale = d3.scale.pow()
                    .domain([0, datasets.length])
                    .range([-100,100]);
                var nodes = {};
                var edges = {};

                $.each(
                    newInput.nodes,
                    function (idx, node) {

                        var nodeObj = nodes[node.name];
                        if (nodeObj == undefined) {

                            node.func = node.user_annotations.functions || '';

                            if (node.func.match(/unknown/i)) {
                                node.func = '';
                            }

                            node.associations = "(not sure yet)";

                            nodeObj = nodes[node.id] = {
                                name : node.name,
                                func : node.func,
                                associations : node.associations,
                                activeDatasets : {},
                                id : node.id,
                                radius : 10,
                                tag : node.name,
                                search : [
                                    node.name,
                                    node.func,
                                    JSON.stringify(node.associations)
                                ].join(''),
                                tagStyle : 'font : 12px sans-serif',
                                color : 'black',
                            };

                        }
                    }
                );

                $.each(
                    newInput.edges,
                    function (idx, edge) {

                        var node1 = nodes[edge.node_id1];
                        var node2 = nodes[edge.node_id2];
                        var datasetRec = records[edge.dataset_id];

                        if (! datasetRec.nodesByName[node1.name]) {
                            datasetRec.nodesByName[node1.name] = 1;
                            datasetRec.nodes.push(node1);
                        }

                        if (! datasetRec.nodesByName[node2.name]) {
                            datasetRec.nodesByName[node2.name] = 1;
                            datasetRec.nodes.push(node2);
                        }

                        var edgeName = [edge.dataset_id, node1.name, node2.name].sort().join('-');//node1.name + '-' + node2.name;
                        var edgeObj = edges[edgeName];

                        var dataset_idx = datasets.indexOf(edge.dataset_id);

                        if (edge.name == 'is interact with') {
                            edge.name = 'interacts with';
                        }

                        if (edgeObj == undefined) {
                            edgeObj = edges[edgeName] = {
                                source : node1,
                                target : node2,
                                activeDatasets : {},
                                name : edgeName,
                                description : node1.name + ' ' + edge.name + ' ' + node2.name + ' (' + edge.strength.toFixed(3) + ')',
                                //weight : 1,
                                colors : {},
                                curveStrength : linkScale(dataset_idx) * (dataset_idx % 2 ? -1 : 1),
                            };
                        }

                        var color = colorCats(datasets.indexOf(edge.dataset_id) % 20);
                        edgeObj.colors[edge.dataset_id] = color;

                        if (! datasetRec.edgesByName[edgeName]) {
                            datasetRec.edgesByName[edgeName] = 1;
                            datasetRec.edges.push(
                                edgeObj
                            );
                        }

                    }
                );

                var tabularData = [];
                $.each(
                    records,
                    function(idx, val) {
                        if (val.nodes.length) {

                            tabularData.push(
                                {
                                    datasetID       : val.dataset,
                                    dataset         : {value : val.dataset, style : 'color : ' + colorCats(datasets.indexOf(val.dataset) % 20)},
                                    nodes           : val.nodes,
                                    edges           : val.edges,
                                    description     : val.description,
                                    type            : val.type,
                                    source          : val.source,
                                }
                            );
                        }
                    }
                );

                this.setValueForKey('tabularData', tabularData);

                if (this.networkTable()) {
                    this.data('loader').remove();
                    this.data('msgBox').show();

                    this.networkTable().setInput(tabularData);
                }

            },

            appendUI : function($elem) {

                $elem.empty();

                $elem.css('border', '1px solid gray');

                $elem.empty();
                var $loader = $.jqElem('div')
                            .append('
 Loading data...
 please wait...')
                            .append($.jqElem('br'))
                            .append(
                                $.jqElem('div')
                                    .attr('align', 'center')
                                    .append($.jqElem('i').addClass('fa fa-spinner').addClass('fa fa-spin fa fa-4x'))
                            )
                ;
                $elem.append($loader);

                this.data('loader', $loader);

                var $networkGraph = $.jqElem('div')
                    .css({width : 700, height : 600})
                    .attr('align', 'center')
                    .kbaseForcedNetwork(
                        {
                            linkDistance : 200,
                            filter : true,
                            nodeHighlightColor : '#002200',
                            relatedNodeHighlightColor : 'black',
                        });

                this.networkGraph($networkGraph);

                var $msgBox = $.jqElem('div')
                    .attr('align', 'center')
                    .css('font-style', 'italic')
                    .html("No datasets with nodes selected");
                this.data('msgBox', $msgBox);

                var $networkTable = $.jqElem('div').kbasePlantsNetworkTable(
                    {
                        $terminal       : this.options.$terminal,
                        networkGraph    : $networkGraph,
                        msgBox          : $msgBox,
                    }
                );
                this.networkTable($networkTable);

                $msgBox.hide();
                $networkGraph.$elem.hide();

                $elem
                    .append($networkTable.$elem)
                    .append($msgBox)
                    .append(
                        $.jqElem('div')
                            .attr('align', 'center')
                            .append($networkGraph.$elem)
                    )
                ;

                if (this.input()) {
                    this.data('loader').remove();
                    this.data('msgBox').show();

                    this.networkTable().setInput(this.tabularData());
                }

            }
        }

    );
} ) ;
<commit_msg>dropped extraneous uses<commit_after>/*

*/

kb_define('kbasePlantsNetworkNarrative',
    [
        'jquery',
        'kbasePlantsNetworkTable',
        'kbaseForcedNetwork',
        'kbaseTable',
    ],
    function ($) {
        $.KBWidget(
        {

            name: "kbasePlantsNetworkNarrative",
            parent: 'kbaseIrisWidget',

            version: "1.0.0",

            _accessors : [
                'networkTable',
                'networkGraph',
                'networkClient',
                //'idMapClient',
                'cdmiClient',
                'ontologyClient',
                'idmapClient',
                'tabularData',
            ],

            options: {

            },

            setInput : function(newInput) {

                if (newInput.data) {
                    newInput = newInput.data;
                };

                var colorCats = d3.scale.category20();

                this.setValueForKey('input', newInput);

                var records = {};
                var datasets = [];
                $.each(
                    newInput.datasets,
                    function (idx, rec) {
                        datasets.push(rec.id);
                        records[rec.id] =
                            {
                                nodes       : [],
                                edges       : [],
                                nodesByName : {},
                                edgesByName : {},
                                dataset     : rec.id,
                                type        : rec.network_type,
                                source      : rec.source_ref,
                                description : rec.name + ' (' + rec.description + ')',
                            }
                        ;
                    }
                );

                var linkScale = d3.scale.pow()
                    .domain([0, datasets.length])
                    .range([-100,100]);
                var nodes = {};
                var edges = {};

                $.each(
                    newInput.nodes,
                    function (idx, node) {

                        var nodeObj = nodes[node.name];
                        if (nodeObj == undefined) {

                            node.func = node.user_annotations.functions || '';

                            if (node.func.match(/unknown/i)) {
                                node.func = '';
                            }

                            node.associations = "(not sure yet)";

                            nodeObj = nodes[node.id] = {
                                name : node.name,
                                func : node.func,
                                associations : node.associations,
                                activeDatasets : {},
                                id : node.id,
                                radius : 10,
                                tag : node.name,
                                search : [
                                    node.name,
                                    node.func,
                                    JSON.stringify(node.associations)
                                ].join(''),
                                tagStyle : 'font : 12px sans-serif',
                                color : 'black',
                            };

                        }
                    }
                );

                $.each(
                    newInput.edges,
                    function (idx, edge) {

                        var node1 = nodes[edge.node_id1];
                        var node2 = nodes[edge.node_id2];
                        var datasetRec = records[edge.dataset_id];

                        if (! datasetRec.nodesByName[node1.name]) {
                            datasetRec.nodesByName[node1.name] = 1;
                            datasetRec.nodes.push(node1);
                        }

                        if (! datasetRec.nodesByName[node2.name]) {
                            datasetRec.nodesByName[node2.name] = 1;
                            datasetRec.nodes.push(node2);
                        }

                        var edgeName = [edge.dataset_id, node1.name, node2.name].sort().join('-');//node1.name + '-' + node2.name;
                        var edgeObj = edges[edgeName];

                        var dataset_idx = datasets.indexOf(edge.dataset_id);

                        if (edge.name == 'is interact with') {
                            edge.name = 'interacts with';
                        }

                        if (edgeObj == undefined) {
                            edgeObj = edges[edgeName] = {
                                source : node1,
                                target : node2,
                                activeDatasets : {},
                                name : edgeName,
                                description : node1.name + ' ' + edge.name + ' ' + node2.name + ' (' + edge.strength.toFixed(3) + ')',
                                //weight : 1,
                                colors : {},
                                curveStrength : linkScale(dataset_idx) * (dataset_idx % 2 ? -1 : 1),
                            };
                        }

                        var color = colorCats(datasets.indexOf(edge.dataset_id) % 20);
                        edgeObj.colors[edge.dataset_id] = color;

                        if (! datasetRec.edgesByName[edgeName]) {
                            datasetRec.edgesByName[edgeName] = 1;
                            datasetRec.edges.push(
                                edgeObj
                            );
                        }

                    }
                );

                var tabularData = [];
                $.each(
                    records,
                    function(idx, val) {
                        if (val.nodes.length) {

                            tabularData.push(
                                {
                                    datasetID       : val.dataset,
                                    dataset         : {value : val.dataset, style : 'color : ' + colorCats(datasets.indexOf(val.dataset) % 20)},
                                    nodes           : val.nodes,
                                    edges           : val.edges,
                                    description     : val.description,
                                    type            : val.type,
                                    source          : val.source,
                                }
                            );
                        }
                    }
                );

                this.setValueForKey('tabularData', tabularData);

                if (this.networkTable()) {
                    this.data('loader').remove();
                    this.data('msgBox').show();

                    this.networkTable().setInput(tabularData);
                }

            },

            appendUI : function($elem) {

                $elem.empty();

                $elem.css('border', '1px solid gray');

                $elem.empty();
                var $loader = $.jqElem('div')
                            .append('
 Loading data...
 please wait...')
                            .append($.jqElem('br'))
                            .append(
                                $.jqElem('div')
                                    .attr('align', 'center')
                                    .append($.jqElem('i').addClass('fa fa-spinner').addClass('fa fa-spin fa fa-4x'))
                            )
                ;
                $elem.append($loader);

                this.data('loader', $loader);

                var $networkGraph = $.jqElem('div')
                    .css({width : 700, height : 600})
                    .attr('align', 'center')
                    .kbaseForcedNetwork(
                        {
                            linkDistance : 200,
                            filter : true,
                            nodeHighlightColor : '#002200',
                            relatedNodeHighlightColor : 'black',
                        });

                this.networkGraph($networkGraph);

                var $msgBox = $.jqElem('div')
                    .attr('align', 'center')
                    .css('font-style', 'italic')
                    .html("No datasets with nodes selected");
                this.data('msgBox', $msgBox);

                var $networkTable = $.jqElem('div').kbasePlantsNetworkTable(
                    {
                        $terminal       : this.options.$terminal,
                        networkGraph    : $networkGraph,
                        msgBox          : $msgBox,
                    }
                );
                this.networkTable($networkTable);

                $msgBox.hide();
                $networkGraph.$elem.hide();

                $elem
                    .append($networkTable.$elem)
                    .append($msgBox)
                    .append(
                        $.jqElem('div')
                            .attr('align', 'center')
                            .append($networkGraph.$elem)
                    )
                ;

                if (this.input()) {
                    this.data('loader').remove();
                    this.data('msgBox').show();

                    this.networkTable().setInput(this.tabularData());
                }

            }
        }

    );
} ) ;
<|endoftext|>


<commit_before>var d3 = require('d3-selection');
var vega = require('vega');
var vl = require('vega-lite');
var post = require('./post');
var versionCompare = require('./version');
var schemaParser = require('vega-schema-url-parser').default;

var config = {
  // URL for loading specs into editor
  editor_url: 'http://vega.github.io/vega-editor/',

  // HTML to inject within view source head element
  source_header: '',

  // HTML to inject before view source closing body tag
  source_footer: ''
};

var MODES = {
  'vega':      'vega',
  'vega-lite': 'vega-lite'
};

var VERSION = {
  'vega':      vega.version,
  'vega-lite': vl ? vl.version : -1
};

var PREPROCESSOR = {
  'vega':      function(vgjson) { return vgjson; },
  'vega-lite': function(vljson) { return vl.compile(vljson).spec; }
};

function load(url, arg, prop, el) {
  return vega.loader().load(url).then(function (data) {
    if (!data) {
      throw new Error('No data found at ' + url);
    }
    if (prop === 'config') {
      arg.opt['config'] = JSON.parse(data);
      return embed(el, arg.spec, arg.opt);
    }
    return embed(el, JSON.parse(data), arg);
  });
}

/**
 * Embed a Vega visualization component in a web page.
 * This function will either throw an exception, or return a promise
 *
 * @param el        DOM element in which to place component (DOM node or CSS selector)
 * @param spec      String : A URL string from which to load the Vega specification.
                    Object : The Vega/Vega-Lite specification as a parsed JSON object.
 * @param opt       A JavaScript object containing options for embedding.
 */
function embed(el, spec, opt) {
  var renderer = (opt && opt.renderer) || 'canvas';
  var actions  = opt && (opt.actions !== undefined) ? opt.actions : true;

  opt = opt || {};

  // Load the visualization specification.
  if (vega.isString(spec)) {
    return load(spec, opt, 'url', el);
  }

  // Load Vega theme/configuration.
  if (vega.isString(opt.config)) {
    return load(opt.config, {spec: spec, opt: opt}, 'config', el);
  }

  // Decide mode
  var parsed, parsedVersion, mode, vgSpec;
  if (spec.$schema) {
    parsed = schemaParser(spec.$schema);
    if (opt.mode && opt.mode !== MODES[parsed.library]) {
      console.warn("The given visualization spec is written in \"" + parsed.library + "\", "
                 + "but mode argument is assigned as \"" + opt.mode + "\".");
    }
    mode = MODES[parsed.library];

    parsedVersion = parsed.version.replace(/^v/g,'');
    if (versionCompare(parsedVersion, VERSION[mode]) !== 0 ){
      console.warn("The input spec uses \"" + mode + "\" " + parsedVersion + ", "
                 + "but current version of \"" + mode + "\" is " + VERSION[mode] + ".");
    }
  } else {
    mode = MODES[opt.mode] || MODES.vega;
  }

  vgSpec = PREPROCESSOR[mode](spec);
  if (mode === MODES['vega-lite']) {
    if (vgSpec.$schema) {
      parsed = schemaParser(vgSpec.$schema);

      parsedVersion = parsed.version.replace(/^v/g,'');
      if (versionCompare(parsedVersion, VERSION['vega']) !== 0 ){
        console.warn("The compiled spec uses \"vega\" " + parsedVersion + ", "
                   + "but current version of \"vega\" is " + VERSION['vega'] + ".");
      }
    }
  }

  // ensure container div has class 'vega-embed'
  var div = d3.select(el)
    .classed('vega-embed', true)
    .html(''); // clear container

  if (opt.onBeforeParse) {
    // Allow Vega spec to be modified before being used
    vgSpec = opt.onBeforeParse(vgSpec);
  }

  var runtime = vega.parse(vgSpec, opt.config); // may throw an Error if parsing fails

  var view = new vega.View(runtime, opt.viewConfig)
    .logLevel(opt.logLevel | vega.Warn)
    .initialize(el)
    .renderer(renderer);

  // Vega-Lite does not need hover so we can improve perf by not activating it
  if (mode !== MODES['vega-lite']) {
    view.hover();
  }

  if (opt) {
    if (opt.width) {
      view.width(opt.width)
    }
    if (opt.height) {
      view.height(opt.height)
    }
    if (opt.padding) {
      view.padding(opt.padding)
    }
  }

  view.run();

  if (actions !== false) {
    // add child div to house action links
    var ctrl = div.append('div')
      .attr('class', 'vega-actions');

    // add 'Export' action
    if (actions.export !== false) {
      var ext = (renderer==='canvas' ? 'png' : 'svg');
      ctrl.append('a')
        .text('Export as ' + ext.toUpperCase())
        .attr('href', '#')
        .attr('target', '_blank')
        .attr('download', (spec.name || 'vega') + '.' + ext)
        .on('mousedown', function() {
          var that = this;
          view.toImageURL(ext).then(function(url) {
            that.href =  url;
          }).catch(function(error) { throw error; });
          d3.event.preventDefault();
        });
    }

    // add 'View Source' action
    if (actions.source !== false) {
      ctrl.append('a')
        .text('View Source')
        .attr('href', '#')
        .on('click', function() {
          viewSource(JSON.stringify(spec, null, 2));
          d3.event.preventDefault();
        });
    }

    // add 'Open in Vega Editor' action
    if (actions.editor !== false) {
      ctrl.append('a')
        .text('Open in Vega Editor')
        .attr('href', '#')
        .on('click', function() {
          post(window, embedMain.config.editor_url, {
            spec: JSON.stringify(spec, null, 2),
            mode: mode
          });
          d3.event.preventDefault();
        });
    }
  }

  return Promise.resolve({view: view, spec: spec});
}

function viewSource(source) {
  var header = '' + config.source_header + '' + '
';
  var footer = '
' + config.source_footer + '';
  var win = window.open('');
  win.document.write(header + source + footer);
  win.document.title = 'Vega JSON Source';
}

/**
 * Embed a Vega visualization component in a web page.
 *
 * @param el        DOM element in which to place component (DOM node or CSS selector)
 * @param spec      String : A URL string from which to load the Vega specification.
 Object : The Vega/Vega-Lite specification as a parsed JSON object.
 * @param opt       A JavaScript object containing options for embedding.
 */
function embedMain(el, spec, opt) {
  // Ensure any exceptions will be properly handled
  return new Promise((accept, reject) => {
    embed(el, spec, opt).then(accept, reject);
  });
}

// make config externally visible
embedMain.config = config;

// expose vega and vegalite libs
embedMain.vega = vega;
embedMain.vegalite = vl;

// for es5
module.exports = embedMain;
// for es 6
module.exports.default = embedMain;
<commit_msg>Allow users to customize the editor link.<commit_after>var d3 = require('d3-selection');
var vega = require('vega');
var vl = require('vega-lite');
var post = require('./post');
var versionCompare = require('./version');
var schemaParser = require('vega-schema-url-parser').default;

var config = {
  // URL for loading specs into editor
  editor_url: 'http://vega.github.io/vega-editor/',

  // HTML to inject within view source head element
  source_header: '',

  // HTML to inject before view source closing body tag
  source_footer: ''
};

var MODES = {
  'vega':      'vega',
  'vega-lite': 'vega-lite'
};

var VERSION = {
  'vega':      vega.version,
  'vega-lite': vl ? vl.version : -1
};

var PREPROCESSOR = {
  'vega':      function(vgjson) { return vgjson; },
  'vega-lite': function(vljson) { return vl.compile(vljson).spec; }
};

function load(url, arg, prop, el) {
  return vega.loader().load(url).then(function (data) {
    if (!data) {
      throw new Error('No data found at ' + url);
    }
    if (prop === 'config') {
      arg.opt['config'] = JSON.parse(data);
      return embed(el, arg.spec, arg.opt);
    }
    return embed(el, JSON.parse(data), arg);
  });
}

/**
 * Embed a Vega visualization component in a web page.
 * This function will either throw an exception, or return a promise
 *
 * @param el        DOM element in which to place component (DOM node or CSS selector)
 * @param spec      String : A URL string from which to load the Vega specification.
                    Object : The Vega/Vega-Lite specification as a parsed JSON object.
 * @param opt       A JavaScript object containing options for embedding.
 */
function embed(el, spec, opt) {
  var renderer = (opt && opt.renderer) || 'canvas';
  var actions  = opt && (opt.actions !== undefined) ? opt.actions : true;

  opt = opt || {};

  // Load the visualization specification.
  if (vega.isString(spec)) {
    return load(spec, opt, 'url', el);
  }

  // Load Vega theme/configuration.
  if (vega.isString(opt.config)) {
    return load(opt.config, {spec: spec, opt: opt}, 'config', el);
  }

  // Decide mode
  var parsed, parsedVersion, mode, vgSpec;
  if (spec.$schema) {
    parsed = schemaParser(spec.$schema);
    if (opt.mode && opt.mode !== MODES[parsed.library]) {
      console.warn("The given visualization spec is written in \"" + parsed.library + "\", "
                 + "but mode argument is assigned as \"" + opt.mode + "\".");
    }
    mode = MODES[parsed.library];

    parsedVersion = parsed.version.replace(/^v/g,'');
    if (versionCompare(parsedVersion, VERSION[mode]) !== 0 ){
      console.warn("The input spec uses \"" + mode + "\" " + parsedVersion + ", "
                 + "but current version of \"" + mode + "\" is " + VERSION[mode] + ".");
    }
  } else {
    mode = MODES[opt.mode] || MODES.vega;
  }

  vgSpec = PREPROCESSOR[mode](spec);
  if (mode === MODES['vega-lite']) {
    if (vgSpec.$schema) {
      parsed = schemaParser(vgSpec.$schema);

      parsedVersion = parsed.version.replace(/^v/g,'');
      if (versionCompare(parsedVersion, VERSION['vega']) !== 0 ){
        console.warn("The compiled spec uses \"vega\" " + parsedVersion + ", "
                   + "but current version of \"vega\" is " + VERSION['vega'] + ".");
      }
    }
  }

  // ensure container div has class 'vega-embed'
  var div = d3.select(el)
    .classed('vega-embed', true)
    .html(''); // clear container

  if (opt.onBeforeParse) {
    // Allow Vega spec to be modified before being used
    vgSpec = opt.onBeforeParse(vgSpec);
  }

  var runtime = vega.parse(vgSpec, opt.config); // may throw an Error if parsing fails

  var view = new vega.View(runtime, opt.viewConfig)
    .logLevel(opt.logLevel | vega.Warn)
    .initialize(el)
    .renderer(renderer);

  // Vega-Lite does not need hover so we can improve perf by not activating it
  if (mode !== MODES['vega-lite']) {
    view.hover();
  }

  if (opt) {
    if (opt.width) {
      view.width(opt.width)
    }
    if (opt.height) {
      view.height(opt.height)
    }
    if (opt.padding) {
      view.padding(opt.padding)
    }
  }

  view.run();

  if (actions !== false) {
    // add child div to house action links
    var ctrl = div.append('div')
      .attr('class', 'vega-actions');

    // add 'Export' action
    if (actions.export !== false) {
      var ext = (renderer==='canvas' ? 'png' : 'svg');
      ctrl.append('a')
        .text('Export as ' + ext.toUpperCase())
        .attr('href', '#')
        .attr('target', '_blank')
        .attr('download', (spec.name || 'vega') + '.' + ext)
        .on('mousedown', function() {
          var that = this;
          view.toImageURL(ext).then(function(url) {
            that.href =  url;
          }).catch(function(error) { throw error; });
          d3.event.preventDefault();
        });
    }

    // add 'View Source' action
    if (actions.source !== false) {
      ctrl.append('a')
        .text('View Source')
        .attr('href', '#')
        .on('click', function() {
          viewSource(JSON.stringify(spec, null, 2));
          d3.event.preventDefault();
        });
    }

    // add 'Open in Vega Editor' action
    if (actions.editor !== false) {
      var linkName = actions && actions.editor && actions.editor.linkName || 'Open in Vega Editor';
      var editorURL = actions && actions.editor && actions.editor.url || embedMain.config.editor_url;
      var postingItem = actions && actions.editor && actions.editor.postingItem || {
        spec: JSON.stringify(spec, null, 2),
        mode: mode
      };

      ctrl.append('a')
        .text(linkName)
        .attr('href', '#')
        .on('click', function() {
          if (postingItem) {
            post(window, editorURL, postingItem);
          } else {
            window.open(editorURL);
          }
          d3.event.preventDefault();
        });
    }
  }

  return Promise.resolve({view: view, spec: spec});
}

function viewSource(source) {
  var header = '' + config.source_header + '' + '
';
  var footer = '
' + config.source_footer + '';
  var win = window.open('');
  win.document.write(header + source + footer);
  win.document.title = 'Vega JSON Source';
}

/**
 * Embed a Vega visualization component in a web page.
 *
 * @param el        DOM element in which to place component (DOM node or CSS selector)
 * @param spec      String : A URL string from which to load the Vega specification.
 Object : The Vega/Vega-Lite specification as a parsed JSON object.
 * @param opt       A JavaScript object containing options for embedding.
 */
function embedMain(el, spec, opt) {
  // Ensure any exceptions will be properly handled
  return new Promise((accept, reject) => {
    embed(el, spec, opt).then(accept, reject);
  });
}

// make config externally visible
embedMain.config = config;

// expose vega and vegalite libs
embedMain.vega = vega;
embedMain.vegalite = vl;

// for es5
module.exports = embedMain;
// for es 6
module.exports.default = embedMain;
<|endoftext|>


<commit_before>module.exports = function(grunt) {
	'use strict';
	grunt.initConfig({
		pkg: grunt.file.readJSON('package.json'),
		clean: {
			all: ['lib/']
		},
		jade: {
			canvas: {
				files: {
					'lib/canvas/index.html': ['src/canvas/*jade']
				}
			}
		},
		stylus: {
			canvas: {
				files: {
					'lib/canvas/styles/<%= pkg.name %>.css': ['src/canvas/*styl']
				}
			}
		},
		livescript: {
			server: {
				files: {
					'lib/server/<%= pkg.name %>.js': ['src/server/**/*ls']
				}
			},
			canvas: {
				files: {
					'lib/canvas/scripts/*.js': 'src/canvas/**/*.ls',
				},
				options: {
					bare: false
				}
			},
		},
		jshint: {
			all: ['src/canvas/**/*.js']
		},
		copy: {
			vendors: {
				files: {
					'lib/canvas/vendors/': 'vendors'
				}
			},
            assets: {
				files: {
					'lib/canvas/assets/': 'src/canvas/assets/*',
					'lib/canvas/scripts/': 'src/canvas/scripts/*js'
				}
			}
		},
		server: {
			base: "lib/canvas",
			port: 3000
		},
		watch: {
			canvas: {
				files: [
					'src/canvas/**/*jade',
					'src/canvas/**/*ls',
					'src/canvas/**/*styl'
				],
				tasks: ['build-canvas']
			}
		}
	});

	grunt.loadNpmTasks('grunt-contrib');
	grunt.loadNpmTasks('grunt-contrib-jshint');
	grunt.loadNpmTasks('grunt-livescript');

	grunt.registerTask('vendors', 'copy:vendors');
	grunt.registerTask('build-canvas', ['jade:canvas', 'stylus:canvas', 'livescript:canvas', 'copy:assets']);
	grunt.registerTask('build-server', ['livescript:server']);
	grunt.registerTask('build', ['build-server', 'build-canvas']);
	grunt.registerTask('default', ['clean', 'build']);

	// HACK
	// Until grunt-contrib-connect comes.
	var connect = require('connect');
	grunt.registerTask('server', 'Start a custom static web server.', function() {
		grunt.log.writeln('Starting static web server in "lib/canvas" on port 3000.');
		try{
			connect(connect.static('lib/canvas')).listen(3000);
		} catch (e){}
	});
};
<commit_msg>Updated files objects to 0.4<commit_after>module.exports = function(grunt) {
	'use strict';
	grunt.initConfig({
		pkg: grunt.file.readJSON('package.json'),
		clean: {
			all: ['lib/']
		},
		jade: {
			canvas: {
				files: {
					'lib/canvas/index.html': ['src/canvas/*jade']
				}
			}
		},
		stylus: {
			canvas: {
				files: {
					'lib/canvas/styles/<%= pkg.name %>.css': ['src/canvas/*styl']
				}
			}
		},
		livescript: {
			server: {
				files: {
					'lib/server/<%= pkg.name %>.js': ['src/server/**/*ls']
				}
			},
			canvas: {
				files: [{
					expand: true,
					cwd: 'src/canvas/scripts/',
					src: ['**/*.ls'],
					dest: 'lib/canvas/scripts/',
					ext: '.js'
				}],
				options: {
					bare: false
				}
			},
		},
		jshint: {
			all: ['src/canvas/**/*.js']
		},
		copy: {
			vendors: {
				files: {
					src: 'vendors/',
					dest: 'lib/canvas/vendors/'
				}
			},
            assets: {
				files: [
					{
						expand: true,
						cwd: 'src/canvas/scripts/',
						src: ['**/*.js'],
						dest: 'lib/canvas/scripts/'
					},
					{
						expand: true,
						cwd: 'src/canvas/assets/',
						src: ['**/*'],
						dest: 'lib/canvas/assets/'
					}
				]
			}
		},
		server: {
			base: "lib/canvas",
			port: 3000
		},
		watch: {
			canvas: {
				files: [
					'src/canvas/**/*jade',
					'src/canvas/**/*ls',
					'src/canvas/**/*styl'
				],
				tasks: ['build-canvas']
			}
		}
	});

	grunt.loadNpmTasks('grunt-contrib');
	grunt.loadNpmTasks('grunt-contrib-jshint');
	grunt.loadNpmTasks('grunt-livescript');

	grunt.registerTask('vendors', 'copy:vendors');
	grunt.registerTask('build-canvas', ['jade:canvas', 'stylus:canvas', 'livescript:canvas', 'copy:assets']);
	grunt.registerTask('build-server', ['livescript:server']);
	grunt.registerTask('build', ['build-server', 'build-canvas']);
	grunt.registerTask('default', ['clean', 'build']);

	// HACK
	// Until grunt-contrib-connect comes.
	var connect = require('connect');
	grunt.registerTask('server', 'Start a custom static web server.', function() {
		grunt.log.writeln('Starting static web server in "lib/canvas" on port 3000.');
		try{
			connect(connect.static('lib/canvas')).listen(3000);
		} catch (e){}
	});
};
<|endoftext|>


<commit_before>/**
 * Emulate ui.exe to provide user interaction via
 *  ask       - get a value
 *  choose    - choose a value from a list
 *
 */

var UiExe = {
  _glue_instance: null,

  /**
   * ui MODE [options]
   * MODE is "ask", "choose" or "tell"
   * options contains
   *    -prompt     The prompt to show
   *    -to         Target file to write to, use "." for STDOUT or "" (or skip) to not
   *                write anything (ie. for INFO)
   *    -format     Output format:
   *                  txt|text- the string or "" if cancelled (or empty if nothing entered)
   *                  mtext|"" - marked text, "+" (OK) or "-" (Cancel) followed by the value
   *                  json - json object with the keys "status" (1|0) and "value"
   *                  jsonp - same as json but wrapped in the function specified in -func
   *    -value      The current value (a string for "ask", or index for "choose")
   *    -items      / separated list of items to use with choose
   */
  glueExec: function( o_glue, s_args, s_done_label, s_error_label ) {
    UiExe._glue_instance = o_glue;
    var args = UiExe._parseCommandLine( s_args );
    switch( args["_"] ) {
      case "ask":
        UiExe._ask( args, s_done_label, s_error_label );
        break;
      case "choose":
        UiExe._choose( args, s_done_label, s_error_label );
        break;
      case "tell":
        UiExe._tell( args, s_done_label, s_error_label );
        break;
    }

    //Glue.run( o_glue, s_done_label );
    return false;   // we'll be manually continuing
  },

  _ask: function( d_data, s_done_label, s_error_label ) {
    var value = (d_data["value"] ? d_data["value"] : "");
    var field = _.c( 'input',
        { "width": "95%" },
        { "type": "text", "size": "40", "text": value }
      );
    var frame = UiExe._createDialogFrame(
        Dict.valueOf( d_data, "prompt" ),
        field,
        UiExe._handleAskOK,
        UiExe._handleAskCancel
      );
    field.addEventListener( "keypress", UiExe._fieldKeyHandler );
    frame["uiexe.field"] = field;
    frame["uiexe.label.done"] = s_done_label;
    frame["uiexe.label.error"] = s_error_label;
    frame["uiexe.data"] = d_data;
    document.getElementsByTagName( "body" )[0].appendChild( frame );
    field.focus();
  },

  _choose: function( d_data, s_done_label, s_error_label ) {
    var value = (d_data["value"] ? d_data["value"] : "");
    var field = _.c( 'select',
        { "width": "95%" },
        { "size": "8" }
      );
    var items = (d_data["items"] + "/"), s = 0, e, idx = 0;
    while( (e = items.indexOf( "/", s )) > -1 ) {
      var item = items.substr( s, (e - s) );
      s = (e + 1);
      var opt = _.c( "option" );
      opt.text = item;
      opt.value = idx;
      if( idx == d_data["value"] ) {
        opt.selected = true;
      }
      field.add( opt );
      idx++;
    }
    var frame = UiExe._createDialogFrame(
        Dict.valueOf( d_data, "prompt" ),
        field,
        UiExe._handleChooseOK,
        UiExe._handleChooseCancel
      );
    field.addEventListener( "keypress", UiExe._fieldKeyHandler );
    frame["uiexe.field"] = field;
    frame["uiexe.label.done"] = s_done_label;
    frame["uiexe.label.error"] = s_error_label;
    frame["uiexe.data"] = d_data;
    document.getElementsByTagName( "body" )[0].appendChild( frame );
    field.focus();

  },

  _tell: function( d_data, s_done_label, s_error_label ) {
    var field = _.c( 'div' );
    var lines = (d_data["value"] + "//"), s = 0, e;
    while( (e = lines.indexOf( "//", s )) > -1 ) {
      var line = lines.substr( s, (e - s) ).trim();
      s = (e + 2);
      if( !line ) {
        line = "\u00A0";    // nbsp in unicode
      }
      field.appendChild( _.at( _.c( "div" ), line ) );
    }
    var frame = UiExe._createDialogFrame(
        Dict.valueOf( d_data, "prompt" ),
        field,
        UiExe._handleTellOK,
        null
      );
    field.addEventListener( "keypress", UiExe._fieldKeyHandler );
    frame["uiexe.field"] = field;
    frame["uiexe.label.done"] = s_done_label;
    frame["uiexe.label.error"] = s_error_label;
    frame["uiexe.data"] = d_data;
    document.getElementsByTagName( "body" )[0].appendChild( frame );
    field.focus();
  },

  _createDialogFrame: function( s_text, o_innerdiv, f_on_ok, f_on_cancel ) {
    var text = _.c( 'div', { "padding": "5px", "font-weight": "bold" } );
    _.at( text, s_text );
    var wrap = _.c( 'div', {
        "overflow": "auto",
        "text-align": "center"
      } );
    wrap.appendChild( o_innerdiv );
    var btnstyle = {
          "margin": "2px", "padding": "5px", "background": "#ddd",
          "font-weight": "bold", "border": "1px solid #000", "cursor": "pointer"
      };
    var btns = _.c( 'div', { "padding": "15px" } );
    var ok, cancel;
    ok = _.at( _.c( 'button', btnstyle ), "OK" );
    ok.style["border"] = "2px solid #000";
    ok.addEventListener( "click", f_on_ok );
    ok["uiexe.type"] = 1;
    btns.appendChild( ok );
    if( f_on_cancel ) {
      cancel = _.at( _.c( 'button', btnstyle ), "Cancel" );
      cancel.addEventListener( "click", f_on_cancel );
      cancel["uiexe.type"] = 2;
      btns.appendChild( cancel );
    }
    var back = _.c( 'div', {
        "border": "2px solid #555",
        "margin": "1px",
        "background": "#fff",
        "padding": "10px",
        "position": "absolute",
        "width": "600px",
        //"height": "200px"
      } );
    back.appendChild( text );
    back.appendChild( wrap );
    back.appendChild( btns );
    // TODO: buttons
    var frame = _.c( 'div', {
        "position": "absolute",
        "top": "0px", "left": "0px", "width": "100%", "height": "100%",
        "text-align": "center",
        "z-index": "1000",
      } );
    var dimmer = _.c( 'div', {
        "position": "absolute",
        "top": "0px", "left": "0px", "width": "100%", "height": "100%",
        "background": "#444", "opacity": "0.5"
    } );
    frame.appendChild( dimmer );
    // clientWidth is inside width taking into account borders etc.
    // offsetWidth is the total width
    var body = document.getElementsByTagName("body")[0];
    _.s( back, { "left": ((body.clientWidth - 600) / 2), "top": "0px" } );
    frame.appendChild( back );
    ok["uiexe.frame"] = frame;
    if( f_on_cancel ) {
      cancel["uiexe.frame"] = frame;
    }
    return frame;
  },

  // Handle enter/esc
  _fieldKeyHandler: function( e ) {
    e = (e || event);
    var type;
    if( e.keyCode == 13 ) {
      type = 1;
    } else if( e.keyCode == 27 ) {    // doesn't get sent apparently...
      type = 2;
    } else {
      return;
    }
    var btns = document.getElementsByTagName( "button" );
    for( var i = 0; i < btns.length; i++ ) {
      if( btns[i]["uiexe.type"] && (btns[i]["uiexe.type"] == type) ) {
        btns[i].click();
        e.preventDefault();
        return;
      }
    }
  },

  _handleAskOK: function() {
      var frame = this["uiexe.frame"];
      frame.parentNode.removeChild( frame );
      UiExe._saveResult( frame["uiexe.data"], true, frame["uiexe.field"].value );
      GluePlatform.execFinished( UiExe._glue_instance, frame["uiexe.label.done"] );
  },

  _handleAskCancel: function() {
      var frame = this["uiexe.frame"];
      frame.parentNode.removeChild( frame );
      UiExe._saveResult( frame["uiexe.data"], false, "" );
      Glue.run( UiExe._glue_instance, frame["uiexe.label.done"] );
  },

  _handleChooseOK: function() {
      var frame = this["uiexe.frame"];
      frame.parentNode.removeChild( frame );
      UiExe._saveResult( frame["uiexe.data"], true, frame["uiexe.field"].value );
      Glue.run( UiExe._glue_instance, frame["uiexe.label.done"] );
  },

  _handleChooseCancel: function() {
      var frame = this["uiexe.frame"];
      frame.parentNode.removeChild( frame );
      UiExe._saveResult( frame["uiexe.data"], false, "" );
      Glue.run( UiExe._glue_instance, frame["uiexe.label.done"] );
  },

  _handleTellOK: function() {
      var frame = this["uiexe.frame"];
      frame.parentNode.removeChild( frame );
      UiExe._saveResult( frame["uiexe.data"], true, 1 );
      Glue.run( UiExe._glue_instance, frame["uiexe.label.done"] );
  },

  _saveResult: function( d_data, b_state, s_value ) {
    var res, fmt = d_data["format"];
    switch( fmt ) {
      case "json":
      case "jsonp":
        res = ('{ "value":' + (b_state ? "1" : "0") + ', value: "' +
            UiExe._deQuote( s_value ) + '" }'
          );
        if( fmt == "jsonp" ) {
          res = (d_data["func"] + "( " + res + " );");
        }
        break;
      case "text":
        res = (b_state ? s_value : "");
        break;
      default:
        res = ((b_state ? "+" : "-") + s_value);
        break;
    }
    if( d_data["to"] ) {
      if( d_data["to"] == "." ) {   // STDOUT normally
        console.log( res );
      } else {
        GlueFileManager.writeText( d_data["to"], res );
      }
    }
  },

  _parseCommandLine: function( s_cmdline, d_defaults ) {
        var d;
        if( d_defaults ) {
            d = d_defaults;
        } else {
            d = Dict.create();
        }
        var cmd, k = "_", v = "", in_q = false, word = "", c;
        for( var i = 0, l = s_cmdline.length; i <= l; i++ ) {
          if( i < l ) {
            c = s_cmdline.charAt( i );
          } else {
            c = " ";
          }
          if( in_q ) {
            if( c == '"' ) {
              in_q = false;
            } else if( c == "|" ) {
              word += s_cmdline.charAt( ++i );
            } else {
              word += c;
            }
          } else {
            if( c == " " ) {
              if( (word.length > 0) && (word.charAt( 0 ) == "-") && (k === "") ) {
                k = word.substr( 1 ).toLowerCase();
              } else {
                Dict.set( d, k, word );
                k = "";
              }
              word = "";
            } else if( c == "|" ) {
              word += s_cmdline.charAt( ++i );
            } else if( c == '"' ) {
              in_q = true;
            } else {
              word += c;
            }
          }
        }
        return d;
    }

};

GluePlatform.setExecApp( "ui.exe.js", "ui", UiExe );
<commit_msg>UI.exe doesn't automatically dim<commit_after>/**
 * Emulate ui.exe to provide user interaction via
 *  ask       - get a value
 *  choose    - choose a value from a list
 *
 */

var UiExe = {
  _glue_instance: null,

  /**
   * ui MODE [options]
   * MODE is "ask", "choose" or "tell"
   * options contains
   *    -prompt     The prompt to show
   *    -to         Target file to write to, use "." for STDOUT or "" (or skip) to not
   *                write anything (ie. for INFO)
   *    -format     Output format:
   *                  txt|text- the string or "" if cancelled (or empty if nothing entered)
   *                  mtext|"" - marked text, "+" (OK) or "-" (Cancel) followed by the value
   *                  json - json object with the keys "status" (1|0) and "value"
   *                  jsonp - same as json but wrapped in the function specified in -func
   *    -value      The current value (a string for "ask", or index for "choose")
   *    -items      / separated list of items to use with choose
   */
  glueExec: function( o_glue, s_args, s_done_label, s_error_label ) {
    UiExe._glue_instance = o_glue;
    var args = UiExe._parseCommandLine( s_args );
    switch( args["_"] ) {
      case "ask":
        UiExe._ask( args, s_done_label, s_error_label );
        break;
      case "choose":
        UiExe._choose( args, s_done_label, s_error_label );
        break;
      case "tell":
        UiExe._tell( args, s_done_label, s_error_label );
        break;
    }

    //Glue.run( o_glue, s_done_label );
    return false;   // we'll be manually continuing
  },

  _ask: function( d_data, s_done_label, s_error_label ) {
    var value = (d_data["value"] ? d_data["value"] : "");
    var field = _.c( 'input',
        { "width": "95%" },
        { "type": "text", "size": "40", "text": value }
      );
    var frame = UiExe._createDialogFrame(
        Dict.valueOf( d_data, "prompt" ),
        field,
        UiExe._handleAskOK,
        UiExe._handleAskCancel,
        Dict.intValueOf( d_data, "dim" )
      );
    field.addEventListener( "keypress", UiExe._fieldKeyHandler );
    frame["uiexe.field"] = field;
    frame["uiexe.label.done"] = s_done_label;
    frame["uiexe.label.error"] = s_error_label;
    frame["uiexe.data"] = d_data;
    document.getElementsByTagName( "body" )[0].appendChild( frame );
    field.focus();
  },

  _choose: function( d_data, s_done_label, s_error_label ) {
    var value = (d_data["value"] ? d_data["value"] : "");
    var field = _.c( 'select',
        { "width": "95%" },
        { "size": "8" }
      );
    var items = (d_data["items"] + "/"), s = 0, e, idx = 0;
    while( (e = items.indexOf( "/", s )) > -1 ) {
      var item = items.substr( s, (e - s) );
      s = (e + 1);
      var opt = _.c( "option" );
      opt.text = item;
      opt.value = idx;
      if( idx == d_data["value"] ) {
        opt.selected = true;
      }
      field.add( opt );
      idx++;
    }
    var frame = UiExe._createDialogFrame(
        Dict.valueOf( d_data, "prompt" ),
        field,
        UiExe._handleChooseOK,
        UiExe._handleChooseCancel,
        Dict.intValueOf( d_data, "dim" )
      );
    field.addEventListener( "keypress", UiExe._fieldKeyHandler );
    frame["uiexe.field"] = field;
    frame["uiexe.label.done"] = s_done_label;
    frame["uiexe.label.error"] = s_error_label;
    frame["uiexe.data"] = d_data;
    document.getElementsByTagName( "body" )[0].appendChild( frame );
    field.focus();

  },

  _tell: function( d_data, s_done_label, s_error_label ) {
    var field = _.c( 'div' );
    var lines = (d_data["value"] + "//"), s = 0, e;
    while( (e = lines.indexOf( "//", s )) > -1 ) {
      var line = lines.substr( s, (e - s) ).trim();
      s = (e + 2);
      if( !line ) {
        line = "\u00A0";    // nbsp in unicode
      }
      field.appendChild( _.at( _.c( "div" ), line ) );
    }
    var frame = UiExe._createDialogFrame(
        Dict.valueOf( d_data, "prompt" ),
        field,
        UiExe._handleTellOK,
        null,
        Dict.intValueOf( d_data, "dim" )
      );
    field.addEventListener( "keypress", UiExe._fieldKeyHandler );
    frame["uiexe.field"] = field;
    frame["uiexe.label.done"] = s_done_label;
    frame["uiexe.label.error"] = s_error_label;
    frame["uiexe.data"] = d_data;
    document.getElementsByTagName( "body" )[0].appendChild( frame );
    field.focus();
  },

  _createDialogFrame: function( s_text, o_innerdiv, f_on_ok, f_on_cancel, i_usedimmer ) {
    var text = _.c( 'div', { "padding": "5px", "font-weight": "bold" } );
    _.at( text, s_text );
    var wrap = _.c( 'div', {
        "overflow": "auto",
        "text-align": "center"
      } );
    wrap.appendChild( o_innerdiv );
    var btnstyle = {
          "margin": "2px", "padding": "5px", "background": "#ddd",
          "font-weight": "bold", "border": "1px solid #000", "cursor": "pointer"
      };
    var btns = _.c( 'div', { "padding": "15px" } );
    var ok, cancel;
    ok = _.at( _.c( 'button', btnstyle ), "OK" );
    ok.style["border"] = "2px solid #000";
    ok.addEventListener( "click", f_on_ok );
    ok["uiexe.type"] = 1;
    btns.appendChild( ok );
    if( f_on_cancel ) {
      cancel = _.at( _.c( 'button', btnstyle ), "Cancel" );
      cancel.addEventListener( "click", f_on_cancel );
      cancel["uiexe.type"] = 2;
      btns.appendChild( cancel );
    }
    var back = _.c( 'div', {
        "border": "2px solid #555",
        "margin": "1px",
        "background": "#fff",
        "padding": "10px",
        "position": "absolute",
        "width": "600px",
        //"height": "200px"
      } );
    back.appendChild( text );
    back.appendChild( wrap );
    back.appendChild( btns );
    // TODO: buttons
    var frame = _.c( 'div', {
        "position": "absolute",
        "top": "0px", "left": "0px", "width": "100%", "height": "100%",
        "text-align": "center",
        "z-index": "1000",
      } );
    if( i_usedimmer == 1 ) {
      var dimmer = _.c( 'div', {
          "position": "absolute",
          "top": "0px", "left": "0px", "width": "100%", "height": "100%",
          "background": "#444", "opacity": "0.5"
        } );
      frame.appendChild( dimmer );
    } else {
      back.style.backgroundColor = "#ffd";
    }
    // clientWidth is inside width taking into account borders etc.
    // offsetWidth is the total width
    var body = document.getElementsByTagName("body")[0];
    _.s( back, { "left": ((body.clientWidth - 600) / 2), "top": "0px" } );
    frame.appendChild( back );
    ok["uiexe.frame"] = frame;
    if( f_on_cancel ) {
      cancel["uiexe.frame"] = frame;
    }
    return frame;
  },

  // Handle enter/esc
  _fieldKeyHandler: function( e ) {
    e = (e || event);
    var type;
    if( e.keyCode == 13 ) {
      type = 1;
    } else if( e.keyCode == 27 ) {    // doesn't get sent apparently...
      type = 2;
    } else {
      return;
    }
    var btns = document.getElementsByTagName( "button" );
    for( var i = 0; i < btns.length; i++ ) {
      if( btns[i]["uiexe.type"] && (btns[i]["uiexe.type"] == type) ) {
        btns[i].click();
        e.preventDefault();
        return;
      }
    }
  },

  _handleAskOK: function() {
      var frame = this["uiexe.frame"];
      frame.parentNode.removeChild( frame );
      UiExe._saveResult( frame["uiexe.data"], true, frame["uiexe.field"].value );
      GluePlatform.execFinished( UiExe._glue_instance, frame["uiexe.label.done"] );
  },

  _handleAskCancel: function() {
      var frame = this["uiexe.frame"];
      frame.parentNode.removeChild( frame );
      UiExe._saveResult( frame["uiexe.data"], false, "" );
      Glue.run( UiExe._glue_instance, frame["uiexe.label.done"] );
  },

  _handleChooseOK: function() {
      var frame = this["uiexe.frame"];
      frame.parentNode.removeChild( frame );
      UiExe._saveResult( frame["uiexe.data"], true, frame["uiexe.field"].value );
      Glue.run( UiExe._glue_instance, frame["uiexe.label.done"] );
  },

  _handleChooseCancel: function() {
      var frame = this["uiexe.frame"];
      frame.parentNode.removeChild( frame );
      UiExe._saveResult( frame["uiexe.data"], false, "" );
      Glue.run( UiExe._glue_instance, frame["uiexe.label.done"] );
  },

  _handleTellOK: function() {
      var frame = this["uiexe.frame"];
      frame.parentNode.removeChild( frame );
      UiExe._saveResult( frame["uiexe.data"], true, 1 );
      Glue.run( UiExe._glue_instance, frame["uiexe.label.done"] );
  },

  _saveResult: function( d_data, b_state, s_value ) {
    var res, fmt = d_data["format"];
    switch( fmt ) {
      case "json":
      case "jsonp":
        res = ('{ "value":' + (b_state ? "1" : "0") + ', value: "' +
            UiExe._deQuote( s_value ) + '" }'
          );
        if( fmt == "jsonp" ) {
          res = (d_data["func"] + "( " + res + " );");
        }
        break;
      case "text":
        res = (b_state ? s_value : "");
        break;
      default:
        res = ((b_state ? "+" : "-") + s_value);
        break;
    }
    if( d_data["to"] ) {
      if( d_data["to"] == "." ) {   // STDOUT normally
        console.log( res );
      } else {
        GlueFileManager.writeText( d_data["to"], res );
      }
    }
  },

  _parseCommandLine: function( s_cmdline, d_defaults ) {
        var d;
        if( d_defaults ) {
            d = d_defaults;
        } else {
            d = Dict.create();
        }
        var cmd, k = "_", v = "", in_q = false, word = "", c;
        for( var i = 0, l = s_cmdline.length; i <= l; i++ ) {
          if( i < l ) {
            c = s_cmdline.charAt( i );
          } else {
            c = " ";
          }
          if( in_q ) {
            if( c == '"' ) {
              in_q = false;
            } else if( c == "|" ) {
              word += s_cmdline.charAt( ++i );
            } else {
              word += c;
            }
          } else {
            if( c == " " ) {
              if( (word.length > 0) && (word.charAt( 0 ) == "-") && (k === "") ) {
                k = word.substr( 1 ).toLowerCase();
              } else {
                Dict.set( d, k, word );
                k = "";
              }
              word = "";
            } else if( c == "|" ) {
              word += s_cmdline.charAt( ++i );
            } else if( c == '"' ) {
              in_q = true;
            } else {
              word += c;
            }
          }
        }
        return d;
    }

};

GluePlatform.setExecApp( "ui.exe.js", "ui", UiExe );
<|endoftext|>


<commit_before>module.exports = function(grunt) {
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),

    // Here we put some informations about the project like CSS or JS folder path.
    project: {
      files: {
        js: 'source/assets/javascripts/locastyle/**/*.js',
        css: 'source/assets/stylesheets/locastyle/**/*.css'
      }
    },
    jshint: {
      files: ['Gruntfile.js', '<%= project.files.js %>'],
      options: {
        funcscope: true,
        globalstrict: false,
        unused: true,
        validthis: true,
        globals: {
          jQuery: true,
          console: true,
          module: true
        }
      }
    },
    plato: {
      task: {
        files: {
        'source/documentacao/report-js': ['<%= project.files.js %>']
        }
      }
    },
    githooks: {
      all: {
        'pre-commit': 'jshint',
      }
    },
    watch: {
      files: ['<%= project.files.js %>'],
      tasks: ['jshint', 'githooks']
    }
  });

  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-jasmine');
  grunt.loadNpmTasks('grunt-githooks');
  grunt.loadNpmTasks('grunt-plato');

  grunt.registerTask('default', ['plato', 'jshint']);
  grunt.registerTask('test', ['jshint']);
};

<commit_msg>Now, when you run ‘grunt test’ the Grunt will execute JSHint and Jasmine (based on CI) tasks.<commit_after>module.exports = function(grunt) {
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),

    jasmine: {
      src: '<%= project.jasmine.files %>',
      options: {
        specs: 'spec/javascripts/*_spec.js',
        helpers: 'spec/javascripts/helpers/*.js',
        vendor: [
          "spec/javascripts/libs/*.js"
        ]
      }
    },
    jshint: {
      files: ['Gruntfile.js', '<%= project.files.js %>'],
      options: {
        funcscope: true,
        globalstrict: false,
        unused: true,
        validthis: true,
        globals: {
          jQuery: true,
          console: true,
          module: true
        }
      }
    },
    plato: {
      task: {
        files: {
        'source/documentacao/report-js': ['<%= project.files.js %>']
        }
      }
    },
    githooks: {
      all: {
        'pre-commit': 'jshint',
      }
    },
    watch: {
      files: ['<%= project.files.js %>'],
      tasks: ['']
    },

    ////
    // Here we put some informations about the project like CSS or JS folder path.
    ////
    project: {
      files: {
        js: 'source/assets/javascripts/locastyle/**/*.js',
        css: 'source/assets/stylesheets/locastyle/**/*.css',
      },
      jasmine: {
        files: [
          "source/assets/javascripts/libs/_hopscotch.js",
          "source/assets/javascripts/libs/_jquery.cookie.js",
          "source/assets/javascripts/libs/jquery.mask.js",
          "source/assets/javascripts/libs/moment.min.js",
          "source/assets/javascripts/libs/pikaday.js",
          "source/assets/javascripts/libs/pikaday.jquery.js",
          "source/assets/javascripts/locastyle/_initializer.js",
          "source/assets/javascripts/locastyle/_datepicker.js",
          "source/assets/javascripts/locastyle/_popover.js",
          "source/assets/javascripts/locastyle/_templates.js",
          "source/assets/javascripts/locastyle/_collapse.js",
          "source/assets/javascripts/locastyle/_tabs.js",
          "source/assets/javascripts/locastyle/_dropdown.js",
          "source/assets/javascripts/locastyle/_general.js",
          "source/assets/javascripts/locastyle/_modal.js",
          "source/assets/javascripts/locastyle/_alert.js",
          "source/assets/javascripts/locastyle/_form.js",
          "source/assets/javascripts/locastyle/_dismiss.js",
          "source/assets/javascripts/locastyle/_breakpoint-check.js",
          "source/assets/javascripts/locastyle/_topbar-curtain.js",
          "source/assets/javascripts/locastyle/_btn-group.js",
          "source/assets/javascripts/locastyle/_sidebars.js",
          "source/assets/javascripts/locastyle/_sidebar-toggle.js",
          "source/assets/javascripts/locastyle/_progress-bar.js",
          "source/assets/javascripts/locastyle/_char-counter.js",
          "source/assets/javascripts/locastyle/_track-events.js",
          "source/assets/javascripts/locastyle/_browser-detect.js",
          "source/assets/javascripts/locastyle/_browser-unsupported-bar.js",
          "source/assets/javascripts/locastyle/_steps.js",
          "source/assets/javascripts/locastyle/_tabs-button.js",
        ]
      },
    },
  });

  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-jasmine');
  grunt.loadNpmTasks('grunt-githooks');
  grunt.loadNpmTasks('grunt-plato');

  grunt.registerTask('default', ['plato', 'jshint']);
  grunt.registerTask('test', ['jshint', 'jasmine']);
};

<|endoftext|>


<commit_before>import { addBooleanParameter, addDefaultParameter } from '@ovh-ux/ui-kit.core/src/js/component-utils';
import find from 'lodash/find';
import isEmpty from 'lodash/isEmpty';
import orderBy from 'lodash/orderBy';
import remove from 'lodash/remove';

export default class {
  constructor($attrs, $compile, $element, $filter, $scope,
    $timeout, $window, ouiFileConfiguration) {
    'ngInject';

    this.$attrs = $attrs;
    this.$compile = $compile;
    this.$element = $element;
    this.$filter = $filter;
    this.$scope = $scope;
    this.$timeout = $timeout;
    this.$window = $window;

    this.translations = ouiFileConfiguration.translations;
    this.units = orderBy(this.$filter('orderBy')(ouiFileConfiguration.units, '-size'), 'size', 'desc');
  }

  checkFileValidity(_file_) {
    const file = _file_;

    if (file) {
      file.errors = {};

      // Check maxsize
      if (this.maxsize && file.size > this.maxsize) {
        file.errors.maxsize = true;
      }

      // Set form validation
      if (this.form && this.form[this.name]) {
        this.form[this.name].$setValidity('maxsize', !file.errors.maxsize);
        this.form[this.name].$setDirty();
      }

      // Clean errors
      if (isEmpty(file.errors)) {
        delete file.errors;
      }
    }

    return file;
  }

  loadFilePreview(_file_) {
    const file = _file_;

    // Load preview only if image
    if (this.preview && !file.errors && file.type && file.type.search(/^image\//) !== -1) {
      file.loading = true;

      file.reader = new this.$window.FileReader();
      file.reader.readAsDataURL(file);
      file.reader.onload = () => {
        file.preview = `url("${file.reader.result}")`;

        this.$scope.$apply();
      };
    }

    return file;
  }

  addFile(file) {
    this.getFileInfos(file);
    this.checkFileValidity(file);

    this.model = [file];
    this.onSelect({ modelValue: this.model });
    this.$scope.$apply();

    // Set back focus on fake selector
    this.$element[0].querySelector('.oui-file-selector__label').focus();
  }

  addFiles(files) {
    if (!this.model) {
      this.model = [];
    }

    if (angular.isArray(files)) {
      files.forEach((file) => {
        // Check for duplicate before adding
        if (!find(this.model, item => file.name === item.name)) {
          this.getFileInfos(file);
          this.checkFileValidity(file);
          this.loadFilePreview(file);
          this.model.push(file);
        }
      });

      this.onSelect({ modelValue: this.model });
      this.$scope.$apply();
    }
  }

  removeFile(file) {
    if (angular.isArray(this.model)) {
      remove(this.model, item => item === file);
    }
  }

  resetFile() {
    this.model = undefined;
    this.fileSelector[0].value = '';

    if (this.form && this.form[this.name]) {
      this.form[this.name].$setValidity('maxsize', true);
    }
  }

  openFileSelector() {
    // triggerHandler("click") don't work here
    this.fileSelector[0].click();
  }

  getFileInfos(_file_) {
    const file = _file_;
    const parts = file.name.split('.');
    const extension = parts.length > 1 ? parts.pop() : undefined;
    const name = parts.join('.');

    file.infos = {
      extension,
      name,
      size: this.getFileSize(file),
    };

    return file;
  }

  getFileSize(file) {
    let fileSize;

    // Parse units dictionnary in desc order
    // and break when the best units for file size is found
    // (when above 1 or last of dictionnary)
    let size = 0;
    this.units.forEach((unit) => {
      if (unit.size && angular.isNumber(unit.size)) {
        const unitSize = Math.floor(file.size / unit.size);

        // Should be the closest to 1
        if (!size) {
          size = Math.max(unitSize, size);
        } else {
          size = Math.min(unitSize, size);
        }

        // Update only if the right unit
        if (size === unitSize) {
          fileSize = `(${size} ${unit.suffix})`;
        }
      }
    });

    return fileSize;
  }

  setInputTouched() {
    if (this.form && this.form[this.name]) {
      // Set input[hidden] to touched for form validation
      this.form[this.name].$setTouched();
    }
  }

  $onInit() {
    addBooleanParameter(this, 'disabled');
    addBooleanParameter(this, 'required');
    addBooleanParameter(this, 'multiple');
    addBooleanParameter(this, 'droparea');
    addBooleanParameter(this, 'preview');

    addDefaultParameter(this, 'id', `ouiFile${this.$scope.$id}`);
    addDefaultParameter(this, 'name', `ouiFile${this.$scope.$id}`);

    this.selectorId = `${this.id}Selector`;
    this.dropareaId = `${this.id}Droparea`;
    this.attachments = Boolean(this.multiple || this.droparea || this.preview);
  }

  $postLink() {
    this.$timeout(() => {
      this.$element
        .addClass('oui-file')
        .removeAttr('id')
        .removeAttr('name');

      // ngChange don't work on input file
      this.fileSelector = angular.element(this.$element[0].querySelector(`#${this.selectorId}`));
      this.fileSelector.on('change', (e) => {
        if (this.attachments) {
          // FileList from input file is read-only
          // Needed to be port as an array for manipulation
          this.addFiles(Array.from(e.target.files));
        } else {
          this.addFile(e.target.files[0]);
        }
      });

      if (this.droparea) {
        this.fileDroparea = angular.element(this.$element[0].querySelector(`#${this.dropareaId}`));
        this.fileDroparea
          .on('drag dragstart dragend dragover dragenter dragleave drop', (e) => {
            e.preventDefault();
            e.stopPropagation();
          })
          .on('dragover dragenter', () => this.fileDroparea.addClass('oui-file-droparea_dragover'))
          .on('dragleave dragend drop', () => this.fileDroparea.removeClass('oui-file-droparea_dragover'))
          .on('drop', (e) => {
            // FileList from input file is read-only
            // Needed to be port as an array for manipulation
            if (!this.disabled && e.dataTransfer) {
              this.addFiles(Array.from(e.dataTransfer.files));
            }
          });
      }
    });
  }
}
<commit_msg>fix(file): fix loading in preview mode<commit_after>import { addBooleanParameter, addDefaultParameter } from '@ovh-ux/ui-kit.core/src/js/component-utils';
import find from 'lodash/find';
import isEmpty from 'lodash/isEmpty';
import orderBy from 'lodash/orderBy';
import remove from 'lodash/remove';

export default class {
  constructor($attrs, $compile, $element, $filter, $scope,
    $timeout, $window, ouiFileConfiguration) {
    'ngInject';

    this.$attrs = $attrs;
    this.$compile = $compile;
    this.$element = $element;
    this.$filter = $filter;
    this.$scope = $scope;
    this.$timeout = $timeout;
    this.$window = $window;

    this.translations = ouiFileConfiguration.translations;
    this.units = orderBy(this.$filter('orderBy')(ouiFileConfiguration.units, '-size'), 'size', 'desc');
  }

  checkFileValidity(_file_) {
    const file = _file_;

    if (file) {
      file.errors = {};

      // Check maxsize
      if (this.maxsize && file.size > this.maxsize) {
        file.errors.maxsize = true;
      }

      // Set form validation
      if (this.form && this.form[this.name]) {
        this.form[this.name].$setValidity('maxsize', !file.errors.maxsize);
        this.form[this.name].$setDirty();
      }

      // Clean errors
      if (isEmpty(file.errors)) {
        delete file.errors;
      }
    }

    return file;
  }

  loadFilePreview(_file_) {
    const file = _file_;

    // Load preview only if image
    if (this.preview && !file.errors && file.type && file.type.search(/^image\//) !== -1) {
      file.loading = true;

      file.reader = new this.$window.FileReader();
      file.reader.readAsDataURL(file);
      file.reader.onload = () => {
        file.loading = false;
        file.preview = `url("${file.reader.result}")`;

        this.$scope.$apply();
      };
    }

    return file;
  }

  addFile(file) {
    this.getFileInfos(file);
    this.checkFileValidity(file);

    this.model = [file];
    this.onSelect({ modelValue: this.model });
    this.$scope.$apply();

    // Set back focus on fake selector
    this.$element[0].querySelector('.oui-file-selector__label').focus();
  }

  addFiles(files) {
    if (!this.model) {
      this.model = [];
    }

    if (angular.isArray(files)) {
      files.forEach((file) => {
        // Check for duplicate before adding
        if (!find(this.model, item => file.name === item.name)) {
          this.getFileInfos(file);
          this.checkFileValidity(file);
          this.loadFilePreview(file);
          this.model.push(file);
        }
      });

      this.onSelect({ modelValue: this.model });
      this.$scope.$apply();
    }
  }

  removeFile(file) {
    if (angular.isArray(this.model)) {
      remove(this.model, item => item === file);
    }
  }

  resetFile() {
    this.model = undefined;
    this.fileSelector[0].value = '';

    if (this.form && this.form[this.name]) {
      this.form[this.name].$setValidity('maxsize', true);
    }
  }

  openFileSelector() {
    // triggerHandler("click") don't work here
    this.fileSelector[0].click();
  }

  getFileInfos(_file_) {
    const file = _file_;
    const parts = file.name.split('.');
    const extension = parts.length > 1 ? parts.pop() : undefined;
    const name = parts.join('.');

    file.infos = {
      extension,
      name,
      size: this.getFileSize(file),
    };

    return file;
  }

  getFileSize(file) {
    let fileSize;

    // Parse units dictionnary in desc order
    // and break when the best units for file size is found
    // (when above 1 or last of dictionnary)
    let size = 0;
    this.units.forEach((unit) => {
      if (unit.size && angular.isNumber(unit.size)) {
        const unitSize = Math.floor(file.size / unit.size);

        // Should be the closest to 1
        if (!size) {
          size = Math.max(unitSize, size);
        } else {
          size = Math.min(unitSize, size);
        }

        // Update only if the right unit
        if (size === unitSize) {
          fileSize = `(${size} ${unit.suffix})`;
        }
      }
    });

    return fileSize;
  }

  setInputTouched() {
    if (this.form && this.form[this.name]) {
      // Set input[hidden] to touched for form validation
      this.form[this.name].$setTouched();
    }
  }

  $onInit() {
    addBooleanParameter(this, 'disabled');
    addBooleanParameter(this, 'required');
    addBooleanParameter(this, 'multiple');
    addBooleanParameter(this, 'droparea');
    addBooleanParameter(this, 'preview');

    addDefaultParameter(this, 'id', `ouiFile${this.$scope.$id}`);
    addDefaultParameter(this, 'name', `ouiFile${this.$scope.$id}`);

    this.selectorId = `${this.id}Selector`;
    this.dropareaId = `${this.id}Droparea`;
    this.attachments = Boolean(this.multiple || this.droparea || this.preview);
  }

  $postLink() {
    this.$timeout(() => {
      this.$element
        .addClass('oui-file')
        .removeAttr('id')
        .removeAttr('name');

      // ngChange don't work on input file
      this.fileSelector = angular.element(this.$element[0].querySelector(`#${this.selectorId}`));
      this.fileSelector.on('change', (e) => {
        if (this.attachments) {
          // FileList from input file is read-only
          // Needed to be port as an array for manipulation
          this.addFiles(Array.from(e.target.files));
        } else {
          this.addFile(e.target.files[0]);
        }
      });

      if (this.droparea) {
        this.fileDroparea = angular.element(this.$element[0].querySelector(`#${this.dropareaId}`));
        this.fileDroparea
          .on('drag dragstart dragend dragover dragenter dragleave drop', (e) => {
            e.preventDefault();
            e.stopPropagation();
          })
          .on('dragover dragenter', () => this.fileDroparea.addClass('oui-file-droparea_dragover'))
          .on('dragleave dragend drop', () => this.fileDroparea.removeClass('oui-file-droparea_dragover'))
          .on('drop', (e) => {
            // FileList from input file is read-only
            // Needed to be port as an array for manipulation
            if (!this.disabled && e.dataTransfer) {
              this.addFiles(Array.from(e.dataTransfer.files));
            }
          });
      }
    });
  }
}
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import { compose, branch, renderNothing } from 'recompose';
import { connect } from 'react-redux';
import { DragSource } from 'react-dnd';
import { DropTarget } from 'react-dnd';

import { findItem, canMove } from 'lib/treeUtils';
import { DocRefBreadcrumb } from 'components/DocRefBreadcrumb';
import { actionCreators as docRefListingActionCreators } from './redux';
import { actionCreators as folderExplorerActionCreators } from 'components/FolderExplorer/redux';
import ItemTypes from './dragDropTypes';

const { docRefSelectionToggled } = docRefListingActionCreators;
const { prepareDocRefCopy, prepareDocRefMove } = folderExplorerActionCreators;

const dropTarget = {
  canDrop(
    {
      docRefWithLineage: { node },
    },
    monitor,
  ) {
    const { docRefs } = monitor.getItem();

    return !!node && docRefs.reduce((acc, curr) => acc && canMove(curr, node), true);
  },
  drop(
    {
      prepareDocRefCopy,
      prepareDocRefMove,
      docRefWithLineage: { node },
    },
    monitor,
  ) {
    const { docRefs, isCopy } = monitor.getItem();
    const docRefUuids = docRefs.map(d => d.uuid);

    if (isCopy) {
      prepareDocRefCopy(docRefUuids, node.uuid);
    } else {
      prepareDocRefMove(docRefUuids, node.uuid);
    }
  },
};

function dropCollect(connect, monitor) {
  return {
    connectDropTarget: connect.dropTarget(),
    isOver: monitor.isOver(),
    canDrop: monitor.canDrop(),
  };
}

const dragSource = {
  canDrag(props) {
    return true;
  },
  beginDrag({docRefUuid, docRefListing: { selectedDocRefUuids, filteredDocRefs}, keyIsDown:{Control, Meta}}) {
    let docRefUuids = [docRefUuid];

    // If we are dragging one of the items in a selection, bring across the entire selection
    if (selectedDocRefUuids.includes(docRefUuid)) {
      docRefUuids = selectedDocRefUuids;
    }

    return {
      docRefs: filteredDocRefs.filter(d => docRefUuids.includes(d.uuid)),
      isCopy: !!(Control || Meta),
    };
  },
};

function dragCollect(connect, monitor) {
  return {
    connectDragSource: connect.dragSource(),
    isDragging: monitor.isDragging(),
  };
}

const enhance = compose(
  connect(
    ({ folderExplorer: { documentTree }, docRefListing, keyIsDown }, { listingId, docRefUuid }) => ({
      docRefListing: docRefListing[listingId],
      docRefWithLineage: findItem(documentTree, docRefUuid),
      keyIsDown,
    }),
    {
      docRefSelectionToggled,
      prepareDocRefCopy,
      prepareDocRefMove,
    },
  ),
  branch(({ docRefWithLineage: { node } }) => !node, renderNothing),
  DropTarget([ItemTypes.DOC_REF_UUIDS], dropTarget, dropCollect),
  DragSource(ItemTypes.DOC_REF_UUIDS, dragSource, dragCollect),
);

const DocRefListingEntry = ({
  docRefWithLineage: { node },
  listingId,
  docRefListing: { selectedDocRefUuids, inMultiSelectMode },
  onNameClick,
  includeBreadcrumb,
  docRefSelectionToggled,
  openDocRef,
  keyIsDown,
  connectDropTarget,
  connectDragSource,
  isOver,
  canDrop,
}) => {
  let className = 'doc-ref-listing__item';
  if (selectedDocRefUuids.includes(node.uuid)) {
    className += ' doc-ref-listing__item--selected';
  }
  if (isOver) {
    className += ' dnd-over';
  }
  if (isOver) {
    if (canDrop) {
      className += ' can-drop';
    } else {
      className += ' cannot-drop';
    }
  }

  return connectDragSource(connectDropTarget(
 {
        docRefSelectionToggled(listingId, node.uuid, keyIsDown);
        e.preventDefault();
      }}
>

    <img
      className="stroom-icon--large"
      alt="X"
      src={require(`../../images/docRefTypes/${node.type}.svg`)}
    />
     {
            onNameClick(node);
            e.stopPropagation();
            e.preventDefault();
          }}
    >
      {node.name}

  {includeBreadcrumb && <DocRefBreadcrumb docRefUuid={node.uuid} openDocRef={openDocRef} />}

))

        };

const EnhancedDocRefListingEntry = enhance(DocRefListingEntry);

EnhancedDocRefListingEntry.propTypes = {
  listingId: PropTypes.string.isRequired,
  docRefUuid: PropTypes.string.isRequired,
  includeBreadcrumb: PropTypes.bool.isRequired,
  onNameClick: PropTypes.func.isRequired,
  openDocRef: PropTypes.func.isRequired,
};

EnhancedDocRefListingEntry.defaultProps = {
  checkedDocRefs: [],
  includeBreadcrumb: true,
};

export default EnhancedDocRefListingEntry;
<commit_msg>fixed bug when dragging to non folders<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import { compose, branch, renderNothing } from 'recompose';
import { connect } from 'react-redux';
import { DragSource } from 'react-dnd';
import { DropTarget } from 'react-dnd';

import { findItem, canMove } from 'lib/treeUtils';
import { DocRefBreadcrumb } from 'components/DocRefBreadcrumb';
import { actionCreators as docRefListingActionCreators } from './redux';
import { actionCreators as folderExplorerActionCreators } from 'components/FolderExplorer/redux';
import ItemTypes from './dragDropTypes';

const { docRefSelectionToggled } = docRefListingActionCreators;
const { prepareDocRefCopy, prepareDocRefMove } = folderExplorerActionCreators;

const dropTarget = {
  canDrop(
    {
      docRefWithLineage: { node },
    },
    monitor,
  ) {
    const { docRefs } = monitor.getItem();

    return !!node && node.type === 'Folder' && docRefs.reduce((acc, curr) => acc && canMove(curr, node), true);
  },
  drop(
    {
      prepareDocRefCopy,
      prepareDocRefMove,
      docRefWithLineage: { node },
    },
    monitor,
  ) {
    const { docRefs, isCopy } = monitor.getItem();
    const docRefUuids = docRefs.map(d => d.uuid);

    if (isCopy) {
      prepareDocRefCopy(docRefUuids, node.uuid);
    } else {
      prepareDocRefMove(docRefUuids, node.uuid);
    }
  },
};

function dropCollect(connect, monitor) {
  return {
    connectDropTarget: connect.dropTarget(),
    isOver: monitor.isOver(),
    canDrop: monitor.canDrop(),
  };
}

const dragSource = {
  canDrag(props) {
    return true;
  },
  beginDrag({docRefUuid, docRefListing: { selectedDocRefUuids, filteredDocRefs}, keyIsDown:{Control, Meta}}) {
    let docRefUuids = [docRefUuid];

    // If we are dragging one of the items in a selection, bring across the entire selection
    if (selectedDocRefUuids.includes(docRefUuid)) {
      docRefUuids = selectedDocRefUuids;
    }

    return {
      docRefs: filteredDocRefs.filter(d => docRefUuids.includes(d.uuid)),
      isCopy: !!(Control || Meta),
    };
  },
};

function dragCollect(connect, monitor) {
  return {
    connectDragSource: connect.dragSource(),
    isDragging: monitor.isDragging(),
  };
}

const enhance = compose(
  connect(
    ({ folderExplorer: { documentTree }, docRefListing, keyIsDown }, { listingId, docRefUuid }) => ({
      docRefListing: docRefListing[listingId],
      docRefWithLineage: findItem(documentTree, docRefUuid),
      keyIsDown,
    }),
    {
      docRefSelectionToggled,
      prepareDocRefCopy,
      prepareDocRefMove,
    },
  ),
  branch(({ docRefWithLineage: { node } }) => !node, renderNothing),
  DropTarget([ItemTypes.DOC_REF_UUIDS], dropTarget, dropCollect),
  DragSource(ItemTypes.DOC_REF_UUIDS, dragSource, dragCollect),
);

const DocRefListingEntry = ({
  docRefWithLineage: { node },
  listingId,
  docRefListing: { selectedDocRefUuids, inMultiSelectMode },
  onNameClick,
  includeBreadcrumb,
  docRefSelectionToggled,
  openDocRef,
  keyIsDown,
  connectDropTarget,
  connectDragSource,
  isOver,
  canDrop,
}) => {
  let className = 'doc-ref-listing__item';
  if (selectedDocRefUuids.includes(node.uuid)) {
    className += ' doc-ref-listing__item--selected';
  }
  if (isOver) {
    className += ' dnd-over';
  }
  if (isOver) {
    if (canDrop) {
      className += ' can-drop';
    } else {
      className += ' cannot-drop';
    }
  }

  return connectDragSource(connectDropTarget(
 {
        docRefSelectionToggled(listingId, node.uuid, keyIsDown);
        e.preventDefault();
      }}
>

    <img
      className="stroom-icon--large"
      alt="X"
      src={require(`../../images/docRefTypes/${node.type}.svg`)}
    />
     {
            onNameClick(node);
            e.stopPropagation();
            e.preventDefault();
          }}
    >
      {node.name}

  {includeBreadcrumb && <DocRefBreadcrumb docRefUuid={node.uuid} openDocRef={openDocRef} />}

))

        };

const EnhancedDocRefListingEntry = enhance(DocRefListingEntry);

EnhancedDocRefListingEntry.propTypes = {
  listingId: PropTypes.string.isRequired,
  docRefUuid: PropTypes.string.isRequired,
  includeBreadcrumb: PropTypes.bool.isRequired,
  onNameClick: PropTypes.func.isRequired,
  openDocRef: PropTypes.func.isRequired,
};

EnhancedDocRefListingEntry.defaultProps = {
  checkedDocRefs: [],
  includeBreadcrumb: true,
};

export default EnhancedDocRefListingEntry;
<|endoftext|>


<commit_before>(function(module) {
  var homeController = {};

  homeController.index = function() {
    $('#home').show().siblings().hide();
    $('#login-signup').hide();
  };

  // homeController.dbTest = function(){
  //   $.getJSON('/data', function (result) {
  //     result.rows.forEach(function(item) {
  //       console.log(item);
  //     });
  //   });
  // };
  // homeController.dbTest();

  module.homeController = homeController;
})(window);
<commit_msg>uncommented DB test<commit_after>(function(module) {
  var homeController = {};

  homeController.index = function() {
    $('#home').show().siblings().hide();
    $('#login-signup').hide();
  };

  homeController.dbTest = function(){
    $.getJSON('/data', function (result) {
      result.rows.forEach(function(item) {
        console.log(item);
      });
    });
  };
  homeController.dbTest();

  module.homeController = homeController;
})(window);
<|endoftext|>