<commit_before>// Copyright (c) 2015 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import Stdio from 'axiom/fs/stdio';

import ReadableStreamForwarder from 'axiom/fs/stream/readable_stream_forwarder';
import WritableStreamForwarder from 'axiom/fs/stream/writable_stream_forwarder';

/**
 * @constructor @extends {Stdio}
 * @param {!Stdio} parentStdio
 */
export var NestedStdio = function(parentStdio) {
  // Note: we wrap the streams so that "onData", "onEnd" and any other event
  // handlers added are scoped to the nested stdio lifetime.
  var stdin = new ReadableStreamForwarder(parentStdio.stdin);
  var signal = new ReadableStreamForwarder(parentStdio.signal);
  var ttyin = new ReadableStreamForwarder(parentStdio.ttyin);
  var stdout = new WritableStreamForwarder(parentStdio.stdout);
  var stderr = new WritableStreamForwarder(parentStdio.stderr);
  var ttyout = new WritableStreamForwarder(parentStdio.ttyout);
  Stdio.call(this, stdin, stdout, stderr, signal, ttyin, ttyout);

  // Copy any additional properties from parent
  for(var key in parentStdio) {
    if (!this[key]) this[key] = parentStdio[key];
  }
  /** @const @type {!Stdio} */
  this.parentStdio = parentStdio;
};

export default NestedStdio;

NestedStdio.prototype = Object.create(Stdio.prototype);

/**
 * Calls `end` on all stream forwarders.
 *
 * @return {void}
 */
NestedStdio.prototype.end = function() {
  for(var key in this) {
    var item = this[key];
    if ((item instanceof ReadableStreamForwarder) ||
        (item instanceof WritableStreamForwarder)) {
      item.end();
    }
  }
};

/**
 * Calls `close` on all stream forwarders.
 *
 * @return {void}
 */
NestedStdio.prototype.close = function(error) {
  for(var key in this) {
    var item = this[key];
    if ((item instanceof ReadableStreamForwarder) ||
        (item instanceof WritableStreamForwarder)) {
      item.close(error);
    }
  }
};
<commit_msg>Address code review feedback:<commit_after>// Copyright (c) 2015 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import Stdio from 'axiom/fs/stdio';

import ReadableStreamForwarder from 'axiom/fs/stream/readable_stream_forwarder';
import WritableStreamForwarder from 'axiom/fs/stream/writable_stream_forwarder';

/**
 * @constructor @extends {Stdio}
 * @param {!Stdio} parentStdio
 */
export var NestedStdio = function(parentStdio) {
  // Note: we wrap the streams so that "onData", "onEnd" and any other event
  // handlers added are scoped to the nested stdio lifetime.
  var stdin = new ReadableStreamForwarder(parentStdio.stdin);
  var signal = new ReadableStreamForwarder(parentStdio.signal);
  var ttyin = new ReadableStreamForwarder(parentStdio.ttyin);
  var stdout = new WritableStreamForwarder(parentStdio.stdout);
  var stderr = new WritableStreamForwarder(parentStdio.stderr);
  var ttyout = new WritableStreamForwarder(parentStdio.ttyout);
  Stdio.call(this, stdin, stdout, stderr, signal, ttyin, ttyout);

  // Copy any additional properties from parent
  for(var key in parentStdio) {
    if (!this[key]) this[key] = parentStdio[key];
  }
  /** @const @type {!Stdio} */
  this.parentStdio = parentStdio;
};

export default NestedStdio;

NestedStdio.prototype = Object.create(Stdio.prototype);

NestedStdio.streamNames =
    ['stdin ', 'signal', 'ttyin ', 'stdout', 'stderr', 'ttyout'];

/**
 * Calls `end` on all stream forwarders.
 *
 * @return {void}
 */
NestedStdio.prototype.end = function() {
  NestedStdio.streamNames.forEach(function(key) {
    var item = this[key];
    if ((item instanceof ReadableStreamForwarder) ||
        (item instanceof WritableStreamForwarder)) {
      item.end();
    }
  });
};

/**
 * Calls `close` on all stream forwarders.
 *
 * @return {void}
 */
NestedStdio.prototype.close = function(error) {
  NestedStdio.streamNames.forEach(function(key) {
    var item = this[key];
    if ((item instanceof ReadableStreamForwarder) ||
        (item instanceof WritableStreamForwarder)) {
      item.close(error);
    }
  });
};
<|endoftext|>


<commit_before>"use strict";

var Base = require('../../index.js')
var proto = Base.prototype
var define = Object.defineProperty
var util = require('../../../util')

var Emitter = module.exports = new Base({
  $define: {
    $executePostponed: true,
    $generateConstructor: function() {
      return (function Emitter( val, event ) {
        if(event) {
          this.$lastStamp = this.$postPonedStamp = event.$stamp
        }
        //emitter does not use on $new for now so Base is sufficient (faster)
        Base.apply(this, arguments)
      })
    },
    $exec:function( bind, event ) {
      var emitter = this
      emitter.$lastStamp = emitter.$postPonedStamp = event.$stamp

      //seperating them is very nice since it makes execution faster
      if(emitter.$onFn) {
        emitter.$onFn.$each(function(property) {
          property.call( bind, event, emitter._$meta )
        })
      }

      if(emitter.$onBase) {
        //this is specific for the $change type so make a seperate change thing perhaps ?
        emitter.$onBase.$each(function(property) {
          property.$emit('$change', event)
        })
      }

      if(emitter.$onBound) {
        emitter.$onBound.$each(function(property) {
          if(property[2]) {
            property[0].apply(
              property[1] || bind,
              [ event, emitter._$meta ].concat( property[2] )
            )
          } else {
            property[0].call( property[1] || bind, event, emitter._$meta )
          }
        })
      }

      if(emitter._$meta) {
        emitter._$meta = null
      }

      //make this into ._$bind ?
      if(this.__$bind__ ) {
        this.__$bind__ = null
      }

    },
    $addListener:function( val, key ) {

      if(!key) {
        console.warn('no key generate it!')
        key = generateId( this )
      } else {
        console.warn('this is the key!', key)
      }

      //optmize this /w keyinternal
      //do we want to search trough all the keys and just use arrays /w ref here? (or something)

      if( typeof val === 'function' )
      {
        add( this, '$onFn', val, key )
      } else if( val instanceof Base ) {
        if(!add( this, '$onBase', val, key )) {
          if(!val.$listensOnBase) {
            val.$setKeyInternal( '$listensOnBase', {}, false )
          }
          var listensOnBase =  val.$listensOnBase
          listensOnBase.$setKeyInternal( generateId( listensOnBase ) )
        }
      } else if( val instanceof Array ) {
        if(!add( this, '$onBound', val, key ) ) {

          if(val[2]) {
            val[2] = val.slice(2)
            val = val.slice(0,2)
          }

          if( val[1] instanceof Base ) {
            if(!val.$listensOnBound) {
              val[1].$setKeyInternal( '$listensOnBound', {}, false )
            }
            var listensOnBound =  val[1].$listensOnBound
            listensOnBound.$setKeyInternal( generateId( listensOnBound ) )
          }
        }
      }
      // console.log('add listener', this.$toString())
    },
    $set:function(val, event) {
      //this is a bit strange
      if(util.isPlainObj(val) && !(val instanceof Array)) {
        if(val.$define) {
          proto.$set.apply(this, arguments)
        } else {
          for(var key$ in val) {
            console.error(key$)
            //sharing keys e.g. a key can be function or a method how to solve?

            //how to remove?

            this.$addListener(val[key$], key$)
          }
        }
      } else {
        this.$addListener(val, 'val')
      }
      //!!!on construction ook shit doen voor inheritance!!!
      //redo this mofo!
    },
    $bind:{
      get:function(val, event) {
        //double check (instances again)
        return this.__bind__ || this.$parent.$parent
      }
    },
    $postpone: function( event ) {
      if(!event) {
        console.error('$postpone does not have event')
        return
      }

      if( event.$stamp !== this.$postPonedStamp ) {
        this.__$bind__ = this.$bind
        event.$postpone(this)
        this.$postPonedStamp = event.$stamp
      }
    },
    $emitEvent:function( event, force, meta ) {
      if(meta) {
        this._$meta = meta
      }
      if( this.$lastStamp !== event.$stamp ) {
        if( event.$origin !== this.$bind && !force ) {
          this.$postpone( event )
        } else {
          this.$exec( this.$bind, event )
        }
      }
    }
  }
}).$Constructor

function generateId( base ) {
  //think about instances
  return base._$id ? base._$id++ : (base._$id = 1)
}

function add( base, type, val, key ) {
  if(!base[type] ) {
    base.$setKeyInternal( type, {}, false )
  }
  for(var i in base[type]) {
    if(base[type][i]===val) {
      console.error('allready added!', val.$path)
      return true
    }
  }
  // val.$ignoreFire = true
  base[type][key] = val
  // base[type].$setKeyInternal( key, val, false )
}<commit_msg>functions and bound listeners do not need to be unique<commit_after>"use strict";

var Base = require('../../index.js')
var proto = Base.prototype
var define = Object.defineProperty
var util = require('../../../util')

