<commit_before>const fs = require('fs')
const whitelist = __dirname + '/commands/whitelist.json'

get = function(callback) {
	fs.readFile(whitelist, 'utf8', (err, text) => {
		let domains = JSON.parse(text)
		callback(err, domains)
	})
}

add = function(domain, callback) {
	get((err, domains) => {
		let domainsList = JSON.parse(domains)
		domainsList.push(domain)
		fs.writeFile(whitelist, JSON.stringify(domainsList), callback)
	})
}

remove = function(domain, callback) {
	get((err, domains) => {
		let domainsList = JSON.parse(domains)
		let domainIndex = domainsList.indexOf(domain)
		if (domainIndex >= 0) {
			domainsList.splice(domainIndex, 1)
		}
		fs.writeFile(whitelist, JSON.stringify(domainList), callback)
	})
}

module.exports = {

	command: (slapp) => {
		slapp.command('/whitelist', '(\\w*)\\s*(\\w*)', (msg, text, command, argument) => {
			if (command) {
				switch (command) {
					case 'get':
						get((err, domains) => {
							let formattedMessage = {
								attachments: [
									{
										fallback: JSON.stringify(domains),
										title: 'List of all whitelisted emails',
										fields: []
									}
								]
							}
							let index;
							for (index = 0; index < domains.length; index++) {
								formattedMessage.attachments.fields.push({
									'title': '',
									'value': domains[index],
									'short': true
								})
							}
						})
						break
					case 'add':
						add(argument, (err) => {
							msg.respond(argument + ' has been added to the whitelist.', (err) => {})
						})
						break
					case 'remove':
						remove(argument, (err) => {
							msg.respond(argument + ' has been removed from the whitelist.', (err) => {})
						})
						break
				}
			} else {
				msg.respond('/whitelist Usage:\n/whitelist [add domain] - Adds the domain to the whitelist\n/whitelist [remove domain] - Removes the domain from the whitelist\n/whitelist [get] - Gets the whitelist', (err) => {})
			}
		})
	},

	'get': get

}<commit_msg>tunes<commit_after>const fs = require('fs')
const whitelist = __dirname + '/whitelist.json'

get = function(callback) {
	fs.readFile(whitelist, 'utf8', (err, text) => {
		let domains = JSON.parse(text)
		callback(err, domains)
	})
}

add = function(domain, callback) {
	get((err, domains) => {
		let domainsList = JSON.parse(domains)
		domainsList.push(domain)
		fs.writeFile(whitelist, JSON.stringify(domainsList), callback)
	})
}

remove = function(domain, callback) {
	get((err, domains) => {
		let domainsList = JSON.parse(domains)
		let domainIndex = domainsList.indexOf(domain)
		if (domainIndex >= 0) {
			domainsList.splice(domainIndex, 1)
		}
		fs.writeFile(whitelist, JSON.stringify(domainList), callback)
	})
}

module.exports = {

	command: (slapp) => {
		slapp.command('/whitelist', '(\\w*)\\s*(\\w*)', (msg, text, command, argument) => {
			if (command) {
				switch (command) {
					case 'get':
						get((err, domains) => {
							let formattedMessage = {
								attachments: [
									{
										fallback: JSON.stringify(domains),
										title: 'List of all whitelisted emails',
										fields: []
									}
								]
							}
							let index;
							for (index = 0; index < domains.length; index++) {
								formattedMessage.attachments.fields.push({
									'title': '',
									'value': domains[index],
									'short': true
								})
							}
						})
						break
					case 'add':
						add(argument, (err) => {
							msg.respond(argument + ' has been added to the whitelist.', (err) => {})
						})
						break
					case 'remove':
						remove(argument, (err) => {
							msg.respond(argument + ' has been removed from the whitelist.', (err) => {})
						})
						break
				}
			} else {
				msg.respond('/whitelist Usage:\n/whitelist [add domain] - Adds the domain to the whitelist\n/whitelist [remove domain] - Removes the domain from the whitelist\n/whitelist [get] - Gets the whitelist', (err) => {})
			}
		})
	},

	'get': get

}<|endoftext|>


<commit_before>'use strict';

var readabilityCallback = function(dataRdb, target, id, progress) {
  var bIsJquery = target instanceof jQuery;
  if (!bIsJquery) {
    target = $(target.selector);
  }

  if (dataRdb.error) {
    target.find('.readability-circle')
      .find('span')
      .html($('<i>', {
        class: 'fa fa-ban',
        'aria-hidden': 'true',
      }));
  }

  if (dataRdb.readability === undefined) {
    return;
  }

  var difficulty = dataRdb.readability.difficulty;

  if (target.find('.rdb').length === 0) {
    var readabilityColor = 'red';
    if (difficulty === 'average') {
      readabilityColor = 'orange';
    } else if (difficulty === 'easy') {
      readabilityColor = 'green';
    }
    progress.destroy();
    progress =
    new ProgressBar.Circle(
    document.getElementById(id).querySelector('.readability-circle'), {
      strokeWidth: 7,
      trailWidth: 7,
      trailColor: '#ddd',
      color: readabilityColor,
      easing: 'easeInOut',
      duration: 800,
    });
    target.find('.readability-circle')
      .find('span')
      .html($('<i>', {
        class: 'fa fa-book',
        'aria-hidden': 'true',
      }));

    try {
      progress.animate(1);
    } catch (e) {
      progress.set(1);
    }

  }
};

var trustabilityCallback = function(data, target, id, progress) {
  if (data.trustability === undefined) {
    target.find('.trustability-circle')
      .find('span')
      .html($('<i>', {
        class: 'fa fa-ban',
        'aria-hidden': 'true',
      }));
    return;
  }

  var bIsJquery = target instanceof jQuery;
  if (!bIsJquery) {
    target = $(target.selector);
  }

  var score = data.trustability.score;

  if (target.find('.trb').length === 0) {

    var trustabilityColor = 'red';
    if (score > 33 && score <= 66) {
      trustabilityColor = 'orange';
    } else if (score > 66) {
      trustabilityColor = 'green';
    }
    progress.destroy();
    progress =
      new ProgressBar.Circle(
        document.getElementById(id).querySelector('.trustability-circle'), {
          strokeWidth: 7,
          trailWidth: 7,
          trailColor: '#ddd',
          color: trustabilityColor,
          easing: 'easeInOut',
          duration: 800,
        });
    target.find('.trustability-circle')
      .find('span')
      .html($('<i>', {
        class: 'fa fa-stethoscope',
        'aria-hidden': 'true',
      }));
    progress.animate(score / 100);
  }
};

var requestKconnect = function(event, link) {
  var domain = kconnect.getDomainFromUrl(link);
  var trustabilityRequest = kconnect.getIsTrustable(domain);
  var readabilityRequest = kconnect.getReadability(link);
  var layerId = 'layer' + event.target.id;
  var $logoId =  $(event.target);

  var fa = document.createElement('style');
  fa.type = 'text/css';
  fa.textContent = '@font-face { font-family: FontAwesome; src: url("' +
    chrome.extension.getURL('fonts/fontawesome-webfont.woff') +
  '"); }';
  document.head.appendChild(fa);

  var popUp = $('<div>', {
    class: 'kconnectPopup',
    style: 'display: none',
    id: layerId,
  }).append($('<div>', {
    class: 'honPopup-header',
  }).text(domain))
    .append($('<div>',{
      class: 'k-infos trustability',
    }).append($('<h4>').text(chrome.i18n.getMessage('trustabilityTitle')))
      .append($('<div>', {
        class: 'trustability-circle',
      }).append($('<span>'))))
    .append($('<div>',{
      class: 'k-infos readability',
    }).append($('<h4>').text(chrome.i18n.getMessage('readabilityTitle')))
      .append($('<div>', {
        class: 'readability-circle',
      }).append($('<span>'))));

  $('body').append(popUp);

  var $layerId =  $('#' + layerId);

  var borderX = 10;
  if (event.pageX + 290 > document.body.getBoundingClientRect().right) {
    borderX = event.pageX + 300 - document.body.getBoundingClientRect().right;
  }

  $layerId.css('left', event.pageX - borderX);
  $layerId.css('top', event.pageY - 10);

  var timeoutId;
  var hideTimeoutId;
  // Add honLogo eventListener
  $logoId.hover(function() {
    if (!timeoutId) {
      timeoutId = window.setTimeout(function() {
        timeoutId = null;
        $layerId.show();
      }, 200);
    }
  }, function() {
    if (timeoutId) {
      window.clearTimeout(timeoutId);
      timeoutId = null;
    }
  });

  $layerId.hover(function() {
    if (hideTimeoutId) {
      window.clearTimeout(hideTimeoutId);
      hideTimeoutId = null;
    }
  }, function() {
    if (!hideTimeoutId) {
      hideTimeoutId = window.setTimeout(function() {
        hideTimeoutId = null;
        $layerId.hide();
      }, 200);
    }
  });

  var rProgress = new ProgressBar.Circle(
    document.getElementById(layerId).querySelector('.readability-circle'), {
    strokeWidth: 7,
    trailWidth: 7,
    trailColor: '#ddd',
  });
  $layerId.find('.readability-circle')
    .find('span')
    .append(
      $('<i>', {
        class: 'fa fa-question',
        'aria-hidden': 'true',
      })
    );

  var tProgress = new ProgressBar.Circle(
    document.getElementById(layerId).querySelector('.trustability-circle'), {
    strokeWidth: 7,
    trailWidth: 7,
    trailColor: '#ddd',
  });
  $layerId.find('.trustability-circle')
    .find('span')
    .append(
      $('<i>', {
        class: 'fa fa-question',
        'aria-hidden': 'true',
      })
    );

  $.when(trustabilityRequest)
    .then(function(trustabilityResponse) {
      trustabilityCallback(trustabilityResponse, $layerId, layerId, tProgress);
    });

  $.when(readabilityRequest)
    .then(function(readabilityResponse) {
      readabilityCallback(readabilityResponse, $layerId, layerId, rProgress);
    }, function(error) {
      readabilityCallback(error.responseJSON, $layerId, layerId, rProgress);
    });

  $layerId.show();
};

