<commit_before>/**
 * @class  	WebAlloy
 * @author  Flavio De Stefano <flavio.destefano@caffeinalab.com>
 */

/**
 * * **jsExt**: The extension to use for Javascript files. Default: `.jslocal`
 * @type {Object}
 */
var config = _.extend({
	jsExt: '.jslocal'
}, Alloy.CFG.T.weballoy);
exports.config = config;

var libDir = [];
var helpers = {};

/**
 * Add an helper for the WebView
 * @param {String} 		name   The name of the helper
 * @param {Function} 	method The callback
 */
function addHelper(name, method) {
	helpers[name] = method;
}
exports.addHelper = addHelper;

function embedText(f) {
	var file = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory, f);
	if (file.exists() === false) {
		Ti.API.warn('Weballoy: File not found (' + f + ')');
		return '';
	}

	var read = file.read().text;
	file = null;
	return read;
}

function embedCSS(f) {
	return '';
}

function embedJS(f) {
	return '';
}

/**
 * @method createView
 * @param  {Object} args Arguments for the view.
 * @return {Ti.UI.WebView}
 */
exports.createView = function(args) {
	args = args || {};
	if (_.isEmpty(args.name)) {
		throw new Error('WebAlloy: you must pass a name');
	}

	var uniqid = _.uniqueId();
	var $ui = Ti.UI.createWebView(_.extend({
		disableBounce: true,
		uniqid: uniqid,
		enableZoomControls: false,
		backgroundColor: 'transparent'
	}, args));

	$ui.addEventListener('load', function(){
		if (args.autoHeight === true) {
			$ui.height = $ui.evalJS('document.body.clientHeight');
		}
		if (_.isFunction(args.loaded)) args.loaded();
	});

	// Include head (styles)
	var html = '<!DOCTYPE html><meta charset="utf-8" />';
	html += '<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=no;" />';

	// Install the global event handler for this specific WebView
	html += '';

	// Include global css
	html += embedCSS('web/app.css');
	html += embedCSS('web/styles/' + args.name + '.css');

	html += '';

	// Include template
	$ui.tpl = _.template(embedText('web/views/' + args.name + '.tpl'));

	html += '
';
	html += $ui.tpl(_.extend({}, helpers, args.webdata));
	html += '
';

	// Include libs
	_.each(libDir, function(js) {
		html += embedJS(js);
	});

	// Include footer
	html += embedJS('web/app' + config.jsExt);
	html += embedJS('web/controllers/' + args.name + config.jsExt);
	html += '';

	$ui.html = html;

	$ui._ = function(js) {
		return $ui.evalJS(js);
	};

	$ui.call = function() {
		var args = _.map(Array.prototype.slice.call(arguments, 1), function(a) { return JSON.stringify(a); });
		return $ui._( arguments[0] + '(' + args.join(',') + ')' );
	};

	$ui.$ = function(selector) {
		return {
			call: function() {
				var args = _.map(Array.prototype.slice.call(arguments, 1), function(a) { return JSON.stringify(a); });
				return $ui._( 'document.querySelector("' + selector + '").' + arguments[0] + '(' + args.join(',') + ')' );
			},
			get: function(name) {
				return $ui._( 'document.querySelector("' + selector + '").' + name );
			},
			set: function(name, value) {
				return $ui._( 'document.querySelector("' + selector + '").' + name + ' = ' + JSON.stringify(value) );
			}
		};
	};

	$ui.render = function(data) {
		$ui.$('#main').set('innerHTML', $ui.tpl(_.extend({}, helpers, data)));
	};

	// Install the API listener
	if (args.webapi != null) {

		var webapiListener = function(event) {
			if (!_.isFunction(args.webapi[event.name])) return;
			args.webapi[event.name].call($ui, event.data);
		};

		Ti.App.addEventListener('__weballoy' + uniqid, webapiListener);
		$ui.webapiUnbind = function() {
			Ti.App.removeEventListener('weballoy_' + uniqid, webapiListener);
		};
	}

	return $ui;
};

/*
Init
*/

var jsFiles = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory, 'web/lib').getDirectoryListing();
_.each(jsFiles, function(js) {
	libDir.push('web/lib/'+js);
});
<commit_msg>Refactor Weballoy<commit_after>/**
 * @class  	WebAlloy
 * @author  Flavio De Stefano <flavio.destefano@caffeinalab.com>
 */

/**
 * * **jsExt**: The extension to use for Javascript files. Default: `.jslocal`
 * @type {Object}
 */
var config = _.extend({
	jsExt: '.jslocal'
}, Alloy.CFG.T.weballoy);
exports.config = config;

var libDir = [];
var helpers = {};

function embedText(f) {
	var file = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory, f);
	if (file.exists() === false) {
		Ti.API.warn('Weballoy: File not found (' + f + ')');
		return '';
	}

	var read = file.read().text;
	file = null;
	return read;
}

function embedCSS(f) {
	return '';
}

function embedJS(f) {
	return '';
}

function getHTML(args) {
	// Include head (styles)
	var html = '<!DOCTYPE html><meta charset="utf-8" />';
	html += '<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=no;" />';

	// Install the global event handler for this specific WebView
	html += '\';

	// Include global css
	html += embedCSS('web/app.css');
	html += embedCSS('web/styles/' + args.name + '.css');

	html += '';

	// Include template
	$ui.tpl = _.template(embedText('web/views/' + args.name + '.tpl'));

	html += '
';
	html += $ui.tpl(_.extend({}, helpers, args.webdata));
	html += '
';

	// Include libs
	_.each(libDir, function(js) {
		html += embedJS(js);
	});

	// Include footer
	html += embedJS('web/app' + config.jsExt);
	html += embedJS('web/controllers/' + args.name + config.jsExt);

	html += '';

	return html;
}

/**
 * Add an helper for the WebView
 * @param {String} 		name   The name of the helper
 * @param {Function} 	method The callback
 */
exports.addHelper = function(name, method) {
	helpers[name] = method;
};

/**
 * @method createView
 * @param  {Object} args Arguments for the view.
 * @return {Ti.UI.WebView}
 */
exports.createView = function(args) {
	args = args || {};
	if (_.isEmpty(args.name)) {
		throw new Error('WebAlloy: you must pass a name');
	}

	args.uniqid = _.uniqueId();
	var $ui = Ti.UI.createWebView(_.extend({
		disableBounce: true,
		uniqid: args.uniqid,
		enableZoomControls: false,
		backgroundColor: 'transparent'
	}, args));

	$ui.addEventListener('load', function(){
		if (args.autoHeight === true) {
			$ui.height = $ui.evalJS('document.body.clientHeight');
		}
		if (_.isFunction(args.loaded)) args.loaded();
	});

	$ui.html = getHTML(args);

	$ui._ = function(js) {
		return $ui.evalJS(js);
	};

	$ui.call = function() {
		var args = _.map(Array.prototype.slice.call(arguments, 1), function(a) { return JSON.stringify(a); });
		return $ui._( arguments[0] + '(' + args.join(',') + ')' );
	};

	$ui.$ = function(selector) {
		return {
			call: function() {
				var args = _.map(Array.prototype.slice.call(arguments, 1), function(a) { return JSON.stringify(a); });
				return $ui._( 'document.querySelector("' + selector + '").' + arguments[0] + '(' + args.join(',') + ')' );
			},
			get: function(name) {
				return $ui._( 'document.querySelector("' + selector + '").' + name );
			},
			set: function(name, value) {
				return $ui._( 'document.querySelector("' + selector + '").' + name + ' = ' + JSON.stringify(value) );
			}
		};
	};

	$ui.render = function(data) {
		$ui.$('#main').set('innerHTML', $ui.tpl(_.extend({}, helpers, data)));
	};

	// Install the API listener
	if (args.webapi != null) {

		var webapiListener = function(event) {
			if (!_.isFunction(args.webapi[event.name])) return;
			args.webapi[event.name].call($ui, event.data);
		};

		Ti.App.addEventListener('__weballoy' + args.uniqid, webapiListener);
		$ui.webapiUnbind = function() {
			Ti.App.removeEventListener('weballoy_' + args.uniqid, webapiListener);
		};
	}

	return $ui;
};

/*
Init
*/

var jsFiles = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory, 'web/lib').getDirectoryListing();
_.each(jsFiles, function(js) {
	libDir.push('web/lib/'+js);
});
<|endoftext|>