var Emitter = module.exports = new Base({
  $define: {
    $executePostponed: true,
    $generateConstructor: function() {
      return (function Emitter( val, event ) {
        if(event) {
          this.$lastStamp = this.$postPonedStamp = event.$stamp
        }
        //emitter does not use on $new for now so Base is sufficient (faster)
        Base.apply(this, arguments)
      })
    },
    $exec:function( bind, event ) {
      var emitter = this
      emitter.$lastStamp = emitter.$postPonedStamp = event.$stamp

      //seperating them is very nice since it makes execution faster
      if(emitter.$onFn) {
        emitter.$onFn.$each(function(property) {
          property.call( bind, event, emitter._$meta )
        })
      }

      if(emitter.$onBase) {
        //this is specific for the $change type so make a seperate change thing perhaps ?
        emitter.$onBase.$each(function(property) {
          property.$emit('$change', event)
        })
      }

      if(emitter.$onBound) {
        emitter.$onBound.$each(function(property) {
          if(property[2]) {
            property[0].apply(
              property[1] || bind,
              [ event, emitter._$meta ].concat( property[2] )
            )
          } else {
            property[0].call( property[1] || bind, event, emitter._$meta )
          }
        })
      }

      if(emitter._$meta) {
        emitter._$meta = null
      }

      //make this into ._$bind ?
      if(this.__$bind__ ) {
        this.__$bind__ = null
      }

    },
    $addListener:function( val, key ) {

      if(!key) {
        console.warn('no key generate it!')
        key = generateId( this )
      } else {
        console.warn('this is the key!', key)
      }

      //optmize this /w keyinternal
      //do we want to search trough all the keys and just use arrays /w ref here? (or something)

      if( typeof val === 'function' )
      {
        add( this, '$onFn', val, key )
      } else if( val instanceof Base ) {
        if( !add( this, '$onBase', val, key, true ) ) {
          if(!val.$listensOnBase) {
            val.$setKeyInternal( '$listensOnBase', {}, false )
          }
          var listensOnBase =  val.$listensOnBase
          listensOnBase.$setKeyInternal( generateId( listensOnBase ) )
        }
      } else if( val instanceof Array ) {
        add( this, '$onBound', val, key )
        if(val[2]) {
          val[2] = val.slice(2)
          val = val.slice(0,2)
        }
        if( val[1] instanceof Base ) {
          if(!val.$listensOnBound) {
            val[1].$setKeyInternal( '$listensOnBound', {}, false )
          }
          var listensOnBound =  val[1].$listensOnBound
          listensOnBound.$setKeyInternal( generateId( listensOnBound ) )
        }
      }
      // console.log('add listener', this.$toString())
    },
    $set:function(val, event) {
      //this is a bit strange
      if(util.isPlainObj(val) && !(val instanceof Array)) {
        if(val.$define) {
          proto.$set.apply(this, arguments)
        } else {
          for(var key$ in val) {
            console.error(key$)
            //sharing keys e.g. a key can be function or a method how to solve?

            //how to remove?

            this.$addListener(val[key$], key$)
          }
        }
      } else {
        this.$addListener(val, 'val')
      }
      //!!!on construction ook shit doen voor inheritance!!!
      //redo this mofo!
    },
    $bind:{
      get:function(val, event) {
        //double check (instances again)
        return this.__bind__ || this.$parent.$parent
      }
    },
    $postpone: function( event ) {
      if(!event) {
        console.error('$postpone does not have event')
        return
      }

      if( event.$stamp !== this.$postPonedStamp ) {
        this.__$bind__ = this.$bind
        event.$postpone(this)
        this.$postPonedStamp = event.$stamp
      }
    },
    $emitEvent:function( event, force, meta ) {
      if(meta) {
        this._$meta = meta
      }
      if( this.$lastStamp !== event.$stamp ) {
        if( event.$origin !== this.$bind && !force ) {
          this.$postpone( event )
        } else {
          this.$exec( this.$bind, event )
        }
      }
    }
  }
}).$Constructor

function generateId( base ) {
  //think about instances
  return base._$id ? base._$id++ : (base._$id = 1)
}

function add( base, type, val, key, unique ) {

  if(!base[type] ) {
    base.$setKeyInternal( type, {}, false )
  } else if( unique ) {
    for(var i in base[type]) {
      //!!!propably dont want this for functions!!!
      if(base[type][i]===val) {
        console.error('allready added!', val.$path)
        return true
      }
    }
  }
  // val.$ignoreFire = true
  base[type][key] = val
  // base[type].$setKeyInternal( key, val, false )
}<|endoftext|>


<commit_before>/**
 * @package     hubzero-cms
 * @file        modules/mod_reportproblems/mod_reportproblems.js
 * @copyright   Copyright 2005-2011 Purdue University. All rights reserved.
 * @license     http://www.gnu.org/licenses/lgpl-3.0.html LGPLv3
 */

//----------------------------------------------------------
// Slider
//----------------------------------------------------------
if (typeof(Fx) === 'undefined') {
	// Stop everything
} else {
	Fx.Slider = Fx.Base.extend({

		options: {
		},

		initialize: function(el, options) {
			this.el = $(el);
			this.el.style.overflow = 'hidden';
			this.el.iniWidth = this.el.offsetWidth;
			this.el.iniHeight = this.el.offsetHeight;
			this.parent(this.options);
		},

		go: function() {
			this.duration = this.options.duration;
			this.startTime = (new Date).getTime();
			this.timer = setInterval (this.step.bind(this), 13);
		},

		step: function() {
			var time  = (new Date).getTime();
			var Tpos   = (time - this.startTime) / (this.duration);
			if (time >= this.duration+this.startTime) {
				this.now = this.to;
				clearInterval (this.timer);
				this.timer = null;
				if (this.options.onComplete) setTimeout(this.options.onComplete.bind(this), 10);
			} else {
				this.now = ((-Math.cos(Tpos*Math.PI)/2) + 0.5) * (this.to-this.from) + this.from;
				//this time-position, sinoidal transition thing is from script.aculo.us
			}
			this.increase();
		},

		custom: function(from, to) {
			if (this.timer != null) return;
			this.from = from;
			this.to = to;
			this.go();
		},

		hide: function() {
			this.now = 0;
			this.increase();
		},

		clearTimer: function() {
			clearInterval(this.timer);
			this.timer = null;
		},

		increase: function() {
			this.el.style.height = this.now + "px";
		},

		toggle: function() {
			if (this.el.offsetHeight > 0) this.custom(this.el.offsetHeight, 0);
			else this.custom(0, this.el.scrollHeight);
		}
	});

	//----------------------------------------------------------
	// Establish the namespace if it doesn't exist
	//----------------------------------------------------------
	if (!HUB) {
		var HUB = {
			Modules: {}
		};
	} else if (!HUB.Modules) {
		HUB.Modules = {};
	}

	//----------------------------------------------------------
	// Trouble Report form
	//----------------------------------------------------------
	HUB.Modules.ReportProblems = new Class({

		options: {
			container: null,
			paneId:    'help-pane',
			formId:    'troublereport',
			nameId:    'trName',
			emailId:   'trEmail',
			loginId:   'trLogin',
			problemId: 'trProblem',
			captchaId: 'trAnswer',
			loaderId:  'trSending',
			successId: 'trSuccess',
			sendId:    'send-form'
		},

		baseheight: '200px',

		open: false,

		initialize: function(container, options) {

			this.container = $(container);
			if (!this.container) {
				return;
			}
			this.setOptions(options);

			this.send = $(this.options.sendId);
			this.success = $(this.options.successId);

			this.pane = $(this.options.paneId);
			this.pane.setStyle('height','0px');

			var p = new Element('p').setText(' Sending report ...');
			var img = new Element('img', {'src':HUB.Base.templatepath+'images/anim/circling-ball-black.gif'}).injectTop(p);

			this.loader = $(this.options.loaderId);
			p.injectInside(this.loader);

			var fa = new Fx.Slider(this.pane, {
				duration: 800,
				onComplete: function(){
					if (this.open == true) {
						this.open = false;
						this.container.setStyle('visibility','hidden');
						//this.send.setStyle('display','none');
					} else {
						this.open = true;
					}
				}
			});

			var res = new Element('div', {
				id: 'help-btn-close',
				alt: 'Close',
				title: 'Close',
				events: {
					'click': function(event) {
						fa.toggle();
						if ($('tab')) {
							if ($('tab').hasClass('active')) {
								$('tab').removeClass('active');
							}
						}
					}
				}
			}).injectInside(this.pane);

			this.tab = $('tab');
			if ($('tab')) {
				$('tab').addEvent('click', function(e) {
					new Event(e).stop();
					if ($('tab').hasClass('active')) {
						$('tab').removeClass('active');
					} else {
						$('tab').addClass('active');
					}
					if (this.open == false) {
						this.container.setStyle('visibility','visible');
						this.open = true;

					} else {
						//this.container.setStyle('visibility','hidden');
						this.open = false;
					}
					fa.toggle();
					return false;
				}.bindWithEvent(this));

				this.name    = $(this.options.nameId);
				this.email   = $(this.options.emailId);
				this.login   = $(this.options.loginId);
				this.problem = $(this.options.problemId);
				this.answer  = $(this.options.captchaId);

				this.frm = $(this.options.formId);
				if (this.frm) {
					var d = document.createElement('DIV');
					d.innerHTML = '';
					document.body.appendChild(d);

					this.frm.target = 'upload_target';
					this.frm.addEvent('submit', function(e) {
						new Event(e).stop();
						this.validateFields();
					}.bindWithEvent(this));

					this.baseheight = this.frm.getStyle('height');
				}
			}
		},

		hideTimer: function() {
			this.loader.hide();
			this.success.innerHTML = document.getElementById('upload_target').contentWindow.document.getElementById('report-response').innerHTML;
			this.success.setStyles({
				'display':'block',
				'height':this.baseheight
			});
		},

		resetForm: function() {
			this.problem.setProperties({'value':''});
			this.success.hide();
			this.frm.setStyle('display','block');
		},

		reshowForm: function() {
			this.success.hide();
			this.frm.setStyle('display','block');
		},

		sendReport: function() {
			this.frm.hide();
			this.loader.setStyles({
				'display':'block',
				'height':this.baseheight
			});
			success = this.success;
			//AIM.submit(this.frm, {'onStart' : startCallback, 'onComplete' : completeCallback});
			/*this.frm.send({
				update: success,
				onComplete: function() {
					HUB.ReportProblem.hideTimer();
				}
	        });*/
			this.frm.submit();
		},

		validateFields: function() {
			var whiteSpace = /^[\s]+$/;

			if (this.problem.value == '' || whiteSpace.test(this.problem.value) ) {
				alert("You're trying to send an empty trouble report. Please type something and try again.");
				this.problem.focus();
			} else if (this.name.value == '' || whiteSpace.test(this.name.value) ) {
				alert("The 'name' field is required. Please type something and try again.");
				this.name.focus();
			} else if (this.email.value == '' || this.validateEmail(this.email.value) === false) {
				alert("Please provide a valid email address.");
				this.email.focus();
			} else if (this.answer.value == '') {
				alert("Please provide an answer to the math question.");
				this.answer.focus();
			} else {
				this.sendReport();
			}
		},

		validateEmail: function(emailStr) {
			var emailReg1 = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/; // not valid
			var emailReg2 = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,6}|[0-9]{1,3})(\]?)$/; // valid
			if (!(!emailReg1.test(emailStr) && emailReg2.test(emailStr))) {
				return false;
			}
			return true;
		}
	});

	HUB.Modules.ReportProblems.implement(new Events, new Options);

	//----------------------------------------------------------

	function initReportProblem()
	{
		HUB.ReportProblem = new HUB.Modules.ReportProblems('help-container',{});
	}

	//----------------------------------------------------------

	window.addEvent('domready', initReportProblem);
}
<commit_msg>Changes to clear the file upload field when submitting a second ticket from the same page load.<commit_after>/**
 * @package     hubzero-cms
 * @file        modules/mod_reportproblems/mod_reportproblems.js
 * @copyright   Copyright 2005-2011 Purdue University. All rights reserved.
 * @license     http://www.gnu.org/licenses/lgpl-3.0.html LGPLv3
 */