var updateLinks = function() {
  var deferred = new $.Deferred();

  // Get links
  var links = [];
  var hrefSelector = '';
  var trustabilityRequested = 0;
  // Match Google
  if (window.location.host.indexOf('google') > -1) {
    hrefSelector = 'h3.r>a';
  }
  // Match Yahoo
  else if (window.location.host.indexOf('yahoo') > -1) {
    hrefSelector = '#web div.compTitle h3.title>a';
  }
  // Match Bing
  else if (window.location.host.indexOf('bing') > -1) {
    hrefSelector = 'li.b_algo h2>a';
  }
  var nodeList = document.querySelectorAll(hrefSelector);
  for (var i = 0; i < nodeList.length; ++i) {
    links[i] = nodeList[i].href;
  }
  links.forEach(function(link, index) {
    var honLogo = $(nodeList.item(index)).parent();

    var logoId = 'kconnectLogo_' + index;

    var honCodeLogo = $('<div>', {
        target: '_blank',
        id: logoId,
        class: 'hon kconnectLogo',
      });

    if (honLogo.children('.kconnectLogo').length === 0) {
      // Normalize Search Engine parents' behaviors
      honLogo.parent().css('overflow','visible');
      honLogo.parent().css('position','relative');
      honLogo.append(honCodeLogo);

      // Add onClick listener
      $('#' + logoId).one('click', function(e) {
        requestKconnect(e, link);
      });
    }

    trustabilityRequested++;
    if (trustabilityRequested === links.length) {
      deferred.resolve();
    }
  });

  return deferred.promise();
};

updateLinks().done(function() {});
<commit_msg>better error handler<commit_after>'use strict';

var readabilityCallback = function(dataRdb, target, id, progress) {
  var bIsJquery = target instanceof jQuery;
  if (!bIsJquery) {
    target = $(target.selector);
  }

  if (dataRdb.error || dataRdb.readability === undefined) {
    target.find('.readability-circle')
      .find('span')
      .html($('<i>', {
        class: 'fa fa-ban',
        'aria-hidden': 'true',
      }));
    return;
  }

  var difficulty = dataRdb.readability.difficulty;

  if (target.find('.rdb').length === 0) {
    var readabilityColor = 'red';
    if (difficulty === 'average') {
      readabilityColor = 'orange';
    } else if (difficulty === 'easy') {
      readabilityColor = 'green';
    }
    progress.destroy();
    progress =
    new ProgressBar.Circle(
    document.getElementById(id).querySelector('.readability-circle'), {
      strokeWidth: 7,
      trailWidth: 7,
      trailColor: '#ddd',
      color: readabilityColor,
      easing: 'easeInOut',
      duration: 800,
    });
    target.find('.readability-circle')
      .find('span')
      .html($('<i>', {
        class: 'fa fa-book',
        'aria-hidden': 'true',
      }));

    try {
      progress.animate(1);
    } catch (e) {
      progress.set(1);
    }

  }
};

var trustabilityCallback = function(data, target, id, progress) {
  if (data.error || data.trustability === undefined) {
    target.find('.trustability-circle')
      .find('span')
      .html($('<i>', {
        class: 'fa fa-ban',
        'aria-hidden': 'true',
      }));
    return;
  }

  var bIsJquery = target instanceof jQuery;
  if (!bIsJquery) {
    target = $(target.selector);
  }

  var score = data.trustability.score;

  if (target.find('.trb').length === 0) {

    var trustabilityColor = 'red';
    if (score > 33 && score <= 66) {
      trustabilityColor = 'orange';
    } else if (score > 66) {
      trustabilityColor = 'green';
    }
    progress.destroy();
    progress =
      new ProgressBar.Circle(
        document.getElementById(id).querySelector('.trustability-circle'), {
          strokeWidth: 7,
          trailWidth: 7,
          trailColor: '#ddd',
          color: trustabilityColor,
          easing: 'easeInOut',
          duration: 800,
        });
    target.find('.trustability-circle')
      .find('span')
      .html($('<i>', {
        class: 'fa fa-stethoscope',
        'aria-hidden': 'true',
      }));
    progress.animate(score / 100);
  }
};

var requestKconnect = function(event, link) {
  var domain = kconnect.getDomainFromUrl(link);
  var trustabilityRequest = kconnect.getIsTrustable(domain);
  var readabilityRequest = kconnect.getReadability(link);
  var layerId = 'layer' + event.target.id;
  var $logoId =  $(event.target);

  var fa = document.createElement('style');
  fa.type = 'text/css';
  fa.textContent = '@font-face { font-family: FontAwesome; src: url("' +
    chrome.extension.getURL('fonts/fontawesome-webfont.woff') +
  '"); }';
  document.head.appendChild(fa);

  var popUp = $('<div>', {
    class: 'kconnectPopup',
    style: 'display: none',
    id: layerId,
  }).append($('<div>', {
    class: 'honPopup-header',
  }).text(domain))
    .append($('<div>',{
      class: 'k-infos trustability',
    }).append($('<h4>').text(chrome.i18n.getMessage('trustabilityTitle')))
      .append($('<div>', {
        class: 'trustability-circle',
      }).append($('<span>'))))
    .append($('<div>',{
      class: 'k-infos readability',
    }).append($('<h4>').text(chrome.i18n.getMessage('readabilityTitle')))
      .append($('<div>', {
        class: 'readability-circle',
      }).append($('<span>'))));

  $('body').append(popUp);

  var $layerId =  $('#' + layerId);

  var borderX = 10;
  if (event.pageX + 290 > document.body.getBoundingClientRect().right) {
    borderX = event.pageX + 300 - document.body.getBoundingClientRect().right;
  }

  $layerId.css('left', event.pageX - borderX);
  $layerId.css('top', event.pageY - 10);

  var timeoutId;
  var hideTimeoutId;
  // Add honLogo eventListener
  $logoId.hover(function() {
    if (!timeoutId) {
      timeoutId = window.setTimeout(function() {
        timeoutId = null;
        $layerId.show();
      }, 200);
    }
  }, function() {
    if (timeoutId) {
      window.clearTimeout(timeoutId);
      timeoutId = null;
    }
  });

  $layerId.hover(function() {
    if (hideTimeoutId) {
      window.clearTimeout(hideTimeoutId);
      hideTimeoutId = null;
    }
  }, function() {
    if (!hideTimeoutId) {
      hideTimeoutId = window.setTimeout(function() {
        hideTimeoutId = null;
        $layerId.hide();
      }, 200);
    }
  });

  var rProgress = new ProgressBar.Circle(
    document.getElementById(layerId).querySelector('.readability-circle'), {
    strokeWidth: 7,
    trailWidth: 7,
    trailColor: '#ddd',
  });
  $layerId.find('.readability-circle')
    .find('span')
    .append(
      $('<i>', {
        class: 'fa fa-question',
        'aria-hidden': 'true',
      })
    );

  var tProgress = new ProgressBar.Circle(
    document.getElementById(layerId).querySelector('.trustability-circle'), {
    strokeWidth: 7,
    trailWidth: 7,
    trailColor: '#ddd',
  });
  $layerId.find('.trustability-circle')
    .find('span')
    .append(
      $('<i>', {
        class: 'fa fa-question',
        'aria-hidden': 'true',
      })
    );

  $.when(trustabilityRequest)
    .then(function(trustabilityResponse) {
      trustabilityCallback(trustabilityResponse, $layerId, layerId, tProgress);
    });

  $.when(readabilityRequest)
    .then(function(readabilityResponse) {
      readabilityCallback(readabilityResponse, $layerId, layerId, rProgress);
    }, function(error) {
      readabilityCallback(error.responseJSON, $layerId, layerId, rProgress);
    });

  $layerId.show();
};

var updateLinks = function() {
  var deferred = new $.Deferred();

  // Get links
  var links = [];
  var hrefSelector = '';
  var trustabilityRequested = 0;
  // Match Google
  if (window.location.host.indexOf('google') > -1) {
    hrefSelector = 'h3.r>a';
  }
  // Match Yahoo
  else if (window.location.host.indexOf('yahoo') > -1) {
    hrefSelector = '#web div.compTitle h3.title>a';
  }
  // Match Bing
  else if (window.location.host.indexOf('bing') > -1) {
    hrefSelector = 'li.b_algo h2>a';
  }
  var nodeList = document.querySelectorAll(hrefSelector);
  for (var i = 0; i < nodeList.length; ++i) {
    links[i] = nodeList[i].href;
  }
  links.forEach(function(link, index) {
    var honLogo = $(nodeList.item(index)).parent();

    var logoId = 'kconnectLogo_' + index;

    var honCodeLogo = $('<div>', {
        target: '_blank',
        id: logoId,
        class: 'hon kconnectLogo',
      });

    if (honLogo.children('.kconnectLogo').length === 0) {
      // Normalize Search Engine parents' behaviors
      honLogo.parent().css('overflow','visible');
      honLogo.parent().css('position','relative');
      honLogo.append(honCodeLogo);

      // Add onClick listener
      $('#' + logoId).one('click', function(e) {
        requestKconnect(e, link);
      });
    }

    trustabilityRequested++;
    if (trustabilityRequested === links.length) {
      deferred.resolve();
    }
  });

  return deferred.promise();
};

