<commit_before>import test from 'tape'
import {DefaultDOMElement} from 'substance'

import DocumentJupyterConverter from '../../src/document/DocumentJupyterConverter'

test('DocumentJupyterConverter:match', function (t) {
  t.ok(DocumentJupyterConverter.match('foo.ipynb'))
  t.notOk(DocumentJupyterConverter.match('foo.html'))
  t.end()
})

test('DocumentJupyterConverter:encodingLessThan', function (t) {
  // Tests character encoding by DefaultDOMElement
  let el = DefaultDOMElement.createElement('pre')

  el.text('Less than < char')
  t.equal(el.text(), 'Less than < char')

  // Currently, fails under Node.js
  if (typeof window !== 'undefined') {
    el.html('Less than < char')
    t.equal(el.html(), 'Less than < char')
  }

  el.text('Less than < char')
  t.equal(el.text(), 'Less than < char')

  el.html('Less than < char')
  t.equal(el.html(), 'Less than < char')

  t.end()
})

test('DocumentJupyterConverter:import', t => {
  const converter = new DocumentJupyterConverter()
  const i = json => converter.importContent(json)

  t.equal(
    i('{"cells":[{"cell_type":"markdown","source":["# Heading 1\\n"]}]}'),
    '
Heading 1
',
    'can be called with a JSON string'
  )

  t.equal(
    i({cells: [{cell_type: 'markdown', source: ['# Heading 1\n']}]}),
    '
Heading 1
',
    'can be called with Javascript object'
  )

  t.equal(
    i({
      metadata: { language_info: { name: 'python' } },
      cells: [
        {cell_type: 'markdown', source: ['# Heading 1\n']},
        {cell_type: 'code', source: ['dict(foo="bar")\n']}
      ]
    }),
    '
Heading 1

dict(foo="bar")

',
    'cells'
  )

  t.equal(
    i({
      metadata: { language_info: { name: 'python' } },
      cells: [
        {cell_type: 'code', source: ['dict(foo=\'bar\')\n']}
      ]
    }),
    '

dict(foo=\'bar\')

',
    'code cells with apostrophes'
  )

  // Currently, fails under Node.js due to improper encoding of <
  if (typeof window !== 'undefined') {
    t.equal(
      i({cells: [{cell_type: 'markdown', source: ['```\n', 'let x = 56\n', 'x < 65\n', '```\n']}]}),
      '
let x = 56\nx < 65
',
      'Markdown code block'
    )

    t.equal(
      i({
        metadata: { language_info: { name: 'R' } },
        cells: [
          {
            cell_type: 'code',
            source: ['x <- 6\n', 'plot(1,x)\n'],
            outputs: [
              {
                output_type: 'execute_result',
                data: {
                  'image/png': 'PNGdata'
                }
              }
            ]
          }
        ]
      }),
      '

x <- 6\nplot(1,x)

',
      'cells with output'
    )

  }

  t.end()
})

test('DocumentJupyterConverter:export', t => {
  const converter = new DocumentJupyterConverter()
  const e = (html, options) => {
    options = options || {}
    return converter.exportContent(html, options)
  }

  t.equal(
    e('
Heading 1
'),
`{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# Heading 1\\n"
      ]
    }
  ],
  "metadata": {},
  "nbformat": 4,
  "nbformat_minor": 2
}`,
  'defaults to pretty')

  t.equal(
    e('
Heading 1
', {pretty: false}),
    '{"cells":[{"cell_type":"markdown","metadata":{},"source":["# Heading 1\\n"]}],"metadata":{},"nbformat":4,"nbformat_minor":2}',
    'can set pretty false'
  )
  t.deepEqual(
    e('
Heading 1
', {stringify: false}),
    {cells: [{cell_type: 'markdown', metadata: {}, source: ['# Heading 1\n']}], metadata: {}, nbformat: 4, nbformat_minor: 2},
    'can set stringify false'
  )

  // Currently, fails under Node.js due to improper encoding of <
  if (typeof window !== 'undefined') {
    t.deepEqual(
      e(`

Heading 1

x <- 6
x*7

`, {stringify: false}
      ),
      {
        cells: [
          {
            cell_type: 'markdown',
            metadata: {},
            source: [
              '# Heading 1\n'
            ]
          },
          {
            cell_type: 'code',
            metadata: {},
            source: [
              'x <- 6\n',
              'x*7\n'
            ],
            outputs: [
              {
                output_type: 'execute_result',
                data: {
                  'image/png': 'iVBORw0KGgoAAAANSUhEUgAAAJYAAACWCAYAAAA8'
                }
              }
            ],
            execution_count: null
          }
        ],
        metadata: {},
        nbformat: 4,
        nbformat_minor: 2
      },
      'mix dom content and cells'
    )
  }

  t.end()
})

test('DocumentJupyterConverter:import+export', t => {
  const converter = new DocumentJupyterConverter()
  // Function to do round trip conversion and checking.
  // Takes an array of cells
  function f (cells, message) {
    let nb = {
      cells: cells,
      metadata: {},
      nbformat: 4,
      nbformat_minor: 2
    }
    let html = converter.importContent(nb)
    let json = converter.exportContent(html, {stringify: false})
    t.deepEqual(json, nb, message)
  }

  f([
    {
      cell_type: 'markdown',
      metadata: {},
      source: [
        '# Heading 1\n',
        '\n',
        'Paragraph one\n'
      ]
    }
  ], 'just markdown cells')

  f([
    {
      cell_type: 'markdown',
      metadata: {},
      source: [
        '# Heading 1\n',
        '\n',
        'Paragraph one\n',
        '\n',
        'Paragraph two\n'
      ]
    }, {
      cell_type: 'code',
      execution_count: null,
      metadata: {},
      outputs: [],
      source: [
        'x = 6\n',
        'y = 7\n'
      ]
    }, {
      cell_type: 'markdown',
      metadata: {},
      source: [
        'Paragraph three\n'
      ]
    }
  ], 'mixed markdown and code cells')

  // Currently, fails under Node.js
  if (typeof window !== 'undefined') {
    f([
      {
        cell_type: 'markdown',
        metadata: {},
        source: [
          'Less than < character\n'
        ]
      }, {
        cell_type: 'code',
        execution_count: null,
        metadata: {},
        outputs: [],
        source: [
          'x <- 6\n',
          'y <- 7\n'
        ]
      }
    ], 'conversion of < chars')
  }

  t.end()
})
<commit_msg>Enable all Jupyter converter tests.<commit_after>import test from 'tape'
import {DefaultDOMElement} from 'substance'

import DocumentJupyterConverter from '../../src/document/DocumentJupyterConverter'

test('DocumentJupyterConverter:match', function (t) {
  t.ok(DocumentJupyterConverter.match('foo.ipynb'))
  t.notOk(DocumentJupyterConverter.match('foo.html'))
  t.end()
})

test('DocumentJupyterConverter:encodingLessThan', function (t) {
  // Tests character encoding by DefaultDOMElement
  let el = DefaultDOMElement.createElement('pre')

  el.text('Less than < char')
  t.equal(el.text(), 'Less than < char')

  el.html('Less than < char')
  t.equal(el.html(), 'Less than < char')

  el.text('Less than < char')
  t.equal(el.text(), 'Less than < char')

  el.html('Less than < char')
  t.equal(el.html(), 'Less than < char')

  t.end()
})

test('DocumentJupyterConverter:import', t => {
  const converter = new DocumentJupyterConverter()
  const i = json => converter.importContent(json)

  t.equal(
    i('{"cells":[{"cell_type":"markdown","source":["# Heading 1\\n"]}]}'),
    '
Heading 1
',
    'can be called with a JSON string'
  )

  t.equal(
    i({cells: [{cell_type: 'markdown', source: ['# Heading 1\n']}]}),
    '
Heading 1
',
    'can be called with Javascript object'
  )

  t.equal(
    i({
      metadata: { language_info: { name: 'python' } },
      cells: [
        {cell_type: 'markdown', source: ['# Heading 1\n']},
        {cell_type: 'code', source: ['dict(foo="bar")\n']}
      ]
    }),
    '
Heading 1

dict(foo="bar")

',
    'cells'
  )

  t.equal(
    i({
      metadata: { language_info: { name: 'python' } },
      cells: [
        {cell_type: 'code', source: ['dict(foo=\'bar\')\n']}
      ]
    }),
    '

dict(foo=\'bar\')

',
    'code cells with apostrophes'
  )

  t.equal(
    i({cells: [{cell_type: 'markdown', source: ['```\n', 'let x = 56\n', 'x < 65\n', '```\n']}]}),
    '
let x = 56\nx < 65
',
    'Markdown code block'
  )

  t.equal(
    i({
      metadata: { language_info: { name: 'R' } },
      cells: [
        {
          cell_type: 'code',
          source: ['x <- 6\n', 'plot(1,x)\n'],
          outputs: [
            {
              output_type: 'execute_result',
              data: {
                'image/png': 'PNGdata'
              }
            }
          ]
        }
      ]
    }),
    '

x <- 6\nplot(1,x)

',
    'cells with output'
  )

  t.end()
})

test('DocumentJupyterConverter:export', t => {
  const converter = new DocumentJupyterConverter()
  const e = (html, options) => {
    options = options || {}
    return converter.exportContent(html, options)
  }

  t.equal(
    e('
Heading 1
'),
`{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# Heading 1\\n"
      ]
    }
  ],
  "metadata": {},
  "nbformat": 4,
  "nbformat_minor": 2
}`,
  'defaults to pretty')

  t.equal(
    e('
Heading 1
', {pretty: false}),
    '{"cells":[{"cell_type":"markdown","metadata":{},"source":["# Heading 1\\n"]}],"metadata":{},"nbformat":4,"nbformat_minor":2}',
    'can set pretty false'
  )
  t.deepEqual(
    e('
Heading 1
', {stringify: false}),
    {cells: [{cell_type: 'markdown', metadata: {}, source: ['# Heading 1\n']}], metadata: {}, nbformat: 4, nbformat_minor: 2},
    'can set stringify false'
  )

  t.deepEqual(
    e(`

Heading 1

x <- 6
x*7

`, {stringify: false}
    ),
    {
      cells: [
        {
          cell_type: 'markdown',
          metadata: {},
          source: [
            '# Heading 1\n'
          ]
        },
        {
          cell_type: 'code',
          metadata: {},
          source: [
            'x <- 6\n',
            'x*7\n'
          ],
          outputs: [
            {
              output_type: 'execute_result',
              data: {
                'image/png': 'iVBORw0KGgoAAAANSUhEUgAAAJYAAACWCAYAAAA8'
              }
            }
          ],
          execution_count: null
        }
      ],
      metadata: {},
      nbformat: 4,
      nbformat_minor: 2
    },
    'mix dom content and cells'
  )

  t.end()
})

test('DocumentJupyterConverter:import+export', t => {
  const converter = new DocumentJupyterConverter()
  // Function to do round trip conversion and checking.
  // Takes an array of cells
  function f (cells, message) {
    let nb = {
      cells: cells,
      metadata: {},
      nbformat: 4,
      nbformat_minor: 2
    }
    let html = converter.importContent(nb)
    let json = converter.exportContent(html, {stringify: false})
    t.deepEqual(json, nb, message)
  }

  f([
    {
      cell_type: 'markdown',
      metadata: {},
      source: [
        '# Heading 1\n',
        '\n',
        'Paragraph one\n'
      ]
    }
  ], 'just markdown cells')

  f([
    {
      cell_type: 'markdown',
      metadata: {},
      source: [
        '# Heading 1\n',
        '\n',
        'Paragraph one\n',
        '\n',
        'Paragraph two\n'
      ]
    }, {
      cell_type: 'code',
      execution_count: null,
      metadata: {},
      outputs: [],
      source: [
        'x = 6\n',
        'y = 7\n'
      ]
    }, {
      cell_type: 'markdown',
      metadata: {},
      source: [
        'Paragraph three\n'
      ]
    }
  ], 'mixed markdown and code cells')

  f([
    {
      cell_type: 'markdown',
      metadata: {},
      source: [
        'Less than < character\n'
      ]
    }, {
      cell_type: 'code',
      execution_count: null,
      metadata: {},
      outputs: [],
      source: [
        'x <- 6\n',
        'y <- 7\n'
      ]
    }
  ], 'conversion of < chars')

  t.end()
})
<|endoftext|>


<commit_before>/**
 * Toolbar Core Module
 * @class Core.Module.Toolbar
 * @author Jerome Vial, Bruno Santos
 */
define(function(require, exports, module) {

	var appIconConfig = require('config/icon/app');
	var fontIconConfig = require('config/icon/font');
	var mdiIconConfig = require('config/icon/mdi');
	var langControlsConfigEn = require('config/sys/lang/control/en');
	var langControlsConfigFr = require('config/sys/lang/control/fr');
	var settings = require('Core/Module/Settings/Settings');

	var _log = __debug('core-module-toolbar').defineLevel();

	var Toolbar = new Class({

		/**
		 * Initialize Toolbar
		 * @param {Object} obj
		 */
		_initToolbar: function(obj) {
			_log.debug('_initToolbar', obj);

			this.langControl = {
				en: langControlsConfigEn,
				fr: langControlsConfigFr
			};

			this.toolbar = {};
			this.control = {};

			this._initToolbarReady(obj);

			if (!obj.list) {
				_log.warn('missing list field');
				return;
			}

			for (var i = 0; obj.list.length > i; i++) {
				var name = obj.list[i];
				var bar = obj[name];

				if (!bar) {
					continue;
				}

				//_log.debug(name, bar.container);

				if (!this.container[bar.container]) {
					if (!bar.container) {
						continue;
					}

					this.container['_init' + bar.container.capitalize()]();
				}

				var element = this.toolbar[name] = new Element('div', {
					'class': 'ui-toolbar'
				}).addEvents({

				}).inject(this.container[bar.container]);

				if (bar.klss) {
					element.addClass(bar.klss);
				}

				element.addClass('toolbar-' + name);

				this._initToolbarComp(bar, element);
			}

			this.container.fireEvent('resize');
		},

		/**
		 * init toolbar eeady
		 * @return {void}
		 */
		_initToolbarReady: function(obj) {
			var self = this;
			this.ready = 0;
			this.isReady = 0;

			Object.map(obj, function(map) {
				if (map.list) {
					self.ready = self.ready + map.list.length;
				}
			});

			this.addEvent('isReady', function(isReady) {
				//_log.debug('isready', isReady);
				if (isReady >= this.ready) {
					//_log.debug('toolbarReady');
					self.fireEvent('toolbarReady', isReady);
				}
			});
		},

		/**
		 * [_initMore description]
		 * @return {void}
		 */
		_initMore: function() {
			_log.debug('_initMore', this.container, this.control.more, this.toolbar.more);

			if (!this.control || !this.toolbar) {
				_log.warn('missing control or toolbar');
				return null;
			}

			var timer = null;

			var toolbar = this.toolbar.more;
			var control = this.control.more;

			if (!control || !toolbar) {
				_log.warn('missing control or toolbar', control, toolbar);
				return;
			}

			control.addEvent('press', function(ev) {
				_log.debug('-- press', ev);
				//var coord = control.getCoordinates();
				toolbar.setStyles({
					display: 'inline-block'
				});

				return true;
			});

			this.addEvent('control::pressed', function() {
				toolbar.setStyle('display', 'none');
			});

			toolbar.addEvents({
				/**
				 * @ignore
				 */
				mouseleave: function() {
					clearTimeout(timer);
					timer = setTimeout(function() {
						toolbar.setStyle('display', 'none');
					}, 500);
				},
				/**
				 * @ignore
				 */
				mouseenter: function() {
					clearTimeout(timer);
				},
				/**
				 * @ignore
				 */
				click: function() {
					toolbar.setStyle('display', 'none');
				}
			});
		},

		/**
		 * [_initToolbarComp description]
		 * @param {Object} bar
		 */
		_initToolbarComp: function(bar, element) {
			_log.debug('_initToolbarComp', bar, element);

			bar.list = bar.list || [];

			for (var i = 0; i < bar.list.length; i++) {
				var name = bar.list[i];
				var def = bar[name];
				this._instanciateComp(name, def, element);
			}
		},

		/**
		 * [_instanciateComp description]
		 * @param  {string} name    [description]
		 * @param  {Object} def     [description]
		 * @param  {HTMLElement} element [description]
		 * @return {void}
		 */
		_instanciateComp: function(name, def, element) {
			_log.debug('_instanciateComp', name, def, element);

			var self = this;
			var clss = 'UI/Control/Button';
			var opts;

			def = def || {};

			// init class
			var l = name.split(/\:\:/);

			name = l[0];
			l.splice(0, 1);

			var klss = l.join(' ');

			if (name === 'separator') {
				clss = 'UI/Control/Separator';
			}

			if (def.clss) {
				clss = def.clss;
			}

			if (def.opts) {
				opts = def.opts;
				opts.text = Locale.get('control.' + name, name) || name;

				opts.icon = mdiIconConfig[def.icon || name] || fontIconConfig[def.icon || name] || 'mdi-action-help';
			} else {
				opts = {
					name: name,
					icon: fontIconConfig[def.icon || name] || 'mdi-action-help',
					type: 'action',
					klss: klss
				};
			}

			if (!name) {
				_log.warn('missing name');
				return;
			}

			//var	Clss = api.strToClss(clss);

			var lang;

			if (settings && settings.getLang) {
				lang = settings.getLang() || 'en';
			} else {
				lang = 'en';
			}

			if (!this.langControl[lang]) {
				lang = 'en';
			}

			var text;
			if (def.text) {
				text = this.langControl[lang][name] || def.text;
			}

			if (clss === 'UI/Control/Button' || clss === 'UI/Control/ButtonMenu') {
				opts.text = this.langControl[lang][name] || Locale.get('control.' + name, name) || text || name;
			}

			var role = null;

			if (!this.sandbox) {
				_log.warn('no sandbox');
			} else {
				var user = this.sandbox.getCurrentUser();
				if (user && user.role) {
					role = user.role;
				}
			}

			var isAllow = true;

			this.options.control = this.options.control || {};

			if (!this.options.control[role]) {
				isAllow = true;
			} else {
				if (!this.options.control[role].disallowed) {
					isAllow = true;
				} else if (this.options.control[role].disallowed.indexOf(name) > -1) {
					isAllow = false;
				}
			}

			if (isAllow) {
				_log.debug('require module', name, clss, opts);
				this._requireModule(clss, function(Clss) {
					//_log.debug('Clss', typeOf(Clss));

					if (!Clss) {
						_log.warn('not found, should require?', name, opts);
						return;
					}

					self.control[name] = new Clss(opts).inject(element);

					// init more toolbar menu
					if (name === 'more') {
						self._initMore();
						return;
					}

					self.control[name].addEvents({
						/**
						 * @ignore
						 */
						change: function(value) {
							//var name =  this.options.name;
							//_log.debug('change', this);
							if (this.isEnable()) {
								self.fireEvent(name, value);
							}
						}
					});

					if (clss === 'UI/Control/Button') {
						self.control[name].addEvents({
							/**
							 * @ignore
							 */
							press: function() {
								_log.debug('press', name);
								self.fireEvent('control::pressed');
								//var name =  this.options.name;
								//_log.debug('press', name, this.isEnable());
								if (this.isEnable()) {
									self.fireEvent('control::' + name, this);
									self.fireEvent(name, [self]);
								}
							}
						});
					}

					if (clss === 'UI/Control/Upload') {
						self.control[name].addEvents({
							/**
							 * @ignore
							 */
							uploadFile: function(files) {
								_log.debug('uploadFile', files);
								if (this.isEnable()) {
									//self.fireEvent('control::'+name, this);
									self.fireEvent(name, [files]);
								}
							}
						});
					}

					if (clss === 'UI/Control/Field') {
						self.control[name].addEvents({
							/**
							 * @ignore
							 */
							change: function() {
								//_log.debug('change', name, this.isEnable());
								self.fireEvent('control::pressed');
								//var name =  this.options.name;
								//_log.debug('press', name, this.isEnable());
								if (this.isEnable()) {
									self.fireEvent('control::' + name, this);
									self.fireEvent(name, [self]);
								}
							}
						});
					}

					if (clss === 'UI/Control/ButtonMenu') {
						self.control[name].addEvents({
							/**
							 * @ignore
							 */
							press: function(name) {
								self.fireEvent('control::pressed');
								//var name =  this.options.name;
								_log.debug('ButtonMenu press', name, this.isEnable());
								if (this.isEnable()) {
									self.fireEvent('control::' + name, this);
									self.fireEvent(name, [self]);
								}
							}
						});
					}
				});

				self.isReady++;
				self.fireEvent('isReady', self.isReady);
			}
		},

		/**
		 * [_requireView description]
		 * @return {void}
		 */
		_requireModule: function(module, cb) {
			_log.debug('_requireModule', module);
			if (typeOf(module) === 'class') {
				cb(module);
				return;
			}

			require([module], function(Class) {
				cb(Class);
			}, function(err) {
				_log.error(module, err);
				cb();
			});
		}

	});

	module.exports = Toolbar;

});
<commit_msg>indent file using spaces<commit_after>/**
 * Toolbar Core Module
 * @class Core.Module.Toolbar
 * @author Jerome Vial, Bruno Santos
 */
define(function(require, exports, module) {

  var appIconConfig = require('config/icon/app');
  var fontIconConfig = require('config/icon/font');
  var mdiIconConfig = require('config/icon/mdi');
  var langControlsConfigEn = require('config/sys/lang/control/en');
  var langControlsConfigFr = require('config/sys/lang/control/fr');
  var settings = require('Core/Module/Settings/Settings');

  var _log = __debug('core-module-toolbar').defineLevel();

  var Toolbar = new Class({

    /**
     * Initialize Toolbar
     * @param {Object} obj
     */
    _initToolbar: function(obj) {
      _log.debug('_initToolbar', obj);

      this.langControl = {
        en: langControlsConfigEn,
        fr: langControlsConfigFr
      };

      this.toolbar = {};
      this.control = {};

      this._initToolbarReady(obj);

      if (!obj.list) {
        _log.warn('missing list field');
        return;
      }

      for (var i = 0; obj.list.length > i; i++) {
        var name = obj.list[i];
        var bar = obj[name];

        if (!bar) {
          continue;
        }

        //_log.debug(name, bar.container);

        if (!this.container[bar.container]) {
          if (!bar.container) {
            continue;
          }

          this.container['_init' + bar.container.capitalize()]();
        }

        var element = this.toolbar[name] = new Element('div', {
          'class': 'ui-toolbar'
        }).addEvents({

        }).inject(this.container[bar.container]);

        if (bar.klss) {
          element.addClass(bar.klss);
        }

        element.addClass('toolbar-' + name);

        this._initToolbarComp(bar, element);
      }

      this.container.fireEvent('resize');
    },

    /**
     * init toolbar eeady
     * @return {void}
     */
    _initToolbarReady: function(obj) {
      var self = this;
      this.ready = 0;
      this.isReady = 0;

      Object.map(obj, function(map) {
        if (map.list) {
          self.ready = self.ready + map.list.length;
        }
      });

      this.addEvent('isReady', function(isReady) {
        //_log.debug('isready', isReady);
        if (isReady >= this.ready) {
          //_log.debug('toolbarReady');
          self.fireEvent('toolbarReady', isReady);
        }
      });
    },

    /**
     * [_initMore description]
     * @return {void}
     */
    _initMore: function() {
      _log.debug('_initMore', this.container, this.control.more, this.toolbar.more);

      if (!this.control || !this.toolbar) {
        _log.warn('missing control or toolbar');
        return null;
      }

      var timer = null;

      var toolbar = this.toolbar.more;
      var control = this.control.more;

      if (!control || !toolbar) {
        _log.warn('missing control or toolbar', control, toolbar);
        return;
      }

      control.addEvent('press', function(ev) {
        _log.debug('-- press', ev);
        //var coord = control.getCoordinates();
        toolbar.setStyles({
          display: 'inline-block'
        });

        return true;
      });

      this.addEvent('control::pressed', function() {
        toolbar.setStyle('display', 'none');
      });

      toolbar.addEvents({
        /**
         * @ignore
         */
        mouseleave: function() {
          clearTimeout(timer);
          timer = setTimeout(function() {
            toolbar.setStyle('display', 'none');
          }, 500);
        },
        /**
         * @ignore
         */
        mouseenter: function() {
          clearTimeout(timer);
        },
        /**
         * @ignore
         */
        click: function() {
          toolbar.setStyle('display', 'none');
        }
      });
    },

    /**
     * [_initToolbarComp description]
     * @param {Object} bar
     */
    _initToolbarComp: function(bar, element) {
      _log.debug('_initToolbarComp', bar, element);

      bar.list = bar.list || [];

      for (var i = 0; i < bar.list.length; i++) {
        var name = bar.list[i];
        var def = bar[name];
        this._instanciateComp(name, def, element);
      }
    },

    /**
     * [_instanciateComp description]
     * @param  {string} name    [description]
     * @param  {Object} def     [description]
     * @param  {HTMLElement} element [description]
     * @return {void}
     */
    _instanciateComp: function(name, def, element) {
      _log.debug('_instanciateComp', name, def, element);

      var self = this;
      var clss = 'UI/Control/Button';
      var opts;

      def = def || {};

      // init class
      var l = name.split(/\:\:/);

      name = l[0];
      l.splice(0, 1);

      var klss = l.join(' ');

      if (name === 'separator') {
        clss = 'UI/Control/Separator';
      }

      if (def.clss) {
        clss = def.clss;
      }

      if (def.opts) {
        opts = def.opts;
        opts.text = Locale.get('control.' + name, name) || name;

        opts.icon = mdiIconConfig[def.icon || name] || fontIconConfig[def.icon || name] || 'mdi-action-help';
      } else {
        opts = {
          name: name,
          icon: fontIconConfig[def.icon || name] || 'mdi-action-help',
          type: 'action',
          klss: klss
        };
      }

      if (!name) {
        _log.warn('missing name');
        return;
      }

      //var	Clss = api.strToClss(clss);

      var lang;

      if (settings && settings.getLang) {
        lang = settings.getLang() || 'en';
      } else {
        lang = 'en';
      }

      if (!this.langControl[lang]) {
        lang = 'en';
      }

      var text;
      if (def.text) {
        text = this.langControl[lang][name] || def.text;
      }

      if (clss === 'UI/Control/Button' || clss === 'UI/Control/ButtonMenu') {
        opts.text = this.langControl[lang][name] || Locale.get('control.' + name, name) || text || name;
      }

      var role = null;

      if (!this.sandbox) {
        _log.warn('no sandbox');
      } else {
        var user = this.sandbox.getCurrentUser();
        if (user && user.role) {
          role = user.role;
        }
      }

      var isAllow = true;

      this.options.control = this.options.control || {};

      if (!this.options.control[role]) {
        isAllow = true;
      } else {
        if (!this.options.control[role].disallowed) {
          isAllow = true;
        } else if (this.options.control[role].disallowed.indexOf(name) > -1) {
          isAllow = false;
        }
      }

      if (isAllow) {
        _log.debug('require module', name, clss, opts);
        this._requireModule(clss, function(Clss) {
          //_log.debug('Clss', typeOf(Clss));

          if (!Clss) {
            _log.warn('not found, should require?', name, opts);
            return;
          }

          self.control[name] = new Clss(opts).inject(element);

          // init more toolbar menu
          if (name === 'more') {
            self._initMore();
            return;
          }

          self.control[name].addEvents({
            /**
             * @ignore
             */
            change: function(value) {
              //var name =  this.options.name;
              //_log.debug('change', this);
              if (this.isEnable()) {
                self.fireEvent(name, value);
              }
            }
          });

          if (clss === 'UI/Control/Button') {
            self.control[name].addEvents({
              /**
               * @ignore
               */
              press: function() {
                _log.debug('press', name);
                self.fireEvent('control::pressed');
                //var name =  this.options.name;
                //_log.debug('press', name, this.isEnable());
                if (this.isEnable()) {
                  self.fireEvent('control::' + name, this);
                  self.fireEvent(name, [self]);
                }
              }
            });
          }

          if (clss === 'UI/Control/Upload') {
            self.control[name].addEvents({
              /**
               * @ignore
               */
              uploadFile: function(files) {
                _log.debug('uploadFile', files);
                if (this.isEnable()) {
                  //self.fireEvent('control::'+name, this);
                  self.fireEvent(name, [files]);
                }
              }
            });
          }

          if (clss === 'UI/Control/Field') {
            self.control[name].addEvents({
              /**
               * @ignore
               */
              change: function() {
                //_log.debug('change', name, this.isEnable());
                self.fireEvent('control::pressed');
                //var name =  this.options.name;
                //_log.debug('press', name, this.isEnable());
                if (this.isEnable()) {
                  self.fireEvent('control::' + name, this);
                  self.fireEvent(name, [self]);
                }
              }
            });
          }

          if (clss === 'UI/Control/ButtonMenu') {
            self.control[name].addEvents({
              /**
               * @ignore
               */
              press: function(name) {
                self.fireEvent('control::pressed');
                //var name =  this.options.name;
                _log.debug('ButtonMenu press', name, this.isEnable());
                if (this.isEnable()) {
                  self.fireEvent('control::' + name, this);
                  self.fireEvent(name, [self]);
                }
              }
            });
          }
        });

        self.isReady++;
        self.fireEvent('isReady', self.isReady);
      }
    },

    /**
     * [_requireView description]
     * @return {void}
     */
    _requireModule: function(module, cb) {
      _log.debug('_requireModule', module);
      if (typeOf(module) === 'class') {
        cb(module);
        return;
      }

      require([module], function(Class) {
        cb(Class);
      }, function(err) {
        _log.error(module, err);
        cb();
      });
    }

  });

  module.exports = Toolbar;

});
<|endoftext|>


<commit_before>// General application constants.
export const version = '0.14.1';
export const docUrl = 'https://github.com/TrueWill/embracer';
<commit_msg>Version 0.14.2<commit_after>// General application constants.
export const version = '0.14.2';
export const docUrl = 'https://github.com/TrueWill/embracer';
<|endoftext|>


<commit_before>import React, { Component } from 'react';

export default class SearchBar extends Component {
	render() {
		return (
			<form className="input-group">
				<input />

					<button type="submit" className="btn btn-secondary">Submit</button>

			</form>
		)
	}
}<commit_msg>set 2 - SearchBar refinement<commit_after>import React, { Component } from 'react';

export default class SearchBar extends Component {
	constructor(props){
		super(props);
		this.state = { term: '' };
		this.onInputChange = this.onInputChange.bind(this);//Otherwise, this.setState will fail
	}
	onInputChange(event){
		console.log(event.target.value);
		this.setState({term:event.target.value});
	}
	render() {
		return (
			<form className="input-group">
				<input
					placeholder="Get a five day forecast in your favorite cities"
					className="form-control"
					value={this.state.term}
					onChange={this.onInputChange}
				/>

					<button type="submit" className="btn btn-secondary">Submit</button>

			</form>
		)
	}
}<|endoftext|>


<commit_before>var _ = require("underscore");
var models = require("../models");
var Character = models.Character;

var makerPage = function(req, res)
{
	Character.CharacterModel.findByOwner(req.session.account._id, function(err, docs)
	{
		if(err)
		{
			console.log(err);
			return res.status(400).json({error: "An error occured"});
		}
		res.render('app', {characters: docs});
	});
};

var makeCharacter = function(req, res)
{
	if(!req.body.name || !req.body.age || !req.body.race || !req.body.profession)
	{
		return res.status(400).json({error: "Name, age, race, and class are required"});
	}

	// character class = profession
	var characterData =
	{
		name: req.body.name,
		age: req.body.age,
		race: req.body.race,
		profession: req.body.profession,
		owner: req.session.account._id
	};

	var query =
	{
		name: req.body.name,
		owner: req.session.account._id
	};

	Character.CharacterModel.findOne(query, function(err, docs)
	{
		if(err)
		{
			console.log(err);
			return res.status(400).json({error: "An error occured"});
		}
		if(docs == null)
		{

			var newCharacter = new Character.CharacterModel(characterData);

			newCharacter.save(function(err)
			{
				if(err)
				{
					console.log(err);
					return res.status(400).json({error: "An error occured"});
				}
				res.json({redirect: '/maker'});
			});
		}
		else
		{
			return res.status(400).json({error: "You have already used that name"});
		}
	});
};

var changeCharacter = function(req, res)
{
	if(!req.body.name || !req.body.age || !req.body.race || !req.body.profession)
	{
		return res.status(400).json({error: "Name, age, race, and class are required"});
	}

	// character class = profession
	var characterData =
	{
		name: req.body.name,
		age: req.body.age,
		race: req.body.race,
		profession: req.body.profession,
<<<<<<< HEAD
		owner: req.session.account._id
	};

	var query = { name: req.body.name, owner: req.session.account._id };
=======
		id: req.body.id,
		owner: req.session.account._id
	};

	var query = { id: req.body.id, owner: req.session.account._id };
>>>>>>> origin/master
	Character.CharacterModel.findOneAndUpdate(query, characterData, function(err, docs)
	{
		if(err)
		{
			console.log(err);
			return res.status(400).json({error: "An error occured"});
		}
		res.json({redirect: '/editor'});
	});
};

var viewPage = function(req, res)
{
	Character.CharacterModel.findAll(req.session.account._id, function(err, docs)
	{
		if(err)
		{
			console.log(err);
			return res.status(400).json({error: "An error occured"});
		}
		res.render('view',{characters: docs});
	});
};

var editor = function(req, res)
{
	Character.CharacterModel.findByOwner(req.session.account._id, function(err, docs)
	{
		if(err)
		{
			console.log(err);
			return res.status(400).json({error: "An error occured"});
		}
		res.render('editor',{characters: docs});
	});
};

module.exports.makerPage = makerPage;
module.exports.make = makeCharacter;
module.exports.viewPage = viewPage;
module.exports.editor = editor;
module.exports.edit = changeCharacter;<commit_msg>Hot fix due to git adding junk.<commit_after>var _ = require("underscore");
var models = require("../models");
var Character = models.Character;

var makerPage = function(req, res)
{
	Character.CharacterModel.findByOwner(req.session.account._id, function(err, docs)
	{
		if(err)
		{
			console.log(err);
			return res.status(400).json({error: "An error occured"});
		}
		res.render('app', {characters: docs});
	});
};

var makeCharacter = function(req, res)
{
	if(!req.body.name || !req.body.age || !req.body.race || !req.body.profession)
	{
		return res.status(400).json({error: "Name, age, race, and class are required"});
	}

	// character class = profession
	var characterData =
	{
		name: req.body.name,
		age: req.body.age,
		race: req.body.race,
		profession: req.body.profession,
		owner: req.session.account._id
	};

	var query =
	{
		name: req.body.name,
		owner: req.session.account._id
	};

	Character.CharacterModel.findOne(query, function(err, docs)
	{
		if(err)
		{
			console.log(err);
			return res.status(400).json({error: "An error occured"});
		}
		if(docs === null)
		{

			var newCharacter = new Character.CharacterModel(characterData);

			newCharacter.save(function(err)
			{
				if(err)
				{
					console.log(err);
					return res.status(400).json({error: "An error occured"});
				}
				res.json({redirect: '/maker'});
			});
		}
		else
		{
			return res.status(400).json({error: "You have already used that name"});
		}
	});
};

var changeCharacter = function(req, res)
{
	if(!req.body.name || !req.body.age || !req.body.race || !req.body.profession)
	{
		return res.status(400).json({error: "Name, age, race, and class are required"});
	}

	// character class = profession
	var characterData =
	{
		name: req.body.name,
		age: req.body.age,
		race: req.body.race,
		profession: req.body.profession,
		owner: req.session.account._id
	};

	var query =
	{   name: req.body.name,
	    owner: req.session.account._id,
		id: req.body.id,
	};

	Character.CharacterModel.findOneAndUpdate(query, characterData, function(err, docs)
	{
		if(err)
		{
			console.log(err);
			return res.status(400).json({error: "An error occured"});
		}
		res.json({redirect: '/editor'});
	});
};

var viewPage = function(req, res)
{
	Character.CharacterModel.findAll(req.session.account._id, function(err, docs)
	{
		if(err)
		{
			console.log(err);
			return res.status(400).json({error: "An error occured"});
		}
		res.render('view',{characters: docs});
	});
};

var editor = function(req, res)
{
	Character.CharacterModel.findByOwner(req.session.account._id, function(err, docs)
	{
		if(err)
		{
			console.log(err);
			return res.status(400).json({error: "An error occured"});
		}
		res.render('editor',{characters: docs});
	});
};

module.exports.makerPage = makerPage;
module.exports.make = makeCharacter;
module.exports.viewPage = viewPage;
module.exports.editor = editor;
module.exports.edit = changeCharacter;<|endoftext|>


<commit_before>describe("Packages Tab", function() {
  beforeEach(function() {
    cy.configureCluster({
      mesos: "1-task-healthy",
      universePackages: true
    });
  });

  it("should display correct error message for invalid repo uri", function() {
    cy
      .route({
        method: "POST",
        url: /package\/search/,
        status: 400,
        response: {
          type: "RepositoryUriSyntax",
          name: "Invalid",
          message: "The url for Invalid does not have correct syntax"
        }
      })
      .visitUrl({ url: "/universe/packages", logIn: true });

    cy
      .get(".page-body-content .alert-content")
      .should(
        "contain",
        "The url for Invalid does not have correct syntax. You can go to the Repositories Settings page to change installed repositories."
      );
  });

  it("should display correct message for 'no index' error", function() {
    cy
      .route({
        method: "POST",
        url: /package\/search/,
        status: 400,
        response: {
          type: "IndexNotFound",
          name: "Invalid",
          message: "The index file is missing in Invalid"
        }
      })
      .visitUrl({ url: "/universe", logIn: true });

    cy
      .get(".page-body-content .alert-content")
      .should(
        "contain",
        "The index file is missing in Invalid. You can go to the Repositories Settings page to change installed repositories."
      );
  });

  it("should display correct message for missing package file", function() {
    cy
      .route({
        method: "POST",
        url: /package\/search/,
        status: 400,
        response: {
          type: "PackageFileMissing",
          name: "Invalid",
          message: "The package file is missing in Invalid"
        }
      })
      .visitUrl({ url: "/universe", logIn: true });

    cy
      .get(".page-body-content .alert-content")
      .should(
        "contain",
        "The package file is missing in Invalid. You can go to the Repositories Settings page to change installed repositories."
      );
  });

  it("should use default repository name if not provided", function() {
    cy
      .route({
        method: "POST",
        url: /package\/search/,
        status: 400,
        response: {
          type: "PackageFileMissing",
          message: "The package file is missing in a repository"
        }
      })
      .visitUrl({ url: "/universe", logIn: true });

    cy
      .get(".page-body-content .alert-content")
      .should(
        "contain",
        "The package file is missing in a repository. You can go to the Repositories Settings page to change installed repositories."
      );
  });

  it("should default error message for missing package file", function() {
    cy
      .route({
        method: "POST",
        url: /package\/search/,
        status: 400,
        response: { message: "Some other error" }
      })
      .visitUrl({ url: "/universe", logIn: true });

    cy.get(".panel-content h3").should("contain", "An Error Occurred");
  });

  context("searching", function() {
    beforeEach(function() {
      cy.visitUrl({ url: "/universe", logIn: true });
      cy.get("input").type("cass");
    });

    it("should hide certified panels", function() {
      cy
        .get("h4")
        .contains("Certified Services")
        .should(function($certifiedHeading) {
          expect($certifiedHeading.length).to.equal(0);
        });
    });

    it("should should only cassandra in panels", function() {
      cy.get(".panel").should(function($panels) {
        expect($panels.length).to.equal(1);
      });
    });
  });

  context("selected packages", function() {
    beforeEach(function() {
      cy.visitUrl({ url: "/universe", logIn: true });
      cy
        .get("h4")
        .contains("Certified Services")
        .closest(".pod")
        .find(".panel")
        .as("panels");
    });

    it("should have the first 9 packages as selected", function() {
      cy.get("@panels").should(function($panels) {
        expect($panels.length).to.equal(9);
      });
    });
  });

  context.only("package panels", function() {
    beforeEach(function() {
      cy.visitUrl({ url: "/universe", logIn: true });
    });

    it("should open the modal when the panel button is clicked", function() {
      cy.get(".panel").contains("arangodb").click();
      cy.get(".button.button-success").contains("Deploy").click();

      cy.get(".modal").should(function($modal) {
        expect($modal.length).to.equal(1);
      });
    });

    it("shouldn't open the modal when the panel is clicked", function() {
      cy.get(".panel").contains("arangodb").click();

      cy.get(".modal").should(function($modal) {
        expect($modal.length).to.equal(0);
      });
    });
  });

  context("package table", function() {
    beforeEach(function() {
      cy.visitUrl({ url: "/universe", logIn: true });
    });

    it("should show the very last item in the table", function() {
      // Ensure table has rendered before beginning
      cy.get("table").get(".page-body").then(function($pageBodyResults) {
        const $pageBody = $pageBodyResults.get(0);
        // Adjust page-body for option (Mac OS)
        // 'Show scroll bars: Automatically based on mouse or trackpad'
        $pageBody.scrollTop = $pageBody.scrollHeight - $pageBody.clientHeight;
        cy.get(".page-body .gm-scroll-view").then(function($scrolViewResults) {
          const $gmScrolView = $scrolViewResults.get(0);
          // Adjust page-body for option (Mac OS)
          // 'Show scroll bars: Always'
          $gmScrolView.scrollTop =
            $gmScrolView.scrollHeight - $gmScrolView.clientHeight;
          cy.get("table").contains("zeppelin");
        });
      });
    });
  });
});
<commit_msg>chore(PackagesTab-cy): Remove .only 😳<commit_after>describe("Packages Tab", function() {
  beforeEach(function() {
    cy.configureCluster({
      mesos: "1-task-healthy",
      universePackages: true
    });
  });

  it("should display correct error message for invalid repo uri", function() {
    cy
      .route({
        method: "POST",
        url: /package\/search/,
        status: 400,
        response: {
          type: "RepositoryUriSyntax",
          name: "Invalid",
          message: "The url for Invalid does not have correct syntax"
        }
      })
      .visitUrl({ url: "/universe/packages", logIn: true });

    cy
      .get(".page-body-content .alert-content")
      .should(
        "contain",
        "The url for Invalid does not have correct syntax. You can go to the Repositories Settings page to change installed repositories."
      );
  });

  it("should display correct message for 'no index' error", function() {
    cy
      .route({
        method: "POST",
        url: /package\/search/,
        status: 400,
        response: {
          type: "IndexNotFound",
          name: "Invalid",
          message: "The index file is missing in Invalid"
        }
      })
      .visitUrl({ url: "/universe", logIn: true });

    cy
      .get(".page-body-content .alert-content")
      .should(
        "contain",
        "The index file is missing in Invalid. You can go to the Repositories Settings page to change installed repositories."
      );
  });

  it("should display correct message for missing package file", function() {
    cy
      .route({
        method: "POST",
        url: /package\/search/,
        status: 400,
        response: {
          type: "PackageFileMissing",
          name: "Invalid",
          message: "The package file is missing in Invalid"
        }
      })
      .visitUrl({ url: "/universe", logIn: true });

    cy
      .get(".page-body-content .alert-content")
      .should(
        "contain",
        "The package file is missing in Invalid. You can go to the Repositories Settings page to change installed repositories."
      );
  });

  it("should use default repository name if not provided", function() {
    cy
      .route({
        method: "POST",
        url: /package\/search/,
        status: 400,
        response: {
          type: "PackageFileMissing",
          message: "The package file is missing in a repository"
        }
      })
      .visitUrl({ url: "/universe", logIn: true });

    cy
      .get(".page-body-content .alert-content")
      .should(
        "contain",
        "The package file is missing in a repository. You can go to the Repositories Settings page to change installed repositories."
      );
  });

  it("should default error message for missing package file", function() {
    cy
      .route({
        method: "POST",
        url: /package\/search/,
        status: 400,
        response: { message: "Some other error" }
      })
      .visitUrl({ url: "/universe", logIn: true });

    cy.get(".panel-content h3").should("contain", "An Error Occurred");
  });

  context("searching", function() {
    beforeEach(function() {
      cy.visitUrl({ url: "/universe", logIn: true });
      cy.get("input").type("cass");
    });

    it("should hide certified panels", function() {
      cy
        .get("h4")
        .contains("Certified Services")
        .should(function($certifiedHeading) {
          expect($certifiedHeading.length).to.equal(0);
        });
    });

    it("should should only cassandra in panels", function() {
      cy.get(".panel").should(function($panels) {
        expect($panels.length).to.equal(1);
      });
    });
  });

  context("selected packages", function() {
    beforeEach(function() {
      cy.visitUrl({ url: "/universe", logIn: true });
      cy
        .get("h4")
        .contains("Certified Services")
        .closest(".pod")
        .find(".panel")
        .as("panels");
    });

    it("should have the first 9 packages as selected", function() {
      cy.get("@panels").should(function($panels) {
        expect($panels.length).to.equal(9);
      });
    });
  });

  context("package panels", function() {
    beforeEach(function() {
      cy.visitUrl({ url: "/universe", logIn: true });
    });

    it("should open the modal when the panel button is clicked", function() {
      cy.get(".panel").contains("arangodb").click();
      cy.get(".button.button-success").contains("Deploy").click();

      cy.get(".modal").should(function($modal) {
        expect($modal.length).to.equal(1);
      });
    });

    it("shouldn't open the modal when the panel is clicked", function() {
      cy.get(".panel").contains("arangodb").click();

      cy.get(".modal").should(function($modal) {
        expect($modal.length).to.equal(0);
      });
    });
  });

  context("package table", function() {
    beforeEach(function() {
      cy.visitUrl({ url: "/universe", logIn: true });
    });

    it("should show the very last item in the table", function() {
      // Ensure table has rendered before beginning
      cy.get("table").get(".page-body").then(function($pageBodyResults) {
        const $pageBody = $pageBodyResults.get(0);
        // Adjust page-body for option (Mac OS)
        // 'Show scroll bars: Automatically based on mouse or trackpad'
        $pageBody.scrollTop = $pageBody.scrollHeight - $pageBody.clientHeight;
        cy.get(".page-body .gm-scroll-view").then(function($scrolViewResults) {
          const $gmScrolView = $scrolViewResults.get(0);
          // Adjust page-body for option (Mac OS)
          // 'Show scroll bars: Always'
          $gmScrolView.scrollTop =
            $gmScrolView.scrollHeight - $gmScrolView.clientHeight;
          cy.get("table").contains("zeppelin");
        });
      });
    });
  });
});
<|endoftext|>


<commit_before>import module from '../helpers/module-for-db';
import { test } from '../helpers/qunit';

module('document-underscore-camelize');

let model = {
  id: 'thing',
  firstName: 'Duck',
  lastName: 'Yellow',
  fullAddress: {
    country: 'Latvia',
    streetName: 'Yellow str',
    addressComponents: [
      {
        roomNumber: {
          numberValue: '1'
        }
      }
    ]
  }
};

let doc = {
  "_id": "thing",
  "first_name": "Duck",
  "full_address": {
    "address_components": [
      {
        "room_number": {
          "number_value": "1"
        }
      }
    ],
    "country": "Latvia",
    "street_name": "Yellow str"
  },
  "last_name": "Yellow"
};

test('serialize', function(assert) {
  let instance = this.db.doc(model);
  assert.deepEqual(instance.serialize('model'), model);
  assert.deepEqual(instance.serialize('document'), doc);
});

test('deserialize', function(assert) {
  let instance = this.db.push(doc);
  assert.deepEqual(instance.serialize('model'), model);
});
<commit_msg>remove underscore-camelize test<commit_after><|endoftext|>


<commit_before>import React from 'react';
import PropTable from './components/propTable';
import { storiesOf } from '@storybook/react';
import { Store, State } from '@sambego/storybook-state';
import { checkA11y } from 'storybook-addon-a11y';
import { withInfo } from '@storybook/addon-info';
import {
  Banner,
  Box,
  Button,
  ButtonGroup,
  Heading3,
  Link,
  PopoverHorizontal,
  PopoverVertical,
  TextBody,
  TextSmall,
} from '../components';
import { withKnobs, select } from '@storybook/addon-knobs/react';
import PropTypes from 'prop-types';

const store = new Store({
  active: false,
});

const colors = ['neutral', 'mint', 'violet', 'ruby', 'gold', 'aqua', 'teal'];
const tints = ['lightest', 'light', 'normal', 'dark', 'darkest'];

const handleButtonClick = event => {
  store.set({ anchorEl: event.currentTarget, active: true });
};

const handleCloseClick = () => {
  store.set({ active: false });
};

const contentBoxWithSingleTextLine = (
  <Box padding={4}>
    <TextBody>
      This is the popover content with a{' '}
      <Link href="#" inherit={false}>
        link
      </Link>{' '}
      inside
    </TextBody>
  </Box>
);

storiesOf('Popover', module)
  .addDecorator((story, context) =>
    withInfo({
      TableComponent: PropTable,
      propTablesExclude: [Link, TextBody, TextSmall, Button, State, Banner, Heading3, ButtonGroup, Box],
    })(story)(context),
  )
  .addDecorator(checkA11y)
  .addDecorator(withKnobs)
  .add('horizontal', () => (
    <Box>
      <Button onClick={handleButtonClick} label="Open a horizontalPopover" />
      <State store={store}>
        <PopoverHorizontal
          active={false}
          backdrop="transparent"
          color={select('Color', colors, 'neutral')}
          direction="west"
          position="middle"
          onEscKeyDown={handleCloseClick}
          onOverlayClick={handleCloseClick}
          tint={select('Tint', tints, 'lightest')}
        >
          {contentBoxWithSingleTextLine}
        </PopoverHorizontal>
      </State>
    </Box>
  ))
  .add('vertical', () => (
    <Box>
      <Button onClick={handleButtonClick} label="Open a vertical Popover" />
      <State store={store}>
        <PopoverVertical
          active={false}
          backdrop="transparent"
          color={select('Color', colors, 'neutral')}
          direction="south"
          position="center"
          onEscKeyDown={handleCloseClick}
          onOverlayClick={handleCloseClick}
          tint={select('Tint', tints, 'lightest')}
        >
          {contentBoxWithSingleTextLine}
        </PopoverVertical>
      </State>
    </Box>
  ))
  .add('with title', () => (
    <Box>
      <Button onClick={handleButtonClick} label="Open titled Popover" />
      <State store={store}>
        <PopoverVertical
          active={false}
          backdrop="transparent"
          color={select('Color', colors, 'neutral')}
          direction="south"
          position="center"
          onEscKeyDown={handleCloseClick}
          onOverlayClick={handleCloseClick}
          tint={select('Tint', tints, 'lightest')}
        >
          <Banner fullWidth>
            <Heading3>Popover Title</Heading3>
          </Banner>
          {contentBoxWithSingleTextLine}
        </PopoverVertical>
      </State>
    </Box>
  ))
  .add('with title & subtitle', () => (
    <Box>
      <Button onClick={handleButtonClick} label="Open titled & subtitled Popover" />
      <State store={store}>
        <PopoverVertical
          active={false}
          backdrop="transparent"
          color={select('Color', colors, 'neutral')}
          direction="south"
          position="center"
          onEscKeyDown={handleCloseClick}
          onOverlayClick={handleCloseClick}
          tint={select('Tint', tints, 'lightest')}
        >
          <Banner color="neutral" fullWidth>
            <Heading3>Popover Title</Heading3>
            <TextSmall marginTop={1}>This is the popover content</TextSmall>
          </Banner>
          {contentBoxWithSingleTextLine}
        </PopoverVertical>
      </State>
    </Box>
  ))
  .add('with close button', () => (
    <Box>
      <Button onClick={handleButtonClick} label="Open Popover with close button" />
      <State store={store}>
        <PopoverVertical
          active={false}
          backdrop="transparent"
          color={select('Color', colors, 'neutral')}
          direction="south"
          position="center"
          onEscKeyDown={handleCloseClick}
          onOverlayClick={handleCloseClick}
          tint={select('Tint', tints, 'lightest')}
        >
          <Banner onClose={handleCloseClick} fullWidth>
            <Heading3>I am a heading 3</Heading3>
          </Banner>
          {contentBoxWithSingleTextLine}
        </PopoverVertical>
      </State>
    </Box>
  ))
  .add('with actions', () => (
    <Box>
      <Button onClick={handleButtonClick} label="Open Popover with actions" />
      <State store={store}>
        <PopoverVertical
          active={false}
          backdrop="transparent"
          color={select('Color', colors, 'neutral')}
          direction="south"
          position="center"
          onEscKeyDown={handleCloseClick}
          onOverlayClick={handleCloseClick}
          tint={select('Tint', tints, 'lightest')}
        >
          {contentBoxWithSingleTextLine}
          <ButtonGroup justifyContent="flex-end" padding={4}>
            <Button label="Cancel" />
            <Button level="primary" label="Confirm" />
          </ButtonGroup>
        </PopoverVertical>
      </State>
    </Box>
  ))
  .add('with dark backdrop', () => (
    <Box>
      <Button onClick={handleButtonClick} label="Open a Popover with dark backdrop" />
      <State store={store}>
        <PopoverVertical
          active={false}
          backdrop="dark"
          color={select('Color', colors, 'neutral')}
          direction="south"
          position="center"
          onEscKeyDown={handleCloseClick}
          onOverlayClick={handleCloseClick}
          tint={select('Tint', tints, 'lightest')}
        >
          {contentBoxWithSingleTextLine}
        </PopoverVertical>
      </State>
    </Box>
  ))
  .add('experiment 1', () => (
    <Box>
      <Button onClick={handleButtonClick} label="Open a experimental Popover" />
      <State store={store}>
        <PopoverVertical
          active={false}
          backdrop="transparent"
          color={select('Color', colors, 'neutral')}
          direction="south"
          position="center"
          onEscKeyDown={handleCloseClick}
          onOverlayClick={handleCloseClick}
          tint={select('Tint', tints, 'lightest')}
        >
          <Box padding={4}>
            <Heading3>I am a heading 3</Heading3>
            <TextBody marginTop={2}>
              Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore
              et dolore magna aliquyam erat, sed diam voluptua.
            </TextBody>
          </Box>
        </PopoverVertical>
      </State>
    </Box>
  ))
  .add('experiment 2', () => (
    <Box>
      <Button onClick={handleButtonClick} label="Open a experimental Popover" />
      <State store={store}>
        <PopoverVertical
          active={false}
          backdrop="transparent"
          color={select('Color', colors, 'neutral')}
          direction="south"
          position="center"
          onEscKeyDown={handleCloseClick}
          onOverlayClick={handleCloseClick}
          tint={select('Tint', tints, 'lightest')}
        >
          <Box padding={4}>

Lorem ipsum

dolor sit amet

          </Box>
        </PopoverVertical>
      </State>
    </Box>
  ));
<commit_msg>fix lint errors in popover story by removing unused import<commit_after>import React from 'react';
import PropTable from './components/propTable';
import { storiesOf } from '@storybook/react';
import { Store, State } from '@sambego/storybook-state';
import { checkA11y } from 'storybook-addon-a11y';
import { withInfo } from '@storybook/addon-info';
import {
  Banner,
  Box,
  Button,
  ButtonGroup,
  Heading3,
  Link,
  PopoverHorizontal,
  PopoverVertical,
  TextBody,
  TextSmall,
} from '../components';
import { withKnobs, select } from '@storybook/addon-knobs/react';

const store = new Store({
  active: false,
});

const colors = ['neutral', 'mint', 'violet', 'ruby', 'gold', 'aqua', 'teal'];
const tints = ['lightest', 'light', 'normal', 'dark', 'darkest'];

const handleButtonClick = event => {
  store.set({ anchorEl: event.currentTarget, active: true });
};

const handleCloseClick = () => {
  store.set({ active: false });
};

const contentBoxWithSingleTextLine = (
  <Box padding={4}>
    <TextBody>
      This is the popover content with a{' '}
      <Link href="#" inherit={false}>
        link
      </Link>{' '}
      inside
    </TextBody>
  </Box>
);

storiesOf('Popover', module)
  .addDecorator((story, context) =>
    withInfo({
      TableComponent: PropTable,
      propTablesExclude: [Link, TextBody, TextSmall, Button, State, Banner, Heading3, ButtonGroup, Box],
    })(story)(context),
  )
  .addDecorator(checkA11y)
  .addDecorator(withKnobs)
  .add('horizontal', () => (
    <Box>
      <Button onClick={handleButtonClick} label="Open a horizontalPopover" />
      <State store={store}>
        <PopoverHorizontal
          active={false}
          backdrop="transparent"
          color={select('Color', colors, 'neutral')}
          direction="west"
          position="middle"
          onEscKeyDown={handleCloseClick}
          onOverlayClick={handleCloseClick}
          tint={select('Tint', tints, 'lightest')}
        >
          {contentBoxWithSingleTextLine}
        </PopoverHorizontal>
      </State>
    </Box>
  ))
  .add('vertical', () => (
    <Box>
      <Button onClick={handleButtonClick} label="Open a vertical Popover" />
      <State store={store}>
        <PopoverVertical
          active={false}
          backdrop="transparent"
          color={select('Color', colors, 'neutral')}
          direction="south"
          position="center"
          onEscKeyDown={handleCloseClick}
          onOverlayClick={handleCloseClick}
          tint={select('Tint', tints, 'lightest')}
        >
          {contentBoxWithSingleTextLine}
        </PopoverVertical>
      </State>
    </Box>
  ))
  .add('with title', () => (
    <Box>
      <Button onClick={handleButtonClick} label="Open titled Popover" />
      <State store={store}>
        <PopoverVertical
          active={false}
          backdrop="transparent"
          color={select('Color', colors, 'neutral')}
          direction="south"
          position="center"
          onEscKeyDown={handleCloseClick}
          onOverlayClick={handleCloseClick}
          tint={select('Tint', tints, 'lightest')}
        >
          <Banner fullWidth>
            <Heading3>Popover Title</Heading3>
          </Banner>
          {contentBoxWithSingleTextLine}
        </PopoverVertical>
      </State>
    </Box>
  ))
  .add('with title & subtitle', () => (
    <Box>
      <Button onClick={handleButtonClick} label="Open titled & subtitled Popover" />
      <State store={store}>
        <PopoverVertical
          active={false}
          backdrop="transparent"
          color={select('Color', colors, 'neutral')}
          direction="south"
          position="center"
          onEscKeyDown={handleCloseClick}
          onOverlayClick={handleCloseClick}
          tint={select('Tint', tints, 'lightest')}
        >
          <Banner color="neutral" fullWidth>
            <Heading3>Popover Title</Heading3>
            <TextSmall marginTop={1}>This is the popover content</TextSmall>
          </Banner>
          {contentBoxWithSingleTextLine}
        </PopoverVertical>
      </State>
    </Box>
  ))
  .add('with close button', () => (
    <Box>
      <Button onClick={handleButtonClick} label="Open Popover with close button" />
      <State store={store}>
        <PopoverVertical
          active={false}
          backdrop="transparent"
          color={select('Color', colors, 'neutral')}
          direction="south"
          position="center"
          onEscKeyDown={handleCloseClick}
          onOverlayClick={handleCloseClick}
          tint={select('Tint', tints, 'lightest')}
        >
          <Banner onClose={handleCloseClick} fullWidth>
            <Heading3>I am a heading 3</Heading3>
          </Banner>
          {contentBoxWithSingleTextLine}
        </PopoverVertical>
      </State>
    </Box>
  ))
  .add('with actions', () => (
    <Box>
      <Button onClick={handleButtonClick} label="Open Popover with actions" />
      <State store={store}>
        <PopoverVertical
          active={false}
          backdrop="transparent"
          color={select('Color', colors, 'neutral')}
          direction="south"
          position="center"
          onEscKeyDown={handleCloseClick}
          onOverlayClick={handleCloseClick}
          tint={select('Tint', tints, 'lightest')}
        >
          {contentBoxWithSingleTextLine}
          <ButtonGroup justifyContent="flex-end" padding={4}>
            <Button label="Cancel" />
            <Button level="primary" label="Confirm" />
          </ButtonGroup>
        </PopoverVertical>
      </State>
    </Box>
  ))
  .add('with dark backdrop', () => (
    <Box>
      <Button onClick={handleButtonClick} label="Open a Popover with dark backdrop" />
      <State store={store}>
        <PopoverVertical
          active={false}
          backdrop="dark"
          color={select('Color', colors, 'neutral')}
          direction="south"
          position="center"
          onEscKeyDown={handleCloseClick}
          onOverlayClick={handleCloseClick}
          tint={select('Tint', tints, 'lightest')}
        >
          {contentBoxWithSingleTextLine}
        </PopoverVertical>
      </State>
    </Box>
  ))
  .add('experiment 1', () => (
    <Box>
      <Button onClick={handleButtonClick} label="Open a experimental Popover" />
      <State store={store}>
        <PopoverVertical
          active={false}
          backdrop="transparent"
          color={select('Color', colors, 'neutral')}
          direction="south"
          position="center"
          onEscKeyDown={handleCloseClick}
          onOverlayClick={handleCloseClick}
          tint={select('Tint', tints, 'lightest')}
        >
          <Box padding={4}>
            <Heading3>I am a heading 3</Heading3>
            <TextBody marginTop={2}>
              Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore
              et dolore magna aliquyam erat, sed diam voluptua.
            </TextBody>
          </Box>
        </PopoverVertical>
      </State>
    </Box>
  ))
  .add('experiment 2', () => (
    <Box>
      <Button onClick={handleButtonClick} label="Open a experimental Popover" />
      <State store={store}>
        <PopoverVertical
          active={false}
          backdrop="transparent"
          color={select('Color', colors, 'neutral')}
          direction="south"
          position="center"
          onEscKeyDown={handleCloseClick}
          onOverlayClick={handleCloseClick}
          tint={select('Tint', tints, 'lightest')}
        >
          <Box padding={4}>

Lorem ipsum

dolor sit amet

          </Box>
        </PopoverVertical>
      </State>
    </Box>
  ));
<|endoftext|>


<commit_before>'use strict';

var projectQuestions = [
    {
        type: 'input',
        name: 'projectName',
        message: 'What do you want to name this project?',
        default: 'omaha-project'
    },
    {
        type: 'input',
        name: 'sourceDirectory',
        message: 'Where do you want to put the source code?',
        default: './'
    },
    {
        type: 'confirm',
        name: 'benchmark',
        message: 'Add benchmarking support using Benchmark.js?',
        default: true
    },
    {
        type: 'confirm',
        name: 'coveralls',
        message: 'Integrate with Coveralls.io?',
        default: true
    },
    {
        type: 'confirm',
        name: 'jsinspect',
        message: 'Detect copy-pasted and structurally similar code with JS Inspect?',
        default: true
    }
];
var webappQuestions = [
    {
        type: 'list',
        name: 'scriptBundler',
        message: 'Which technology for bundling scripts before deployment?',
        choices: ['requirejs', 'browserify']
    },
    {
        type: 'list',
        name: 'cssPreprocessor',
        message: 'Which CSS pre-processor?',
        choices: ['less', 'Sass', 'none']
    },
    {
        type: 'list',
        name: 'templateTechnology',
        message: 'Which technology for templates?',
        choices: ['handlebars', 'underscore']
    },
    {
        type: 'confirm',
        name: 'aria',
        message: 'Enforce ARIA and Section 508 standards?',
        default: true
    },
    {
        type: 'confirm',
        name: 'imagemin',
        message: 'Use image compression for deployed application?',
        default: true
    }
];

var defaults = {project: {}, webapp: {}};
projectQuestions.forEach(function(question) {
    defaults.project[question.name] = question.default;
});
webappQuestions.forEach(function(question) {
    var defaultValue = (question.type === 'list') ? question.choices[0].toLowerCase() : question.default;
    var promptOption = {};
    switch (question.name) {
        case 'scriptBundler':
            promptOption.useBrowserify = (defaultValue === 'browserify');
            break;
        case 'cssPreprocessor':
            promptOption.useLess = (defaultValue === 'less');
            break;
        case 'templateTechnology':
            promptOption.useHandlebars = (defaultValue === 'handlebars');
            break;
        default:
            promptOption[question.name] = defaultValue;
    }
    for (var key in promptOption) {
        defaults.webapp[key] = promptOption[key];
    }
});
defaults.useSass = !defaults.useLess;

defaults.webapp.scriptBundler = 'requirejs';
defaults.webapp.cssPreprocessor = 'less';
defaults.webapp.templateTechnology = 'handlebars';

function promptMessageFormat(type) {
    function addLeadingZero(step) {return (step < 10) ? ('0' + step) : step;}
    var total = projectQuestions.length + webappQuestions.length;
    return function(question, index) {
        var step = index + 1 + (type === 'webapp' ? projectQuestions.length : 0);
        question.message = require('chalk')[step === total ? 'green' : 'gray']('('+ addLeadingZero(step) + '/' + total + ') ') + question.message;
        return question;
    }
}

exports.project = {
    defaults: defaults.project,
    questions: projectQuestions.map(promptMessageFormat('project'))
};
exports.webapp = {
    defaults: defaults.webapp,
    questions: webappQuestions.map(promptMessageFormat('webapp'))
};
<commit_msg>Fix steps numbering when scaffolding project<commit_after>'use strict';

var projectQuestions = [
    {
        type: 'input',
        name: 'projectName',
        message: 'What do you want to name this project?',
        default: 'omaha-project'
    },
    {
        type: 'input',
        name: 'sourceDirectory',
        message: 'Where do you want to put the source code?',
        default: './'
    },
    {
        type: 'confirm',
        name: 'benchmark',
        message: 'Add benchmarking support using Benchmark.js?',
        default: true
    },
    {
        type: 'confirm',
        name: 'coveralls',
        message: 'Integrate with Coveralls.io?',
        default: true
    },
    {
        type: 'confirm',
        name: 'jsinspect',
        message: 'Detect copy-pasted and structurally similar code with JS Inspect?',
        default: true
    }
];
var webappQuestions = [
    {
        type: 'list',
        name: 'scriptBundler',
        message: 'Which technology for bundling scripts before deployment?',
        choices: ['requirejs', 'browserify']
    },
    {
        type: 'list',
        name: 'cssPreprocessor',
        message: 'Which CSS pre-processor?',
        choices: ['less', 'Sass', 'none']
    },
    {
        type: 'list',
        name: 'templateTechnology',
        message: 'Which technology for templates?',
        choices: ['handlebars', 'underscore']
    },
    {
        type: 'confirm',
        name: 'aria',
        message: 'Enforce ARIA and Section 508 standards?',
        default: true
    },
    {
        type: 'confirm',
        name: 'imagemin',
        message: 'Use image compression for deployed application?',
        default: true
    }
];

var defaults = {project: {}, webapp: {}};
projectQuestions.forEach(function(question) {
    defaults.project[question.name] = question.default;
});
webappQuestions.forEach(function(question) {
    var defaultValue = (question.type === 'list') ? question.choices[0].toLowerCase() : question.default;
    var promptOption = {};
    switch (question.name) {
        case 'scriptBundler':
            promptOption.useBrowserify = (defaultValue === 'browserify');
            break;
        case 'cssPreprocessor':
            promptOption.useLess = (defaultValue === 'less');
            break;
        case 'templateTechnology':
            promptOption.useHandlebars = (defaultValue === 'handlebars');
            break;
        default:
            promptOption[question.name] = defaultValue;
    }
    for (var key in promptOption) {
        defaults.webapp[key] = promptOption[key];
    }
});
defaults.useSass = !defaults.useLess;

defaults.webapp.scriptBundler = 'requirejs';
defaults.webapp.cssPreprocessor = 'less';
defaults.webapp.templateTechnology = 'handlebars';

function promptMessageFormat(type) {
    function addLeadingZero(step) {return (step < 10) ? ('0' + step) : step;}
    var isWebapp = (type === 'webapp');
    var total = projectQuestions.length + (isWebapp ? webappQuestions.length : 0);
    return function(question, index) {
        var step = index + 1 + (isWebapp ? projectQuestions.length : 0);
        question.message = require('chalk')[step === total ? 'green' : 'gray']('('+ addLeadingZero(step) + '/' + total + ') ') + question.message;
        return question;
    }
}

exports.project = {
    defaults: defaults.project,
    questions: projectQuestions.map(promptMessageFormat('project'))
};
exports.webapp = {
    defaults: defaults.webapp,
    questions: webappQuestions.map(promptMessageFormat('webapp'))
};
<|endoftext|>


<commit_before>'use strict';

module.exports = [
  {
    type: 'input',
    name: 'appName',
    message: 'What\'s the name of your app?'
  },
  {
    type: 'checkbox',
    name: 'target',
    message: 'What kind of app do you want to create?',
    choices: [
      {
        value: 'web',
        name: 'Responsive web app',
        checked: true
      },
      {
        value: 'cordova',
        name: 'Mobile app (using Cordova)'
      }
      // {
      //   value: 'electron',
      //   name: 'Desktop app (using Cordova)'
      // }
    ]
  },
  {
    type: 'confirm',
    name: 'pwa',
    message: 'Do you want progressive web app support? (manifest and service worker)',
    default: true,
    when: props => props.target.includes('web')
  },
  {
    type: 'checkbox',
    name: 'mobile',
    message: 'Which mobile platform do you want to support?',
    when: props => props.target.includes('cordova'),
    choices: [
      {
        value: 'ios',
        name: 'iOS',
        checked: true
      },
      {
        value: 'android',
        name: 'Android',
        checked: true
      }
      // {
      //   value: 'windows',
      //   name: 'Windows (Universal)'
      // }
    ]
  },
  {
    type: 'checkbox',
    name: 'webview',
    message: 'Use enhanced web view?',
    when: props => props.target.includes('cordova'),
    choices: props => {
      const choices = [];
      if (props.mobile.includes('ios')) {
        choices.push({
          value: 'wkwebview',
          name: '[iOS] WKWebView (Ionic version)',
          checked: true
        });
      }
      if (props.mobile.includes('android')) {
        choices.push({
          value: 'crosswalk',
          name: '[Android] Crosswalk',
          checked: false
        });
      }
      return choices;
    }
  },
  {
    type: 'list',
    name: 'ui',
    message: 'Which UI framework do you want?',
    choices: [
      {
        value: 'bootstrap',
        name: 'Bootstrap (more website-oriented)'
      },
      {
        value: 'ionic',
        name: 'Ionic (more mobile-oriented)'
      }
    ],
    default: props => props.target.includes('cordova') ? 'ionic' : 'bootstrap'
  },
  {
    type: 'confirm',
    name: 'auth',
    message: 'Do you want authentication?',
    default: true
  }
];
<commit_msg>Fixed generator crash when updating projects from old versions<commit_after>'use strict';

module.exports = [
  {
    type: 'input',
    name: 'appName',
    message: 'What\'s the name of your app?'
  },
  {
    type: 'checkbox',
    name: 'target',
    message: 'What kind of app do you want to create?',
    choices: [
      {
        value: 'web',
        name: 'Responsive web app',
        checked: true
      },
      {
        value: 'cordova',
        name: 'Mobile app (using Cordova)'
      }
      // {
      //   value: 'electron',
      //   name: 'Desktop app (using Cordova)'
      // }
    ]
  },
  {
    type: 'confirm',
    name: 'pwa',
    message: 'Do you want progressive web app (PWA) support? (manifest and service worker)',
    default: true,
    when: props => props.target && props.target.includes('web')
  },
  {
    type: 'checkbox',
    name: 'mobile',
    message: 'Which mobile platform do you want to support?',
    when: props => props.target && props.target.includes('cordova'),
    choices: [
      {
        value: 'ios',
        name: 'iOS',
        checked: true
      },
      {
        value: 'android',
        name: 'Android',
        checked: true
      }
      // {
      //   value: 'windows',
      //   name: 'Windows (Universal)'
      // }
    ]
  },
  {
    type: 'checkbox',
    name: 'webview',
    message: 'Use enhanced web view?',
    when: props => props.target && props.target.includes('cordova'),
    choices: props => {
      const choices = [];
      if (props.mobile.includes('ios')) {
        choices.push({
          value: 'wkwebview',
          name: '[iOS] WKWebView (Ionic version)',
          checked: true
        });
      }
      if (props.mobile.includes('android')) {
        choices.push({
          value: 'crosswalk',
          name: '[Android] Crosswalk',
          checked: false
        });
      }
      return choices;
    }
  },
  {
    type: 'list',
    name: 'ui',
    message: 'Which UI framework do you want?',
    choices: [
      {
        value: 'bootstrap',
        name: 'Bootstrap (more website-oriented)'
      },
      {
        value: 'ionic',
        name: 'Ionic (more mobile-oriented)'
      }
    ],
    default: props => props.target && props.target.includes('cordova') ? 'ionic' : 'bootstrap'
  },
  {
    type: 'confirm',
    name: 'auth',
    message: 'Do you want authentication?',
    default: true
  }
];
<|endoftext|>


<commit_before>'use strict';

module.exports = [
  {
    type: 'input',
    name: 'appName',
    message: 'What\'s the name of your app?'
  },
  {
    type: 'checkbox',
    name: 'target',
    message: 'What kind of app do you want to create?',
    choices: [
      {
        value: 'web',
        name: 'Responsive web app',
        checked: true
      },
      {
        value: 'cordova',
        name: 'Mobile app (using Cordova)'
      }
      // {
      //   value: 'electron',
      //   name: 'Desktop app (using Cordova)'
      // }
    ]
  },
  {
    type: 'confirm',
    name: 'pwa',
    message: 'Do you want progressive web app (PWA) support? (manifest and service worker)',
    default: true,
    when: props => props.target && props.target.includes('web')
  },
  {
    type: 'checkbox',
    name: 'mobile',
    message: 'Which mobile platform do you want to support?',
    when: props => props.target && props.target.includes('cordova'),
    choices: [
      {
        value: 'ios',
        name: 'iOS',
        checked: true
      },
      {
        value: 'android',
        name: 'Android',
        checked: true
      }
      // {
      //   value: 'windows',
      //   name: 'Windows (Universal)'
      // }
    ]
  },
  {
    type: 'checkbox',
    name: 'webview',
    message: 'Use enhanced web view?',
    when: props => props.target && props.target.includes('cordova'),
    choices: props => {
      const choices = [];
      if (props.mobile.includes('ios')) {
        choices.push({
          value: 'wkwebview',
          name: '[iOS] WKWebView (Ionic version)',
          checked: true
        });
      }
      if (props.mobile.includes('android')) {
        choices.push({
          value: 'crosswalk',
          name: '[Android] Crosswalk',
          checked: false
        });
      }
      return choices;
    }
  },
  {
    type: 'list',
    name: 'ui',
    message: 'Which UI framework do you want?',
    choices: [
      {
        value: 'bootstrap',
        name: 'Bootstrap (more website-oriented)'
      },
      {
        value: 'material',
        name: 'Angular Material (more website-oriented)'
      },
      {
        value: 'ionic',
        name: 'Ionic (more mobile-oriented)'
      }
    ],
    default: props => props.target && props.target.includes('cordova') ? 'ionic' : 'bootstrap'
  },
  {
    type: 'confirm',
    name: 'auth',
    message: 'Do you want authentication?',
    default: true
  }
];
<commit_msg>Updated prompt wording<commit_after>'use strict';

module.exports = [
  {
    type: 'input',
    name: 'appName',
    message: 'What\'s the name of your app?'
  },
  {
    type: 'checkbox',
    name: 'target',
    message: 'What kind of app do you want to create?',
    choices: [
      {
        value: 'web',
        name: 'Web app',
        checked: true
      },
      {
        value: 'cordova',
        name: 'Mobile app (using Cordova)'
      }
      // {
      //   value: 'electron',
      //   name: 'Desktop app (using Cordova)'
      // }
    ]
  },
  {
    type: 'confirm',
    name: 'pwa',
    message: 'Do you want a progressive web app? (with manifest and service worker)',
    default: true,
    when: props => props.target && props.target.includes('web')
  },
  {
    type: 'checkbox',
    name: 'mobile',
    message: 'Which mobile platform do you want to support?',
    when: props => props.target && props.target.includes('cordova'),
    choices: [
      {
        value: 'ios',
        name: 'iOS',
        checked: true
      },
      {
        value: 'android',
        name: 'Android',
        checked: true
      }
      // {
      //   value: 'windows',
      //   name: 'Windows (Universal)'
      // }
    ]
  },
  {
    type: 'checkbox',
    name: 'webview',
    message: 'Use enhanced web view?',
    when: props => props.target && props.target.includes('cordova'),
    choices: props => {
      const choices = [];
      if (props.mobile.includes('ios')) {
        choices.push({
          value: 'wkwebview',
          name: '[iOS] WKWebView (best for iOS 9+)',
          checked: true
        });
      }
      if (props.mobile.includes('android')) {
        choices.push({
          value: 'crosswalk',
          name: '[Android] Crosswalk (best for Android < 4.4 support)',
          checked: false
        });
      }
      return choices;
    }
  },
  {
    type: 'list',
    name: 'ui',
    message: 'Which UI framework do you want?',
    choices: [
      {
        value: 'bootstrap',
        name: 'Bootstrap (more website-oriented)'
      },
      {
        value: 'material',
        name: 'Angular Material (more website-oriented)'
      },
      {
        value: 'ionic',
        name: 'Ionic (more mobile-oriented)'
      }
    ],
    default: props => props.target && props.target.includes('cordova') ? 'ionic' : 'bootstrap'
  },
  {
    type: 'confirm',
    name: 'auth',
    message: 'Do you want authentication?',
    default: true
  }
];
<|endoftext|>


<commit_before><commit_msg>Init creation of a sub generator for build<commit_after>(function() {

    'use strict';

    var yeoman = require('yeoman-generator'),
        chalk = require('chalk');

    var BuildGenerator = module.exports = yeoman.generators.Base.extend({

        constructor: function () {
            yeoman.generators.Base.apply(this, arguments);
        },

        initTask: function() {
            this.log(chalk.cyan('\t \t  ___           __  __     _    _ '));
            this.log(chalk.cyan('\t \t / __| __ __ _ / _|/ _|___| |__| |'));
            this.log(chalk.cyan('\t \t \\__ \\/ _/ _` |  _|  _/ _ \\ / _` |'));
            this.log(chalk.cyan('\t \t |___/\\__\\__,_|_| |_| \\___/_\\__,_| \n'));
            this.log(chalk.cyan('\t \t [        Generating Build       ] \n \n'));
            this.log(chalk.green('Wait until build finish. After all I will create a zip file with all contents of your project. \n \n'));
        },

        buildTask: function() {
            this.spawnCommand('grunt', ['build']);
        }

    });

})();
<|endoftext|>


<commit_before>function saveTextAsFile()
{
	var textToWrite = codeEditor.getValue();
	var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});
	var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;

	var downloadLink = document.createElement("a");
	downloadLink.download = fileNameToSaveAs+".imp";
	downloadLink.innerHTML = "Download File";
	if (window.URL != null)
	{
		// Chrome allows the link to be clicked
		// without actually adding it to the DOM.
		downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
	}
	else
	{
		// Firefox requires the link to be added to the DOM
		// before it can be clicked.
		downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
		downloadLink.onclick = destroyClickedElement;
		downloadLink.style.display = "none";
		document.body.appendChild(downloadLink);
	}

	downloadLink.click();
}

function destroyClickedElement(event)
{
	document.body.removeChild(event.target);
}

function loadFileAsText()
{
	var fileToLoad = document.getElementById("fileToLoad").files[0];
	var fileReader = new FileReader();
	fileReader.onload = function(fileLoadedEvent)
	{
		codeEditor.setValue(fileLoadedEvent.target.result);
	};
	fileReader.readAsText(fileToLoad, "UTF-8");
}

function getResultConds(){
	//ajax request to get conditions
	document.getElementById("result-div").value= document.getElementById("inputTextToSave").value;
}

document.onload = function(){
	//checked jsperf.com for perfomance
	document.getElementById("loadFileBtn").addEventListener("click", loadFileAsText);
	document.getElementById("saveAsFileBtn").addEventListener("click", saveTextAsFile);
	document.getElementById("getResult").addEventListener("click", getResultConds);

};<commit_msg>text interface static folder<commit_after>function saveTextAsFile()
{
	var textToWrite = codeEditor.getValue();
	var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});
	var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;

	var downloadLink = document.createElement("a");
	downloadLink.download = fileNameToSaveAs+".imp";
	downloadLink.innerHTML = "Download File";
	if (window.URL != null)
	{
		// Chrome allows the link to be clicked
		// without actually adding it to the DOM.
		downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
	}
	else
	{
		// Firefox requires the link to be added to the DOM
		// before it can be clicked.
		downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
		downloadLink.onclick = destroyClickedElement;
		downloadLink.style.display = "none";
		document.body.appendChild(downloadLink);
	}

	downloadLink.click();
}

function destroyClickedElement(event)
{
	document.body.removeChild(event.target);
}

function loadFileAsText()
{
	var fileToLoad = document.getElementById("fileToLoad").files[0];
	var fileReader = new FileReader();
	fileReader.onload = function(fileLoadedEvent)
	{
		codeEditor.setValue(fileLoadedEvent.target.result);
	};
	fileReader.readAsText(fileToLoad, "UTF-8");
}

function getResultConds(){
	//ajax request to get conditions
	document.getElementById("result-div").value= document.getElementById("inputTextToSave").value;
}

document.onload = function(){
	alert("jel");
	//checked jsperf.com for perfomance
	document.getElementById("loadFileBtn").addEventListener("click", loadFileAsText);
	document.getElementById("saveAsFileBtn").addEventListener("click", saveTextAsFile);
	document.getElementById("getResult").addEventListener("click", getResultConds);

};<|endoftext|>


<commit_before>'use strict';

const db = require('../models/index');
const Boom = require('boom');
const imageUpload = require('../services/image');

class CuriosityController{

	static create(request, reply){

		let curiosity = request.payload;

        imageUpload(curiosity.image, function(response){
			curiosity.pathImage = response;
            curiosity.publicationDate = new Date();

            db.Curiosity
                .build(curiosity)
                .save()
                .then((curiositySaved) => {
                    return reply.view('question-curiosity/register');
                })
                .catch((err) => {
                    return reply(Boom.badImplementation());
                });
        });
	};

    static get(request, reply){
        db.Curiosity
            .findAll({
                where: {
                    status: 'Active'
                }
            })
            .then((curiosities) => {
                return reply(curiosities);
            })
            .catch((err) => {
                return reply(Boom.badImplementation());
            });
    }
}

module.exports = CuriosityController;
<commit_msg>arrumando busca curiosidades<commit_after>'use strict';

const db = require('../models/index');
const Boom = require('boom');
const imageUpload = require('../services/image');

class CuriosityController{

	static create(request, reply){

		let curiosity = request.payload;

        imageUpload(curiosity.image, function(response){
			curiosity.pathImage = response;
            curiosity.publicationDate = new Date();

            db.Curiosity
                .build(curiosity)
                .save()
                .then((curiositySaved) => {
                    return reply.view('question-curiosity/register');
                })
                .catch((err) => {
                    return reply(Boom.badImplementation());
                });
        });
	};

    static get(request, reply){
        db.Curiosity
            .findAll()
            .then((curiosities) => {
                return reply(curiosities);
            })
            .catch((err) => {
                return reply(Boom.badImplementation());
            });
    }
}

module.exports = CuriosityController;
<|endoftext|>


<commit_before>var redisHandler = require('../redis');
var config = require('../config');

exports.render = function(req, res, next) {
  var context = { projects: require(config.SERVER_CONFIG_FILE) };

  redisHandler.getProjects()
    .then(function(projects) {
      for (var key in projects) {
        if (context.projects.hasOwnProperty(key)) {
          context.projects[key].status = JSON.parse(projects[key]);
        }
      }

      res.render('index', context);
    })
    .catch(next);
};
<commit_msg>Fix project list fetching on frontpage<commit_after>var redisHandler = require('../redis');
var config = require('../config');

exports.render = function(req, res, next) {
  var context = { projects: config.PROJECTS };

  redisHandler.getProjects()
    .then(function(projects) {
      for (var key in projects) {
        if (context.projects.hasOwnProperty(key)) {
          context.projects[key].status = JSON.parse(projects[key]);
        }
      }
      res.render('index', context);
    })
    .catch(next);
};
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import PropTypes from 'prop-types';

import playerContextFilter from '../factories/playerContextFilter';
import * as PlayerPropTypes from '../PlayerPropTypes';
import { logWarning } from '../utils/console';

class VideoDisplay extends Component {
  componentDidMount () {
    this.checkForBadStuff();
    const { pipeVideoStreamToCanvas, displayWidth, displayHeight } = this.props;
    let warnedAboutNoImageData = false;
    const {
      endStream,
      setCanvasSize
    } = pipeVideoStreamToCanvas(this.canvas, ctx => {
      const { width, height } = this.canvas;
      if (this.props.processFrame && width && height) {
        const frameData = ctx.getImageData(0, 0, width, height);
        const newFrameData = this.props.processFrame(frameData);
        if (!(newFrameData instanceof ImageData)) {
          if (!warnedAboutNoImageData) {
            logWarning(
              'The processFrame function should return an ImageData object. ' +
              'Normally you\'ll just mutate the provided ImageData and ' +
              'return it.'
            );
            warnedAboutNoImageData = true;
          }
        } else {
          ctx.putImageData(newFrameData, 0, 0);
        }
      }
    });
    setCanvasSize(displayWidth, displayHeight);
    this.endStream = endStream;
    this.setCanvasSize = setCanvasSize;
  }

  componentDidUpdate () {
    this.checkForBadStuff();
    this.setCanvasSize(this.props.displayWidth, this.props.displayHeight);
  }

  componentWillUnmount () {
    this.endStream();
  }

  checkForBadStuff () {
    if (
      !this.warnedAboutBadStuff &&
      this.props.processFrame &&
      !this.props.displayWidth &&
      !this.props.displayHeight
    ) {
      logWarning(
        'VideoDisplay: Supplying a processFrame function without also ' +
        'giving a displayWidth or displayHeight means the video will be ' +
        'processed at the full resolution. This may lead to a poor framerate.'
      );
      this.warnedAboutBadStuff = true;
    }
  }

  render () {
    const canvasAttributes = { ...this.props };
    delete canvasAttributes.pipeVideoStreamToCanvas;
    delete canvasAttributes.processFrame;
    delete canvasAttributes.displayWidth;
    delete canvasAttributes.displayHeight;
    return <canvas {...canvasAttributes} ref={elem => this.canvas = elem} />;
  }
}

VideoDisplay.propTypes = {
  pipeVideoStreamToCanvas: PropTypes.func.isRequired,
  /* TODO: for documentation
  We might want to use this grayscale function in an example
    processFrame: function (frameData) {
      for (let i = 0; i < frameData.data.length; i += 4) {
        const r = frameData.data[i + 0];
        const g = frameData.data[i + 1];
        const b = frameData.data[i + 2];

        // convert to simple grayscale
        const average = (r + g + b) / 3;
        frameData.data[i + 0] = average;
        frameData.data[i + 1] = average;
        frameData.data[i + 2] = average;
      }
      return frameData;
    }
  */
  processFrame: PropTypes.func,
  displayWidth: PropTypes.number,
  displayHeight: PropTypes.number
};

export default playerContextFilter(VideoDisplay, ['pipeVideoStreamToCanvas']);
<commit_msg>Slight VideoDisplay refactor; new scaleForDevicePixelRatio bool prop.<commit_after>import React, { Component } from 'react';
import PropTypes from 'prop-types';

import playerContextFilter from '../factories/playerContextFilter';
import * as PlayerPropTypes from '../PlayerPropTypes';
import { logWarning } from '../utils/console';

class VideoDisplay extends Component {
  componentDidMount () {
    this.checkForBadStuff();
    const { displayWidth, displayHeight } = this.getDeviceDisplayDimensions();
    const {
      endStream,
      setCanvasSize
    } = this.props.pipeVideoStreamToCanvas(this.canvas, ctx => {
      this.handleFrameUpdate(ctx);
    });
    setCanvasSize(displayWidth, displayHeight);
    this.endStream = endStream;
    this.setCanvasSize = setCanvasSize;
  }

  componentDidUpdate () {
    this.checkForBadStuff();
    const { displayWidth, displayHeight } = this.getDeviceDisplayDimensions();
    this.setCanvasSize(displayWidth, displayHeight);
  }

  componentWillUnmount () {
    this.endStream();
  }

  checkForBadStuff () {
    if (
      !this.warnedAboutBadStuff &&
      this.props.processFrame &&
      !this.props.displayWidth &&
      !this.props.displayHeight
    ) {
      logWarning(
        'VideoDisplay: Supplying a processFrame function without also ' +
        'giving a displayWidth or displayHeight means the video will be ' +
        'processed at the full resolution. This may lead to a poor framerate.'
      );
      this.warnedAboutBadStuff = true;
    }
  }

  getDeviceDisplayDimensions () {
    const { displayWidth, displayHeight, scaleForDevicePixelRatio } = this.props;
    const scale = scaleForDevicePixelRatio && window.devicePixelRatio || 1;
    return {
      displayWidth: displayWidth && (scale * displayWidth),
      displayHeight: displayHeight && (scale * displayHeight)
    };
  }

  handleFrameUpdate (canvasContext) {
    const { width, height } = this.canvas;
    if (!(this.props.processFrame && width && height)) {
      return;
    }
    const frameData = canvasContext.getImageData(0, 0, width, height);
    const newFrameData = this.props.processFrame(frameData);
    if (newFrameData instanceof ImageData) {
      canvasContext.putImageData(newFrameData, 0, 0);
      return;
    }
    if (!this.warnedAboutNoImageData) {
      logWarning(
        'The processFrame function should return an ImageData object. ' +
        'Normally you\'ll just mutate the provided ImageData and ' +
        'return it.'
      );
      this.warnedAboutNoImageData = true;
    }
  }

  render () {
    const canvasAttributes = { ...this.props };
    delete canvasAttributes.pipeVideoStreamToCanvas;
    delete canvasAttributes.processFrame;
    delete canvasAttributes.displayWidth;
    delete canvasAttributes.displayHeight;
    delete canvasAttributes.scaleForDevicePixelRatio;
    return <canvas {...canvasAttributes} ref={elem => this.canvas = elem} />;
  }
}

VideoDisplay.propTypes = {
  pipeVideoStreamToCanvas: PropTypes.func.isRequired,
  /* TODO: for documentation
  We might want to use this grayscale function in an example
    processFrame: function (frameData) {
      for (let i = 0; i < frameData.data.length; i += 4) {
        const r = frameData.data[i + 0];
        const g = frameData.data[i + 1];
        const b = frameData.data[i + 2];

        // convert to simple grayscale
        const average = (r + g + b) / 3;
        frameData.data[i + 0] = average;
        frameData.data[i + 1] = average;
        frameData.data[i + 2] = average;
      }
      return frameData;
    }
  */
  processFrame: PropTypes.func,
  displayWidth: PropTypes.number,
  displayHeight: PropTypes.number,
  scaleForDevicePixelRatio: PropTypes.bool
};

VideoDisplay.defaultProps = {
  scaleForDevicePixelRatio: true
};

export default playerContextFilter(VideoDisplay, ['pipeVideoStreamToCanvas']);
<|endoftext|>