//----------------------------------------------------------
// Slider
//----------------------------------------------------------
if (typeof(Fx) === 'undefined') {
	// Stop everything
} else {
	Fx.Slider = Fx.Base.extend({

		options: {
		},

		initialize: function(el, options) {
			this.el = $(el);
			this.el.style.overflow = 'hidden';
			this.el.iniWidth = this.el.offsetWidth;
			this.el.iniHeight = this.el.offsetHeight;
			this.parent(this.options);
		},

		go: function() {
			this.duration = this.options.duration;
			this.startTime = (new Date).getTime();
			this.timer = setInterval (this.step.bind(this), 13);
		},

		step: function() {
			var time  = (new Date).getTime();
			var Tpos   = (time - this.startTime) / (this.duration);
			if (time >= this.duration+this.startTime) {
				this.now = this.to;
				clearInterval (this.timer);
				this.timer = null;
				if (this.options.onComplete) setTimeout(this.options.onComplete.bind(this), 10);
			} else {
				this.now = ((-Math.cos(Tpos*Math.PI)/2) + 0.5) * (this.to-this.from) + this.from;
				//this time-position, sinoidal transition thing is from script.aculo.us
			}
			this.increase();
		},

		custom: function(from, to) {
			if (this.timer != null) return;
			this.from = from;
			this.to = to;
			this.go();
		},

		hide: function() {
			this.now = 0;
			this.increase();
		},

		clearTimer: function() {
			clearInterval(this.timer);
			this.timer = null;
		},

		increase: function() {
			this.el.style.height = this.now + "px";
		},

		toggle: function() {
			if (this.el.offsetHeight > 0) this.custom(this.el.offsetHeight, 0);
			else this.custom(0, this.el.scrollHeight);
		}
	});

	//----------------------------------------------------------
	// Establish the namespace if it doesn't exist
	//----------------------------------------------------------
	if (!HUB) {
		var HUB = {
			Modules: {}
		};
	} else if (!HUB.Modules) {
		HUB.Modules = {};
	}

	//----------------------------------------------------------
	// Trouble Report form
	//----------------------------------------------------------
	HUB.Modules.ReportProblems = new Class({

		options: {
			container: null,
			paneId:    'help-pane',
			formId:    'troublereport',
			nameId:    'trName',
			emailId:   'trEmail',
			loginId:   'trLogin',
			problemId: 'trProblem',
			captchaId: 'trAnswer',
			uploadId:  'trUpload',
			loaderId:  'trSending',
			successId: 'trSuccess',
			sendId:    'send-form'
		},

		baseheight: '200px',

		open: false,

		initialize: function(container, options) {

			this.container = $(container);
			if (!this.container) {
				return;
			}
			this.setOptions(options);

			this.send = $(this.options.sendId);
			this.success = $(this.options.successId);

			this.pane = $(this.options.paneId);
			this.pane.setStyle('height','0px');

			var p = new Element('p').setText(' Sending report ...');
			var img = new Element('img', {'src':HUB.Base.templatepath+'images/anim/circling-ball-black.gif'}).injectTop(p);

			this.loader = $(this.options.loaderId);
			p.injectInside(this.loader);

			var fa = new Fx.Slider(this.pane, {
				duration: 800,
				onComplete: function(){
					if (this.open == true) {
						this.open = false;
						this.container.setStyle('visibility','hidden');
						//this.send.setStyle('display','none');
					} else {
						this.open = true;
					}
				}
			});

			this.name    = $(this.options.nameId);
			this.email   = $(this.options.emailId);
			this.login   = $(this.options.loginId);
			this.problem = $(this.options.problemId);
			this.answer  = $(this.options.captchaId);
			this.upload  = $(this.options.uploadId);

			var res = new Element('div', {
				id: 'help-btn-close',
				alt: 'Close',
				title: 'Close',
				events: {
					'click': function(event) {
						fa.toggle();
						if ($('tab')) {
							if ($('tab').hasClass('active')) {
								$('tab').removeClass('active');
							}
						}
					}
				}
			}).injectInside(this.pane);

			this.tab = $('tab');
			if ($('tab')) {
				$('tab').addEvent('click', function(e) {
					new Event(e).stop();
					if ($('tab').hasClass('active')) {
						$('tab').removeClass('active');
					} else {
						$('tab').addClass('active');
					}
					if (this.open == false) {
						this.container.setStyle('visibility','visible');
						this.open = true;

					} else {
						//this.container.setStyle('visibility','hidden');
						this.open = false;
					}
					fa.toggle();
					return false;
				}.bindWithEvent(this));

				this.frm = $(this.options.formId);
				if (this.frm) {
					var d = document.createElement('DIV');
					d.innerHTML = '';
					document.body.appendChild(d);

					this.frm.target = 'upload_target';
					this.frm.addEvent('submit', function(e) {
						new Event(e).stop();
						this.validateFields();
					}.bindWithEvent(this));

					this.baseheight = this.frm.getStyle('height');
				}
			}
		},

		hideTimer: function() {
			this.loader.hide();
			this.success.innerHTML = document.getElementById('upload_target').contentWindow.document.getElementById('report-response').innerHTML;
			this.success.setStyles({
				'display':'block',
				'height':this.baseheight
			});
		},

		resetForm: function() {
			this.problem.setProperties({'value':''});
			this.upload.parentNode.innerHTML = this.upload.parentNode.innerHTML;
			this.success.hide();
			this.frm.setStyle('display','block');
		},

		reshowForm: function() {
			this.success.hide();
			this.frm.setStyle('display','block');
		},

		sendReport: function() {
			this.frm.hide();
			this.loader.setStyles({
				'display':'block',
				'height':this.baseheight
			});
			success = this.success;
			//AIM.submit(this.frm, {'onStart' : startCallback, 'onComplete' : completeCallback});
			/*this.frm.send({
				update: success,
				onComplete: function() {
					HUB.ReportProblem.hideTimer();
				}
	        });*/
			this.frm.submit();
		},

		validateFields: function() {
			var whiteSpace = /^[\s]+$/;

			if (this.problem.value == '' || whiteSpace.test(this.problem.value) ) {
				alert("You're trying to send an empty trouble report. Please type something and try again.");
				this.problem.focus();
			} else if (this.name.value == '' || whiteSpace.test(this.name.value) ) {
				alert("The 'name' field is required. Please type something and try again.");
				this.name.focus();
			} else if (this.email.value == '' || this.validateEmail(this.email.value) === false) {
				alert("Please provide a valid email address.");
				this.email.focus();
			} else if (this.answer.value == '') {
				alert("Please provide an answer to the math question.");
				this.answer.focus();
			} else {
				this.sendReport();
			}
		},

		validateEmail: function(emailStr) {
			var emailReg1 = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/; // not valid
			var emailReg2 = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,6}|[0-9]{1,3})(\]?)$/; // valid
			if (!(!emailReg1.test(emailStr) && emailReg2.test(emailStr))) {
				return false;
			}
			return true;
		}
	});

	HUB.Modules.ReportProblems.implement(new Events, new Options);

	//----------------------------------------------------------

	function initReportProblem()
	{
		HUB.ReportProblem = new HUB.Modules.ReportProblems('help-container',{});
	}

	//----------------------------------------------------------

	window.addEvent('domready', initReportProblem);
}
<|endoftext|>


<commit_before>
'use strict';

var extend = require('util')._extend,
	validatorLog = require('./ValidatorLog'),
	Utils = require('./Utils');

/**
 *
 * @class ValidatorDataSchema
 * @namespace ValidatorDataSchema
 * @param {object} options
 * @constructor
 *
 * Swagger importer
 */
function ValidatorDataSchema(options) {
	this.init(options);
}