updateLinks().done(function() {});
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

'use strict';

var path = require('path');
var config = require('../config');
var STATIC_PATH = path.join(__dirname, '..', '..', config.get('server_staticPath'));

var baseController = {
  get: function (request, reply) {
    var page = request.auth.isAuthenticated ? 'app.html' : 'index.html';
    reply.file(path.join(STATIC_PATH, page));
  }
};

module.exports = baseController;
<commit_msg>fix(server): Removes caching for root path.<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

'use strict';

var fs = require('fs');
var path = require('path');
var config = require('../config');
var STATIC_PATH = path.join(__dirname, '..', '..', config.get('server_staticPath'));

var baseController = {
  get: function (request, reply) {
    var page = request.auth.isAuthenticated ? 'app.html' : 'index.html';

    fs.readFile(path.join(STATIC_PATH, page), 'utf8', function (err, data) {
      if (err) {
        throw err;
      }

      reply(data);
    });
  }
};

module.exports = baseController;
<|endoftext|>


<commit_before>// testing page task management

Template.tasks.helpers({

  hideCompleted: function () { // return whether to hide completed tasks
    return Session.equals('hideDoneTasks', true);
  },

  tasks: function () { // sort, linkify and return tasks for this repo
    if (Session.equals('hideDoneTasks', true)) {
      var chkd = Tasks.find({checked: {$ne: true}}, {sort: {time: -1}});
      return chkd.map(function(task){
        task.linkd = linkifyStr(task.text);
        return task;
      });
    } else { // dont hide completed - return all repo task items
      var unchkd = Tasks.find({}, {sort: {checked: 1, time: -1}});
      return unchkd.map(function(task){
        task.linkd = linkifyStr(task.text);
        return task;
      });
    }
  },

  taskCount: function () { // return amount of incomplete tasks
    if (Session.equals('hideDoneTasks', true))
      return Tasks.find({checked: {$ne: true}}).count();
    else
      return Tasks.find({}).count();
  },

});

Template.tasks.events({

  'submit .new-task': function(e) { // create a new task
    e.preventDefault();
    $(e.target).blur();
    var task = $('#task-name')[0].value; //check value
    if (task == null || task == '') return false;
    $('#task-name')[0].value = ''; // reset form text
    Meteor.call('addTask', task);
  },

  'change .hide-completed': function (e) { // toggle for showing completed
    Session.set('hideDoneTasks', e.target.checked);
  },

});

// individual task item helpers and events

Template.task.helpers({

  mine: function() { // return true for tasks this user created, used to style
    return (prof().login === this.username);
  },

  current: function() {
    return Session.equals('focusPane', this._id);
  },

});

Template.task.events({

  'click .task': function() { // click to focus issue, again to reset
    if ( Session.equals('focusPane', this._id) )
      Session.set('focusPane', null);
    else
      Session.set('focusPane', this._id);
  },

  'click .toggle-checked': function () { // check or uncheck a task
    Meteor.call('setChecked', this); // server will deal with task updates
    Session.set('focusPane', null); // reset the currently selected task
  },

  'click .del': function () { // delete a task from this repo
    Meteor.call('deleteTask', this);
  }

});

// github issue event integration

Template.issues.helpers({

  issues: function () { // sort and return issues for this repo
    return Issues.find({}, {sort: {'issue.updated_at': -1}});
  },

  issueCount: function () { // return amount of open issues
    return Issues.find({}).count();
  },

});

Template.issues.events({

  'click .reload': function () { // update the issues for this repo
    Meteor.call('initIssues');
  }

});

// individual issue helpers

Template.issue.helpers({

  current: function() {
    return Session.equals('focusPane', this._id);
  },

  screen: function() { // return an issue screenshot
    var screen;
    if (this.feedback)
      screen = Screens.findOne(this.feedback.imglink);
    if (screen)
      return screen.img;
  },

  labels: function () {
    if (this.issue)
      return this.issue.labels;
  },

});

Template.issue.events({

  'click .issue': function(e) { // click to focus issue, again to reset
    if ( Session.equals('focusPane', this._id) )
      Session.set('focusPane', null);
    else
      Session.set('focusPane', this._id);
  },

  'click .closeissue': function(e) { // click to close a given issue
    var trulyClose = confirm("Are you sure you'd like to close this issue?");
    if (trulyClose)
      Meteor.call('closeIssue', this);
  },

});
<commit_msg>adding prof<commit_after>// testing page task management

var prof = Meteor.g.prof;

Template.tasks.helpers({

  hideCompleted: function () { // return whether to hide completed tasks
    return Session.equals('hideDoneTasks', true);
  },

  tasks: function () { // sort, linkify and return tasks for this repo
    if (Session.equals('hideDoneTasks', true)) {
      var chkd = Tasks.find({checked: {$ne: true}}, {sort: {time: -1}});
      return chkd.map(function(task){
        task.linkd = linkifyStr(task.text);
        return task;
      });
    } else { // dont hide completed - return all repo task items
      var unchkd = Tasks.find({}, {sort: {checked: 1, time: -1}});
      return unchkd.map(function(task){
        task.linkd = linkifyStr(task.text);
        return task;
      });
    }
  },

  taskCount: function () { // return amount of incomplete tasks
    if (Session.equals('hideDoneTasks', true))
      return Tasks.find({checked: {$ne: true}}).count();
    else
      return Tasks.find({}).count();
  },

});

Template.tasks.events({

  'submit .new-task': function(e) { // create a new task
    e.preventDefault();
    $(e.target).blur();
    var task = $('#task-name')[0].value; //check value
    if (task == null || task == '') return false;
    $('#task-name')[0].value = ''; // reset form text
    Meteor.call('addTask', task);
  },

  'change .hide-completed': function (e) { // toggle for showing completed
    Session.set('hideDoneTasks', e.target.checked);
  },

});

// individual task item helpers and events

Template.task.helpers({

  mine: function() { // return true for tasks this user created, used to style
    return (prof().login === this.username);
  },

  current: function() {
    return Session.equals('focusPane', this._id);
  },

});

Template.task.events({

  'click .task': function() { // click to focus issue, again to reset
    if ( Session.equals('focusPane', this._id) )
      Session.set('focusPane', null);
    else
      Session.set('focusPane', this._id);
  },

  'click .toggle-checked': function () { // check or uncheck a task
    Meteor.call('setChecked', this); // server will deal with task updates
    Session.set('focusPane', null); // reset the currently selected task
  },

  'click .del': function () { // delete a task from this repo
    Meteor.call('deleteTask', this);
  }

});

// github issue event integration

Template.issues.helpers({

  issues: function () { // sort and return issues for this repo
    return Issues.find({}, {sort: {'issue.updated_at': -1}});
  },

  issueCount: function () { // return amount of open issues
    return Issues.find({}).count();
  },

});

Template.issues.events({

  'click .reload': function () { // update the issues for this repo
    Meteor.call('initIssues');
  }

});

// individual issue helpers

Template.issue.helpers({

  current: function() {
    return Session.equals('focusPane', this._id);
  },

  screen: function() { // return an issue screenshot
    var screen;
    if (this.feedback)
      screen = Screens.findOne(this.feedback.imglink);
    if (screen)
      return screen.img;
  },

  labels: function () {
    if (this.issue)
      return this.issue.labels;
  },

});

Template.issue.events({

  'click .issue': function(e) { // click to focus issue, again to reset
    if ( Session.equals('focusPane', this._id) )
      Session.set('focusPane', null);
    else
      Session.set('focusPane', this._id);
  },

  'click .closeissue': function(e) { // click to close a given issue
    var trulyClose = confirm("Are you sure you'd like to close this issue?");
    if (trulyClose)
      Meteor.call('closeIssue', this);
  },

});
<|endoftext|>


<commit_before>'use strict';
/**
 * Created by jsturtevant on 1/18/14.
 */
var options = {};

chrome.runtime.sendMessage({method: "getOptions"}, function(response) {
    options = response.options

    Mousetrap.bind(options.shortcutKey, function(e) {
        var elementList = document.querySelectorAll('input[type=text]');
        var textboxes = Array.prototype.slice.call(elementList,0);
        textboxes.forEach(function(textbox){
            var string = textbox.value;

            if (string.match(options.shortcuts[0].key)){
                var newValue = string.replace(options.shortcuts[0].key,options.shortcuts[0].value);
                textbox.value = newValue;
            }
        });

        return false;
    });
});

Mousetrap.stopCallback =function(e, element, combo) {
    // if the element has the class "mousetrap" then no need to stop
    if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) {
        return false;
    }

    // stop for input, select, and textarea
    return  element.tagName == 'SELECT' || element.tagName == 'TEXTAREA' || (element.contentEditable && element.contentEditable == 'true');
}

<commit_msg>added support for text areas<commit_after>'use strict';
/**
 * Created by jsturtevant on 1/18/14.
 */
var options = {};

chrome.runtime.sendMessage({method: "getOptions"}, function(response) {
    options = response.options

    Mousetrap.bind(options.shortcutKey, function(e) {
        var elementList = document.querySelectorAll('input[type=text], textarea');
        var textboxes = Array.prototype.slice.call(elementList,0);
        textboxes.forEach(function(textbox){
            var string = textbox.value;

            if (string.match(options.shortcuts[0].key)){
                var newValue = string.replace(options.shortcuts[0].key,options.shortcuts[0].value);
                textbox.value = newValue;
            }
        });

        return false;
    });
});