<commit_before>var Dialog = {
  level: 0,
  zIndex: 1000,
  zIndexStep: 10,
  show: function(id) {
    if ($('#modal-background').length === 0) {
      $('body').append($('

'));
    }
    var $modal = $(id);

    var zIndex = Dialog.zIndex + Dialog.zIndexStep * Dialog.level;
    $('#modal-background').css('z-index', zIndex);
    $modal.css('z-index', zIndex + 1).show();
    $modal.find(ClientSideValidations.selectors.forms).resetClientSideValidations();

    Dialog.level += 1;
  },

  hide: function(el) {
    $modal = $(el);
    $modal.hide();
    Dialog.level -= 1;

    if (Dialog.level === 0) {
      $('#modal-background').remove();
    } else {
      var zIndex = Dialog.zIndex + Dialog.zIndexStep * (Dialog.level - 1);
      $('#modal-background').css('z-index', zIndex);
    }
  }
};

$(document).on('click', '[data-toggle=modal]', function(event) {
  event.preventDefault();
  Dialog.show($(this).data('target') || $(this).attr('href'));
});

$(document).on('click', '[data-close=modal]', function(event) {
  event.preventDefault();
  Dialog.hide($(this).closest('.modal-dialog'));
});
<commit_msg>esc to close modal.<commit_after>var Dialog = {
  level: 0,
  zIndex: 1000,
  zIndexStep: 10,
  show: function(id) {
    if ($('#modal-background').length === 0) {
      $('body').append($('

'));
    }
    var $modal = $(id);

    var zIndex = Dialog.zIndex + Dialog.zIndexStep * Dialog.level;
    $('#modal-background').css('z-index', zIndex);
    $modal.css('z-index', zIndex + 1).show();
    $modal.find(ClientSideValidations.selectors.forms).resetClientSideValidations();

    Dialog.level += 1;
    $modal.addClass('modal-level-' + Dialog.level);
  },

  hide: function(el) {
    $modal = $(el);
    $modal.hide();
    Dialog.level -= 1;

    if (Dialog.level === 0) {
      $('#modal-background').remove();
    } else {
      var zIndex = Dialog.zIndex + Dialog.zIndexStep * (Dialog.level - 1);
      $('#modal-background').css('z-index', zIndex);
    }
  }
};

$(document).on('click', '[data-toggle=modal]', function(event) {
  event.preventDefault();
  Dialog.show($(this).data('target') || $(this).attr('href'));
});

$(document).on('click', '[data-close=modal]', function(event) {
  event.preventDefault();
  Dialog.hide($(this).closest('.modal-dialog'));
});

$(document).on('keyup', function(event) {
  if (event.keyCode === 27 && Dialog.level > 0) { // Esc
    Dialog.hide('.modal-level-' + Dialog.level);
  }
});
<|endoftext|>


<commit_before>/*
 * Script adapted from timeout-dialog.js v1.0.1, 01-03-2012
 *
 * @author: Rodrigo Neri (@rigoneri)
 *
 * (The MIT License)
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

 Date.now = Date.now || function() { return +new Date; };

 if (!window.console){ console = {log: function() {}} };

function secondsToTime (secs) {
  var hours = Math.floor(secs / (60 * 60))

  var divisorForMinutes = secs % (60 * 60)
  var minutes = Math.floor(divisorForMinutes / 60)

  var divisorForSeconds = divisorForMinutes % 60
  var seconds = Math.ceil(divisorForSeconds)

  var obj = {
    'h': hours,
    'm': minutes,
    's': seconds
  }
  return obj
}

String.prototype.format = function () {
  var s = this
  var i = arguments.length

  while (i--) {
    s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i])
  }
  return s
}

!function ($) {
  $.timeoutDialog = function (options) {
    var settings = {
      timeout: 900,
      countdown: 60,
      time: 'minutes',
      title: 'You’re about to be signed out',
      message: 'For your security, you’ll be signed out in {0} if there’s no activity on your account. ',
      keep_alive_url: '/keep-alive',
      logout_url: '/sign-out',
      restart_on_yes: true,
      dialog_width: 340,
      close_on_escape: true,
      background_no_scroll: true,
      keep_alive_button_text: 'Get another {0} minutes'
    }

    $.extend(settings, options)

    var TimeoutDialog = {
      init: function () {
        this.setupDialogTimer()
      },

      setupDialogTimer: function () {
        var self = this
        window.setTimeout(function () {
          self.setupDialog()
        }, ((settings.timeout) - (settings.countdown)) * 1000)
      },

      setupDialog: function () {
        // check this
        var self = this
        self.dialogOpen = true
        self.startTime = Math.round(Date.now()/1000, 0);
        self.currentMin = Math.ceil(settings.timeout / 60)
        self.destroyDialog()
        if (settings.background_no_scroll) {
          $('html').addClass('noScroll')
        }
        var time = secondsToTime(settings.countdown)
        var timeout = secondsToTime(settings.timeout)
         // AL: Add live region and edit dialog structure
        $('
' +

            '
' + settings.title + '
' +

            '
' +
                settings.message + '
' + time.m + ' ' + settings.time + '' +
            '
' +

            '<button id="timeout-keep-signin-btn" class="button">' + settings.keep_alive_button_text.format(settings.timeout / 60) + '</button>' +

        '
' +

        '

')

        .appendTo('body')

        // AL: disable the non-dialog page to prevent confusion for VoiceOver users
        $('#skiplink-container, body>header, #global-cookie-message, body>main, body>footer').attr('aria-hidden', 'true')

        var activeElement = document.activeElement

        var modalFocus = document.getElementById("timeout-dialog")
        modalFocus.focus()

        self.addEvents();

        self.startCountdown(settings.countdown)

        self.escPress = function (event) {
          if (self.dialogOpen && event.keyCode === 27) {
            // close the dialog
            self.keepAlive()
            activeElement.focus()
          }
        }

        self.closeDialog = function () {
          if (self.dialogOpen) {
            self.keepAlive()
            activeElement.focus()
          }
        }

        // AL: prevent scrolling on touch, but allow pinch zoom
        self.handleTouch = function(e){
            var touches = e.originalEvent.touches || e.originalEvent.changedTouches;
            if ($('#timeout-dialog').length) {
                if(touches.length == 1){
                    e.preventDefault();
                }
            }
        }
        // AL: add touchmove handler
        $(document).on('touchmove', self.handleTouch)
        $(document).on('keydown', self.escPress)
        $('#timeout-keep-signin-btn').on('click', self.closeDialog)
      },

      destroyDialog: function () {
        $(document).off('touchmove', self.handleTouch)
        if ($('#timeout-dialog').length) {
          self.dialogOpen = false
          $('.timeout-overlay').remove()
          $('#timeout-dialog').remove()
          if (settings.background_no_scroll) {$('html').removeClass('noScroll')}
        }
        // AL: re-enable the non-dialog page
        $('#skiplink-container, body>header, #global-cookie-message, body>main, body>footer').removeAttr('aria-hidden')
      },

      // AL: moved updater to own call to allow calling from other events
      updateUI: function(counter){
        var self = this
        if (counter < 60) {
            $('#timeout-countdown').html(counter + " seconds")
          } else {
            var newCounter = Math.ceil(counter / 60);
            if(newCounter < self.currentMin){
                self.currentMin = newCounter
                $('#timeout-countdown').html(newCounter + " minutes")
            }
          }
      },

      addEvents: function(){
        var self = this;

        // trap focus in modal (or browser chrome)
        $('a, input, textarea, button, [tabindex]').not('[tabindex="-1"]').on("focus", function (event) {
            var modalFocus = document.getElementById("timeout-dialog")
            if(modalFocus && self.dialogOpen){
                if(!modalFocus.contains(event.target)) {
                    event.stopPropagation()
                    modalFocus.focus()
                }
            }
        });

        function handleFocus(){
            if(self.dialogOpen){
                // clear the countdown
                window.clearInterval(self.countdown)
                // calculate remaining time
                var expiredSeconds = (Math.round(Date.now()/1000, 0)) - self.startTime;
                var currentCounter = settings.countdown - expiredSeconds;

                self.updateUI(currentCounter);
                self.startCountdown(currentCounter);
            }
        }

        // AL: handle browsers pausing timeouts/intervals by recalculating the remaining time on window focus
        // need to widen this to cover the setTimeout which triggers the dialog for browsers which pause timers on blur
        // hiding this from IE8 as it breaks the reset - to investigate further
        if (navigator.userAgent.match(/MSIE 8/) == null) {
            //$(window).on("blur", function(){
                $(window).off("focus", handleFocus);
                $(window).on("focus", handleFocus);
            //});

        }
      },

      startCountdown: function (counter) {
        var self = this
        self.countdown = window.setInterval(function () {
          counter -= 1

          self.updateUI(counter);

          if (counter <= 0) {
            self.signOut()
          }
        }, 1000)
      },

      keepAlive: function () {
        var self = this
        self.destroyDialog()
        window.clearInterval(this.countdown)
        $(document).off('keydown', self.escPress)

        $.get(settings.keep_alive_url, function (data) {
          if (data === 'OK') {
            if (settings.restart_on_yes) {
              self.setupDialogTimer()
            }
          }
          else {
            self.signOut()
          }
        })
      },

      signOut: function () {
        var self = this
        window.clearInterval(self.countdown)
        self.destroyDialog()
        window.location = settings.logout_url

       }

    }

    TimeoutDialog.init()
  }
}(window.jQuery)<commit_msg>Dialog state<commit_after>/*
 * Script adapted from timeout-dialog.js v1.0.1, 01-03-2012
 *
 * @author: Rodrigo Neri (@rigoneri)
 *
 * (The MIT License)
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

 Date.now = Date.now || function() { return +new Date; };

 if (!window.console){ console = {log: function() {}} };

function secondsToTime (secs) {
  var hours = Math.floor(secs / (60 * 60))

  var divisorForMinutes = secs % (60 * 60)
  var minutes = Math.floor(divisorForMinutes / 60)

  var divisorForSeconds = divisorForMinutes % 60
  var seconds = Math.ceil(divisorForSeconds)

  var obj = {
    'h': hours,
    'm': minutes,
    's': seconds
  }
  return obj
}

String.prototype.format = function () {
  var s = this
  var i = arguments.length

  while (i--) {
    s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i])
  }
  return s
}

!function ($) {
  $.timeoutDialog = function (options) {
    var settings = {
      timeout: 900,
      countdown: 60,
      time: 'minutes',
      title: 'You’re about to be signed out',
      message: 'For your security, you’ll be signed out in {0} if there’s no activity on your account. ',
      keep_alive_url: '/keep-alive',
      logout_url: '/sign-out',
      restart_on_yes: true,
      dialog_width: 340,
      close_on_escape: true,
      background_no_scroll: true,
      keep_alive_button_text: 'Get another {0} minutes'
    }

    $.extend(settings, options)

    var TimeoutDialog = {
      init: function () {
        this.setupDialogTimer()
      },

      setupDialogTimer: function () {
        var self = this
        self.dialogOpen = false
        window.setTimeout(function () {
          self.setupDialog()
        }, ((settings.timeout) - (settings.countdown)) * 1000)
      },

      setupDialog: function () {
        // check this
        var self = this
        self.dialogOpen = true
        self.startTime = Math.round(Date.now()/1000, 0);
        self.currentMin = Math.ceil(settings.timeout / 60)
        self.destroyDialog()
        if (settings.background_no_scroll) {
          $('html').addClass('noScroll')
        }
        var time = secondsToTime(settings.countdown)
        var timeout = secondsToTime(settings.timeout)
         // AL: Add live region and edit dialog structure
        $('
' +

            '
' + settings.title + '
' +

            '
' +
                settings.message + '
' + time.m + ' ' + settings.time + '' +
            '
' +

            '<button id="timeout-keep-signin-btn" class="button">' + settings.keep_alive_button_text.format(settings.timeout / 60) + '</button>' +

        '
' +

        '

')

        .appendTo('body')

        // AL: disable the non-dialog page to prevent confusion for VoiceOver users
        $('#skiplink-container, body>header, #global-cookie-message, body>main, body>footer').attr('aria-hidden', 'true')

        var activeElement = document.activeElement

        var modalFocus = document.getElementById("timeout-dialog")
        modalFocus.focus()

        self.addEvents();

        self.startCountdown(settings.countdown)

        self.escPress = function (event) {
          if (self.dialogOpen && event.keyCode === 27) {
            // close the dialog
            self.keepAlive()
            activeElement.focus()
          }
        }

        self.closeDialog = function () {
          if (self.dialogOpen) {
            self.keepAlive()
            activeElement.focus()
          }
        }

        // AL: prevent scrolling on touch, but allow pinch zoom
        self.handleTouch = function(e){
            var touches = e.originalEvent.touches || e.originalEvent.changedTouches;
            if ($('#timeout-dialog').length) {
                if(touches.length == 1){
                    e.preventDefault();
                }
            }
        }
        // AL: add touchmove handler
        $(document).on('touchmove', self.handleTouch)
        $(document).on('keydown', self.escPress)
        $('#timeout-keep-signin-btn').on('click', self.closeDialog)
      },

      destroyDialog: function () {
        $(document).off('touchmove', self.handleTouch)
        if ($('#timeout-dialog').length) {
          self.dialogOpen = false
          $('.timeout-overlay').remove()
          $('#timeout-dialog').remove()
          if (settings.background_no_scroll) {$('html').removeClass('noScroll')}
        }
        // AL: re-enable the non-dialog page
        $('#skiplink-container, body>header, #global-cookie-message, body>main, body>footer').removeAttr('aria-hidden')
      },

      // AL: moved updater to own call to allow calling from other events
      updateUI: function(counter){
        var self = this
        if (counter < 60) {
          $('#timeout-countdown').html(counter + " seconds")
        } else {
          var newCounter = Math.ceil(counter / 60);
          if(newCounter < self.currentMin){
              self.currentMin = newCounter
              $('#timeout-countdown').html(newCounter + " minutes")
          }
        }
      },

      addEvents: function(){
        var self = this;

        // trap focus in modal (or browser chrome)
        $('a, input, textarea, button, [tabindex]').not('[tabindex="-1"]').on("focus", function (event) {
            var modalFocus = document.getElementById("timeout-dialog")
            if(modalFocus && self.dialogOpen){
                if(!modalFocus.contains(event.target)) {
                    event.stopPropagation()
                    modalFocus.focus()
                }
            }
        });

        function handleFocus(){
            if(self.dialogOpen){
                // clear the countdown
                window.clearInterval(self.countdown)
                // calculate remaining time
                var now = Math.round(Date.now()/1000, 0)
                var expiredSeconds = now - self.startTime;
                var currentCounter = settings.countdown - expiredSeconds;
                //console.log('Expired = ' + expiredSeconds + ' (' + now + ' - ' + self.startTime + ')');
                //console.log('CurrentCounter = ' + currentCounter + '(' + settings.countdown + ' - ' + expiredSeconds + ')');

                self.updateUI(currentCounter);
                self.startCountdown(currentCounter);
            }
        }

        // AL: handle browsers pausing timeouts/intervals by recalculating the remaining time on window focus
        // need to widen this to cover the setTimeout which triggers the dialog for browsers which pause timers on blur
        // hiding this from IE8 as it breaks the reset - to investigate further
        if (navigator.userAgent.match(/MSIE 8/) == null) {
            //$(window).on("blur", function(){
                $(window).off("focus", handleFocus);
                $(window).on("focus", handleFocus);
            //});

        }
      },

      startCountdown: function (counter) {
        var self = this
        self.countdown = window.setInterval(function () {
          counter -= 1

          self.updateUI(counter);

          if (counter <= 0) {
            self.signOut()
          }
        }, 1000)
      },

      keepAlive: function () {
        var self = this
        self.destroyDialog()
        window.clearInterval(this.countdown)
        $(document).off('keydown', self.escPress)

        $.get(settings.keep_alive_url, function (data) {
          if (data === 'OK') {
            if (settings.restart_on_yes) {
              self.setupDialogTimer()
            }
          }
          else {
            self.signOut()
          }
        })
      },

      signOut: function () {
        var self = this
        window.clearInterval(self.countdown)
        self.destroyDialog()
        window.location = settings.logout_url

       }

    }

    TimeoutDialog.init()
  }
}(window.jQuery)<|endoftext|>


<commit_before>/* global module, require, console */
(function() {
  'use strict';

  var Backbone = require('backbone'),
      _ = require('underscore'),
      jQuery = require('jquery'),
      Workflow;
  // Custom third party extension to Backbone, see below
  Backbone.DeepModel = require('../lib/backbone-deep-model.js');
  // Load Backbone.Validation extension
  require('backbone-validation');
  _.extend(Backbone.DeepModel.prototype, Backbone.Validation.mixin);

  /* We extend DeepModel instead of Model so we can listen on changes for
   * nested objects like workflow.config. */
  Workflow = Backbone.DeepModel.extend({
    initialize: function() {
      this._setPluginValidators();
      if (this.isNew()) {
        this._setDefaultConfiguration();
      }
    },
    validation: {
      name: {
        required: true,
        // All printable ASCII characters, except '/'
        pattern: /^[\x20-\x2E\x30-\x7E]*$/,
        msg: 'Non-ASCII characters and "/" are not permitted.'
      }
    },
    validate: function() {
      // NOTE: We monkey patch the stupid Backbone.Validation mixin, as it
      // pretends as if validation is always successful...
      return Backbone.Validation.mixin.validate.bind(this)();
    },
    /**
     * Initiates the submissiong of the workflow to a remote postprocessing
     * server for postprocessing and output generation.
     *
     * @param {requestCallback} callback Callback to execute after API request
     *                                   is completed.
     */
    submit: function(callback) {
      console.debug("Submitting workflow " + this.id + " for postprocessing");
      jQuery.post('/workflow/' + this.id + '/submit')
        .fail(function() {
          console.error("Could not submit workflow " + this.id);
        }).complete(callback);
    },
    /**
     * Initiates the transfer to a removable storage device.
     *
     * @param {requestCallback} callback Callback to execute after API request is
     *                                   completed.
     */
    transfer: function(callback) {
      console.debug("Initiating transfer for workflow " + this.id + "");
      jQuery.post('/workflow/' + this.id + '/transfer')
        .fail(function() {
          console.error("Could not transfer workflow " + this.id);
        }).complete(callback);
    },
    /**
     * Prepares devices for capture.
     *
     * @param {requestCallback} callback Callback to execute after API request is
     *                                   completed.
     */
    prepareCapture: function(callback) {
      jQuery.post(
        '/workflow/' + this.id + '/prepare_capture',
        function() {
          console.debug("Preparation successful");
        }.bind(this)).fail(function() {
          console.error("Capture preparation failed");
        }).complete(callback);
    },
    /**
     * Triggers a capture.
     *
     * @param {boolean} retake Discard the previous shot and retake it
     * @param {requestCallback} callback Callback to execute after API request is
     *                                   completed.
     */
    triggerCapture: function(retake, callback) {
      jQuery.post(
        '/workflow/' + this.id + "/capture" + (retake ? '?retake=true' : ''),
        function(data) {
          console.debug("Capture succeeded");
          if (retake) {
            // Since the model will not change (number of images and names
            // don't change) we have to manually trigger a 'change' event
            // to force a re-render of the bound components.
            this.trigger('change');
          } else {
            // Add image objects from response to the model
            this.set('images', this.get('images').concat(data.images));
          }
        }.bind(this)).fail(function() {
          console.error("Capture failed");
        }).complete(callback);
    },
    /**
     * Indicate the end of the capture process to the server.
     *
     * @param {requestCallback} callback Callback to execute after API request is
     *                                   completed.
     */
    finishCapture: function(callback) {
      jQuery.post('/workflow/' + this.id + "/finish_capture", function() {
        console.debug("Capture successfully finished");
      }).fail(function() {
        console.error("Capture could not be finished.");
      }).complete(callback);
    },
    /**
     * Set default configuration from our global `pluginTemplates` object.
     *
     * @private
     */
    _setDefaultConfiguration: function() {
      var templates = window.pluginTemplates;
      _.each(templates, function(template, plugin) {
        _.each(template, function(option, name) {
          var path = 'config.' + plugin + '.' + name;
          if (option.selectable) {
            this.set(path, option.value[0]);
          } else {
            this.set(path, option.value);
          }
        }, this);
      }, this);
    },
    /**
     * Auto-generate Backbone validators for our configuration fields from
     * the global `pluginTemplates` object.
     *
     * @private
     */
    _setPluginValidators: function() {
      var templates = window.pluginTemplates;
      _.each(templates, function(template, plugin) {
        _.each(template, function(option, name) {
          var path = 'config.' + plugin + '.' + name;
          if (option.selectable) {
            this.validation[path] = {
              oneOf: option.value
            };
          } else if (_.isNumber(option.value)) {
            this.validation[path] = {
              pattern: 'number',
              msg: 'Must be a number.'
            };
          }
        }, this);
      }, this);
    }
  });

  /**
   * Callback for API requests. Executed after the request finished, no
   * matter if successfull or unsuccessful.
   *
   * @param {jQuery.xhr} xhr - The XHTTPRequest object
   * @param {string} xhr - The request tatus
   */

  module.exports = Backbone.Collection.extend({
    model: Workflow,
    url: '/workflow',
    connectEvents: function(eventDispatcher) {
      eventDispatcher.on('workflow:created', function(workflow) {
        if (!this.contains(workflow)) {
          this.add(workflow);
        }
      }, this);
      eventDispatcher.on('workflow:removed', function(workflowId) {
        var workflow = this.get(workflowId);
        if (workflow) {
          this.remove(workflow);
        }
      }, this);
    url: '/workflow'
  });
}());
<commit_msg>web: Encapsulate adding of new images into its own function<commit_after>/* global module, require, console */
(function() {
  'use strict';

  var Backbone = require('backbone'),
      _ = require('underscore'),
      jQuery = require('jquery'),
      Workflow;
  // Custom third party extension to Backbone, see below
  Backbone.DeepModel = require('../lib/backbone-deep-model.js');
  // Load Backbone.Validation extension
  require('backbone-validation');
  _.extend(Backbone.DeepModel.prototype, Backbone.Validation.mixin);

  /* We extend DeepModel instead of Model so we can listen on changes for
   * nested objects like workflow.config. */
  Workflow = Backbone.DeepModel.extend({
    initialize: function() {
      this._setPluginValidators();
      if (this.isNew()) {
        this._setDefaultConfiguration();
      }
    },
    validation: {
      name: {
        required: true,
        // All printable ASCII characters, except '/'
        pattern: /^[\x20-\x2E\x30-\x7E]*$/,
        msg: 'Non-ASCII characters and "/" are not permitted.'
      }
    },
    validate: function() {
      // NOTE: We monkey patch the stupid Backbone.Validation mixin, as it
      // pretends as if validation is always successful...
      return Backbone.Validation.mixin.validate.bind(this)();
    },
    /**
     * Initiates the submissiong of the workflow to a remote postprocessing
     * server for postprocessing and output generation.
     *
     * @param {requestCallback} callback Callback to execute after API request
     *                                   is completed.
     */
    submit: function(callback) {
      console.debug("Submitting workflow " + this.id + " for postprocessing");
      jQuery.post('/workflow/' + this.id + '/submit')
        .fail(function() {
          console.error("Could not submit workflow " + this.id);
        }).complete(callback);
    },
    /**
     * Initiates the transfer to a removable storage device.
     *
     * @param {requestCallback} callback Callback to execute after API request is
     *                                   completed.
     */
    transfer: function(callback) {
      console.debug("Initiating transfer for workflow " + this.id + "");
      jQuery.post('/workflow/' + this.id + '/transfer')
        .fail(function() {
          console.error("Could not transfer workflow " + this.id);
        }).complete(callback);
    },
    /**
     * Prepares devices for capture.
     *
     * @param {requestCallback} callback Callback to execute after API request is
     *                                   completed.
     */
    prepareCapture: function(callback) {
      jQuery.post(
        '/workflow/' + this.id + '/prepare_capture',
        function() {
          console.debug("Preparation successful");
        }.bind(this)).fail(function() {
          console.error("Capture preparation failed");
        }).complete(callback);
    },
    /**
     * Triggers a capture.
     *
     * @param {boolean} retake Discard the previous shot and retake it
     * @param {requestCallback} callback Callback to execute after API request is
     *                                   completed.
     */
    triggerCapture: function(retake, callback) {
      jQuery.post(
        '/workflow/' + this.id + "/capture" + (retake ? '?retake=true' : ''),
        function(data) {
          console.debug("Capture succeeded");
          this.addImages(data.images);
          // Since no 'real' update of the images takes place during a
          // retake, but we would like to update the dependant views anyway
          // to get the latest versions of the images, we force a 'change'
          // event.
          if (retake) {
            this.trigger('change');
          }
        }.bind(this)).fail(function() {
          console.error("Capture failed");
        }).complete(callback);
    },
    /**
     * Indicate the end of the capture process to the server.
     *
     * @param {requestCallback} callback Callback to execute after API request is
     *                                   completed.
     */
    finishCapture: function(callback) {
      jQuery.post('/workflow/' + this.id + "/finish_capture", function() {
        console.debug("Capture successfully finished");
      }).fail(function() {
        console.error("Capture could not be finished.");
      }).complete(callback);
    },
    addImages: function(images) {
      var modified = false;
      _.each(images, function(img) {
        if (!_.contains(this.get('images'), img)) {
          this.get('images').push(img);
          modified = true;
        }
      }, this);
      if (modified) {
        this.trigger('change');
      }
    },
    /**
     * Set default configuration from our global `pluginTemplates` object.
     *
     * @private
     */
    _setDefaultConfiguration: function() {
      var templates = window.pluginTemplates;
      _.each(templates, function(template, plugin) {
        _.each(template, function(option, name) {
          var path = 'config.' + plugin + '.' + name;
          if (option.selectable) {
            this.set(path, option.value[0]);
          } else {
            this.set(path, option.value);
          }
        }, this);
      }, this);
    },
    /**
     * Auto-generate Backbone validators for our configuration fields from
     * the global `pluginTemplates` object.
     *
     * @private
     */
    _setPluginValidators: function() {
      var templates = window.pluginTemplates;
      _.each(templates, function(template, plugin) {
        _.each(template, function(option, name) {
          var path = 'config.' + plugin + '.' + name;
          if (option.selectable) {
            this.validation[path] = {
              oneOf: option.value
            };
          } else if (_.isNumber(option.value)) {
            this.validation[path] = {
              pattern: 'number',
              msg: 'Must be a number.'
            };
          }
        }, this);
      }, this);
    }
  });

  /**
   * Callback for API requests. Executed after the request finished, no
   * matter if successfull or unsuccessful.
   *
   * @param {jQuery.xhr} xhr - The XHTTPRequest object
   * @param {string} xhr - The request tatus
   */

  module.exports = Backbone.Collection.extend({
    model: Workflow,
    url: '/workflow',
    connectEvents: function(eventDispatcher) {
      eventDispatcher.on('workflow:created', function(workflow) {
        if (!this.contains(workflow)) {
          this.add(workflow);
        }
      }, this);
      eventDispatcher.on('workflow:removed', function(workflowId) {
        var workflow = this.get(workflowId);
        if (workflow) {
          this.remove(workflow);
        }
      }, this);
    }
  });
}());
<|endoftext|>


<commit_before>/*
 * Memcing
 * Copyright (c) 2014 Fatih Cetinkaya (http://github.com/cmfatih/memcing)
 * For the full copyright and license information, please view the LICENSE.txt file.
 */

// pipe module implements stream operations.
//
// TODO: This module needs a lot of things such as mime type detection, JSON support, etc.
//       For now just keep it simple.

// Init reqs
/* jslint node: true */
'use strict';

var utilex = require('utilex'),
    q      = require('q'),
    csv    = require('csv')
;

// Init the module
exports = module.exports = function(options, cacheInstance) {

  // Init vars
  var config          = {
        isDebug:      false,
        verbose:      1,
        stdin: {
          // stream, cmd or csv
          kind: 'stream',
          csv: {delimiter: ',', fieldKey: 1, fieldFilter: null}
        }
      },
      stdinHasPipe,   // checks stdin - function
      stdoutHasPipe,  // checks stdout - function
      start           // start - function

  ;

  // Check options
  if(typeof cacheInstance !== 'object') throw new Error('Invalid cache instance!');

  if(options) {
    if(options.isDebug === true)      config.isDebug = true;
    if(options.verbose !== undefined) config.verbose = options.verbose;

    if(options.stdin !== undefined) {
      if(options.stdin.kind === 'stream' || options.stdin.kind === 'cmd' || options.stdin.kind === 'csv') {
        config.stdin.kind = options.stdin.kind;
      }

      if(options.stdin.csv !== undefined) {
        if(options.stdin.csv.delimiter !== undefined) {
          if(options.stdin.csv.delimiter === 'tab') {
            config.stdin.csv.delimiter = '\t';
          } else {
            config.stdin.csv.delimiter = options.stdin.csv.delimiter;
          }
        }

        if(options.stdin.csv.fieldKey !== undefined && !isNaN(options.stdin.csv.fieldKey)) {
          config.stdin.csv.fieldKey = options.stdin.csv.fieldKey;
        }

        if(options.stdin.csv.fieldFilter) {
          config.stdin.csv.fieldFilter = options.stdin.csv.fieldFilter;
        }
      }
    }
  }

  // Returns whether is there a stream on stdin or not.
  stdinHasPipe = function stdinHasPipe() {
    return (process.stdin.isTTY === true) ? false : true;
  };

  // Returns whether is there a stream on stdout or not.
  stdoutHasPipe = function stdoutHasPipe() {
    return (process.stdout.isTTY === true) ? false : true;
  };

  // Starts reading
  start = function start() {

    if(config.isDebug) utilex.tidyLog('[pipe.start]');

    // Init vars
    var deferred = q.defer(),
        cacheCmd,
        i
    ;

    // Check config
    if(stdinHasPipe() !== true) {
      deferred.resolve();
      return deferred.promise;
    }

    if(config.stdin.kind === 'stream' || config.stdin.kind === 'cmd') {

      // Init vars
      var StrDecoder  = require('string_decoder').StringDecoder,
          decoder     = new StrDecoder('utf8'),
          cntRead     = 0,
          cntReadable = 0,
          lines       = [],
          lineF       = '',
          buffer      = '',
          chunk,
          spaceIndex
      ;

      // readable event
      process.stdin.on('readable', function() {

        // Read stdin
        while (null !== (chunk = process.stdin.read(4))) {

          buffer += decoder.write(chunk);   // decode chunk data
          lines   = buffer.split(/\r?\n/g); // split from line endings
          buffer  = lines.pop();            // keep the last part

          // Execute commands line by line
          for (i = 0; i < lines.length; i++) {
            if(lines[i]) {
              lineF = ('' + lines[i]).trim();

              if(config.stdin.kind === 'stream') {
                spaceIndex = lineF.indexOf(' ');
                cacheCmd   = cacheInstance.set(lineF.substring(0, spaceIndex), lineF.substring(spaceIndex + 1)); // TODO: What to do with errors?
              }
              else if(config.stdin.kind === 'cmd') {
                cacheCmd = cacheInstance.execCmd(lineF); // TODO: What to do with errors?
              }

              if(config.isDebug) utilex.tidyLog('[pipe.start.stdin.readable.lines]: ' + lines[i] + ' - ' + JSON.stringify(cacheCmd));
            }
          }

          cntRead++;
        }

        // Check buffer and execute the command if any
        if(buffer) {
          buffer = ('' + buffer).trim();

          if(config.stdin.kind === 'stream') {
            spaceIndex = buffer.indexOf(' ');
            cacheCmd   = cacheInstance.set(buffer.substring(0, spaceIndex), buffer.substring(spaceIndex + 1)); // TODO: What to do with errors?
          }
          else if(config.stdin.kind === 'cmd') {
            cacheCmd = cacheInstance.execCmd(buffer); // TODO: What to do with errors?
          }

          if(config.isDebug) utilex.tidyLog('[pipe.start.stdin.readable.buffer]: ' + buffer + ' - ' + JSON.stringify(cacheCmd));

          buffer = '';
        }

        cntReadable++;

        if(config.isDebug) utilex.tidyLog('[pipe.start.stdin.readable]:' + cntReadable);
      });

      // end event
      process.stdin.on('end', function() {
        if(config.isDebug) utilex.tidyLog('[pipe.start.stdin.end]: ' + cntReadable + ':' + cntRead);

        deferred.resolve();
      });

    } else if(config.stdin.kind === 'csv') {

      // Init vars
      var fieldKey    = config.stdin.csv.fieldKey-1,
          fieldFilter = (config.stdin.csv.fieldFilter) ? config.stdin.csv.fieldFilter.split(',') : null,
          entryKey,
          entryVal,
          csvFields
      ;

      // Read csv
      csv()
      .from.stream(process.stdin, {delimiter: config.stdin.csv.delimiter, comment: '#'})
      .on('record', function(record) {

        if(record[fieldKey]) {

          entryKey  = (''+record[fieldKey]).trim();
          csvFields = record;

          // Get only filtered fields
          if(fieldFilter) {
            csvFields = [];
            for(i = 0; i < fieldFilter.length; i++) {
              if(record[fieldFilter[i]-1]) csvFields.push(record[fieldFilter[i]-1]);
            }
          }

          // Set as string or `parse-able` array
          entryVal = (csvFields.length === 1) ? csvFields[0] : "['" + csvFields.join("','") + "']";

          cacheCmd = cacheInstance.set(entryKey, entryVal); // TODO: What to do with errors?

          if(config.isDebug) utilex.tidyLog('[pipe.start.csv.record.cacheCmd]: ' + JSON.stringify(record) + ' - ' + JSON.stringify(cacheCmd));
        }
      })
      .on('error', function(err) {
        deferred.reject(err.message);
      })
      .on('end', function(count) {
        if(config.isDebug) utilex.tidyLog('[pipe.start.csv.end]: ' + count);

        deferred.resolve();
      });
    }

    return deferred.promise;
  };

  // Return
  return {
    stdinHasPipe: stdinHasPipe,
    stdoutHasPipe: stdoutHasPipe,
    start: start
  };
};<commit_msg>Change buffer size for stdin.read<commit_after>/*
 * Memcing
 * Copyright (c) 2014 Fatih Cetinkaya (http://github.com/cmfatih/memcing)
 * For the full copyright and license information, please view the LICENSE.txt file.
 */

// pipe module implements stream operations.
//
// TODO: This module needs a lot of things such as mime type detection, JSON support, etc.
//       For now just keep it simple.

// Init reqs
/* jslint node: true */
'use strict';

var utilex = require('utilex'),
    q      = require('q'),
    csv    = require('csv')
;

// Init the module
exports = module.exports = function(options, cacheInstance) {

  // Init vars
  var config          = {
        isDebug:      false,
        verbose:      1,
        stdin: {
          // stream, cmd or csv
          kind: 'stream',
          csv: {delimiter: ',', fieldKey: 1, fieldFilter: null}
        }
      },
      stdinHasPipe,   // checks stdin - function
      stdoutHasPipe,  // checks stdout - function
      start           // start - function

  ;

  // Check options
  if(typeof cacheInstance !== 'object') throw new Error('Invalid cache instance!');

  if(options) {
    if(options.isDebug === true)      config.isDebug = true;
    if(options.verbose !== undefined) config.verbose = options.verbose;

    if(options.stdin !== undefined) {
      if(options.stdin.kind === 'stream' || options.stdin.kind === 'cmd' || options.stdin.kind === 'csv') {
        config.stdin.kind = options.stdin.kind;
      }

      if(options.stdin.csv !== undefined) {
        if(options.stdin.csv.delimiter !== undefined) {
          if(options.stdin.csv.delimiter === 'tab') {
            config.stdin.csv.delimiter = '\t';
          } else {
            config.stdin.csv.delimiter = options.stdin.csv.delimiter;
          }
        }

        if(options.stdin.csv.fieldKey !== undefined && !isNaN(options.stdin.csv.fieldKey)) {
          config.stdin.csv.fieldKey = options.stdin.csv.fieldKey;
        }

        if(options.stdin.csv.fieldFilter) {
          config.stdin.csv.fieldFilter = options.stdin.csv.fieldFilter;
        }
      }
    }
  }

  // Returns whether is there a stream on stdin or not.
  stdinHasPipe = function stdinHasPipe() {
    return (process.stdin.isTTY === true) ? false : true;
  };

  // Returns whether is there a stream on stdout or not.
  stdoutHasPipe = function stdoutHasPipe() {
    return (process.stdout.isTTY === true) ? false : true;
  };

  // Starts reading
  start = function start() {

    if(config.isDebug) utilex.tidyLog('[pipe.start]');

    // Init vars
    var deferred = q.defer(),
        cacheCmd,
        i
    ;

    // Check config
    if(stdinHasPipe() !== true) {
      deferred.resolve();
      return deferred.promise;
    }

    if(config.stdin.kind === 'stream' || config.stdin.kind === 'cmd') {

      // Init vars
      var StrDecoder  = require('string_decoder').StringDecoder,
          decoder     = new StrDecoder('utf8'),
          cntRead     = 0,
          cntReadable = 0,
          lines       = [],
          lineF       = '',
          buffer      = '',
          chunk,
          spaceIndex
      ;

      // readable event
      process.stdin.on('readable', function() {

        // Read stdin
        while (null !== (chunk = process.stdin.read())) {

          buffer += decoder.write(chunk);   // decode chunk data
          lines   = buffer.split(/\r?\n/g); // split from line endings
          buffer  = lines.pop();            // keep the last part

          // Execute commands line by line
          for (i = 0; i < lines.length; i++) {
            if(lines[i]) {
              lineF = ('' + lines[i]).trim();

              if(config.stdin.kind === 'stream') {
                spaceIndex = lineF.indexOf(' ');
                cacheCmd   = cacheInstance.set(lineF.substring(0, spaceIndex), lineF.substring(spaceIndex + 1)); // TODO: What to do with errors?
              }
              else if(config.stdin.kind === 'cmd') {
                cacheCmd = cacheInstance.execCmd(lineF); // TODO: What to do with errors?
              }

              if(config.isDebug) utilex.tidyLog('[pipe.start.stdin.readable.lines]: ' + lines[i] + ' - ' + JSON.stringify(cacheCmd));
            }
          }

          cntRead++;
        }

        // Check buffer and execute the command if any
        if(buffer) {
          buffer = ('' + buffer).trim();

          if(config.stdin.kind === 'stream') {
            spaceIndex = buffer.indexOf(' ');
            cacheCmd   = cacheInstance.set(buffer.substring(0, spaceIndex), buffer.substring(spaceIndex + 1)); // TODO: What to do with errors?
          }
          else if(config.stdin.kind === 'cmd') {
            cacheCmd = cacheInstance.execCmd(buffer); // TODO: What to do with errors?
          }

          if(config.isDebug) utilex.tidyLog('[pipe.start.stdin.readable.buffer]: ' + buffer + ' - ' + JSON.stringify(cacheCmd));

          buffer = '';
        }

        cntReadable++;

        if(config.isDebug) utilex.tidyLog('[pipe.start.stdin.readable]:' + cntReadable);
      });

      // end event
      process.stdin.on('end', function() {
        if(config.isDebug) utilex.tidyLog('[pipe.start.stdin.end]: ' + cntReadable + ':' + cntRead);

        deferred.resolve();
      });

    } else if(config.stdin.kind === 'csv') {

      // Init vars
      var fieldKey    = config.stdin.csv.fieldKey-1,
          fieldFilter = (config.stdin.csv.fieldFilter) ? config.stdin.csv.fieldFilter.split(',') : null,
          entryKey,
          entryVal,
          csvFields
      ;

      // Read csv
      csv()
      .from.stream(process.stdin, {delimiter: config.stdin.csv.delimiter, comment: '#'})
      .on('record', function(record) {

        if(record[fieldKey]) {

          entryKey  = (''+record[fieldKey]).trim();
          csvFields = record;

          // Get only filtered fields
          if(fieldFilter) {
            csvFields = [];
            for(i = 0; i < fieldFilter.length; i++) {
              if(record[fieldFilter[i]-1]) csvFields.push(record[fieldFilter[i]-1]);
            }
          }

          // Set as string or `parse-able` array
          entryVal = (csvFields.length === 1) ? csvFields[0] : "['" + csvFields.join("','") + "']";

          cacheCmd = cacheInstance.set(entryKey, entryVal); // TODO: What to do with errors?

          if(config.isDebug) utilex.tidyLog('[pipe.start.csv.record.cacheCmd]: ' + JSON.stringify(record) + ' - ' + JSON.stringify(cacheCmd));
        }
      })
      .on('error', function(err) {
        deferred.reject(err.message);
      })
      .on('end', function(count) {
        if(config.isDebug) utilex.tidyLog('[pipe.start.csv.end]: ' + count);

        deferred.resolve();
      });
    }

    return deferred.promise;
  };

  // Return
  return {
    stdinHasPipe: stdinHasPipe,
    stdoutHasPipe: stdoutHasPipe,
    start: start
  };
};<|endoftext|>


<commit_before>"use strict";

var m   = require("mithril"),
    get = require("lodash.get"),

    field = [ "show", "field" ],

    dom = m("div", "");

module.exports = function(options) {
    /* eslint: eqeqeq:0 */
    var dep = get(options.field, field),
        src, tgt;

    // No conditional visibility config or missing target field
    if(!dep) {
        return false;
    }

    src = options.field.show.value;
    tgt = get(options.state, dep);

    // No target value, so have to hide it
    if(typeof tgt === "undefined") {
        return dom;
    }

    // RegExp matched
    if(options.field.show.type === "regexp") {
        src = new RegExp(src, "i");

        if(src.test(tgt)) {
            return false;
        }
    }

    // Values match-ish
    if(src == tgt) {
        return false;
    }

    // Otherwise this field should hide
    return dom;
};
<commit_msg>Correctly hide fields when target is empty<commit_after>"use strict";

var m   = require("mithril"),
    get = require("lodash.get"),

    field = [ "show", "field" ],

    dom = m("div", "");

module.exports = function(options) {
    /* eslint: eqeqeq:0 */
    var dep = get(options.field, field),
        src, tgt;

    // No conditional visibility config or missing target field
    if(!dep) {
        return false;
    }

    src = options.field.show.value;
    tgt = get(options.state, dep);

    // No target value, so have to hide it
    if(typeof tgt === "undefined" || tgt === null) {
        return dom;
    }

    // RegExp matched
    if(options.field.show.type === "regexp") {
        src = new RegExp(src, "i");

        if(src.test(tgt)) {
            return false;
        }
    }

    // Values match-ish
    if(src == tgt) {
        return false;
    }

    // Otherwise this field should hide
    return dom;
};
<|endoftext|>


<commit_before>const React = require('react')

const Theme = require('./theme')
const configuration = require('./configuration')
const Style = require('./components/style')
const Search = require('./components/search')
const Results = require('./components/results')
const PluginStore = require('./store/pluginStore')
const globalEmitter = require('./lib/globalEmitter')

const Zazu = React.createClass({

  getInitialState () {
    return {
      query: '',
      theme: { css: '' },
      results: [],
    }
  },

  componentDidMount () {
    configuration.load()

    const theme = new Theme(configuration.theme, configuration.pluginDir)
    theme.load().then((theme) => {
      this.setState({
        theme,
      })
    })

    PluginStore.addChangeListener(this.updateResults)

    globalEmitter.on('showWindow', () => {
      PluginStore.setQuery('')
      this.setState({
        query: '',
        results: [],
      })
    })
  },

  componentWillUnmount () {
    PluginStore.removeChangeListener(this.updateResults)
  },

  updateResults () {
    this.setState({
      results: PluginStore.results,
    })
  },

  handleQueryChange (query) {
    PluginStore.setQuery(query)
    this.setState({
      query,
    })
  },

  handleResultAction (result) {
    result.next()
    globalEmitter.emit('hideWindow')
  },

  render () {
    return React.createElement(
      'div',
      null,
      React.createElement(Style, { css: this.state.theme.css }),
      React.createElement(Search, {
        handleQueryChange: this.handleQueryChange,
        value: this.state.query,
      }),
      React.createElement(Results, {
        values: this.state.results,
        handleResultAction: this.handleResultAction,
      })
    )
  },

})

module.exports = Zazu
<commit_msg>Set the query on showWindow after setImmediate.<commit_after>const React = require('react')

const Theme = require('./theme')
const configuration = require('./configuration')
const Style = require('./components/style')
const Search = require('./components/search')
const Results = require('./components/results')
const PluginStore = require('./store/pluginStore')
const globalEmitter = require('./lib/globalEmitter')

const Zazu = React.createClass({

  getInitialState () {
    return {
      query: '',
      theme: { css: '' },
      results: [],
    }
  },

  componentDidMount () {
    configuration.load()

    const theme = new Theme(configuration.theme, configuration.pluginDir)
    theme.load().then((theme) => {
      this.setState({
        theme,
      })
    })

    PluginStore.addChangeListener(this.updateResults)

    globalEmitter.on('showWindow', () => {
      setImmediate(() => PluginStore.setQuery(''))
      this.setState({
        query: '',
        results: [],
      })
    })
  },

  componentWillUnmount () {
    PluginStore.removeChangeListener(this.updateResults)
  },

  updateResults () {
    this.setState({
      results: PluginStore.results,
    })
  },

  handleQueryChange (query) {
    PluginStore.setQuery(query)
    this.setState({
      query,
    })
  },

  handleResultAction (result) {
    result.next()
    globalEmitter.emit('hideWindow')
  },

  render () {
    return React.createElement(
      'div',
      null,
      React.createElement(Style, { css: this.state.theme.css }),
      React.createElement(Search, {
        handleQueryChange: this.handleQueryChange,
        value: this.state.query,
      }),
      React.createElement(Results, {
        values: this.state.results,
        handleResultAction: this.handleResultAction,
      })
    )
  },

})

module.exports = Zazu
<|endoftext|>


<commit_before>var React = require('react');
var PropTypes = React.PropTypes;

import { BarChart, Bar, Cell, CartesianGrid, XAxis, YAxis, Tooltip, Legend, ResponsiveContainer } from 'recharts';
import { HUC12_MAP_FEATUREID, TRA_MAP_FEATUREID, CATALOGING_MAP_FEATUREID, NLCD_MAP_FEATUREID } from '../constants/actionConstants';

const tooltipstyle = {
  width: '100%',
  margin: 0,
  lineHeight: 24,
  border: '1px solid #f5f5f5',
  backgroundColor: 'rgba(255, 255, 255, 0.95)',
  padding: 10,
};

const toolTipLabel = {
  margin: '0',
  color: '#666',
  fontWeight: '700',
};

const CustomToolTipBarCharts  = React.createClass({
  propTypes: {
    type: PropTypes.string,
    payload: PropTypes.array,
    label: PropTypes.string,
  },
  get_layer_id: function(layer){
    switch (layer) {
      case 'baseline':
        return HUC12_MAP_FEATUREID
        break;
      case 'uplift':
        return HUC12_MAP_FEATUREID
        break;
      case 'tra':
        return TRA_MAP_FEATUREID
        break;
      default:
        return HUC12_MAP_FEATUREID
    }
  },
  componentDidMount(){
    $('.recharts-bar-cursor').on("click",function(){console.log('clicked')})
  },
  render() {

    const { active } = this.props;
    let html_hov = '';
    if (active) {
      const { payload, label } = this.props;

      const layer_id = this.get_layer_id(this.props.chart_type)

      // this.props.get_LayerGeom_ByValue(label,this.props.chart_type)
      console.log({value:label,chart_type: this.props.chart_type, layer_id: layer_id})

      const reversed_payload = [ ...payload ].reverse()

      const thedata = reversed_payload.map( bar_segment => {
       const colors = this.props.get_keyColors(bar_segment.name)

        const toolTipName = {
          margin: '0',
          color: colors[1],
        }

        const toolTipValue = {
          fontWeight: '800',
        }

        const value = bar_segment.value ?  bar_segment.value.toString().substring(0,5) : 'N/A';
        const name = bar_segment.name + ": "

        //when tra's have a value of 0 do not display the tool tip...
        if((bar_segment.value === 0 || !bar_segment.value ) && this.props.chart_type.toUpperCase() === 'TRA'){
          return null
        } else {
          return (
{name}{value}
)
        }
      })

      //check to see if there is data in the case of tra's there could be no data and
      //  we want to tell users that there is no data.
      let hasdata = false;
      thedata.map( d  => {
        if(d){hasdata = true}
      })

      const labelstr = label.toString().trim();

      //null tip when there is no id
      if (!labelstr || !hasdata){
        return (
)
      }

      //return tooltip
      return (

{this.props.level_label}: {`${labelstr}`}

          {thedata}

      );
    }

    return null;
  }
});

module.exports = CustomToolTipBarCharts;
<commit_msg>hovers and clicks...<commit_after>var React = require('react');
var PropTypes = React.PropTypes;

import { BarChart, Bar, Cell, CartesianGrid, XAxis, YAxis, Tooltip, Legend, ResponsiveContainer } from 'recharts';
import { HUC12_MAP_FEATUREID, TRA_MAP_FEATUREID, CATALOGING_MAP_FEATUREID, NLCD_MAP_FEATUREID } from '../constants/actionConstants';

const tooltipstyle = {
  width: '100%',
  margin: 0,
  lineHeight: 24,
  border: '1px solid #f5f5f5',
  backgroundColor: 'rgba(255, 255, 255, 0.95)',
  padding: 10,
};

const toolTipLabel = {
  margin: '0',
  color: '#666',
  fontWeight: '700',
};

const CustomToolTipBarCharts  = React.createClass({
  propTypes: {
    type: PropTypes.string,
    payload: PropTypes.array,
    label: PropTypes.string,
  },
  get_layer_id: function(layer){
    switch (layer) {
      case 'baseline':
        return HUC12_MAP_FEATUREID
        break;
      case 'uplift':
        return HUC12_MAP_FEATUREID
        break;
      case 'tra':
        return TRA_MAP_FEATUREID
        break;
      default:
        return HUC12_MAP_FEATUREID
    }
  },
  // componentDidMount(){
  //   const { active } = this.props;
  //   console.log(this.props)
  //   if (active) {
  //     const { payload, label } = this.props;
  //
  //     const layer_id = this.get_layer_id(this.props.chart_type)
  //
  //     $('.recharts-bar-cursor').on("click",function(){console.log('clicked' + JSON.stringify({value:label,chart_type: this.props.chart_type, layer_id: layer_id}))})
  //   }
  // },
  componentWillUpdate: function(nextProps, nextState) {
    // const { payload, labe l } = nextProps.props;

    // console.log(nextProps.payload)
    const layer_id = this.get_layer_id(nextProps.chart_type)

    $('.recharts-bar-cursor').unbind('click');
    $('.recharts-bar-rectangles').unbind('click');
    $('.recharts-bar-cursor').unbind('mouseenter');
    $('.recharts-bar-cursor').unbind('mouseleave');

    $('.recharts-bar-cursor').on("click",function(){console.log('clicked' + JSON.stringify({value:nextProps.label,chart_type: nextProps.chart_type, layer_id}))})
    $('.recharts-bar-rectangles').on("click",function(){console.log('clicked' + JSON.stringify({value:nextProps.label,chart_type: nextProps.chart_type, layer_id}))})

    $('.recharts-bar-cursor').on("mouseenter",function(){console.log('mouseenter' + JSON.stringify({value:nextProps.label,chart_type: nextProps.chart_type, layer_id}))})
    $('.recharts-bar-rectangles').on("mouseenter",function(){console.log('clicked' + JSON.stringify({value:nextProps.label,chart_type: nextProps.chart_type, layer_id}))})

    $('.recharts-bar-cursor').on("mouseleave",function(){console.log('mouseleave' + JSON.stringify({value:null,chart_type: null, layer_id: null}))})
    $('.recharts-bar-rectangles').on("mouseleave",function(){console.log('mouseleave' + JSON.stringify({value:null,chart_type: null, layer_id: null}))})

  },
  render() {

    const { active } = this.props;
    let html_hov = '';
    if (active) {
      const { payload, label } = this.props;

      const layer_id = this.get_layer_id(this.props.chart_type)

      // this.props.get_LayerGeom_ByValue(label,this.props.chart_type)
      // console.log({value:label,chart_type: this.props.chart_type, layer_id: layer_id})

      const reversed_payload = [ ...payload ].reverse()

      const thedata = reversed_payload.map( bar_segment => {
       const colors = this.props.get_keyColors(bar_segment.name)

        const toolTipName = {
          margin: '0',
          color: colors[1],
        }

        const toolTipValue = {
          fontWeight: '800',
        }

        const value = bar_segment.value ?  bar_segment.value.toString().substring(0,5) : 'N/A';
        const name = bar_segment.name + ": "

        //when tra's have a value of 0 do not display the tool tip...
        if((bar_segment.value === 0 || !bar_segment.value ) && this.props.chart_type.toUpperCase() === 'TRA'){
          return null
        } else {
          return (
{name}{value}
)
        }
      })

      //check to see if there is data in the case of tra's there could be no data and
      //  we want to tell users that there is no data.
      let hasdata = false;
      thedata.map( d  => {
        if(d){hasdata = true}
      })

      const labelstr = label.toString().trim();

      //null tip when there is no id
      if (!labelstr || !hasdata){
        return (
)
      }

      //return tooltip
      return (

{this.props.level_label}: {`${labelstr}`}

          {thedata}

      );
    }

    return null;
  }
});

module.exports = CustomToolTipBarCharts;
<|endoftext|>


<commit_before>/* vim: set softtabstop=4 ts=4 sw=4 expandtab tw=120 syntax=javascript: */
/* jshint node:true, unused:true */
'use strict';

module.exports = AppError;

var util = require('util');

var DEFAULT_ERROR_LEVEL = 'error';
var DEFAULT_LOGGER = console.log;

function AppError(opts, context) {
    if (!isError(this)) { return new AppError(opts, context); }
    opts = opts || {};
    if (isString(opts)) { opts = {message: opts} };
    this.type = opts.type || this.constructor.name;
    this.message = opts.message || 'An error occurred.';
    this.data = opts.data || '';
    this.code = opts.code || opts.statusCode || 500;
    this.statusCode = this.code;
    this.isAppError = true;
    this.logError = isUndefined(opts.logError) && true || opts.logError;
    this.captureStack = opts.captureStack;
    if (opts.captureStack) {
        Error.captureStackTrace(this, (context || arguments.callee));
    }
    this._logged = false;
    return this;
}
util.inherits(AppError, Error);
AppError.prototype.name = 'AppError';
AppError.prototype.toJSON = toJSON;
AppError.prototype.toResponseObject = toJSON;
AppError.prototype.log = function log(level, logger) {
    logger = logger || this.DEFAULT_LOGGER || DEFAULT_LOGGER;
    level = level || this.DEFAULT_ERROR_LEVEL || DEFAULT_ERROR_LEVEL;
    if (this.logError && this._logged || !isFunction(logger)) {
        return this;
    }
    logger(level.toUpperCase(), this.toJSON());
    this._logged = true;
    return this;
}

function toJSON() {
    return {
        type: this.type,
        message: this.message,
        data: this.data,
        code: this.code,
    };
};

AppError.createCustom = function createCustom(name, defaults) {
    function CustomError(msg, code, data) {
        if (!isError(this)) { return new CustomError(msg, code, data); }
        var opts = clone(defaults);
        if (isObject(msg)) {
            opts.message = msg.message || msg.msg || opts.message || opts.msg;
            opts.code = msg.code || opts.code || opts.statusCode;
            opts.data = msg.data || opts.data;
        } else {
            opts.message = msg || opts.message || opts.msg;
            opts.code = code || opts.code || opts.statusCode;
            opts.data = data || opts.data;
        }
        AppError.call(this, opts, CustomError);
        return this;
    }
    util.inherits(CustomError, AppError);
    CustomError.prototype.name = name;

    return CustomError;
}

var _has = Object.prototype.hasOwnProperty;

function clone(obj) {
    var o = {}, key;
    var keys = Object.getOwnPropertyNames(obj);
    for (var i=0, len=keys.length; i<len; i++) {
        key = keys[i];
        o[key] = obj[key];
    }
    return o;
}

function has(obj, prop) {
    return _has.call(obj, prop);
}

function isString(value) {
    return 'string' === typeof value;
}

function isError(value) {
    return value instanceof Error;
}

function isFunction(value) {
    return 'function' === typeof value;
}

function isObject(value) {
    return value && 'object' === typeof value;
}

function isUndefined(value) {
    return 'undefined' === typeof value;
}
<commit_msg>Capture stack traces by default.<commit_after>/* vim: set softtabstop=4 ts=4 sw=4 expandtab tw=120 syntax=javascript: */
/* jshint node:true, unused:true */
'use strict';

module.exports = AppError;

var util = require('util');

var DEFAULT_ERROR_LEVEL = 'error';
var DEFAULT_LOGGER = console.log;

function AppError(opts, context) {
    if (!isError(this)) { return new AppError(opts, context); }
    opts = opts || {};
    if (isString(opts)) { opts = {message: opts} };
    this.type = opts.type || this.constructor.name;
    this.message = opts.message || 'An error occurred.';
    this.data = opts.data || '';
    this.code = opts.code || opts.statusCode || 500;
    this.statusCode = this.code;
    this.isAppError = true;
    this.logError = isUndefined(opts.logError) && true || opts.logError;
    this.captureStack = isUndefined(opts.captureStack) && true || opts.captureStack;
    if (opts.captureStack) {
        Error.captureStackTrace(this, (context || arguments.callee));
    }
    this._logged = false;
    return this;
}
util.inherits(AppError, Error);
AppError.prototype.name = 'AppError';
AppError.prototype.toJSON = toJSON;
AppError.prototype.toResponseObject = toJSON;
AppError.prototype.log = function log(level, logger) {
    logger = logger || this.DEFAULT_LOGGER || DEFAULT_LOGGER;
    level = level || this.DEFAULT_ERROR_LEVEL || DEFAULT_ERROR_LEVEL;
    if (this.logError && this._logged || !isFunction(logger)) {
        return this;
    }
    logger(level.toUpperCase(), this.toJSON());
    this._logged = true;
    return this;
}

function toJSON() {
    return {
        type: this.type,
        message: this.message,
        data: this.data,
        code: this.code,
    };
};

AppError.createCustom = function createCustom(name, defaults) {
    function CustomError(msg, code, data) {
        if (!isError(this)) { return new CustomError(msg, code, data); }
        var opts = clone(defaults);
        if (isObject(msg)) {
            opts.message = msg.message || msg.msg || opts.message || opts.msg;
            opts.code = msg.code || opts.code || opts.statusCode;
            opts.data = msg.data || opts.data;
        } else {
            opts.message = msg || opts.message || opts.msg;
            opts.code = code || opts.code || opts.statusCode;
            opts.data = data || opts.data;
        }
        AppError.call(this, opts, CustomError);
        return this;
    }
    util.inherits(CustomError, AppError);
    CustomError.prototype.name = name;

    return CustomError;
}

var _has = Object.prototype.hasOwnProperty;

function clone(obj) {
    var o = {}, key;
    var keys = Object.getOwnPropertyNames(obj);
    for (var i=0, len=keys.length; i<len; i++) {
        key = keys[i];
        o[key] = obj[key];
    }
    return o;
}

function has(obj, prop) {
    return _has.call(obj, prop);
}

function isString(value) {
    return 'string' === typeof value;
}

function isError(value) {
    return value instanceof Error;
}

function isFunction(value) {
    return 'function' === typeof value;
}

function isObject(value) {
    return value && 'object' === typeof value;
}

function isUndefined(value) {
    return 'undefined' === typeof value;
}
<|endoftext|>


<commit_before>'use strict';

angular.module('ehelseEditor').controller('LoginController', [ '$scope', '$rootScope', '$location',  function( $scope, $rootScope, $location) {

    $scope.submit = function(){
        $rootScope.setUserName($scope.username);
        $rootScope.setPassword($scope.password);
        $scope.logIn();
    };

    $scope.logIn = function (username, authtoken) {

        $rootScope.get(
            'users/login/',
            function(data){
                console.log(data);
                $location.path('/main-view').replace();
            },
            function(){}
        );

    };
}]);<commit_msg>Fixed login<commit_after>'use strict';

angular.module('ehelseEditor').controller('LoginController', [ '$scope', '$rootScope', '$location',  function( $scope, $rootScope, $location) {

    $scope.submit = function(){
        $rootScope.setUserName($scope.username);
        $rootScope.setPassword($scope.password);
        $scope.logIn();
    };

    $scope.logIn = function (username, authtoken) {

        $rootScope.get(
            'users/login/',
            function(data){
                $rootScope.currentUser = data;
                console.log(data);
                $location.path('/main-view').replace();
            },
            function(){}
        );

    };
}]);<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	errorHandler = require('./errors.server.controller'),
	_ = require('lodash'),
  popura = require('popura');

const client = popura('Bakuzan', 'Myanime52');

exports.search = function(req, res) {
	//get params here
	var type = '',
		search = '';

	// for now log the result, when got it working just return the query.
	if(type === 'anime') {
		client.searchAnimes(search).then(res => console.log(res)).catch(err => console.log(err));
	} else if (type === 'manga') {
		client.searchMangas(search).then(res => console.log(res)).catch(err => console.log(err));
	}
};
<commit_msg>added console.log<commit_after>'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	errorHandler = require('./errors.server.controller'),
	_ = require('lodash'),
  popura = require('popura');

const client = popura('Bakuzan', 'Myanime52');

exports.search = function(req, res) {
	console.log('search mal: ', req);
	//get params here
	var type = '',
		search = '';

	// for now log the result, when got it working just return the query.
	if(type === 'anime') {
		client.searchAnimes(search).then(res => console.log(res)).catch(err => console.log(err));
	} else if (type === 'manga') {
		client.searchMangas(search).then(res => console.log(res)).catch(err => console.log(err));
	}
};
<|endoftext|>


<commit_before>/**
 *
 * @constructor
 * @augments ElementBuilder
 * @mixes editorBaseBuilderMixin
 */
function ImageBoxBuilder() {
    _.superClass(ImageBoxBuilder, this);
    this.initialize_editorBaseBuilder();
}

_.inherit(ImageBoxBuilder, ElementBuilder);

_.extend(ImageBoxBuilder.prototype, {

    createElement: function (params) {
        return new ImageBox(params.parent);
    },

    applyMetadata: function (params) {
        ElementBuilder.prototype.applyMetadata.call(this, params);

        var element = params.element;
        var metadata = params.metadata;

        if (Array.isArray(metadata.AcceptTypes)) {
            element.setAcceptTypes(metadata.AcceptTypes);
        }

        if (metadata.MaxSize !== null && typeof metadata.MaxSize !== 'undefined') {
            element.setMaxSize(metadata.MaxSize);
        }

        // Привязка данных односторонняя т.к.:
        // 1. по значению из источника данных - сформировать URL изображения.
        // 2. при выборе в элементе файла на загрузку - добавить выбранный файл в очередь на загрузку

        var converter = new ImageBoxValueConverter(element);

        var data = this.applyMetadata_editorBaseBuilder(params, {
            mode: InfinniUI.BindingModes.toElement,
            converter: converter
        });

        var binding = data.valueBinding;
        if (binding) {
            var ds = binding.getSource();

            params.element.onPropertyChanged('file', function (context, args) {
                var file = args.newValue;

                if (file instanceof File) {
                    ds.setProperty(binding.getSourceProperty(), args.newValue)
                }
            });

            ds.onItemsUpdated(function (context, args) {
                /**
                 * @TODO Принудительное обновление изображений. Удалить после изменений на backend'е,
                 * когда будет изменяться BlobInfo
                 */
                var element = params.element;
                var url = element.getValue();
                var pattern = /&salt=.*$/;
                if (url) {
                    var salt = '&salt=' + Date.now();
                    if (pattern.test(url)) {
                        url.replace(pattern, salt);
                    } else {
                        url += salt;
                    }
                    element.setValue(url);
                }
            });
        }

    }

}, editorBaseBuilderMixin);<commit_msg>fix ImageBox removing file<commit_after>/**
 *
 * @constructor
 * @augments ElementBuilder
 * @mixes editorBaseBuilderMixin
 */
function ImageBoxBuilder() {
    _.superClass(ImageBoxBuilder, this);
    this.initialize_editorBaseBuilder();
}

_.inherit(ImageBoxBuilder, ElementBuilder);

_.extend(ImageBoxBuilder.prototype, {

    createElement: function (params) {
        return new ImageBox(params.parent);
    },

    applyMetadata: function (params) {
        ElementBuilder.prototype.applyMetadata.call(this, params);

        var element = params.element;
        var metadata = params.metadata;

        if (Array.isArray(metadata.AcceptTypes)) {
            element.setAcceptTypes(metadata.AcceptTypes);
        }

        if (metadata.MaxSize !== null && typeof metadata.MaxSize !== 'undefined') {
            element.setMaxSize(metadata.MaxSize);
        }

        // Привязка данных односторонняя т.к.:
        // 1. по значению из источника данных - сформировать URL изображения.
        // 2. при выборе в элементе файла на загрузку - добавить выбранный файл в очередь на загрузку

        var converter = new ImageBoxValueConverter(element);

        var data = this.applyMetadata_editorBaseBuilder(params, {
            mode: InfinniUI.BindingModes.toElement,
            converter: converter
        });

        var binding = data.valueBinding;
        if (binding) {
            var ds = binding.getSource();

            params.element.onPropertyChanged('file', function (context, args) {
                var file = args.newValue;

                if (file instanceof File || file === null) {
                    ds.setProperty(binding.getSourceProperty(), args.newValue)
                }
            });

            ds.onItemsUpdated(function (context, args) {
                /**
                 * @TODO Принудительное обновление изображений. Удалить после изменений на backend'е,
                 * когда будет изменяться BlobInfo
                 */
                var element = params.element;
                var url = element.getValue();
                var pattern = /&salt=.*$/;
                if (url) {
                    var salt = '&salt=' + Date.now();
                    if (pattern.test(url)) {
                        url.replace(pattern, salt);
                    } else {
                        url += salt;
                    }
                    element.setValue(url);
                }
            });
        }

    }

}, editorBaseBuilderMixin);<|endoftext|>


<commit_before>// KNOCKOUT DYNAMIC GRID

ko.bindingHandlers.foreachprop = {
    transformObject: function (obj) {
        var properties = [];
        for (var key in obj) {
            if (obj.hasOwnProperty(key)) {
                properties.push({ key: key, value: obj[key] });
            }
        }
        return properties;
    },
    init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        var value = ko.utils.unwrapObservable(valueAccessor()),
            properties = ko.bindingHandlers.foreachprop.transformObject(value);
        ko.applyBindingsToNode(element, { foreach: properties }, bindingContext);
        return { controlsDescendantBindings: true };
    }
};

var sampleOptions = {
    headers: [
        {
            columnName: 'column1',
            width: 'col-xs-4',
            sortable: true
        },{
            columnName: 'column2',
            width: 'col-xs-4',
            sortable: true
        },{
            columnName: 'column3',
            width: 'col-xs-4',
            sortable: true
        }
    ],
    width: '400px',
    height: '400px',
    data: ko.observableArray,
    onClick: function(index, object){ }
}

var defaultOptions = {
    width: '400px',
    height: '400px',
    data: ko.observableArray,
    onClick: function(index, object){ }
}

var kogridErrorHandler = (function() {
    function Handler() {
        var _self = this;

        _self.errMsgs = {
            noOptions: 'Error: no options passed to kogrid!',
            noErrMsg: 'Error: no error message of this type does not exist!',
            miscError: 'Error: something went wrong!',
            noData: 'Error: kogrid needs a configured data-source!',
            noTargetElement: 'Error: kogrid needs a target element!',
            elementNotSetup: 'Error: targetElement must be set up before applying knockout bindings!'
        }

        _self.log = function(errorName) {
            var errMsg = _self.errMsgs[errorName];

            if (!errMsg) {
                errMsg = _self.errMsgs.noErrMsg;
            }
            console.error(errMsg);
        }
    }

    return {
        Handler: Handler
    }
})();

var kogridConstants = {
    gridBody:
        '
\

\

\
                    \

\

\

',
    regexPercent: /(.*)\w+%/g,
    regexPixels: /(.*)\w+px/g,
    regexBootstrapColumn: /col(.*)\w+/g
}

var kogrid = (function(errorHandler, kogridConstants, defaultOptions){
    function Grid(options) {
        var _self = this;

        _self.errorHandler = errorHandler;
        _self.constants = kogridConstants;
        _self.defaultOptions = defaultOptions;

        _self.options = options;
        _self.elementReady = false;

        _self.applyDimension = function(dimensionType, dimensionValue, targetElement) {
            if (dimensionValue.match(_self.constants.regexPercent) ||
            dimensionValue.match(_self.constants.regexPixels)) {
                $(targetElement).css(dimensionType, dimensionValue);
                return 'css';
            }
            else if (dimensionValue.match(_self.constants.regexBootstrapColumn)) {
                $(targetElement).addClass(dimensionValue);
                return 'class';
            }
            return null;
        }

        _self.elementSetup = function(targetElement) {
            var element = $(targetElement);

            element.append(_self.constants.gridBody);

            _self.applyDimension('width', _self.options.width, targetElement);
            _self.applyDimension('height', _self.options.height, targetElement);

            _self.elementReady = true;

            return element;
        }

        _self.applyBindings = function(targetElement) {
            // _self.elementSetup(targetElement);
            if (_self.elementReady) {
                ko.applyBindings(options, targetElement);
            }
            else {
                _self.errorHandler.log('elementNotSetup');
            }
        }

        _self.buildOptions = function(options) {
            for (var key in _self.defaultOptions) {
                if (!options.hasOwnProperty(key)) {
                    options[key] = _self.defaultOptions[key];
                }
            };
            return options
        }

        _self.optionsCheck = function(options) {
            if (!options){
                _self.errorHandler.log('noOptions');
                return false;
            } else if (!options.rawData) {
                _self.errorHandler.log('noData');
                return false;
            } else if (!options.targetElement) {
                _self.errorHandler.log('noTargetElement');
                return false;
            }

            return options;
        }

        _self.init = function() {
            _self.options = _self.optionsCheck(_self.options);
            _self.options = _self.buildOptions(_self.options);
            _self.elementSetup(_self.options.targetElement);
            _self.applyBindings(_self.options.targetElement);
        }();

    }

    return {
        Grid: Grid
    }

})(
    new kogridErrorHandler.Handler(),
    kogridConstants
);
<commit_msg>building the logic for the header configuration<commit_after>// KNOCKOUT DYNAMIC GRID

ko.bindingHandlers.foreachprop = {
    transformObject: function (obj) {
        var properties = [];
        for (var key in obj) {
            if (obj.hasOwnProperty(key)) {
                properties.push({ key: key, value: obj[key] });
            }
        }
        return properties;
    },
    init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        var value = ko.utils.unwrapObservable(valueAccessor()),
            properties = ko.bindingHandlers.foreachprop.transformObject(value);
        ko.applyBindingsToNode(element, { foreach: properties }, bindingContext);
        return { controlsDescendantBindings: true };
    }
};

var sampleOptions = {
    headers: [
        {
            columnName: 'column1',
            width: 'col-xs-4',
            sortable: false
        },{
            columnName: 'column2',
            width: 'col-xs-4',
            sortable: true
        },{
            columnName: 'column3',
            width: 'col-xs-4',
            sortable: true,
            cssClass: 'blue-column',
            align: 'center',
            formatting: '{0:c2}'
        }
    ],
    width: '400px',
    height: '400px',
    data: ko.observableArray,
}

var defaultOptions = {
    width: '400px',
    height: '400px',
    data: ko.observableArray,
    onClick: function(index, object){ }
}

var kogridErrorHandler = (function() {
    function Handler() {
        var _self = this;

        _self.errMsgs = {
            noOptions: 'Error: no options passed to kogrid!',
            noErrMsg: 'Error: no error message of this type does not exist!',
            miscError: 'Error: something went wrong!',
            noData: 'Error: kogrid needs a configured data-source!',
            noTargetElement: 'Error: kogrid needs a target element!',
            elementNotSetup: 'Error: targetElement must be set up before applying knockout bindings!'
        }

        _self.log = function(errorName) {
            var errMsg = _self.errMsgs[errorName];

            if (!errMsg) {
                errMsg = _self.errMsgs.noErrMsg;
            }
            console.error(errMsg);
        }
    }

    return {
        Handler: Handler
    }
})();

var kogridConstants = {
    gridBody:
        '
\

\

\
                    \

\

\

',
    gridHeader:
        '
\

\
                \

\

',
    regexPercent: /(.*)\w+%/g,
    regexPixels: /(.*)\w+px/g,
    regexBootstrapColumn: /col(.*)\w+/g
}

var kogrid = (function(errorHandler, kogridConstants, defaultOptions){
    function Grid(options) {
        var _self = this;

        _self.errorHandler = errorHandler;
        _self.constants = kogridConstants;
        _self.defaultOptions = defaultOptions;

        _self.options = options;
        _self.elementReady = false;

        _self.applyDimension = function(dimensionType, dimensionValue, targetElement) {
            if (dimensionValue.match(_self.constants.regexPercent) ||
            dimensionValue.match(_self.constants.regexPixels)) {
                $(targetElement).css(dimensionType, dimensionValue);
                return 'css';
            }
            else if (dimensionValue.match(_self.constants.regexBootstrapColumn)) {
                $(targetElement).addClass(dimensionValue);
                return 'class';
            }
            return null;
        }

        _self.addGridHeader = function(element) {
            element.append(_self.constants.gridHeader);
            return element;
        }

        _self.setupColumnWidths = function(headers) {
            var gridBody = $('.kogrid-body')
            $.each(headers, function(i, header) {

            });
        }

        _self.addGridBody = function(element) {
            element.append(_self.constants.gridBody);
            return element;
        }

        _self.elementSetup = function(targetElement) {
            var element = $(targetElement);

            _self.addGridHeader(element);
            _self.addGridBody(element);

            // element.append(_self.constants.gridBody);

            _self.applyDimension('width', _self.options.width, targetElement);
            _self.applyDimension('height', _self.options.height, targetElement);

            _self.elementReady = true;

            return element;
        }

        _self.applyBindings = function(targetElement) {
            // _self.elementSetup(targetElement);
            if (_self.elementReady) {
                ko.applyBindings(options, targetElement);
            }
            else {
                _self.errorHandler.log('elementNotSetup');
            }
        }

        _self.buildOptions = function(options) {
            for (var key in _self.defaultOptions) {
                if (!options.hasOwnProperty(key)) {
                    options[key] = _self.defaultOptions[key];
                }
            };
            return options
        }

        _self.optionsCheck = function(options) {
            if (!options){
                _self.errorHandler.log('noOptions');
                return false;
            } else if (!options.rawData) {
                _self.errorHandler.log('noData');
                return false;
            } else if (!options.targetElement) {
                _self.errorHandler.log('noTargetElement');
                return false;
            }

            return options;
        }

        _self.init = function() {
            _self.options = _self.optionsCheck(_self.options);
            _self.options = _self.buildOptions(_self.options);
            _self.elementSetup(_self.options.targetElement);
            _self.applyBindings(_self.options.targetElement);
        }();

    }

    return {
        Grid: Grid
    }

})(
    new kogridErrorHandler.Handler(),
    kogridConstants
);
<|endoftext|>


<commit_before>var async = require('async');
var request = require('request');
var ntlm = require('./lib/ntlm');
var KeepAlive = require('agentkeepalive');
var _ = require('lodash');

var makeRequest = function(method, options, params, callback) {

  if (options.url.toLowerCase().indexOf('https://') === 0) {
    KeepAlive = KeepAlive.HttpsAgent;
  }

  var keepaliveAgent = new KeepAlive();

  if (!options.workstation) options.workstation = '';
  if (!options.ntlm_domain) options.ntlm_domain = '';

  function startAuth($) {
    var type1msg = ntlm.createType1Message(options);
    options.method = method;
    _.extend(options.headers, {
      'Connection': 'keep-alive',
      'Authorization': type1msg
    });
    options.agent = keepaliveAgent;
    request(options, $);
  }

  function requestComplete(res, body, $) {
    if (!res.headers['www-authenticate'])
      return $(new Error('www-authenticate not found on response of second request'));

    var type2msg = ntlm.parseType2Message(res.headers['www-authenticate']);
    var type3msg = ntlm.createType3Message(type2msg, options);
    options.method = method;
    _.extend(options.headers, {
      'Connection': 'keep-alive',
      'Authorization': type3msg
    });

    options.agent = keepaliveAgent;

    if (typeof params == "string")
      options.body = params;
    else
      options.json = params;

    request(options, $);
  }

  async.waterfall([startAuth, requestComplete], callback);
};

exports.get = _.partial(makeRequest, 'get');
exports.post = _.partial(makeRequest, 'post');
exports.put = _.partial(makeRequest, 'put');
exports.delete = _.partial(makeRequest, 'delete');
<commit_msg>Fixed bug that prevented type1 message auth<commit_after>var async = require('async');
var request = require('request');
var ntlm = require('./lib/ntlm');
var KeepAlive = require('agentkeepalive');
var _ = require('lodash');

var makeRequest = function(method, options, params, callback) {

  if (options.url.toLowerCase().indexOf('https://') === 0) {
    KeepAlive = KeepAlive.HttpsAgent;
  }

  var keepaliveAgent = new KeepAlive();

  if (!options.workstation) options.workstation = '';
  if (!options.ntlm_domain) options.ntlm_domain = '';
  if (!options.headers) options.headers = {};

  function startAuth($) {
    var type1msg = ntlm.createType1Message(options);
    options.method = method;
    _.extend(options.headers, {
      'Connection': 'keep-alive',
      'Authorization': type1msg
    });
    options.agent = keepaliveAgent;
    request(options, $);
  }

  function requestComplete(res, body, $) {
    if (!res.headers['www-authenticate'])
      return $(new Error('www-authenticate not found on response of second request'));

    var type2msg = ntlm.parseType2Message(res.headers['www-authenticate']);
    var type3msg = ntlm.createType3Message(type2msg, options);
    options.method = method;
    _.extend(options.headers, {
      'Connection': 'keep-alive',
      'Authorization': type3msg
    });

    options.agent = keepaliveAgent;

    if (typeof params == "string")
      options.body = params;
    else
      options.json = params;

    request(options, $);
  }

  async.waterfall([startAuth, requestComplete], callback);
};

exports.get = _.partial(makeRequest, 'get');
exports.post = _.partial(makeRequest, 'post');
exports.put = _.partial(makeRequest, 'put');
exports.delete = _.partial(makeRequest, 'delete');
<|endoftext|>