ValidatorDataSchema.prototype = extend(ValidatorDataSchema.prototype, Utils.prototype);
ValidatorDataSchema.prototype = extend(ValidatorDataSchema.prototype, {

	constructor : ValidatorDataSchema,

	_defaults: {
		schema: undefined,
		data: undefined
	},

	/**
	 *
	 * @method init
	 * called by constructor
	 * @param {object} options
	 * @public
	 */
	init: function (options) {

		options = extend(this._defaults, options || {});

		this._options = options;
		this._isValid = true;
		this._schema = this._options.schema;
		this._data = this._options.data;
		this._path = this._options.path;
		this._expected = this._options.expected;

		if (!this._schema || typeof this._schema !== 'object') {
			this._isValid = false;
			validatorLog.error('options.schema can\'t be empty!');
		}

		if (!this._data || typeof this._data !== 'object') {
			this._isValid = false;
			validatorLog.error('options.data can\'t be empty!');
		}

		this._dataMap = this._mapData(this._data);
		this._schemaMap = this._mapSchema(this._schema);

		this._invalidCounter = 0;
		this._validateAll();

		var _validation = {};

		_validation.validation = {};
		_validation.validation[this._expected] = {};
		_validation.validation[this._expected].counter = this._invalidCounter;

		this.setMethodStore(this._path, _validation);

		if (this._invalidCounter > 0) {
			validatorLog.error('Mock data in file ' + options.filePathData + ' are invalid! ' +
				'' + this._invalidCounter + ' invalid values found.');

			return false;
		}

		validatorLog.success('Mock data in file ' + options.filePathData + ' are valid!');
		return true;
	},

	/**
	 * @method _validateAll
	 * @returns {void}
	 * @private
	 */
	_validateAll: function () {
		this.for(this._dataMap, function (item) {
			if (!this._validate(item)) {
				this._invalidCounter += 1;
			}
		}.bind(this));
	},

	/**
	 * @method _validate
	 * @param {object} item
	 * @returns {boolean} isValid
	 * @private
	 */
	_validate: function (item) {

		var pathStr = item.path.join('.'),
			schema = this._schemaMap[pathStr];

		if (!schema) {
			validatorLog.error('No schema definition for: ' +  pathStr + ' found, please check you schema and/or mock file!');
			return false;
		}

		if (schema !== item.type) {
			validatorLog.error('invalid type for: ' + pathStr + ' ' +
				'with value ' + item.value + ' found! ' +
				'Value needs to by type of ' + schema + '.'
			);
			return false;
		}

		return true;
	},

	/**
	 * @method _mapSchema
	 * @param {object|Array} schema
	 * @returns {object}
	 * @private
	 */
	_mapSchema: function (schema) {

		var out = [],
			outObj = {};

		this._mapSchemaUnknown({
			data: schema,
			path: [],
			out: out
		});

		this.for(out, function (item) {
			if (item.type !== undefined) {
				outObj[item.path.join('.')] = this._mapType(item.type);
			}
		}.bind(this));

		return outObj;
	},

	/**
	 * @method _mapSchemaUnknown
	 * @param {object} opt
	 * @param {Array} opt.path
	 * @param {object} opt.data
	 * @param {Array} opt.out
	 * @returns {Boolean} isMapped
	 * @private
	 */
	_mapSchemaUnknown: function (opt) {

		if (opt.data instanceof Array) {
			if (opt.data.length > 0) {
				this._mapSchemaArray({
					data: opt.data[0],
					path: opt.path,
					out: opt.out
				});
			}
			return true;
		}

		if (typeof opt.data === 'object') {
			this._mapSchemaObject({
				data: opt.data,
				path: opt.path,
				out: opt.out
			});
			return true;
		}

		return false;
	},

	/**
	 * @method _mapSchemaArray
	 * @param {object} opt
	 * @param {Array} opt.path
	 * @param {object} opt.data
	 * @param {Array} opt.out
	 * @returns {void}
	 * @private
	 */
	_mapSchemaArray: function (opt) {

		opt.out.push({
			path: opt.path.slice(),
			type: 'array'
		});

		var path = opt.path.slice(),
			newPath;

		path.push('[]');

		if (typeof opt.data !== 'object' || opt.data instanceof Array) {
			newPath = path.slice();

			if (opt.data instanceof Array) {
				if (opt.data.length > 0) {
					this._mapSchemaArray({
						data: opt.data[0],
						path: newPath,
						out: opt.out
					});
				}
				return;
			}

			this._mapSchemaString({
				data: opt.data,
				path: newPath,
				out: opt.out
			});
			return;
		}

		this.forIn(opt.data, function (key, value) {

			var newPath = path.slice();

			if (
				this._mapSchemaUnknown({
					data: value,
					path: newPath,
					out: opt.out
				})
			) {
				return;
			}

			newPath.push(key);

			this._mapSchemaString({
				data: value,
				path: newPath,
				out: opt.out
			});

		}.bind(this));

	},

	/**
	 * @method _mapSchemaObject
	 * @param {object} opt
	 * @param {Array} opt.path
	 * @param {object} opt.data
	 * @param {Array} opt.out
	 * @returns {void}
	 * @private
	 */
	_mapSchemaObject: function (opt) {

		opt.out.push({
			path: opt.path.slice(),
			type: 'object'
		});

		this.forIn(opt.data, function (key, value) {
			var newPath = opt.path.slice();

			newPath.push(key);

			if (
				this._mapSchemaUnknown({
					data: value,
					path: newPath,
					out: opt.out
				})
			) {
				return;
			}

			this._mapSchemaString({
				data: value,
				path: newPath,
				out: opt.out
			});

			return true;
		}.bind(this));
	},

	/**
	 * @method _mapSchemaString
	 * @param {object} opt
	 * @param {Array} opt.path
	 * @param {object} opt.data
	 * @param {Array} opt.out
	 * @returns {void}
	 * @private
	 */
	_mapSchemaString: function (opt) {

		var regResult = /(^\$ref-)(.*)/.exec(opt.data);

		if (regResult !== null && regResult.length > 2) {

			var ref = this._getRef(regResult[2]);

			if (ref instanceof Array) {
				if (ref.length > 0) {
					this._mapSchemaArray({
						data: ref[0],
						path: opt.path,
						out: opt.out
					});
				}
				return;
			}

			if (typeof ref === 'object') {
				this._mapSchemaObject({
					data: ref,
					path: opt.path,
					out: opt.out
				});
				return;
			}

			return;
		}

		opt.out.push({
			path: opt.path,
			type: this._mapType(opt.data)
		});
	},

	/**
	 * @method _getRef
	 * @param {String} refName
	 * @returns {Object|Array}
	 * @private
	 */
	_getRef: function (refName) {
		try {
			return JSON.parse(this.readFile(this._options.restPath + '/_DTO/' + refName + '.json'));
		} catch (err) {}

		return {};
	},

	/**
	 * @method _mapData
	 * @param {object} data
	 * @returns {Array}
	 * @private
	 */
	_mapData: function (data) {

		var out = [];

		if (data instanceof Array) {
			this._mapDataArray({
				data: data,
				path: [],
				out: out
			});
		} else if (typeof data === 'object') {
			this._mapDataObject({
				data: data,
				path: [],
				out: out
			});
		}

		return out;
	},

	/**
	 * @method _mapDataObject
	 * @param {object} opt
	 * @param {Array} opt.path
	 * @param {Object|Array} opt.data
	 * @param {Array} opt.out
	 * @returns {void}
	 * @private
	 */
	_mapDataObject: function (opt) {
		this.forIn(opt.data, function (key, value) {
			var newPath = opt.path.slice(),
				type = this._getType(value),
				isObject = (type === 'object'),
				isArray = (type === 'array');

			newPath.push(key);

			if (isObject || isArray) {
				opt.out.push({
					path: newPath,
					type: type
				});
			} else {
				opt.out.push({
					path: newPath,
					type: type,
					value: value
				});
			}

			if (isObject) {
				this._mapDataObject({
					data: value,
					path: newPath,
					out: opt.out
				});
				return;
			}

			if (isArray) {
				this._mapDataArray({
					data: value,
					path: newPath,
					out: opt.out
				});
			}

		}.bind(this));
	},

	/**
	 * @method _mapDataArray
	 * @param {object} opt
	 * @param {Array} opt.path
	 * @param {Object|Array} opt.data
	 * @param {Array} opt.out
	 * @returns {void}
	 * @private
	 */
	_mapDataArray: function (opt) {

		var path = opt.path.slice();
		path.push('[]');

		this.for(opt.data, function (value) {

			var newPath = path.slice(),
				type = this._getType(value);

			if (type === 'object') {
				this._mapDataObject({
					data: value,
					path: newPath,
					out: opt.out
				});
				return;
			}

			if (type === 'array') {
				this._mapDataArray({
					data: value,
					path: newPath,
					out: opt.out
				});
			}

		}.bind(this));

	},

	/**
	 * @method _getType
	 * @param {*} value
	 * @returns {string} type
	 * @private
	 */
	_getType: function (value) {

		if (value instanceof Array) {
			return 'array';
		}

		return (typeof value).toLowerCase();
	},

	/**
	 * @method _mapType
	 * @param {string} type
	 * @returns {string} type
	 * @private
	 */
	_mapType: function (type) {

		switch (type) {
			case 'integer': return 'number';
			case 'float': return 'number';
			case 'bigdezimal': return 'number';
			default: return type;
		}

	}

});

module.exports = ValidatorDataSchema;<commit_msg>[change] #4: validation - better performance, fix reference in reference bug<commit_after>
'use strict';

var extend = require('util')._extend,
	validatorLog = require('./ValidatorLog'),
	Utils = require('./Utils');

/**
 *
 * @class ValidatorDataSchema
 * @namespace ValidatorDataSchema
 * @param {object} options
 * @constructor
 *
 * Swagger importer
 */
function ValidatorDataSchema(options) {
	this.init(options);
}