Mousetrap.stopCallback =function(e, element, combo) {
    // if the element has the class "mousetrap" then no need to stop
    if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) {
        return false;
    }

    // stop for input, select, and textarea
    return  element.tagName == 'SELECT' || (element.contentEditable && element.contentEditable == 'true');
}

<|endoftext|>


<commit_before>var path = require('path');
var db = require('../db/database');
var Song = db.Song;
var Group = db.Group;

var addSong = function(req, res, next) {
  var dateRecorded = req.body.dateRecorded || Date.now();
  var groupId = req.params.id;
  var title = req.body.title;
  var description = req.body.description;

  Song.create({
    title: title || req.filename,
    description: description || '',
    dateRecorded: dateRecorded || Date.now(), // TODO: Receive from UI?
    duration: 100, // TODO: Receive from UI?
    address: req.filename,
    groupId: groupId
  }, {
    include: {
      model: Group
    }
  })
  .then(function(song) {
    res.json(song);
  })
  .catch(function(err) {
    next(err);
  });
};

var getSongByFilename = function(req, res, next) {
  var filename = req.params.filename;
  console.log('params are ' + JSON.stringify(req.params));
  var url = path.resolve(__dirname + '/../uploadInbox/' + filename);
  console.log('url is ' + JSON.stringify(url));
  res.sendFile(url);
};

module.exports = {
  addSong: addSong,
  getSongByFilename: getSongByFilename
};
<commit_msg>(cleanup) get rid of console.logs<commit_after>var path = require('path');
var db = require('../db/database');
var Song = db.Song;
var Group = db.Group;

var addSong = function(req, res, next) {
  var dateRecorded = req.body.dateRecorded || Date.now();
  var groupId = req.params.id;
  var title = req.body.title;
  var description = req.body.description;

  Song.create({
    title: title || req.filename,
    description: description || '',
    dateRecorded: dateRecorded || Date.now(), // TODO: Receive from UI?
    duration: 100, // TODO: Receive from UI?
    address: req.filename,
    groupId: groupId
  }, {
    include: {
      model: Group
    }
  })
  .then(function(song) {
    res.json(song);
  })
  .catch(function(err) {
    next(err);
  });
};

var getSongByFilename = function(req, res, next) {
  var filename = req.params.filename;
  var url = path.resolve(__dirname + '/../uploadInbox/' + filename);
  res.sendFile(url);
};

module.exports = {
  addSong: addSong,
  getSongByFilename: getSongByFilename
};
<|endoftext|>


<commit_before>import { fromJS } from "immutable";
import { Step, Stepper, StepButton } from "material-ui/Stepper";
import Addons from "./steps/Addons";
import ArrowForwardIcon from "material-ui/svg-icons/navigation/arrow-forward";
import DataBases from "./steps/DataBases";
import Notification from "../Notification";
import ProjectName from "./steps/ProjectName";
import PropTypes from "prop-types";
import React from "react";
import Repositories from "./steps/Repositories";
import Stacks from "./steps/Stacks";
import SwipeableViews from "react-swipeable-views";

const Steps = ( {applicationActions, applicationAppState, environments, mysqlAppState, projectNameAppState, provisionerFormActions, rolesActions, setProjectName, userAppState, repositoryAppState, baseAppState, buildbotAppState, cloudProviderAppState, springAppState, nginxAppState, yiiAppState, plainHtmlAppState} ) => {
  const handleChangeStep = (value) => {
    provisionerFormActions.setActiveStep(fromJS({
      active_step: value
    }));
  };
  return (

        <Stepper
            activeStep={applicationAppState.get("active_step")}
            connector={<ArrowForwardIcon />}
        >
          <Step>
            <StepButton onClick={() => handleChangeStep(0)}>
              {"Project Name"}
            </StepButton>
          </Step>
          <Step disabled={projectNameAppState.get("project_name")?false:true}>
            <StepButton onClick={() => handleChangeStep(1)}>
              {"Repository"}
            </StepButton>
          </Step>
          <Step disabled={projectNameAppState.get("project_name")?false:true}>
            <StepButton onClick={() => handleChangeStep(2)}>
              {"Frameworks"}
            </StepButton>
          </Step>
          <Step disabled={applicationAppState.get("stacks")?applicationAppState.get("stacks").size==0?true:false:true}>
            <StepButton onClick={() => handleChangeStep(3)}>
              {"DataBases"}
            </StepButton>
          </Step>
          <Step disabled={applicationAppState.get("stacks")?applicationAppState.get("stacks").size==0?true:false:true}>
            <StepButton onClick={() => handleChangeStep(4)}>
              {"Add-ons"}
            </StepButton>
          </Step>
        </Stepper>
        <SwipeableViews
            index={applicationAppState.get("active_step")}
        >
          <ProjectName
              projectNameAppState={projectNameAppState}
              setActiveStep={handleChangeStep}
              setProjectName={setProjectName}
          />
          <Repositories
              applicationAppState={applicationAppState}
              removeRepo={provisionerFormActions.removeRepo}
              repositories={applicationAppState.get("repositories")?applicationAppState.get("repositories"):fromJS([])}
              repositoriesOptions={applicationAppState.getIn(["steps","repositories"])}
              repositoryAppState={repositoryAppState}
              requestRepositoryAccess={provisionerFormActions.requestRepositoryAccess}
              requestUserRepositories={provisionerFormActions.requestUserRepositories}
              rolesActions={rolesActions}
              setActiveConfigurationStep={provisionerFormActions.setActiveConfigurationStep}
              setActiveStep={handleChangeStep}
              setRepo={provisionerFormActions.setRepo}
              setRepository={provisionerFormActions.setRepository}
              userAppState={userAppState}
          />
          <Stacks
              removeStack={provisionerFormActions.removeStack}
              rolesActions={rolesActions}
              setActiveStep={handleChangeStep}
              setStack={provisionerFormActions.setStack}
              stacks={applicationAppState.get("stacks")?applicationAppState.get("stacks"):fromJS([])}
              stacksOptions={applicationAppState.getIn(["steps","stacks"])}
          />
          <DataBases
              activeEnvironment={environments[applicationAppState.get("active_environment")].id}
              applicationAppState={applicationAppState}
              databases={applicationAppState.get("databases")?applicationAppState.get("databases"):fromJS([])}
              databasesOptions={applicationAppState.getIn(["steps","databases"])}
              environments={environments}
              mysqlAppState={mysqlAppState}
              removeDatabase={provisionerFormActions.removeDatabase}
              rolesActions={rolesActions}
              setActiveConfigurationStep={provisionerFormActions.setActiveConfigurationStep}
              setActiveEnvironment={provisionerFormActions.setActiveEnvironment}
              setActiveStep={handleChangeStep}
              setDatabase={provisionerFormActions.setDatabase}
          />
          <Addons
              addons={applicationAppState.get("addons")?applicationAppState.get("addons"):fromJS([])}
              addonsOptions={applicationAppState.getIn(["steps","addons"])}
              applicationAppState={applicationAppState}
              baseAppState={baseAppState}
              buildbotAppState={buildbotAppState}
              cloudProviderAppState={cloudProviderAppState}
              mysqlAppState={mysqlAppState}
              nginxAppState={nginxAppState}
              plainHtmlAppState={plainHtmlAppState}
              projectNameAppState={projectNameAppState}
              removeAddons={provisionerFormActions.removeAddons}
              repositoryAppState={repositoryAppState}
              requestPostUserProject={provisionerFormActions.requestPostUserProject}
              setActiveStep={handleChangeStep}
              setAddons={provisionerFormActions.setAddons}
              springAppState={springAppState}
              userAppState={userAppState}
              yiiAppState={yiiAppState}
          />
        </SwipeableViews>

      {/* <Notification
          message={applicationAppState.get("notification")}
          setNotification={applicationActions.setNotification}
      /> */}

  );
};

Steps.propTypes = {
  applicationActions: PropTypes.object.isRequired,
  applicationAppState: PropTypes.object.isRequired,
  baseAppState: PropTypes.object.isRequired,
  buildbotAppState: PropTypes.object.isRequired,
  cloudProviderAppState: PropTypes.object.isRequired,
  environments: PropTypes.array.isRequired,
  mysqlAppState: PropTypes.object.isRequired,
  nginxAppState: PropTypes.object.isRequired,
  plainHtmlAppState: PropTypes.object.isRequired,
  projectNameAppState: PropTypes.object.isRequired,
  provisionerFormActions: PropTypes.object.isRequired,
  repositoryAppState: PropTypes.object.isRequired,
  rolesActions: PropTypes.object.isRequired,
  setProjectName: PropTypes.func.isRequired,
  springAppState: PropTypes.object.isRequired,
  userAppState: PropTypes.object.isRequired,
  yiiAppState: PropTypes.object.isRequired
};

export default Steps;
<commit_msg>Remove unecesary functions<commit_after>import { fromJS } from "immutable";
import { Step, Stepper, StepButton } from "material-ui/Stepper";
import Addons from "./steps/Addons";
import ArrowForwardIcon from "material-ui/svg-icons/navigation/arrow-forward";
import DataBases from "./steps/DataBases";
import Notification from "../Notification";
import ProjectName from "./steps/ProjectName";
import PropTypes from "prop-types";
import React from "react";
import Repositories from "./steps/Repositories";
import Stacks from "./steps/Stacks";
import SwipeableViews from "react-swipeable-views";

const Steps = ( {applicationAppState, environments, mysqlAppState, projectNameAppState, provisionerFormActions, rolesActions, setProjectName, userAppState, repositoryAppState, baseAppState, buildbotAppState, cloudProviderAppState, springAppState, nginxAppState, yiiAppState, plainHtmlAppState} ) => {
  const handleChangeStep = (value) => {
    provisionerFormActions.setActiveStep(fromJS({
      active_step: value
    }));
  };
  return (

        <Stepper
            activeStep={applicationAppState.get("active_step")}
            connector={<ArrowForwardIcon />}
        >
          <Step>
            <StepButton onClick={() => handleChangeStep(0)}>
              {"Project Name"}
            </StepButton>
          </Step>
          <Step disabled={projectNameAppState.get("project_name")?false:true}>
            <StepButton onClick={() => handleChangeStep(1)}>
              {"Repository"}
            </StepButton>
          </Step>
          <Step disabled={projectNameAppState.get("project_name")?false:true}>
            <StepButton onClick={() => handleChangeStep(2)}>
              {"Frameworks"}
            </StepButton>
          </Step>
          <Step disabled={applicationAppState.get("stacks")?applicationAppState.get("stacks").size==0?true:false:true}>
            <StepButton onClick={() => handleChangeStep(3)}>
              {"DataBases"}
            </StepButton>
          </Step>
          <Step disabled={applicationAppState.get("stacks")?applicationAppState.get("stacks").size==0?true:false:true}>
            <StepButton onClick={() => handleChangeStep(4)}>
              {"Add-ons"}
            </StepButton>
          </Step>
        </Stepper>
        <SwipeableViews
            index={applicationAppState.get("active_step")}
        >
          <ProjectName
              projectNameAppState={projectNameAppState}
              setActiveStep={handleChangeStep}
              setProjectName={setProjectName}
          />
          <Repositories
              applicationAppState={applicationAppState}
              removeRepo={provisionerFormActions.removeRepo}
              repositories={applicationAppState.get("repositories")?applicationAppState.get("repositories"):fromJS([])}
              repositoriesOptions={applicationAppState.getIn(["steps","repositories"])}
              repositoryAppState={repositoryAppState}
              requestRepositoryAccess={provisionerFormActions.requestRepositoryAccess}
              requestUserRepositories={provisionerFormActions.requestUserRepositories}
              rolesActions={rolesActions}
              setActiveConfigurationStep={provisionerFormActions.setActiveConfigurationStep}
              setActiveStep={handleChangeStep}
              setRepo={provisionerFormActions.setRepo}
              setRepository={provisionerFormActions.setRepository}
              userAppState={userAppState}
          />
          <Stacks
              removeStack={provisionerFormActions.removeStack}
              rolesActions={rolesActions}
              setActiveStep={handleChangeStep}
              setStack={provisionerFormActions.setStack}
              stacks={applicationAppState.get("stacks")?applicationAppState.get("stacks"):fromJS([])}
              stacksOptions={applicationAppState.getIn(["steps","stacks"])}
          />
          <DataBases
              activeEnvironment={environments[applicationAppState.get("active_environment")].id}
              applicationAppState={applicationAppState}
              databases={applicationAppState.get("databases")?applicationAppState.get("databases"):fromJS([])}
              databasesOptions={applicationAppState.getIn(["steps","databases"])}
              environments={environments}
              mysqlAppState={mysqlAppState}
              removeDatabase={provisionerFormActions.removeDatabase}
              rolesActions={rolesActions}
              setActiveConfigurationStep={provisionerFormActions.setActiveConfigurationStep}
              setActiveEnvironment={provisionerFormActions.setActiveEnvironment}
              setActiveStep={handleChangeStep}
              setDatabase={provisionerFormActions.setDatabase}
          />
          <Addons
              addons={applicationAppState.get("addons")?applicationAppState.get("addons"):fromJS([])}
              addonsOptions={applicationAppState.getIn(["steps","addons"])}
              applicationAppState={applicationAppState}
              baseAppState={baseAppState}
              buildbotAppState={buildbotAppState}
              cloudProviderAppState={cloudProviderAppState}
              mysqlAppState={mysqlAppState}
              nginxAppState={nginxAppState}
              plainHtmlAppState={plainHtmlAppState}
              projectNameAppState={projectNameAppState}
              removeAddons={provisionerFormActions.removeAddons}
              repositoryAppState={repositoryAppState}
              requestPostUserProject={provisionerFormActions.requestPostUserProject}
              setActiveStep={handleChangeStep}
              setAddons={provisionerFormActions.setAddons}
              springAppState={springAppState}
              userAppState={userAppState}
              yiiAppState={yiiAppState}
          />
        </SwipeableViews>

      {/* <Notification
          message={applicationAppState.get("notification")}
          setNotification={applicationActions.setNotification}
      /> */}

  );
};

Steps.propTypes = {
  // applicationActions: PropTypes.object.isRequired,
  applicationAppState: PropTypes.object.isRequired,
  baseAppState: PropTypes.object.isRequired,
  buildbotAppState: PropTypes.object.isRequired,
  cloudProviderAppState: PropTypes.object.isRequired,
  environments: PropTypes.array.isRequired,
  mysqlAppState: PropTypes.object.isRequired,
  nginxAppState: PropTypes.object.isRequired,
  plainHtmlAppState: PropTypes.object.isRequired,
  projectNameAppState: PropTypes.object.isRequired,
  provisionerFormActions: PropTypes.object.isRequired,
  repositoryAppState: PropTypes.object.isRequired,
  rolesActions: PropTypes.object.isRequired,
  setProjectName: PropTypes.func.isRequired,
  springAppState: PropTypes.object.isRequired,
  userAppState: PropTypes.object.isRequired,
  yiiAppState: PropTypes.object.isRequired
};

export default Steps;
<|endoftext|>


<commit_before>//@flow
import ContentLoadingView from './routing/ContentLoadingView';
import WindowService from './WindowService';

// storing active url to get back to it while canceling module leave
let previousUrl;
let activeUrl;
let shouldCheckUrl = true;

const originalCheckUrl = Backbone.history.checkUrl;
Backbone.history.checkUrl = () => {
    previousUrl = activeUrl;
    activeUrl = window.location.hash;

    if (shouldCheckUrl) {
        originalCheckUrl.apply(this, arguments);
    }
    shouldCheckUrl = true;
};