ValidatorDataSchema.prototype = extend(ValidatorDataSchema.prototype, Utils.prototype);
ValidatorDataSchema.prototype = extend(ValidatorDataSchema.prototype, {

	constructor : ValidatorDataSchema,

	_defaults: {
		schema: undefined,
		data: undefined
	},

	/**
	 *
	 * @method init
	 * called by constructor
	 * @param {object} options
	 * @public
	 */
	init: function (options) {

		var _validation = {};

		options = extend(this._defaults, options || {});

		this._options = options;
		this._isValid = true;
		this._schema = this._options.schema;
		this._data = this._options.data;
		this._path = this._options.path;
		this._expected = this._options.expected;
		this._schemaMap = {};
		this._invalidCounter = 0;

		if (!this._schema || typeof this._schema !== 'object') {
			this._isValid = false;
			validatorLog.error('options.schema can\'t be empty!');
		}

		if (!this._data || typeof this._data !== 'object') {
			this._isValid = false;
			validatorLog.error('options.data can\'t be empty!');
		}

		this._mapSchema(this._schema);
		this._mapData(this._data);

		_validation.validation = {};
		_validation.validation[this._expected] = {};
		_validation.validation[this._expected].counter = this._invalidCounter;

		this.setMethodStore(this._path, _validation);

		if (this._invalidCounter > 0) {
			validatorLog.error('Mock data in file ' + options.filePathData + ' are invalid! ' +
				'' + this._invalidCounter + ' invalid values found.');

			return false;
		}

		validatorLog.success('Mock data in file ' + options.filePathData + ' are valid!');
		return true;
	},

	/**
	 * @method _mapSchema
	 * @param {object|Array} schema
	 * @returns {object}
	 * @private
	 */
	_mapSchema: function (schema) {

		var out = [],
			outObj = {};

		this._mapSchemaUnknown({
			data: schema,
			path: [],
			out: out,
			refs: []
		});

		return outObj;
	},

	/**
	 * @method _mapSchemaUnknown
	 * @param {object} opt
	 * @param {Array} opt.path
	 * @param {object} opt.data
	 * @param {Array} opt.out
	 * @param {Array} opt.refs
	 * @returns {Boolean} isMapped
	 * @private
	 */
	_mapSchemaUnknown: function (opt) {

		if (opt.data instanceof Array) {
			if (opt.data.length > 0) {
				this._mapSchemaArray({
					data: opt.data[0],
					path: opt.path,
					out: opt.out,
					refs: opt.refs
				});
			}
			return true;
		}

		if (typeof opt.data === 'object') {
			this._mapSchemaObject({
				data: opt.data,
				path: opt.path,
				out: opt.out,
				refs: opt.refs
			});
			return true;
		}

		return false;
	},

	/**
	 * @method _mapSchemaArray
	 * @param {object} opt
	 * @param {Array} opt.path
	 * @param {*} opt.data
	 * @param {Array} opt.out
	 * @param {Array} opt.refs
	 * @returns {void}
	 * @private
	 */
	_mapSchemaArray: function (opt) {

		this._setTmpSchemaObj({
			path: opt.path.slice(),
			type: 'array',
			refs: opt.refs
		});

		var path = opt.path.slice(),
			newPath;

		path.push('[]');

		if (typeof opt.data !== 'object' || opt.data instanceof Array) {
			newPath = path.slice();

			if (opt.data instanceof Array) {
				if (opt.data.length > 0) {
					this._mapSchemaArray({
						data: opt.data[0],
						path: newPath,
						out: opt.out,
						refs: opt.refs
					});
				}
				return;
			}

			this._mapSchemaString({
				data: opt.data,
				path: newPath,
				out: opt.out,
				refs: opt.refs
			});
			return;
		}

		this.forIn(opt.data, function (key, value) {

			var newPath = path.slice();

			if (
				this._mapSchemaUnknown({
					data: value,
					path: newPath,
					out: opt.out,
					refs: opt.refs
				})
			) {
				return;
			}

			newPath.push(key);

			this._mapSchemaString({
				data: value,
				path: newPath,
				out: opt.out,
				refs: opt.refs
			});

		}.bind(this));

	},

	/**
	 * @method _mapSchemaObject
	 * @param {object} opt
	 * @param {Array} opt.path
	 * @param {object} opt.data
	 * @param {Array} opt.out
	 * @param {Array} opt.refs
	 * @returns {void}
	 * @private
	 */
	_mapSchemaObject: function (opt) {

		this._setTmpSchemaObj({
			path: opt.path.slice(),
			type: 'object',
			refs: opt.refs
		});

		this.forIn(opt.data, function (key, value) {
			var newPath = opt.path.slice();

			newPath.push(key);

			if (
				this._mapSchemaUnknown({
					data: value,
					path: newPath,
					out: opt.out,
					refs: opt.refs
				})
			) {
				return;
			}

			this._mapSchemaString({
				data: value,
				path: newPath,
				out: opt.out,
				refs: opt.refs
			});

			return true;
		}.bind(this));
	},

	/**
	 * @method _mapSchemaString
	 * @param {object} opt
	 * @param {Array} opt.path
	 * @param {String} opt.data
	 * @param {Array} opt.out
	 * @param {Array} opt.refs
	 * @returns {void}
	 * @private
	 */
	_mapSchemaString: function (opt) {

		var regResult = /(^\$ref-)(.*)/.exec(opt.data);

		if (regResult !== null && regResult.length > 2) {

			var ref = this._getRef(regResult[2]),
				refs = opt.refs.slice(),
				found1 = refs.indexOf(regResult[2]);

			refs.push(regResult[2]);

			if (found1 >= 0) {
				if (refs.indexOf(regResult[2], found1) >= 0) {
					return;
				}
			}

			if (ref instanceof Array) {
				if (ref.length > 0) {
					this._mapSchemaArray({
						data: ref[0],
						path: opt.path,
						out: opt.out,
						refs: refs
					});
				}
				return;
			}

			if (typeof ref === 'object') {
				this._mapSchemaObject({
					data: ref,
					path: opt.path,
					out: opt.out,
					refs: refs
				});
				return;
			}

			return;
		}

		this._setTmpSchemaObj({
			path: opt.path,
			type: this._mapType(opt.data)
		});
	},

	/**
	 * @method _getRef
	 * @param {String} refName
	 * @returns {Object|Array}
	 * @private
	 */
	_getRef: function (refName) {
		try {
			return JSON.parse(this.readFile(this._options.restPath + '/_DTO/' + refName + '.json'));
		} catch (err) {}

		return {};
	},

	/**
	 * @method _mapData
	 * @param {object} data
	 * @returns {Array}
	 * @private
	 */
	_mapData: function (data) {

		var out = [];

		if (data instanceof Array) {
			this._mapDataArray({
				data: data,
				path: [],
				out: out
			});
		} else if (typeof data === 'object') {
			this._mapDataObject({
				data: data,
				path: [],
				out: out
			});
		}

		return out;
	},

	/**
	 * @method _mapDataObject
	 * @param {object} opt
	 * @param {Array} opt.path
	 * @param {Object|Array} opt.data
	 * @param {Array} opt.out
	 * @returns {void}
	 * @private
	 */
	_mapDataObject: function (opt) {
		this.forIn(opt.data, function (key, value) {
			var newPath = opt.path.slice(),
				type = this._getType(value),
				isObject = (type === 'object'),
				isArray = (type === 'array');

			newPath.push(key);

			if (isObject || isArray) {
				this._validateObject({
					path: newPath,
					type: type
				});
			} else {
				this._validateObject({
					path: newPath,
					type: type,
					value: value
				});
			}

			if (isObject) {
				this._mapDataObject({
					data: value,
					path: newPath,
					out: opt.out
				});
				return;
			}

			if (isArray) {
				this._mapDataArray({
					data: value,
					path: newPath,
					out: opt.out
				});
			}

		}.bind(this));
	},

	/**
	 * @method _validateObject
	 * @param {object} opt
	 * @param {Array} opt.path
	 * @param {String} opt.type
	 * @param {*} opt.value
	 * @returns {void}
	 * @private
	 */
	_validateObject: function (opt) {

		var keyName = this._getSchemaKeyName(opt),
			item = this._schemaMap[keyName],
			pathStr = opt.path.join('.');

		if (!item) {
			validatorLog.error('No schema definition for: ' +  pathStr + ' found, ' +
				'please check you schema and/or mock file!');
			return;
		}

		if (item !== opt.type) {
			validatorLog.error('invalid type for: ' + pathStr + ' ' +
				'with value ' + opt.value + ' found! ' +
				'Value needs to by type of ' + item + '.'
			);
			this._invalidCounter += 1;
		}
	},

	/**
	 * @method _setTmpSchemaObj
	 * @param {object} opt
	 * @param {Array} opt.path
	 * @param {String} opt.type
	 * @returns {void}
	 * @private
	 */
	_setTmpSchemaObj: function (opt) {

		if (!(opt.path instanceof Array) || opt.path.length < 1) {
			return;
		}

		this._schemaMap[this._getSchemaKeyName(opt)] = opt.type;
	},

	/**
	 * @method _getSchemaKeyName
	 * @param {object} opt
	 * @param {Array} opt.path
	 * @returns {String}
	 * @private
	 */
	_getSchemaKeyName (opt) {
		var fileName = opt.path.join('.');

		fileName = fileName.trim();
		return this._getHashCode(fileName);
	},

	/**
	 * @method _getHashCode
	 * @param {String} s
	 * @returns {String}
	 * @private
	 */
	_getHashCode: function(s){
		return s.split('').reduce(function(a,b){a=((a<<5)-a)+b.charCodeAt(0);return a&a},0);
	},

	/**
	 * @method _mapDataArray
	 * @param {object} opt
	 * @param {Array} opt.path
	 * @param {Object|Array} opt.data
	 * @param {Array} opt.out
	 * @returns {void}
	 * @private
	 */
	_mapDataArray: function (opt) {

		var path = opt.path.slice();
		path.push('[]');

		this.for(opt.data, function (value) {

			var newPath = path.slice(),
				type = this._getType(value);

			if (type === 'object') {
				this._mapDataObject({
					data: value,
					path: newPath,
					out: opt.out
				});
				return;
			}

			if (type === 'array') {
				this._mapDataArray({
					data: value,
					path: newPath,
					out: opt.out
				});
			}

		}.bind(this));

	},

	/**
	 * @method _getType
	 * @param {*} value
	 * @returns {string} type
	 * @private
	 */
	_getType: function (value) {

		if (value instanceof Array) {
			return 'array';
		}

		return (typeof value).toLowerCase();
	},

	/**
	 * @method _mapType
	 * @param {*} type
	 * @returns {string} type
	 * @private
	 */
	_mapType: function (type) {

		switch (type) {
			case 'integer': return 'number';
			case 'float': return 'number';
			case 'bigdezimal': return 'number';
			default: return type;
		}

	}

});

module.exports = ValidatorDataSchema;<|endoftext|>


<commit_before>var AppSettings;

AppSettings = (function($) {
  "use strict";
  var config, handleAutoHideSidebarOption, handleDividersSideBarOption, handleThemeOptions, init, pattern;

  pattern = ".user > span, .navigation-sidebar > span,";
  pattern += ".menu .accordion-heading .arrow,";
  pattern += ".menu .accordion-heading a > span,";
  pattern += ".menu .accordion-body > li > a,";
  pattern += ".chat-users .user-list li a > span";
  /*
  */

  config = {
    urlThemes: 'none'
  };
  /*
  */

  init = function(options) {
    $.extend(config, options);
    handleDividersSideBarOption();
    handleAutoHideSidebarOption();
    handleThemeOptions();
  };
  /* Dividers in the sidebar
  */

  handleDividersSideBarOption = function() {
    /*  Sidebar Options
    */
    $("#app-setting #sidebar-dividers").click(function() {
      var $sidebar;

      $sidebar = $(".social-sidebar");
      if ($(this).prop("checked")) {
        $sidebar.addClass("dividers");
      } else {
        $sidebar.removeClass("dividers");
      }
    });
  };
  /* Auto Hide Sidebar Option
  */

  handleAutoHideSidebarOption = function() {
    $("#app-setting #sidebar-autohide").click(function() {
      var $main, $navbar, $sidebar, $wraper;

      $sidebar = $(".social-sidebar");
      $wraper = $(".wraper");
      $navbar = $(".social-navbar");
      $main = $("#main");

      if ($(this).prop("checked")) {
        $sidebar.removeClass("sidebar-full");
        $wraper.removeClass("sidebar-full");
        $.cookie('autohide', 'true', {expires: 7, path: '/'});
      } else {
        $sidebar.addClass("sidebar-full");
        $navbar.removeAttr("style");
        $main.removeAttr("style");
        $sidebar.find(pattern).removeAttr("style");
        $sidebar.find(".search-sidebar img").removeAttr("style");
        $(".icon-user.trigger-user-settings, .input-filter").removeAttr("style");
        $wraper.addClass("sidebar-full");
        $.cookie('autohide', 'false', {expires: 7, path: '/'});
      }

    });
  };
  /*  Navbar Options
  */

  handleThemeOptions = function() {
    $("select[name=\"colorpicker\"]").simplecolorpicker();
    $("select[name=\"colorpicker\"]").on("change", function() {
      var element, themeName, themeStyleSheet;

      themeStyleSheet = $("#theme");
      element = $("option:selected", this);
      if (typeof element.attr("data-class") !== 'undefined') {
        $.cookie('theme', element.attr("data-class"), {expires: 7, path: '/'});
        themeName = config.urlThemes + element.attr("data-class") + '.css';
      } else {
        $.cookie('theme', 'blue', {expires: 7, path: '/'});
        themeName = '#none';
      }
      themeStyleSheet.attr('href', themeName);
    });
  };
  return {
    init: init
  };
})(jQuery);
<commit_msg>fix: 取消'自动隐藏'时菜单不会显示<commit_after>var AppSettings;