export default {
    initialize(options) {
        Object.assign(this, Backbone.Events);
        this.defaultUrl = options.defaultUrl;
        options.modules.forEach(config => {
            const controller = {};

            Object.values(config.routes).forEach(callbackName => {
                controller[callbackName] = (...theArgs) => {
                    this.__onModuleLoaded(callbackName, theArgs, config, config.module);
                };
            });

            new Marionette.AppRouter({
                controller,
                appRoutes: config.routes
            });
        });

        new (Marionette.AppRouter.extend({
            routes: {
                '': 'defaultRoute'
            },
            defaultRoute: () => this.navigateToUrl(this.defaultUrl, { replace: true })
        }))();

        Backbone.history.start();
        Backbone.history.checkUrl();

        window.addEventListener('beforeunload', e => {
            this.trigger('module:leave', {
                page: this.activeModule ? this.activeModule.moduleId : null
            });
            const canLeave = this.activeModule ? this.activeModule.leave(true) : true;

            if (canLeave !== true) {
                // We need just to return smth to show default drowser leaving alert
                (e || window.event).returnValue = '42';
                return '42';
            }
        });
    },

    canNavigateBack() {
        return previousUrl !== undefined;
    },

    navigateBack() {
        Backbone.history.history.back();
    },

    // options: replace (history), trigger (routing)
    navigateToUrl(url, options = {}) {
        let newUrl = url;

        if (options.trigger === undefined) {
            options.trigger = true;
        }

        shouldCheckUrl = options.trigger || activeUrl === url;

        if (!shouldCheckUrl) {
            newUrl = this.__getUpdatedUrl(url);
            if (url !== newUrl) {
                shouldCheckUrl = true;
            }
        }

        Backbone.history.navigate(newUrl, options);
    },

    getPreviousUrl() {
        return previousUrl;
    },

    refresh() {
        Backbone.history.fragment = null;
        this.navigateToUrl(activeUrl);
    },

    setDefaultUrl(newDefaultUrl) {
        this.defaultUrl = newDefaultUrl;
    },

    getRoutHandlers(url = '') {
        const urlParts = url.split('&nxt').splice(1);
        const matchingUrls = [];

        return (Backbone.history.handlers.filter(handler => urlParts.some(part => handler.route.test(part) && matchingUrls.push(part))) || []).map((h, i) => ({
            callback: h.callback,
            route: matchingUrls[i],
            routeRegExp: h.route
        }));
    },

    async __onModuleLoaded(callbackName, routingArgs, config, Module) {
        WindowService.closePopup();
        this.loadingContext = {
            config,
            leavingPromise: null,
            loaded: false
        };

        const customModuleRegion = this.__tryGetSubmoduleRegion(config);

        if (!this.activeModule) {
            this.__showViewPlaceholder();
        } else {
            const isLeaved = await this.__tryLeaveActiveModule(!!customModuleRegion);
            if (!isLeaved) {
                return;
            }
        }

        // reject race condition
        if (this.loadingContext === null || this.loadingContext.config.module !== config.module) {
            return;
        }

        this.loadingContext.loaded = true;
        // reset loading region
        window.app
            .getView()
            .getRegion('contentLoadingRegion')
            .reset();

        if (this.activeModule) {
            this.activeModule.view.setModuleLoading(false);
        }

        const movingOut = this.activeModule && this.activeModule.options.config.module !== config.module;

        let componentQuery;

        const lastArg = _.last(_.compact(routingArgs));
        const index = routingArgs.indexOf(lastArg);

        if (lastArg) {
            componentQuery = lastArg.split('@');

            if (componentQuery && componentQuery.length > 1) {
                routingArgs[index] = componentQuery[0];
            }
        }

        // destroy active module
        if (this.activeModule && movingOut && !customModuleRegion) {
            this.activeModule.destroy();
        }

        let activeSubModule = null;

        if (!this.activeModule || movingOut || customModuleRegion) {
            if (customModuleRegion) {
                activeSubModule = new Module({
                    config,
                    region: customModuleRegion
                });
            } else {
                this.activeModule = new Module({
                    config,
                    region: window.app.getView().getRegion('contentRegion')
                });
            }
        }
        this.trigger('module:loaded', config, callbackName, routingArgs); //args like in Backbone.on('route')

        if (activeSubModule) {
            if (activeSubModule.onRoute) {
                activeSubModule.routerAction = callbackName;
                await activeSubModule.onRoute.apply(activeSubModule, routingArgs);
            }
        }

        // navigate to new module
        this.loadingContext = null;
        if (this.activeModule.onRoute) {
            this.activeModule.routerAction = callbackName;
            const continueHandling = await this.activeModule.onRoute.apply(this.activeModule, routingArgs);
            if (continueHandling === false) {
                return;
            }
        }

        if (!this.__isCurrentModuleSplit() || activeSubModule) {
            try {
                if (activeSubModule) {
                    this.__callRoutingActionForActiveSubModule(callbackName, routingArgs, activeSubModule);
                } else {
                    this.__callRoutingActionForActiveModule(callbackName, routingArgs);
                }
            } catch (e) {
                Core.utils.helpers.throwError(`Failed to find callback method \`${callbackName}\` for the module \`${config.id}` || `${config.module}\`.`);
            }
        } else {
            this.__invalidateSubModules(this.activeModule.moduleRegion.currentView.regionModulesMap);
        }

        this.__setupComponentQuery(componentQuery);
    },

    __showViewPlaceholder() {
        window.app
            .getView()
            .getRegion('contentLoadingRegion')
            .show(new ContentLoadingView());
    },

    async __tryLeaveActiveModule(subModulePresented) {
        const canLeave = await this.activeModule.leave();

        if (!canLeave && this.getPreviousUrl()) {
            // getting back to last url
            this.navigateToUrl(this.getPreviousUrl(), { replace: true, trigger: false });
            return false;
        }
        if (!subModulePresented) {
            //do not trigger events and cancel requests for submodules
            this.trigger('module:leave', {
                page: this.activeModule ? this.activeModule.moduleId : null
            });
            //clear all promises of the previous module
            Core.services.PromiseService.cancelAll();
            if (!this.loadingContext.loaded) {
                this.activeModule.view.setModuleLoading(true);
            }
        }
        return true;
    },

    __tryGetSubmoduleRegion(config) {
        if (this.activeModule && this.activeModule.moduleRegion.currentView) {
            const map = this.activeModule.moduleRegion.currentView.regionModulesMap;

            if (map) {
                const match = map.find(pair => Object.values(config.navigationUrl).some(url => RegExp(pair.routeRegExp).test(url)));
                if (match) {
                    return match.region;
                }
            }
        }

        return null;
    },

    __callRoutingActionForActiveSubModule(callbackName, routingArgs, activeSubModule) {
        if (activeSubModule.routingActions && activeSubModule.routingActions[callbackName]) {
            const configuration = activeSubModule.routingActions[callbackName];

            configuration.routingAction = callbackName;

            activeSubModule.handleRouterEvent.call(activeSubModule, configuration, routingArgs);
        } else {
            const routingCallback = activeSubModule[callbackName];

            if (!routingCallback) {
                throw new Error();
            }
            routingCallback.apply(activeSubModule, routingArgs);
        }
    },

    __callRoutingActionForActiveModule(callbackName, routingArgs) {
        if (this.activeModule.routingActions && this.activeModule.routingActions[callbackName]) {
            const configuration = this.activeModule.routingActions[callbackName];

            configuration.routingAction = callbackName;

            this.activeModule.handleRouterEvent.call(this.activeModule, configuration, routingArgs);
        } else {
            const routingCallback = this.activeModule[callbackName];

            if (!routingCallback) {
                throw new Error();
            }
            routingCallback.apply(this.activeModule, routingArgs);
        }
    },

    __setupComponentQuery(componentQuery) {
        if (componentQuery && componentQuery.length > 1) {
            this.activeModule.componentQuery = componentQuery[1];
        } else {
            this.activeModule.componentQuery = null;
        }
    },

    __getUpdatedUrl(url = '') {
        const cleanUrl = url.replace('#', '');
        const prefix = cleanUrl.split('/')[0];
        const urlParts = window.location.hash.split('&nxt');
        const replaceIndex = urlParts.findIndex(part => part.includes(prefix));

        if (replaceIndex !== -1) {
            urlParts.splice(replaceIndex, 1, cleanUrl);

            return urlParts.join('&nxt');
        }

        return url;
    },

    __isCurrentModuleSplit() {
        return activeUrl.startsWith('#custom');
    },

    __invalidateSubModules(regionModulesMap) {
        regionModulesMap.forEach(module => {
            const cleanUrl = module.pair.route.replace('#', '');
            const prefix = cleanUrl.split('/')[0];
            const urlParts = activeUrl.split('&nxt');
            const replaceIndex = urlParts.findIndex(part => part.includes(prefix));

            if (replaceIndex !== -1 && urlParts[replaceIndex] !== window.location.hash.replace('#', '').split('&nxt')[replaceIndex]) {
                setTimeout(() => module.pair.callback(module.pair.route));
            }
        });
    }
};
<commit_msg>Fix first URL appear, fix multiple reload on simple modules.<commit_after>//@flow
import ContentLoadingView from './routing/ContentLoadingView';
import WindowService from './WindowService';

// storing active url to get back to it while canceling module leave
let previousUrl;
let activeUrl;
let shouldCheckUrl = true;

const originalCheckUrl = Backbone.history.checkUrl;
Backbone.history.checkUrl = () => {
    previousUrl = activeUrl;
    activeUrl = window.location.hash;

    if (shouldCheckUrl) {
        originalCheckUrl.apply(this, arguments);
    }
    shouldCheckUrl = true;
};