AppSettings = (function($) {
  "use strict";
  var config, handleAutoHideSidebarOption, handleDividersSideBarOption, handleThemeOptions, init, pattern;

  pattern = ".user > span, .navigation-sidebar > span,";
  pattern += ".menu .accordion-heading .arrow,";
  pattern += ".menu .accordion-heading a > span,";
  pattern += ".menu .accordion-body > li > a,";
  pattern += ".chat-users .user-list li a > span";
  /*
  */

  config = {
    urlThemes: 'none'
  };
  /*
  */

  init = function(options) {
    $.extend(config, options);
    handleDividersSideBarOption();
    handleAutoHideSidebarOption();
    handleThemeOptions();
  };
  /* Dividers in the sidebar
  */

  handleDividersSideBarOption = function() {
    /*  Sidebar Options
    */
    $("#app-setting #sidebar-dividers").click(function() {
      var $sidebar;

      $sidebar = $(".social-sidebar");
      if ($(this).prop("checked")) {
        $sidebar.addClass("dividers");
      } else {
        $sidebar.removeClass("dividers");
      }
    });
  };
  /* Auto Hide Sidebar Option
  */

  handleAutoHideSidebarOption = function() {
    $("#app-setting #sidebar-autohide").click(function() {
      var $main, $navbar, $sidebar, $wraper;

      $sidebar = $(".social-sidebar");
      $wraper = $(".wraper");
      $navbar = $(".social-navbar");
      $main = $("#main");

      if ($(this).prop("checked")) {
        $wraper.removeClass("sidebar-full");
        $sidebar.removeClass("sidebar-full");
        $.cookie('autohide', 'true', {expires: 7, path: '/'});
      } else {
        $wraper.addClass("sidebar-full");
        $sidebar.addClass("sidebar-full");
        $navbar.removeAttr("style");
        $main.removeAttr("style");
        $sidebar.find(pattern).removeAttr("style");
        $sidebar.find(".search-sidebar img").removeAttr("style");
        $(".icon-user.trigger-user-settings, .input-filter").removeAttr("style");
        $.cookie('autohide', 'false', {expires: 7, path: '/'});
      }

    });
  };
  /*  Navbar Options
  */

  handleThemeOptions = function() {
    $("select[name=\"colorpicker\"]").simplecolorpicker();
    $("select[name=\"colorpicker\"]").on("change", function() {
      var element, themeName, themeStyleSheet;

      themeStyleSheet = $("#theme");
      element = $("option:selected", this);
      if (typeof element.attr("data-class") !== 'undefined') {
        $.cookie('theme', element.attr("data-class"), {expires: 7, path: '/'});
        themeName = config.urlThemes + element.attr("data-class") + '.css';
      } else {
        $.cookie('theme', 'blue', {expires: 7, path: '/'});
        themeName = '#none';
      }
      themeStyleSheet.attr('href', themeName);
    });
  };
  return {
    init: init
  };
})(jQuery);
<|endoftext|>


<commit_before>import { debounce } from './tickers'

CUSTOM_EVENT_LISTENERS = []

/**
 * Check if element is Window
 * @param  {DOMElement} $el - Element to check
 * @return {boolean}    True if window
 */

const isWindow = $el => $el === window

/**
 * Check if element is a DOM element
 * @param  {DOMElement} $el - Element to check
 * @return {boolean}    True if dom element
 */

const isDomElement = $el => ($el instanceof Element || $el instanceof HTMLDocument || $el instanceof HTMLDocument)

/**
 * Check if element is Window or DOM element
 * @param  {Element}    $el - Element to check
 * @return {boolean}    True if window or DOM element
 */

const isValidElement = $el => (isWindow($el) || isDomElement($el))

/**
 * Check if element already has the event attached
 * @param  {Element}    $el     - Element where the event is attached
 * @param  {String}     event   - The event name
 * @return {Boolean}    True if the event is already attached to the element
 */

const customEventIsDefined = ($el, event) => CUSTOM_EVENT_LISTENERS.findIndex(e => e.$el === $el && e.event === event) > -1

/**
 * Add custom event to event storage
 * @param  {Element}    $el     - Element where the event is attached
 * @param  {String}     event   - The event name
 * @return {void}
 */

const addCustomEvent = ($el, event) => {
    if(!customEventIsDefined($el, event)) {
        CUSTOM_EVENT_LISTENERS.push({
            $el,
            event
        })
    }
}

/**
 * Create a sarting event for the event triggered
 * @param  {Element}    $el     - Element to bind the event to
 * @param  {object}     event   - The triggered event's name
 * @return {void}
 */

const addStartEvent = ($el, event, delay = 200) => {

    // Check element
    if(!isValidElement($el)) {
        console.warn(`[addStartEvent:${event}]: Wrong parameter '${el}'. The parameter must be document, window or a DOM element`)
        return
    }

    const eventName = `${event}Start`

    // Check if event already exists
    if(customEventIsDefined($el, eventName)) {
        console.log(`[addStartEvent:${event}]: Already exists for '${el}' element`)
        return
    }

    // Register element and event
    addCustomEvent($el, eventName)

    // Create event
    const startEvent = new CustomEvent(eventName)
    $el.addEventListener(event, debounce(() => {
        $el.dispatchEvent(startEvent)
    }, delay, true))
}

/**
 * Create an ending event for the event triggered
 * @param  {Element}    $el     - Element to bind the event to
 * @param  {object}     event   - The triggered event's name
 * @return {void}
 */

const addEndEvent = ($el, event, delay = 200) => {

    // Check element
    if(!isValidElement($el)) {
        console.warn(`[addEndEvent:${event}]: Wrong parameter '${el}'. The parameter must be document, window or a DOM element`)
        return
    }

    const eventName = `${event}End`

    // Check if event already exists
    if(customEventIsDefined($el, eventName)) {
        console.log(`[addEndEvent:${event}]: Already exists for '${el}' element`)
        return
    }

    // Register element and event
    addCustomEvent($el, eventName)

    // Create event
    const endEvent = new CustomEvent(eventName)
    $el.addEventListener(event, debounce(() => {
        $el.dispatchEvent(endEvent)
    }, delay))
}

/**
 * Add scrollUp event to element (window by default)
 * @param  {Element} $el - Element to bind the event to
 * @return {void}
 */

const addScrollUpEvent = ($el = window) => {

    // Check element
    if(!isValidElement($el)) {
        console.warn(`[addScrollUpEvent]: Wrong parameter '${el}'. The parameter must be window or a DOM element`)
        return
    }

    let scrollTop = $el.scrollTop
    let previousScrollTop = scrollTop
    let direction = 0
    const scrollUp = new CustomEvent('scrollUp')
    const scrollProperty = isWindow($el) ? 'scrollY' : 'scrollTop'

    $el.addEventListener('scroll', e => {
        scrollTop = $el[scrollProperty]

        // Scroll up
        if(scrollTop < previousScrollTop && direction > -1) {
            $el.dispatchEvent(scrollUp)
            direction = -1

        // Scroll down
        } else if(scrollTop > previousScrollTop && direction < 1) {
            direction = 1
        }

        previousScrollTop = scrollTop
    })
}

/**
 * Add scrollDown event to element (window by default)
 * @param  {Element} $el - Element to bind the event to
 * @return {void}
 */

const addScrollDownEvent = ($el = window) => {

    // Check element
    if(!isValidElement($el)) {
        console.warn(`[addScrollDownEvent]: Wrong parameter '${el}'. The parameter must be window or a DOM element`)
        return
    }

    let scrollTop = $el.scrollTop
    let previousScrollTop = scrollTop
    let direction = 0
    const scrollDown = new CustomEvent('scrollDown')
    const scrollProperty = isWindow($el) ? 'scrollY' : 'scrollTop'

    $el.addEventListener('scroll', e => {
        scrollTop = $el[scrollProperty]

        // Scroll up
        if(scrollTop < previousScrollTop && direction > -1) {
            direction = -1

        // Scroll down
        } else if(scrollTop > previousScrollTop && direction < 1) {
            $el.dispatchEvent(scrollDown)
            direction = 1
        }

        previousScrollTop = scrollTop
    })
}

export {
    addStartEvent,
    addEndEvent,
    addScrollUpEvent,
    addScrollDownEvent,
}
<commit_msg>Edit logs<commit_after>import { debounce } from './tickers'

CUSTOM_EVENT_LISTENERS = []

/**
 * Check if element is Window
 * @param  {DOMElement} $el - Element to check
 * @return {boolean}    True if window
 */

const isWindow = $el => $el === window

/**
 * Check if element is a DOM element
 * @param  {DOMElement} $el - Element to check
 * @return {boolean}    True if dom element
 */

const isDomElement = $el => ($el instanceof Element || $el instanceof HTMLDocument || $el instanceof HTMLDocument)

/**
 * Check if element is Window or DOM element
 * @param  {Element}    $el - Element to check
 * @return {boolean}    True if window or DOM element
 */

const isValidElement = $el => (isWindow($el) || isDomElement($el))

/**
 * Check if element already has the event attached
 * @param  {Element}    $el     - Element where the event is attached
 * @param  {String}     event   - The event name
 * @return {Boolean}    True if the event is already attached to the element
 */

const customEventIsDefined = ($el, event) => CUSTOM_EVENT_LISTENERS.findIndex(e => e.$el === $el && e.event === event) > -1

/**
 * Add custom event to event storage
 * @param  {Element}    $el     - Element where the event is attached
 * @param  {String}     event   - The event name
 * @return {void}
 */

const addCustomEvent = ($el, event) => {
    if(!customEventIsDefined($el, event)) {
        CUSTOM_EVENT_LISTENERS.push({
            $el,
            event
        })
    }
}