export default {
    initialize(options) {
        Object.assign(this, Backbone.Events);
        this.defaultUrl = options.defaultUrl;
        options.modules.forEach(config => {
            const controller = {};

            Object.values(config.routes).forEach(callbackName => {
                controller[callbackName] = (...theArgs) => {
                    this.__onModuleLoaded(callbackName, theArgs, config, config.module);
                };
            });

            new Marionette.AppRouter({
                controller,
                appRoutes: config.routes
            });
        });

        new (Marionette.AppRouter.extend({
            routes: {
                '': 'defaultRoute'
            },
            defaultRoute: () => this.navigateToUrl(this.defaultUrl, { replace: true })
        }))();

        Backbone.history.start();
        Backbone.history.checkUrl();

        window.addEventListener('beforeunload', e => {
            this.trigger('module:leave', {
                page: this.activeModule ? this.activeModule.moduleId : null
            });
            const canLeave = this.activeModule ? this.activeModule.leave(true) : true;

            if (canLeave !== true) {
                // We need just to return smth to show default drowser leaving alert
                (e || window.event).returnValue = '42';
                return '42';
            }
        });
    },

    canNavigateBack() {
        return previousUrl !== undefined;
    },

    navigateBack() {
        Backbone.history.history.back();
    },

    // options: replace (history), trigger (routing)
    navigateToUrl(url, options = {}) {
        let newUrl = url;

        if (options.trigger === undefined) {
            options.trigger = true;
        }

        shouldCheckUrl = options.trigger || activeUrl === url;

        if (!shouldCheckUrl) {
            newUrl = this.__getUpdatedUrl(url);
            if (url !== newUrl) {
                shouldCheckUrl = true;
            }
        }

        Backbone.history.navigate(newUrl, options);
    },

    getPreviousUrl() {
        return previousUrl;
    },

    refresh() {
        Backbone.history.fragment = null;
        this.navigateToUrl(activeUrl);
    },

    setDefaultUrl(newDefaultUrl) {
        this.defaultUrl = newDefaultUrl;
    },

    getRoutHandlers(url = '') {
        const urlParts = url.split('&nxt').splice(1);
        const matchingUrls = [];

        return (Backbone.history.handlers.filter(handler => urlParts.some(part => handler.route.test(part) && matchingUrls.push(part))) || []).map((h, i) => ({
            callback: h.callback,
            route: matchingUrls[i],
            routeRegExp: h.route
        }));
    },

    async __onModuleLoaded(callbackName, routingArgs, config, Module) {
        WindowService.closePopup();
        this.loadingContext = {
            config,
            leavingPromise: null,
            loaded: false
        };

        const customModuleRegion = this.__tryGetSubmoduleRegion(config);

        if (!this.activeModule) {
            this.__showViewPlaceholder();
        } else {
            const isLeaved = await this.__tryLeaveActiveModule(!!customModuleRegion);
            if (!isLeaved) {
                return;
            }
        }

        // reject race condition
        if (this.loadingContext === null || this.loadingContext.config.module !== config.module) {
            return;
        }

        this.loadingContext.loaded = true;
        // reset loading region
        window.app
            .getView()
            .getRegion('contentLoadingRegion')
            .reset();

        if (this.activeModule) {
            this.activeModule.view.setModuleLoading(false);
        }

        const movingOut = this.activeModule && this.activeModule.options.config.module !== config.module;

        let componentQuery;

        const lastArg = _.last(_.compact(routingArgs));
        const index = routingArgs.indexOf(lastArg);

        if (lastArg) {
            componentQuery = lastArg.split('@');

            if (componentQuery && componentQuery.length > 1) {
                routingArgs[index] = componentQuery[0];
            }
        }

        // destroy active module
        if (this.activeModule && movingOut && !customModuleRegion) {
            this.activeModule.destroy();
        }

        let activeSubModule = null;

        if (!this.activeModule || movingOut || customModuleRegion) {
            if (customModuleRegion) {
                activeSubModule = new Module({
                    config,
                    region: customModuleRegion
                });
            } else {
                this.activeModule = new Module({
                    config,
                    region: window.app.getView().getRegion('contentRegion')
                });
            }
        }
        this.trigger('module:loaded', config, callbackName, routingArgs); //args like in Backbone.on('route')

        if (activeSubModule) {
            if (activeSubModule.onRoute) {
                activeSubModule.routerAction = callbackName;
                await activeSubModule.onRoute.apply(activeSubModule, routingArgs);
            }
        }

        // navigate to new module
        this.loadingContext = null;
        if (this.activeModule.onRoute) {
            this.activeModule.routerAction = callbackName;
            const continueHandling = await this.activeModule.onRoute.apply(this.activeModule, routingArgs);
            if (continueHandling === false) {
                return;
            }
        }

        if (!this.__isCurrentModuleSplit() || activeSubModule) {
            try {
                if (activeSubModule) {
                    this.__callRoutingActionForActiveSubModule(callbackName, routingArgs, activeSubModule);
                } else {
                    this.__callRoutingActionForActiveModule(callbackName, routingArgs);
                }
            } catch (e) {
                Core.utils.helpers.throwError(`Failed to find callback method \`${callbackName}\` for the module \`${config.id}` || `${config.module}\`.`);
            }
        } else {
            this.__invalidateSubModules(this.activeModule.moduleRegion.currentView.regionModulesMap);
        }

        this.__setupComponentQuery(componentQuery);
    },

    __showViewPlaceholder() {
        window.app
            .getView()
            .getRegion('contentLoadingRegion')
            .show(new ContentLoadingView());
    },

    async __tryLeaveActiveModule(subModulePresented) {
        const canLeave = await this.activeModule.leave();

        if (!canLeave && this.getPreviousUrl()) {
            // getting back to last url
            this.navigateToUrl(this.getPreviousUrl(), { replace: true, trigger: false });
            return false;
        }
        if (!subModulePresented) {
            //do not trigger events and cancel requests for submodules
            this.trigger('module:leave', {
                page: this.activeModule ? this.activeModule.moduleId : null
            });
            //clear all promises of the previous module
            Core.services.PromiseService.cancelAll();
            if (!this.loadingContext.loaded) {
                this.activeModule.view.setModuleLoading(true);
            }
        }
        return true;
    },

    __tryGetSubmoduleRegion(config) {
        if (this.activeModule && this.activeModule.moduleRegion.currentView) {
            const map = this.activeModule.moduleRegion.currentView.regionModulesMap;

            if (map) {
                const match = map.find(pair => Object.values(config.navigationUrl).some(url => RegExp(pair.routeRegExp).test(url)));
                if (match) {
                    return match.region;
                }
            }
        }

        return null;
    },

    __callRoutingActionForActiveSubModule(callbackName, routingArgs, activeSubModule) {
        if (activeSubModule.routingActions && activeSubModule.routingActions[callbackName]) {
            const configuration = activeSubModule.routingActions[callbackName];

            configuration.routingAction = callbackName;

            activeSubModule.handleRouterEvent.call(activeSubModule, configuration, routingArgs);
        } else {
            const routingCallback = activeSubModule[callbackName];

            if (!routingCallback) {
                throw new Error();
            }
            routingCallback.apply(activeSubModule, routingArgs);
        }
    },

    __callRoutingActionForActiveModule(callbackName, routingArgs) {
        if (this.activeModule.routingActions && this.activeModule.routingActions[callbackName]) {
            const configuration = this.activeModule.routingActions[callbackName];

            configuration.routingAction = callbackName;

            this.activeModule.handleRouterEvent.call(this.activeModule, configuration, routingArgs);
        } else {
            const routingCallback = this.activeModule[callbackName];

            if (!routingCallback) {
                throw new Error();
            }
            routingCallback.apply(this.activeModule, routingArgs);
        }
    },

    __setupComponentQuery(componentQuery) {
        if (componentQuery && componentQuery.length > 1) {
            this.activeModule.componentQuery = componentQuery[1];
        } else {
            this.activeModule.componentQuery = null;
        }
    },

    __getUpdatedUrl(url = '') {
        const cleanUrl = url.replace('#', '');
        const prefix = cleanUrl.split('/')[0];
        const urlParts = window.location.hash.split('&nxt');
        const replaceIndex = urlParts.findIndex(part => part.includes(prefix));

        if (replaceIndex !== -1 && urlParts.includes(part => part.includes('#custom'))) {
            urlParts.splice(replaceIndex, 1, cleanUrl);

            return urlParts.join('&nxt');
        }

        return url;
    },

    __isCurrentModuleSplit() {
        return activeUrl?.startsWith('#custom');
    },

    __invalidateSubModules(regionModulesMap) {
        regionModulesMap.forEach(module => {
            const cleanUrl = module.pair.route.replace('#', '');
            const prefix = cleanUrl.split('/')[0];
            const urlParts = activeUrl.split('&nxt');
            const replaceIndex = urlParts.findIndex(part => part.includes(prefix));

            if (replaceIndex !== -1 && urlParts[replaceIndex] !== window.location.hash.replace('#', '').split('&nxt')[replaceIndex]) {
                setTimeout(() => module.pair.callback(module.pair.route));
            }
        });
    }
};
<|endoftext|>


<commit_before>define(['lazoModel', 'utils/modelLoader', 'utils/module', 'async', 'underscore', 'utils/dataschema-json'], function (LazoModel, modelLoader, module, async, _, SchemaJSON) {

    'use strict';

    var UtilModel = {

        process: function (modelName, options, type, child) {
            var modelInstances = options.ctx._rootCtx.modelInstances,
                modelList = options.ctx._rootCtx.modelList,
                gid = LazoModel._getGlobalId(modelName, options.params),
                path = 'models/' + modelName + '/' + type;

            function checkProcessing() {
                if (modelInstances[gid] === null) {
                    return;
                }
                else if (modelInstances[gid].processing) {
                    setTimeout(checkProcessing, 0);
                }
                else if (options.success) {
                    _.defer(options.success, modelInstances[gid]);
                }
            }

            options.error = options.error || function (err) {
                throw err;
            }; // user did not define error bubble up 500

            if (modelInstances[gid]) {
                checkProcessing();
                return;
            }

            modelInstances[gid] = {};
            modelInstances[gid].processing = true;
            var _fetch = function (Model, _default) {
                var data = child ? child.data : (modelList[gid] && modelList[gid].data ? modelList[gid].data : null);
                var m = new Model(data, {name: modelName, ctx: options.ctx, params: options.params, parse: data !== null});

                var registerModel = function (m, options, gid) {
                                        // add model meta info to modelList
                                        var modelMeta = {
                                            data: m._resp,
                                            cid: m.cid,
                                            id: m.id,
                                            name: m.name,
                                            params: options.params
                                        };

                                        if (type === 'collection') {
                                            modelMeta.idMap = [];
                                            m.each(function (model) {
                                                modelMeta.idMap.push({cid: model.cid, id: model.id});
                                            });
                                        }

                                        m.ctx._rootCtx.modelList[gid] = modelMeta;
                                        m.ctx._rootCtx.modelInstances[gid] = m;

                                        if (m.modelsSchema) {
                                            var tasks = [],
                                                success = options.success;

                                            _.each(m.modelsSchema, function (modelSchemaDef) {

                                                var submodeldata = SchemaJSON.apply({resultListLocator: modelSchemaDef.locator}, modelMeta.data),
                                                    subtype = submodeldata && submodeldata.results
                                                        ? (_.isArray(submodeldata.results) ? 'collection' : 'model') : 'model';

                                                tasks.push(function (cb) {
                                                    options.success = function () {cb();};
                                                    UtilModel.process(modelSchemaDef.name, options, subtype,
                                                        {
                                                            parentModel: m,
                                                            data: submodeldata.results,
                                                            schema: modelSchemaDef
                                                        });
                                                });

                                            });

                                            async.parallel(tasks, function (err, results) {
                                                if (success) {
                                                    return success(m);
                                                }
                                            });
                                        }
                                        else {
                                            if (options.success) {
                                                return options.success(m);
                                            }
                                        }
                                    };

                m._default = _default;
                if (options.params && type === 'model') {
                    m.id = _.result(options.params, m.idAttribute);
                }
                if (!_default) {
                    module.addPath(path, options.ctx);
                }

                if (child && child.parentModel) {
                    m.lazoParent = child.parentModel;
                    child.parentModel.lazoChildren = child.parentModel.lazoChildren || {};
                    child.parentModel.lazoChildren[modelName] = m;

                    if (child.schema && child.schema.prop) {
                        child.parentModel[child.schema.prop] = m;

                        child.parentModel._childNames = child.parentModel._childNames || [];
                        child.parentModel._childNames.push(child.schema.prop);
                    }
                }

                // if data in list don't make tunnel call
                if (modelList[gid]) {
                    m.cid = modelList[gid].cid;
                    m._default = _default;
                    if (modelList[gid].idMap) {
                        _.each(modelList[gid].idMap, function (elem) {
                            var modelItem = m.get(elem.id);
                            if (modelItem) {
                                modelItem.cid = elem.cid;
                            }
                        });
                    }

                    modelInstances[gid] = m;
                    if (options.success) {
                        options.success(m);
                    }
                    return;
                }
                else if (options.fetch === false || child) {
                    if (child && child.data) {
                        m._resp = child.data;
                    }
                    registerModel(m, options, gid);
                }
                else {
                    m.fetch({
                        success: function (m) {
                            registerModel(m, options, gid);
                        },
                        error: function (model, response, opts) {
                            modelInstances[gid] = null;
                            LAZO.logger.debug('[common.utils.model.process] Error loading model %s', modelName);
                            if (options.error) { // TODO: error handling
                                return options.error(model, response, opts);
                            }
                        }
                    });
                }

            };

            modelLoader(modelName, type, _fetch);
        },

        create: function (name, attributes, options, type) {
            var _create = function (Model, _default) {

                var modelInstances = options.ctx._rootCtx.modelInstances,
                    gid = LazoModel._getGlobalId(name, options.params);

                if (modelInstances[gid]) {
                    options.success(modelInstances[gid]);
                    return;
                }

                var m = new Model((type === 'model' ? attributes : null), {name: name, ctx: options.ctx, params: options.params, parse: true});
                m._default = _default;
                var modelMeta = {
                    data: (type === 'model' ? attributes : null),
                    cid: m.cid,
                    id: m.id,
                    name: m.name,
                    params: options.params
                };
                m.ctx._rootCtx.modelList[gid] = modelMeta;
                m.ctx._rootCtx.modelInstances[gid] = m;

                if (type === 'model') {

                    if (options.persist == false) {
                        options.success(m);
                    }
                    else {
                        m.save({}, {
                            success: function (model) {
                                if (options.success) {
                                    options.success(model);
                                }
                            },
                            error: function (model, xhr, opts) {
                                LAZO.logger.warn('[common.utils.model.createModel] Error creating model %s', name);
                                if (options.error) {
                                    return options.error(model, xhr, opts);
                                }
                            }
                        });
                    }
                }
                else {
                    if (!_.isArray(attributes)) {
                        if (options.error) {
                            options.error(m, 'attributes must be an array', options);
                        }
                        return;
                    }

                    var modelOptions = {};
                    if (options && options.persist) {
                        modelOptions.persist = options.persist;
                    }

                    _.each(attributes, function (modelData) {
                        m.create(modelData, modelOptions);
                    });

                    if (options.success) {
                        options.success(m);
                    }
                }
            };

            modelLoader(name, type, _create);
        }

    };

    return UtilModel;
});
<commit_msg>check if persist is undefined<commit_after>define(['lazoModel', 'utils/modelLoader', 'utils/module', 'async', 'underscore', 'utils/dataschema-json'], function (LazoModel, modelLoader, module, async, _, SchemaJSON) {

    'use strict';

    var UtilModel = {

        process: function (modelName, options, type, child) {
            var modelInstances = options.ctx._rootCtx.modelInstances,
                modelList = options.ctx._rootCtx.modelList,
                gid = LazoModel._getGlobalId(modelName, options.params),
                path = 'models/' + modelName + '/' + type;

            function checkProcessing() {
                if (modelInstances[gid] === null) {
                    return;
                }
                else if (modelInstances[gid].processing) {
                    setTimeout(checkProcessing, 0);
                }
                else if (options.success) {
                    _.defer(options.success, modelInstances[gid]);
                }
            }

            options.error = options.error || function (err) {
                throw err;
            }; // user did not define error bubble up 500

            if (modelInstances[gid]) {
                checkProcessing();
                return;
            }

            modelInstances[gid] = {};
            modelInstances[gid].processing = true;
            var _fetch = function (Model, _default) {
                var data = child ? child.data : (modelList[gid] && modelList[gid].data ? modelList[gid].data : null);
                var m = new Model(data, {name: modelName, ctx: options.ctx, params: options.params, parse: data !== null});

                var registerModel = function (m, options, gid) {
                                        // add model meta info to modelList
                                        var modelMeta = {
                                            data: m._resp,
                                            cid: m.cid,
                                            id: m.id,
                                            name: m.name,
                                            params: options.params
                                        };

                                        if (type === 'collection') {
                                            modelMeta.idMap = [];
                                            m.each(function (model) {
                                                modelMeta.idMap.push({cid: model.cid, id: model.id});
                                            });
                                        }

                                        m.ctx._rootCtx.modelList[gid] = modelMeta;
                                        m.ctx._rootCtx.modelInstances[gid] = m;

                                        if (m.modelsSchema) {
                                            var tasks = [],
                                                success = options.success;

                                            _.each(m.modelsSchema, function (modelSchemaDef) {

                                                var submodeldata = SchemaJSON.apply({resultListLocator: modelSchemaDef.locator}, modelMeta.data),
                                                    subtype = submodeldata && submodeldata.results
                                                        ? (_.isArray(submodeldata.results) ? 'collection' : 'model') : 'model';

                                                tasks.push(function (cb) {
                                                    options.success = function () {cb();};
                                                    UtilModel.process(modelSchemaDef.name, options, subtype,
                                                        {
                                                            parentModel: m,
                                                            data: submodeldata.results,
                                                            schema: modelSchemaDef
                                                        });
                                                });

                                            });

                                            async.parallel(tasks, function (err, results) {
                                                if (success) {
                                                    return success(m);
                                                }
                                            });
                                        }
                                        else {
                                            if (options.success) {
                                                return options.success(m);
                                            }
                                        }
                                    };

                m._default = _default;
                if (options.params && type === 'model') {
                    m.id = _.result(options.params, m.idAttribute);
                }
                if (!_default) {
                    module.addPath(path, options.ctx);
                }

                if (child && child.parentModel) {
                    m.lazoParent = child.parentModel;
                    child.parentModel.lazoChildren = child.parentModel.lazoChildren || {};
                    child.parentModel.lazoChildren[modelName] = m;

                    if (child.schema && child.schema.prop) {
                        child.parentModel[child.schema.prop] = m;

                        child.parentModel._childNames = child.parentModel._childNames || [];
                        child.parentModel._childNames.push(child.schema.prop);
                    }
                }

                // if data in list don't make tunnel call
                if (modelList[gid]) {
                    m.cid = modelList[gid].cid;
                    m._default = _default;
                    if (modelList[gid].idMap) {
                        _.each(modelList[gid].idMap, function (elem) {
                            var modelItem = m.get(elem.id);
                            if (modelItem) {
                                modelItem.cid = elem.cid;
                            }
                        });
                    }

                    modelInstances[gid] = m;
                    if (options.success) {
                        options.success(m);
                    }
                    return;
                }
                else if (options.fetch === false || child) {
                    if (child && child.data) {
                        m._resp = child.data;
                    }
                    registerModel(m, options, gid);
                }
                else {
                    m.fetch({
                        success: function (m) {
                            registerModel(m, options, gid);
                        },
                        error: function (model, response, opts) {
                            modelInstances[gid] = null;
                            LAZO.logger.debug('[common.utils.model.process] Error loading model %s', modelName);
                            if (options.error) { // TODO: error handling
                                return options.error(model, response, opts);
                            }
                        }
                    });
                }

            };

            modelLoader(modelName, type, _fetch);
        },

        create: function (name, attributes, options, type) {
            var _create = function (Model, _default) {

                var modelInstances = options.ctx._rootCtx.modelInstances,
                    gid = LazoModel._getGlobalId(name, options.params);

                if (modelInstances[gid]) {
                    options.success(modelInstances[gid]);
                    return;
                }

                var m = new Model((type === 'model' ? attributes : null), {name: name, ctx: options.ctx, params: options.params, parse: true});
                m._default = _default;
                var modelMeta = {
                    data: (type === 'model' ? attributes : null),
                    cid: m.cid,
                    id: m.id,
                    name: m.name,
                    params: options.params
                };
                m.ctx._rootCtx.modelList[gid] = modelMeta;
                m.ctx._rootCtx.modelInstances[gid] = m;

                if (type === 'model') {

                    if (options.persist == false) {
                        options.success(m);
                    }
                    else {
                        m.save({}, {
                            success: function (model) {
                                if (options.success) {
                                    options.success(model);
                                }
                            },
                            error: function (model, xhr, opts) {
                                LAZO.logger.warn('[common.utils.model.createModel] Error creating model %s', name);
                                if (options.error) {
                                    return options.error(model, xhr, opts);
                                }
                            }
                        });
                    }
                }
                else {
                    if (!_.isArray(attributes)) {
                        if (options.error) {
                            options.error(m, 'attributes must be an array', options);
                        }
                        return;
                    }

                    var modelOptions = {};
                    if (options && options.persist !== void 0) {
                        modelOptions.persist = options.persist;
                    }

                    _.each(attributes, function (modelData) {
                        m.create(modelData, modelOptions);
                    });

                    if (options.success) {
                        options.success(m);
                    }
                }
            };

            modelLoader(name, type, _create);
        }

    };

    return UtilModel;
});
<|endoftext|>


<commit_before>export default {
	data() {
		return {
			shown: false
		};
	},
	methods: {
		toggle() {
			this.shown = !this.shown;
		}
	}
};
<commit_msg>bugfix search-box-document click<commit_after>

export default {
	data() {
		return {
			shown: false
		};
	},
	mounted() {
		document.addEventListener('click', this.hide, true);
	},
	destroyed() {
		document.removeEventListener('click', this.hide, true);
	},
	methods: {

		hide() {
			this.shown = false;
		},
		toggle() {
			this.shown = !this.shown;
		}
	}
};<|endoftext|>