/**
 * Create a sarting event for the event triggered
 * @param  {Element}    $el     - Element to bind the event to
 * @param  {object}     event   - The triggered event's name
 * @return {void}
 */

const addStartEvent = ($el, event, delay = 200) => {

    const eventName = `${event}Start`

    // Check element
    if(!isValidElement($el)) {
        console.warn(`[addStartEvent:${eventName}]: Wrong parameter '${el}'. The parameter must be document, window or a DOM element`)
        return
    }

    // Check if event already exists
    if(customEventIsDefined($el, eventName)) {
        console.log(`[addStartEvent:${eventName}]: Already exists for '${el}' element`)
        return
    }

    // Register element and event
    addCustomEvent($el, eventName)

    // Create event
    const startEvent = new CustomEvent(eventName)
    $el.addEventListener(event, debounce(() => {
        $el.dispatchEvent(startEvent)
    }, delay, true))
}

/**
 * Create an ending event for the event triggered
 * @param  {Element}    $el     - Element to bind the event to
 * @param  {object}     event   - The triggered event's name
 * @return {void}
 */

const addEndEvent = ($el, event, delay = 200) => {

    const eventName = `${event}End`

    // Check element
    if(!isValidElement($el)) {
        console.warn(`[addEndEvent:${eventName}]: Wrong parameter '${el}'. The parameter must be document, window or a DOM element`)
        return
    }

    // Check if event already exists
    if(customEventIsDefined($el, eventName)) {
        console.log(`[addEndEvent:${eventName}]: Already exists for '${el}' element`)
        return
    }

    // Register element and event
    addCustomEvent($el, eventName)

    // Create event
    const endEvent = new CustomEvent(eventName)
    $el.addEventListener(event, debounce(() => {
        $el.dispatchEvent(endEvent)
    }, delay))
}

/**
 * Add scrollUp event to element (window by default)
 * @param  {Element} $el - Element to bind the event to
 * @return {void}
 */

const addScrollUpEvent = ($el = window) => {

    // Check element
    if(!isValidElement($el)) {
        console.warn(`[addScrollUpEvent]: Wrong parameter '${el}'. The parameter must be window or a DOM element`)
        return
    }

    let scrollTop = $el.scrollTop
    let previousScrollTop = scrollTop
    let direction = 0
    const scrollUp = new CustomEvent('scrollUp')
    const scrollProperty = isWindow($el) ? 'scrollY' : 'scrollTop'

    $el.addEventListener('scroll', e => {
        scrollTop = $el[scrollProperty]

        // Scroll up
        if(scrollTop < previousScrollTop && direction > -1) {
            $el.dispatchEvent(scrollUp)
            direction = -1

        // Scroll down
        } else if(scrollTop > previousScrollTop && direction < 1) {
            direction = 1
        }

        previousScrollTop = scrollTop
    })
}

/**
 * Add scrollDown event to element (window by default)
 * @param  {Element} $el - Element to bind the event to
 * @return {void}
 */

const addScrollDownEvent = ($el = window) => {

    // Check element
    if(!isValidElement($el)) {
        console.warn(`[addScrollDownEvent]: Wrong parameter '${el}'. The parameter must be window or a DOM element`)
        return
    }

    let scrollTop = $el.scrollTop
    let previousScrollTop = scrollTop
    let direction = 0
    const scrollDown = new CustomEvent('scrollDown')
    const scrollProperty = isWindow($el) ? 'scrollY' : 'scrollTop'

    $el.addEventListener('scroll', e => {
        scrollTop = $el[scrollProperty]

        // Scroll up
        if(scrollTop < previousScrollTop && direction > -1) {
            direction = -1

        // Scroll down
        } else if(scrollTop > previousScrollTop && direction < 1) {
            $el.dispatchEvent(scrollDown)
            direction = 1
        }

        previousScrollTop = scrollTop
    })
}

export {
    addStartEvent,
    addEndEvent,
    addScrollUpEvent,
    addScrollDownEvent,
}
<|endoftext|>


<commit_before>var Differ = require('../interfaces/differ.js');
var looksSame = require('looks-same');
var objectAssign = require('object-assign');

/**
* LooksSame Adapter for use with Mugshot
*
* @implements {Differ}
* @class
*/
function LooksSameAdapter(userOptions) {
  var options = {
    highlightColor: '#ff00ff',
    strict: true
  };

  this._options = objectAssign(options, userOptions, {diff: undefined});

  if (this._options.tolerance !== undefined) {
    this._options.strict = false;
  }

  console.log(this._options);
}

LooksSameAdapter.prototype = objectAssign({}, Differ, {
  isEqual: function(img1, img2, callback) {
    var options = objectAssign({}, this._options);

    looksSame(img1, img2, options, callback);
  },

  createDiff: function(img1, img2, callback) {
    var options = objectAssign({}, this._options, {
      reference: img1,
      current: img2
    });

    looksSame.createDiff(options, callback);
  }
});

module.exports = LooksSameAdapter;
<commit_msg>remove console.log of the options obj<commit_after>var Differ = require('../interfaces/differ.js');
var looksSame = require('looks-same');
var objectAssign = require('object-assign');

/**
* LooksSame Adapter for use with Mugshot
*
* @implements {Differ}
* @class
*/
function LooksSameAdapter(userOptions) {
  var options = {
    highlightColor: '#ff00ff',
    strict: true
  };

  this._options = objectAssign(options, userOptions, {diff: undefined});

  if (this._options.tolerance !== undefined) {
    this._options.strict = false;
  }
}

LooksSameAdapter.prototype = objectAssign({}, Differ, {
  isEqual: function(img1, img2, callback) {
    var options = objectAssign({}, this._options);

    looksSame(img1, img2, options, callback);
  },

  createDiff: function(img1, img2, callback) {
    var options = objectAssign({}, this._options, {
      reference: img1,
      current: img2
    });

    looksSame.createDiff(options, callback);
  }
});

module.exports = LooksSameAdapter;
<|endoftext|>


<commit_before>'use strict';

const beautify = require('html').prettyPrint;
const path = require('path');
const Promise = require('bluebird');
const stripIndent = require('strip-indent');

const getNunjucksEnv = require('../utils/getNunjucksEnv');
const renderIframe = require('../renderIframe');

const beautifyOpts = {
  indent_size: 2,
  max_char: 0,
};

/**
 * Custom `@example` annotation.
 *
 * Augments the normal sassdoc @example annotation.
 * If example language is 'njk' (nunjucks), render the example
 * and put the result in the `rendered` property of the parsed example.
 */
module.exports = env => {
  // eslint-disable-next-line global-require
  const baseExampleFn = require('sassdoc/dist/annotation/annotations/example')
    .default;
  const baseExample = baseExampleFn();
  let renderSass;
  return {
    name: 'example',
    parse: baseExample.parse,
    resolve: data => {
      let customNjkEnv;
      let warned = false;
      const iFramePromises = [];
      const sassPromises = [];
      data.forEach(item => {
        if (!item.example) {
          return;
        }
        item.example.forEach(exampleItem => {
          if (exampleItem.type === 'html') {
            exampleItem.rendered = beautify(
              stripIndent(exampleItem.code),
              beautifyOpts
            );
          } else if (exampleItem.type === 'njk') {
            if (!customNjkEnv) {
              customNjkEnv = getNunjucksEnv('Nunjucks @example', env, warned);
            }
            if (!customNjkEnv) {
              warned = true;
              return;
            }
            exampleItem.rendered = beautify(
              stripIndent(customNjkEnv.renderString(exampleItem.code)),
              beautifyOpts
            ).trim();
          } else if (exampleItem.type === 'scss') {
            exampleItem.rendered = undefined;
            if (!renderSass) {
              try {
                let implementation = 'node-sass';
                if (
                  env.herman &&
                  env.herman.sass &&
                  env.herman.sass.implementation
                ) {
                  implementation = env.herman.sass.implementation;
                }
                if (typeof implementation === 'string') {
                  // eslint-disable-next-line global-require
                  implementation = require(implementation);
                }
                renderSass = Promise.promisify(implementation.render);
              } catch (err) {
                env.logger.warn(
                  'Cannot find Sass module, which is required ' +
                    'when using `@example scss` annotation.'
                );
                env.logger.warn(err);
                return;
              }
            }
            let sassData = exampleItem.code;
            let includepaths = [];
            let outputStyle = 'expanded';
            if (env.herman && env.herman.sass) {
              if (env.herman.sass.use) {
                const arr = env.herman.sass.use;
                for (let i = arr.length - 1; i >= 0; i = i - 1) {
                  sassData = `@use '${arr[i]}';\n${sassData}`;
                }
              }
              if (env.herman.sass.includes) {
                const arr = env.herman.sass.includes;
                for (let i = arr.length - 1; i >= 0; i = i - 1) {
                  sassData = `@import '${arr[i]}';\n${sassData}`;
                }
              }
              if (env.herman.sass.includepaths) {
                includepaths = env.herman.sass.includepaths;
              }
              if (env.herman.sass.outputstyle) {
                outputStyle = env.herman.sass.outputstyle;
              }
            }
            const promise = renderSass({
              data: sassData,
              importer: url => {
                if (url[0] === '~') {
                  url = path.resolve('node_modules', url.substr(1));
                }
                return { file: url };
              },
              includePaths: includepaths,
              outputStyle,
            })
              .then(rendered => {
                const encoded = rendered.css.toString('utf-8');
                exampleItem.rendered = encoded;
              })
              .catch(err => {
                env.logger.warn(
                  'Error compiling @example scss: \n' +
                    `${err.message}\n${sassData}`
                );
              });
            sassPromises.push(promise);
          }
          const iframePromise = Promise.all(sassPromises).then(() =>
            renderIframe(env, exampleItem, 'example')
          );
          iFramePromises.push(iframePromise);
        });
      });
      return Promise.all(iFramePromises);
    },
  };
};
<commit_msg>@use before @import<commit_after>'use strict';

const beautify = require('html').prettyPrint;
const path = require('path');
const Promise = require('bluebird');
const stripIndent = require('strip-indent');

const getNunjucksEnv = require('../utils/getNunjucksEnv');
const renderIframe = require('../renderIframe');

const beautifyOpts = {
  indent_size: 2,
  max_char: 0,
};

/**
 * Custom `@example` annotation.
 *
 * Augments the normal sassdoc @example annotation.
 * If example language is 'njk' (nunjucks), render the example
 * and put the result in the `rendered` property of the parsed example.
 */
module.exports = env => {
  // eslint-disable-next-line global-require
  const baseExampleFn = require('sassdoc/dist/annotation/annotations/example')
    .default;
  const baseExample = baseExampleFn();
  let renderSass;
  return {
    name: 'example',
    parse: baseExample.parse,
    resolve: data => {
      let customNjkEnv;
      let warned = false;
      const iFramePromises = [];
      const sassPromises = [];
      data.forEach(item => {
        if (!item.example) {
          return;
        }
        item.example.forEach(exampleItem => {
          if (exampleItem.type === 'html') {
            exampleItem.rendered = beautify(
              stripIndent(exampleItem.code),
              beautifyOpts
            );
          } else if (exampleItem.type === 'njk') {
            if (!customNjkEnv) {
              customNjkEnv = getNunjucksEnv('Nunjucks @example', env, warned);
            }
            if (!customNjkEnv) {
              warned = true;
              return;
            }
            exampleItem.rendered = beautify(
              stripIndent(customNjkEnv.renderString(exampleItem.code)),
              beautifyOpts
            ).trim();
          } else if (exampleItem.type === 'scss') {
            exampleItem.rendered = undefined;
            if (!renderSass) {
              try {
                let implementation = 'node-sass';
                if (
                  env.herman &&
                  env.herman.sass &&
                  env.herman.sass.implementation
                ) {
                  implementation = env.herman.sass.implementation;
                }
                if (typeof implementation === 'string') {
                  // eslint-disable-next-line global-require
                  implementation = require(implementation);
                }
                renderSass = Promise.promisify(implementation.render);
              } catch (err) {
                env.logger.warn(
                  'Cannot find Sass module, which is required ' +
                    'when using `@example scss` annotation.'
                );
                env.logger.warn(err);
                return;
              }
            }
            let sassData = exampleItem.code;
            let includepaths = [];
            let outputStyle = 'expanded';
            if (env.herman && env.herman.sass) {
              if (env.herman.sass.includes) {
                const arr = env.herman.sass.includes;
                for (let i = arr.length - 1; i >= 0; i = i - 1) {
                  sassData = `@import '${arr[i]}';\n${sassData}`;
                }
              }
              if (env.herman.sass.use) {
                const arr = env.herman.sass.use;
                for (let i = arr.length - 1; i >= 0; i = i - 1) {
                  sassData = `@use '${arr[i]}';\n${sassData}`;
                }
              }
              if (env.herman.sass.includepaths) {
                includepaths = env.herman.sass.includepaths;
              }
              if (env.herman.sass.outputstyle) {
                outputStyle = env.herman.sass.outputstyle;
              }
            }
            const promise = renderSass({
              data: sassData,
              importer: url => {
                if (url[0] === '~') {
                  url = path.resolve('node_modules', url.substr(1));
                }
                return { file: url };
              },
              includePaths: includepaths,
              outputStyle,
            })
              .then(rendered => {
                const encoded = rendered.css.toString('utf-8');
                exampleItem.rendered = encoded;
              })
              .catch(err => {
                env.logger.warn(
                  'Error compiling @example scss: \n' +
                    `${err.message}\n${sassData}`
                );
              });
            sassPromises.push(promise);
          }
          const iframePromise = Promise.all(sassPromises).then(() =>
            renderIframe(env, exampleItem, 'example')
          );
          iFramePromises.push(iframePromise);
        });
      });
      return Promise.all(iFramePromises);
    },
  };
};
<|endoftext|>


<commit_before>(function () {
    'use strict';

    angular
        .module('dpShared')
        .component('dpLink', {
            templateUrl: 'modules/shared/components/link/link.html',
            transclude: true,
            bindings: {
                className: '@',
                hoverText: '@',
                type: '@',
                payload: '<'
            },
            controller: DpLinkController,
            controllerAs: 'vm'
        });

    DpLinkController.$inject = ['$location', 'store', 'ACTIONS', 'applicationState'];

    function DpLinkController ($location, store, ACTIONS, applicationState) {
        const vm = this;

        const BUTTON = 'button',
            LINK = 'a';

        vm.className = vm.className || 'o-btn o-btn--link';
        vm.tagName = getTagName(vm.type, vm.payload);

        vm.dispatch = function () {
            store.dispatch(getAction(vm.type, vm.payload));
        };

        function getAction (type, payload) {
            const action = {
                type: ACTIONS[type]
            };
            if (angular.isDefined(payload)) {
                action.payload = payload;
            }
            return action;
        }

        function getTagName (type, payload) {
            if (ACTIONS[type].isButton) {
                return BUTTON;
            } else {
                vm.href = getHref(type, payload);
                vm.followLink = function (event) {
                    // The href attribute is ignored when left-clicking
                    // It's only a fallback for middle and right mouse button
                    event.preventDefault();
                    vm.dispatch();
                };
                return LINK;
            }
        }

        function getHref (type, payload) {
            // Remove state properties that do not relate to the url
            // by converting the state to a url and back
            // This prevents deep copying of large state objects in the reducer (eg dataSelection.markers)
            const reducer = applicationState.getReducer(),
                state = applicationState.getStore().getState(),
                params = applicationState.getStateUrlConverter().state2params(state),
                sourceState = applicationState.getStateUrlConverter().params2state({}, params),
                targetState = reducer(sourceState, getAction(type, payload));

            return applicationState.getStateUrlConverter().state2url(targetState);
        }
    }
})();
<commit_msg>the reducer should not be called with the real state because it will mess up app state tg-2812<commit_after>(function () {
    'use strict';

    angular
        .module('dpShared')
        .component('dpLink', {
            templateUrl: 'modules/shared/components/link/link.html',
            transclude: true,
            bindings: {
                className: '@',
                hoverText: '@',
                type: '@',
                payload: '<'
            },
            controller: DpLinkController,
            controllerAs: 'vm'
        });

    DpLinkController.$inject = ['$location', 'store', 'ACTIONS', 'applicationState'];

    function DpLinkController ($location, store, ACTIONS, applicationState) {
        const vm = this;

        const BUTTON = 'button',
            LINK = 'a';

        vm.className = vm.className || 'o-btn o-btn--link';
        vm.tagName = getTagName(vm.type, vm.payload);

        vm.dispatch = function () {
            store.dispatch(getAction(vm.type, vm.payload));
        };

        function getAction (type, payload) {
            const action = {
                type: ACTIONS[type]
            };
            if (angular.isDefined(payload)) {
                action.payload = payload;
            }
            return action;
        }

        function getTagName (type, payload) {
            if (ACTIONS[type].isButton) {
                return BUTTON;
            } else {
                vm.href = getHref(type, payload);
                vm.followLink = function (event) {
                    // The href attribute is ignored when left-clicking
                    // It's only a fallback for middle and right mouse button
                    event.preventDefault();
                    vm.dispatch();
                };
                return LINK;
            }
        }

        function getHref (type, payload) {
            // Remove state properties that do not relate to the url
            // by converting the state to a url and back
            // This prevents deep copying of large state objects in the reducer (eg dataSelection.markers)
            const reducer = applicationState.getReducer(),
                ghostState = angular.copy(applicationState.getStore().getState()),
                params = applicationState.getStateUrlConverter().state2params(ghostState),
                sourceState = applicationState.getStateUrlConverter().params2state({}, params),
                targetState = reducer(sourceState, getAction(type, payload));

            return applicationState.getStateUrlConverter().state2url(targetState);
        }
    }
})();
<|endoftext|>


<commit_before>'use strict';

const h = require('highland');

class Map {
  constructor(fn) {
    this._fn = fn;
  }

  apply() {
    return h.map(this._fn);
  }
};

class DoTo extends Map {
  constructor(fn) {
    super(
      x => {
        fn(x);
        return x;
      }
    );
  }
};

class Collect {
  apply() {
    return h.collect();
  }
};

class Drop {
  constructor(count) {
    this._count = count;
  }

  apply() {
    return h.drop(this._count || 0);
  }
};

class Filter {
  constructor(fn) {
    this._fn = fn;
  }

  apply() {
    return h.filter(this._fn);
  }
};

class Split {
  apply() {
    return h.split();
  }
};

class ParseJSON extends Map {
  constructor() {
    super(
      file => {

        /**
         * If there is no data then convert 'contents' to JSON:
         */

        if (!file.data) {
          try {
            file.data = JSON.parse(String(file.contents));
          } catch (e) {

          }
        }
        return file;
      }
    );
  }
};

class FromVinyl extends Map {
  constructor() {
    super(file => file.contents);
  }
};

exports.Map = Map;
exports.DoTo = DoTo;
exports.Drop = Drop;
exports.Filter = Filter;
exports.FromVinyl = FromVinyl;
exports.Split = Split;
exports.Collect = Collect;
exports.ParseJSON = ParseJSON;
<commit_msg>add Vinyl transforms<commit_after>'use strict';

const h = require('highland');
const File = require('vinyl');
const toVinyl = require('../toVinyl');

class Map {
  constructor(fn) {
    this._fn = fn;
  }

  apply() {
    return h.map(this._fn);
  }
};

class DoTo extends Map {
  constructor(fn) {
    super(
      x => {
        fn(x);
        return x;
      }
    );
  }
};

class Collect {
  apply() {
    return h.collect();
  }
};

class Drop {
  constructor(count) {
    this._count = count;
  }

  apply() {
    return h.drop(this._count || 0);
  }
};

class Filter {
  constructor(fn) {
    this._fn = fn;
  }

  apply() {
    return h.filter(this._fn);
  }
};

class Split {
  apply() {
    return h.split();
  }
};

class ParseJSON extends Map {
  constructor() {
    super(
      file => {

        /**
         * If there is no data then convert 'contents' to JSON:
         */

        if (!file.data) {
          try {
            file.data = JSON.parse(String(file.contents));
          } catch (e) {

          }
        }
        return file;
      }
    );
  }
};

class FromVinyl extends Map {
  constructor() {
    super(file => file.contents);
  }
};

class ToVinyl extends Map {
  constructor() {
    super(file => {
      return (File.isVinyl(file)) ? file : toVinyl(file);
    });
  }
};

exports.Map = Map;
exports.DoTo = DoTo;
exports.Drop = Drop;
exports.Filter = Filter;
exports.FromVinyl = FromVinyl;
exports.Split = Split;
exports.ToVinyl = ToVinyl;
exports.Collect = Collect;
exports.ParseJSON = ParseJSON;
<|endoftext|>