<commit_before>/*
 * Mentions Input
 * Version 1.0.2
 * Written by: Kenneth Auchenberg (Podio)
 *
 * Using underscore.js
 *
 * License: MIT License - http://www.opensource.org/licenses/mit-license.php
 */

(function ($, _, undefined) {

  // Settings
  var KEY = { BACKSPACE : 8, TAB : 9, RETURN : 13, ESC : 27, LEFT : 37, UP : 38, RIGHT : 39, DOWN : 40, COMMA : 188, SPACE : 32, HOME : 36, END : 35 }; // Keys "enum"
  var defaultSettings = {
    triggerChar   : '@',
    onDataRequest : $.noop,
    minChars      : 2,
    showAvatars   : true,
    elastic       : true,
    display       : 'name',
    onCaret       : true,
    classes       : {
      autoCompleteItemActive : "active"
    },
    templates     : {
      //Element to wrap the textarea, and soon to be created div + hidden inputs
      wrapper                    : _.template('

'),

      // Autocomplete elements
      autocompleteList           : _.template('

'),
      autocompleteListItem       : _.template('<li data-ref-id="<%= id %>" data-ref-type="<%= type %>" data-display="<%= display %>"><%= content %>
'),
      autocompleteListItemAvatar : _.template('<img  src="<%= avatar %>" />'),
      autocompleteListItemIcon   : _.template('<div class="icon <%= icon %>">
'),

      //
 layered under the <textarea>
      mentionsOverlay            : _.template('

'),

      // Syntax for .mentionsInput('val') which will probably be sent to the server
      mentionItemSyntax          : _.template('<%= triggerChar %>[<%= value %>](<%= type %>:<%= id %>)'),

      // Structure for highlighting the text in the
      mentionItemHighlight       : _.template('<strong class="<%= type %>"><%= value %>')
    }
  };

  var utils = {
    htmlEncode       : function (str) {
      return _.escape(str);
    },
    highlightTerm    : function (value, term) {
      if (!term && !term.length) {
        return value;
      }
      return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "$1");
    },
    setCaratPosition : function (domNode, caretPos) {
      if (domNode.createTextRange) {
        var range = domNode.createTextRange();
        range.move('character', caretPos);
        range.select();
      } else {
        if (domNode.selectionStart) {
          domNode.focus();
          domNode.setSelectionRange(caretPos, caretPos);
        } else {
          domNode.focus();
        }
      }
    },

    getCaratPosition : function($el){
    // This is taken straight from live (as of Sep 2012) GitHub code. The
    // technique is known around the web. Just google it. Github's is quite
    // succint though. NOTE: relies on selectionEnd, which as far as IE is concerned,
    // it'll only work on 9+. Good news is nothing will happen if the browser
    // doesn't support it.
	  var a, b, c, d, e, f, g, h, i, j, k;
      if (!(i = $el[0])) return;
      if (!$(i).is("textarea")) return;
      if (i.selectionEnd == null) return;
      g = {
        position: "absolute",
        overflow: "auto",
        whiteSpace: "pre-wrap",
        wordWrap: "break-word",
        boxSizing: "content-box",
        top: 0,
        left: -9999
      }, h = ["boxSizing", "fontFamily", "fontSize", "fontStyle", "fontVariant", "fontWeight", "height", "letterSpacing", "lineHeight", "paddingBottom", "paddingLeft", "paddingRight", "paddingTop", "textDecoration", "textIndent", "textTransform", "width", "word-spacing"];
      for (j = 0, k = h.length; j < k; j++) e = h[j], g[e] = $(i).css(e);
      return c = document.createElement("div"), $(c).css(g), $(i).after(c), b = document.createTextNode(i.value.substring(0, i.selectionEnd)), a = document.createTextNode(i.value.substring(i.selectionEnd)), d = document.createElement("span"), d.innerHTML = " ", c.appendChild(b), c.appendChild(d), c.appendChild(a), c.scrollTop = i.scrollTop, f = $(d).position(), $(c).remove(), f
    },

    rtrim: function(string) {
      return string.replace(/\s+$/,"");
    }
  };

  var MentionsInput = function (settings) {

    var mentionsCollection = [];
    var autocompleteItemCollection = {};
    var inputBuffer = [];
    var currentDataQuery = ''; //https://github.com/podio/jquery-mentions-input/pull/44
    var domInput, elmInputBox, elmInputWrapper, elmAutocompleteList, elmWrapperBox,
        elmMentionsOverlay, elmActiveAutoCompleteItem, currentTriggerChar;

    settings = $.extend(true, {}, defaultSettings, settings );

    function initTextarea() {
      elmInputBox = $(domInput);

      if (elmInputBox.attr('data-mentions-input') == 'true') {
        return;
      }

      elmInputWrapper = elmInputBox.parent();
      elmWrapperBox = $(settings.templates.wrapper());
      elmInputBox.wrapAll(elmWrapperBox);
      elmWrapperBox = elmInputWrapper.find('> div');

      elmInputBox.attr('data-mentions-input', 'true');
      elmInputBox.bind('keydown', onInputBoxKeyDown);
      elmInputBox.bind('keypress', onInputBoxKeyPress);
      elmInputBox.bind('input', onInputBoxInput);
      elmInputBox.bind('click', onInputBoxClick);
      elmInputBox.bind('blur', onInputBoxBlur);

      // Elastic textareas, internal setting for the Dispora guys
      if( settings.elastic ) {
        elmInputBox.elastic();
      }

    }

    function initAutocomplete() {
      elmAutocompleteList = $(settings.templates.autocompleteList());
      elmAutocompleteList.appendTo(elmWrapperBox);
      elmAutocompleteList.delegate('li', 'mousedown', onAutoCompleteItemClick);
    }

    function initMentionsOverlay() {
      elmMentionsOverlay = $(settings.templates.mentionsOverlay());
      elmMentionsOverlay.prependTo(elmWrapperBox);
    }

    function updateValues() {
      var syntaxMessage = getInputBoxValue();

      _.each(mentionsCollection, function (mention) {
        var textSyntax = settings.templates.mentionItemSyntax(_.extend({}, mention, {value: utils.htmlEncode(mention.value)}));
        syntaxMessage = syntaxMessage.replace(mention.value, textSyntax);
      });

      var mentionText = utils.htmlEncode(syntaxMessage);

      _.each(mentionsCollection, function (mention) {
        var formattedMention = _.extend({}, mention, {value: utils.htmlEncode(mention.value)});
        var textSyntax = settings.templates.mentionItemSyntax(formattedMention);
        var textHighlight = settings.templates.mentionItemHighlight(formattedMention);

        mentionText = mentionText.replace(textSyntax, textHighlight);
      });

      mentionText = mentionText.replace(/\n/g, '
');
      mentionText = mentionText.replace(/ {2}/g, '  ');

      elmInputBox.data('messageText', syntaxMessage);
      elmInputBox.trigger('updated');
      elmMentionsOverlay.find('div').html(mentionText);
    }

    function resetBuffer() {
      inputBuffer = [];
    }

    function updateMentionsCollection() {
      var inputText = getInputBoxValue();

      mentionsCollection = _.reject(mentionsCollection, function (mention, index) {
        return !mention.value || inputText.indexOf(mention.value) == -1;
      });
      mentionsCollection = _.compact(mentionsCollection);
    }

    function addMention(mention) {

      var currentMessage = getInputBoxValue();

      // Using a regex to figure out positions
      var regex = new RegExp("\\" + currentTriggerChar + currentDataQuery, "gi");
      regex.exec(currentMessage);

      var startCaretPosition = regex.lastIndex - currentDataQuery.length - 1;
      var currentCaretPosition = regex.lastIndex;

      var start = currentMessage.substr(0, startCaretPosition);
      var end = currentMessage.substr(currentCaretPosition, currentMessage.length);
      var startEndIndex = (start + mention.value).length + 1;

      mentionsCollection.push(
        _.extend({}, mention, {triggerChar : currentTriggerChar})
      );

      // Cleaning before inserting the value, otherwise auto-complete would be triggered with "old" inputbuffer
      resetBuffer();
      currentDataQuery = '';
      hideAutoComplete();

      // Mentions & syntax message
      var updatedMessageText = start + mention.value + ' ' + end;
      elmInputBox.val(updatedMessageText);
      elmInputBox.trigger('mention');
      updateValues();

      // Set correct focus and selection
      elmInputBox.focus();
      utils.setCaratPosition(elmInputBox[0], startEndIndex);
    }

    function getInputBoxValue() {
      return $.trim(elmInputBox.val());
    }

    function onAutoCompleteItemClick(e) {
      var elmTarget = $(this);
      var mention = autocompleteItemCollection[elmTarget.attr('data-uid')];

      addMention(mention);

      return false;
    }

    function onInputBoxClick(e) {
      resetBuffer();
    }

    function onInputBoxBlur(e) {
      hideAutoComplete();
    }

    function checkTriggerChar(inputBuffer, triggerChar) {
      var triggerCharIndex = _.lastIndexOf(inputBuffer, triggerChar);
      if (triggerCharIndex > -1) {
        currentDataQuery = inputBuffer.slice(triggerCharIndex + 1).join('');
        _.defer(_.bind(doSearch, this, currentDataQuery, triggerChar));
      }
    }

    function onInputBoxInput(e) {
      updateValues();
      updateMentionsCollection();
      hideAutoComplete();

      if (_.isArray(settings.triggerChar)) {
        _.each(settings.triggerChar, function (triggerChar) {
          checkTriggerChar(inputBuffer, triggerChar);
        });
      } else {
        checkTriggerChar(inputBuffer, settings.triggerChar);
      }

    }

    function onInputBoxKeyPress(e) {
      if(e.keyCode !== KEY.BACKSPACE) {
        var typedValue = String.fromCharCode(e.which || e.keyCode);
        inputBuffer.push(typedValue);
      }
    }

    function onInputBoxKeyDown(e) {

      // This also matches HOME/END on OSX which is CMD+LEFT, CMD+RIGHT
      if (e.keyCode == KEY.LEFT || e.keyCode == KEY.RIGHT || e.keyCode == KEY.HOME || e.keyCode == KEY.END) {
        // Defer execution to ensure carat pos has changed after HOME/END keys
        _.defer(resetBuffer);

        // IE9 doesn't fire the oninput event when backspace or delete is pressed. This causes the highlighting
        // to stay on the screen whenever backspace is pressed after a highlighed word. This is simply a hack
        // to force updateValues() to fire when backspace/delete is pressed in IE9.
        if (navigator.userAgent.indexOf("MSIE 9") > -1) {
          _.defer(updateValues);
        }

        return;
      }

      if (e.keyCode == KEY.BACKSPACE) {
        inputBuffer = inputBuffer.slice(0, -1 + inputBuffer.length); // Can't use splice, not available in IE
        return;
      }

      if (!elmAutocompleteList.is(':visible')) {
        return true;
      }

      switch (e.keyCode) {
        case KEY.UP:
        case KEY.DOWN:
          var elmCurrentAutoCompleteItem = null;
          if (e.keyCode == KEY.DOWN) {
            if (elmActiveAutoCompleteItem && elmActiveAutoCompleteItem.length) {
              elmCurrentAutoCompleteItem = elmActiveAutoCompleteItem.next();
            } else {
              elmCurrentAutoCompleteItem = elmAutocompleteList.find('li').first();
            }
          } else {
            elmCurrentAutoCompleteItem = $(elmActiveAutoCompleteItem).prev();
          }

          if (elmCurrentAutoCompleteItem.length) {
            selectAutoCompleteItem(elmCurrentAutoCompleteItem);
          }

          return false;

        case KEY.RETURN:
        case KEY.TAB:
          if (elmActiveAutoCompleteItem && elmActiveAutoCompleteItem.length) {
            elmActiveAutoCompleteItem.trigger('mousedown');
            return false;
          }

          break;
      }

      return true;
    }

    function hideAutoComplete() {
      elmActiveAutoCompleteItem = null;
      elmAutocompleteList.empty().hide();
    }

    function selectAutoCompleteItem(elmItem) {
      elmItem.addClass(settings.classes.autoCompleteItemActive);
      elmItem.siblings().removeClass(settings.classes.autoCompleteItemActive);

      elmActiveAutoCompleteItem = elmItem;
    }

    function populateDropdown(query, results) {
      elmAutocompleteList.show();

      // Filter items that has already been mentioned
      var mentionValues = _.pluck(mentionsCollection, 'value');
      results = _.reject(results, function (item) {
        return _.include(mentionValues, item.name);
      });

      if (!results.length) {
        hideAutoComplete();
        return;
      }

      elmAutocompleteList.empty();
      var elmDropDownList = $("
").appendTo(elmAutocompleteList).hide();

      _.each(results, function (item, index) {
        var itemUid = _.uniqueId('mention_');

        autocompleteItemCollection[itemUid] = _.extend({}, item, {value: item.name});

        var elmListItem = $(settings.templates.autocompleteListItem({
          'id'      : utils.htmlEncode(item.id),
          'display' : utils.htmlEncode(item[settings.display]),
          'type'    : utils.htmlEncode(item.type),
          'content' : utils.highlightTerm(utils.htmlEncode((item.name)), query)
        })).attr('data-uid', itemUid);

        if (index === 0) {
          selectAutoCompleteItem(elmListItem);
        }

        if (settings.showAvatars) {
          var elmIcon;

          if (item.avatar) {
            elmIcon = $(settings.templates.autocompleteListItemAvatar({ avatar : item.avatar }));
          } else {
            elmIcon = $(settings.templates.autocompleteListItemIcon({ icon : item.icon }));
          }
          elmIcon.prependTo(elmListItem);
        }
        elmListItem = elmListItem.appendTo(elmDropDownList);
      });

      elmAutocompleteList.show();
      if (settings.onCaret) positionAutocomplete(elmAutocompleteList, elmInputBox);
      elmDropDownList.show();
    }

    function doSearch(query, triggerChar) {
      if (query && query.length && query.length >= settings.minChars) {

        var callback = function callback (responseData) {
          populateDropdown(query, responseData);
          currentTriggerChar = triggerChar;
        }

        settings.onDataRequest.call(this, 'search', query, triggerChar, callback);

      }
    }

    function positionAutocomplete(elmAutocompleteList, elmInputBox) {
      var position = utils.getCaratPosition(elmInputBox),
          lineHeight = parseInt(elmInputBox.css('line-height'), 10) || 18;

      elmAutocompleteList.css('width', '15em'); // Sort of a guess
      elmAutocompleteList.css('left', position.left);
      elmAutocompleteList.css('top', lineHeight + position.top);
    }

    function resetInput() {
      elmInputBox.val('');
      mentionsCollection = [];
      updateValues();
    }

    // Public methods
    return {
      init : function (domTarget) {

        domInput = domTarget;

        initTextarea();
        initAutocomplete();
        initMentionsOverlay();
        resetInput();

        if( settings.prefillMention ) {
          addMention( settings.prefillMention );
        }

      },

      val : function (callback) {
        if (!_.isFunction(callback)) {
          return;
        }

        var value = mentionsCollection.length ? elmInputBox.data('messageText') : getInputBoxValue();
        callback.call(this, value);
      },

      reset : function () {
        resetInput();
      },

      getMentions : function (callback) {
        if (!_.isFunction(callback)) {
          return;
        }

        callback.call(this, mentionsCollection);
      }
    };
  };

  $.fn.mentionsInput = function (method, settings) {

    var outerArguments = arguments;

    if (typeof method === 'object' || !method) {
      settings = $.extend(true, {}, defaultSettings, method);
    }

    return this.each(function () {
      var instance = $.data(this, 'mentionsInput') || $.data(this, 'mentionsInput', new MentionsInput(settings));

      if (_.isFunction(instance[method])) {
        return instance[method].apply(this, Array.prototype.slice.call(outerArguments, 1));

      } else if (typeof method === 'object' || !method) {
        return instance.init.call(this, this);

      } else {
        $.error('Method ' + method + ' does not exist');
      }

    });
  };

})(jQuery, _);<commit_msg>this display thing is confusing me.<commit_after>/*
 * Mentions Input
 * Version 1.0.2
 * Written by: Kenneth Auchenberg (Podio)
 *
 * Using underscore.js
 *
 * License: MIT License - http://www.opensource.org/licenses/mit-license.php
 */

(function ($, _, undefined) {

  // Settings
  var KEY = { BACKSPACE : 8, TAB : 9, RETURN : 13, ESC : 27, LEFT : 37, UP : 38, RIGHT : 39, DOWN : 40, COMMA : 188, SPACE : 32, HOME : 36, END : 35 }; // Keys "enum"
  var defaultSettings = {
    triggerChar   : '@',
    onDataRequest : $.noop,
    minChars      : 2,
    showAvatars   : true,
    elastic       : true,
    display       : 'name',
    onCaret       : true,
    classes       : {
      autoCompleteItemActive : "active"
    },
    templates     : {
      //Element to wrap the textarea, and soon to be created div + hidden inputs
      wrapper                    : _.template('

'),

      // Autocomplete elements
      autocompleteList           : _.template('

'),
      autocompleteListItem       : _.template('<li data-ref-id="<%= id %>" data-ref-type="<%= type %>" data-display="<%= display %>"><%= content %>
'),
      autocompleteListItemAvatar : _.template('<img  src="<%= avatar %>" />'),
      autocompleteListItemIcon   : _.template('<div class="icon <%= icon %>">
'),

      //
 layered under the <textarea>
      mentionsOverlay            : _.template('

'),

      // Syntax for .mentionsInput('val') which will probably be sent to the server
      mentionItemSyntax          : _.template('<%= triggerChar %>[<%= display %>](<%= type %>:<%= id %>)'),

      // Structure for highlighting the text in the
      mentionItemHighlight       : _.template('<strong class="<%= type %>"><%= display %>')
    }
  };

  var utils = {
    htmlEncode       : function (str) {
      return _.escape(str);
    },
    highlightTerm    : function (value, term) {
      if (!term && !term.length) {
        return value;
      }
      return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "$1");
    },
    setCaratPosition : function (domNode, caretPos) {
      if (domNode.createTextRange) {
        var range = domNode.createTextRange();
        range.move('character', caretPos);
        range.select();
      } else {
        if (domNode.selectionStart) {
          domNode.focus();
          domNode.setSelectionRange(caretPos, caretPos);
        } else {
          domNode.focus();
        }
      }
    },

    getCaratPosition : function($el){
    // This is taken straight from live (as of Sep 2012) GitHub code. The
    // technique is known around the web. Just google it. Github's is quite
    // succint though. NOTE: relies on selectionEnd, which as far as IE is concerned,
    // it'll only work on 9+. Good news is nothing will happen if the browser
    // doesn't support it.
	  var a, b, c, d, e, f, g, h, i, j, k;
      if (!(i = $el[0])) return;
      if (!$(i).is("textarea")) return;
      if (i.selectionEnd == null) return;
      g = {
        position: "absolute",
        overflow: "auto",
        whiteSpace: "pre-wrap",
        wordWrap: "break-word",
        boxSizing: "content-box",
        top: 0,
        left: -9999
      }, h = ["boxSizing", "fontFamily", "fontSize", "fontStyle", "fontVariant", "fontWeight", "height", "letterSpacing", "lineHeight", "paddingBottom", "paddingLeft", "paddingRight", "paddingTop", "textDecoration", "textIndent", "textTransform", "width", "word-spacing"];
      for (j = 0, k = h.length; j < k; j++) e = h[j], g[e] = $(i).css(e);
      return c = document.createElement("div"), $(c).css(g), $(i).after(c), b = document.createTextNode(i.value.substring(0, i.selectionEnd)), a = document.createTextNode(i.value.substring(i.selectionEnd)), d = document.createElement("span"), d.innerHTML = " ", c.appendChild(b), c.appendChild(d), c.appendChild(a), c.scrollTop = i.scrollTop, f = $(d).position(), $(c).remove(), f
    },

    rtrim: function(string) {
      return string.replace(/\s+$/,"");
    }
  };

  var MentionsInput = function (settings) {

    var mentionsCollection = [];
    var autocompleteItemCollection = {};
    var inputBuffer = [];
    var currentDataQuery = ''; //https://github.com/podio/jquery-mentions-input/pull/44
    var domInput, elmInputBox, elmInputWrapper, elmAutocompleteList, elmWrapperBox,
        elmMentionsOverlay, elmActiveAutoCompleteItem, currentTriggerChar;

    settings = $.extend(true, {}, defaultSettings, settings );

    function initTextarea() {
      elmInputBox = $(domInput);

      if (elmInputBox.attr('data-mentions-input') == 'true') {
        return;
      }

      elmInputWrapper = elmInputBox.parent();
      elmWrapperBox = $(settings.templates.wrapper());
      elmInputBox.wrapAll(elmWrapperBox);
      elmWrapperBox = elmInputWrapper.find('> div');

      elmInputBox.attr('data-mentions-input', 'true');
      elmInputBox.bind('keydown', onInputBoxKeyDown);
      elmInputBox.bind('keypress', onInputBoxKeyPress);
      elmInputBox.bind('input', onInputBoxInput);
      elmInputBox.bind('click', onInputBoxClick);
      elmInputBox.bind('blur', onInputBoxBlur);

      // Elastic textareas, internal setting for the Dispora guys
      if( settings.elastic ) {
        elmInputBox.elastic();
      }

    }

    function initAutocomplete() {
      elmAutocompleteList = $(settings.templates.autocompleteList());
      elmAutocompleteList.appendTo(elmWrapperBox);
      elmAutocompleteList.delegate('li', 'mousedown', onAutoCompleteItemClick);
    }

    function initMentionsOverlay() {
      elmMentionsOverlay = $(settings.templates.mentionsOverlay());
      elmMentionsOverlay.prependTo(elmWrapperBox);
    }

    function updateValues() {
      var syntaxMessage = getInputBoxValue();

      _.each(mentionsCollection, function (mention) {
        var textSyntax = settings.templates.mentionItemSyntax(_.extend({}, mention, {value: utils.htmlEncode(mention.value)}));
        syntaxMessage = syntaxMessage.replace(mention.value, textSyntax);
      });

      var mentionText = utils.htmlEncode(syntaxMessage);

      _.each(mentionsCollection, function (mention) {
        var formattedMention = _.extend({}, mention, {value: utils.htmlEncode(mention.value)});
        var textSyntax = settings.templates.mentionItemSyntax(formattedMention);
        var textHighlight = settings.templates.mentionItemHighlight(formattedMention);

        mentionText = mentionText.replace(textSyntax, textHighlight);
      });

      mentionText = mentionText.replace(/\n/g, '
');
      mentionText = mentionText.replace(/ {2}/g, '  ');

      elmInputBox.data('messageText', syntaxMessage);
      elmInputBox.trigger('updated');
      elmMentionsOverlay.find('div').html(mentionText);
    }

    function resetBuffer() {
      inputBuffer = [];
    }

    function updateMentionsCollection() {
      var inputText = getInputBoxValue();

      mentionsCollection = _.reject(mentionsCollection, function (mention, index) {
        return !mention.value || inputText.indexOf(mention.value) == -1;
      });
      mentionsCollection = _.compact(mentionsCollection);
    }

    function addMention(mention) {

      var currentMessage = getInputBoxValue();

      // Using a regex to figure out positions
      var regex = new RegExp("\\" + currentTriggerChar + currentDataQuery, "gi");
      regex.exec(currentMessage);

      var startCaretPosition = regex.lastIndex - currentDataQuery.length - 1;
      var currentCaretPosition = regex.lastIndex;

      var start = currentMessage.substr(0, startCaretPosition);
      var end = currentMessage.substr(currentCaretPosition, currentMessage.length);
      var startEndIndex = (start + mention.value).length + 1;

      mentionsCollection.push(
        _.extend({}, mention, {triggerChar : currentTriggerChar})
      );

      // Cleaning before inserting the value, otherwise auto-complete would be triggered with "old" inputbuffer
      resetBuffer();
      currentDataQuery = '';
      hideAutoComplete();

      // Mentions & syntax message
      var updatedMessageText = start + mention.value + ' ' + end;
      elmInputBox.val(updatedMessageText);
      elmInputBox.trigger('mention');
      updateValues();

      // Set correct focus and selection
      elmInputBox.focus();
      utils.setCaratPosition(elmInputBox[0], startEndIndex);
    }

    function getInputBoxValue() {
      return $.trim(elmInputBox.val());
    }

    function onAutoCompleteItemClick(e) {
      var elmTarget = $(this);
      var mention = autocompleteItemCollection[elmTarget.attr('data-uid')];

      addMention(mention);

      return false;
    }

    function onInputBoxClick(e) {
      resetBuffer();
    }

    function onInputBoxBlur(e) {
      hideAutoComplete();
    }

    function checkTriggerChar(inputBuffer, triggerChar) {
      var triggerCharIndex = _.lastIndexOf(inputBuffer, triggerChar);
      if (triggerCharIndex > -1) {
        currentDataQuery = inputBuffer.slice(triggerCharIndex + 1).join('');
        _.defer(_.bind(doSearch, this, currentDataQuery, triggerChar));
      }
    }

    function onInputBoxInput(e) {
      updateValues();
      updateMentionsCollection();
      hideAutoComplete();

      if (_.isArray(settings.triggerChar)) {
        _.each(settings.triggerChar, function (triggerChar) {
          checkTriggerChar(inputBuffer, triggerChar);
        });
      } else {
        checkTriggerChar(inputBuffer, settings.triggerChar);
      }

    }

    function onInputBoxKeyPress(e) {
      if(e.keyCode !== KEY.BACKSPACE) {
        var typedValue = String.fromCharCode(e.which || e.keyCode);
        inputBuffer.push(typedValue);
      }
    }

    function onInputBoxKeyDown(e) {

      // This also matches HOME/END on OSX which is CMD+LEFT, CMD+RIGHT
      if (e.keyCode == KEY.LEFT || e.keyCode == KEY.RIGHT || e.keyCode == KEY.HOME || e.keyCode == KEY.END) {
        // Defer execution to ensure carat pos has changed after HOME/END keys
        _.defer(resetBuffer);

        // IE9 doesn't fire the oninput event when backspace or delete is pressed. This causes the highlighting
        // to stay on the screen whenever backspace is pressed after a highlighed word. This is simply a hack
        // to force updateValues() to fire when backspace/delete is pressed in IE9.
        if (navigator.userAgent.indexOf("MSIE 9") > -1) {
          _.defer(updateValues);
        }

        return;
      }

      if (e.keyCode == KEY.BACKSPACE) {
        inputBuffer = inputBuffer.slice(0, -1 + inputBuffer.length); // Can't use splice, not available in IE
        return;
      }

      if (!elmAutocompleteList.is(':visible')) {
        return true;
      }

      switch (e.keyCode) {
        case KEY.UP:
        case KEY.DOWN:
          var elmCurrentAutoCompleteItem = null;
          if (e.keyCode == KEY.DOWN) {
            if (elmActiveAutoCompleteItem && elmActiveAutoCompleteItem.length) {
              elmCurrentAutoCompleteItem = elmActiveAutoCompleteItem.next();
            } else {
              elmCurrentAutoCompleteItem = elmAutocompleteList.find('li').first();
            }
          } else {
            elmCurrentAutoCompleteItem = $(elmActiveAutoCompleteItem).prev();
          }

          if (elmCurrentAutoCompleteItem.length) {
            selectAutoCompleteItem(elmCurrentAutoCompleteItem);
          }

          return false;

        case KEY.RETURN:
        case KEY.TAB:
          if (elmActiveAutoCompleteItem && elmActiveAutoCompleteItem.length) {
            elmActiveAutoCompleteItem.trigger('mousedown');
            return false;
          }

          break;
      }

      return true;
    }

    function hideAutoComplete() {
      elmActiveAutoCompleteItem = null;
      elmAutocompleteList.empty().hide();
    }

    function selectAutoCompleteItem(elmItem) {
      elmItem.addClass(settings.classes.autoCompleteItemActive);
      elmItem.siblings().removeClass(settings.classes.autoCompleteItemActive);

      elmActiveAutoCompleteItem = elmItem;
    }

    function populateDropdown(query, results) {
      elmAutocompleteList.show();

      // Filter items that has already been mentioned
      var mentionValues = _.pluck(mentionsCollection, 'value');
      results = _.reject(results, function (item) {
        return _.include(mentionValues, item.name);
      });

      if (!results.length) {
        hideAutoComplete();
        return;
      }

      elmAutocompleteList.empty();
      var elmDropDownList = $("
").appendTo(elmAutocompleteList).hide();

      _.each(results, function (item, index) {
        var itemUid = _.uniqueId('mention_');

        autocompleteItemCollection[itemUid] = _.extend({}, item, {value: item.name});

        var elmListItem = $(settings.templates.autocompleteListItem({
          'id'      : utils.htmlEncode(item.id),
          'display' : utils.htmlEncode(item[settings.display]),
          'type'    : utils.htmlEncode(item.type),
          'content' : utils.highlightTerm(utils.htmlEncode((item.name)), query)
        })).attr('data-uid', itemUid);

        if (index === 0) {
          selectAutoCompleteItem(elmListItem);
        }

        if (settings.showAvatars) {
          var elmIcon;

          if (item.avatar) {
            elmIcon = $(settings.templates.autocompleteListItemAvatar({ avatar : item.avatar }));
          } else {
            elmIcon = $(settings.templates.autocompleteListItemIcon({ icon : item.icon }));
          }
          elmIcon.prependTo(elmListItem);
        }
        elmListItem = elmListItem.appendTo(elmDropDownList);
      });

      elmAutocompleteList.show();
      if (settings.onCaret) positionAutocomplete(elmAutocompleteList, elmInputBox);
      elmDropDownList.show();
    }

    function doSearch(query, triggerChar) {
      if (query && query.length && query.length >= settings.minChars) {

        var callback = function callback (responseData) {
          populateDropdown(query, responseData);
          currentTriggerChar = triggerChar;
        }

        settings.onDataRequest.call(this, 'search', query, triggerChar, callback);

      }
    }

    function positionAutocomplete(elmAutocompleteList, elmInputBox) {
      var position = utils.getCaratPosition(elmInputBox),
          lineHeight = parseInt(elmInputBox.css('line-height'), 10) || 18;

      elmAutocompleteList.css('width', '15em'); // Sort of a guess
      elmAutocompleteList.css('left', position.left);
      elmAutocompleteList.css('top', lineHeight + position.top);
    }

    function resetInput() {
      elmInputBox.val('');
      mentionsCollection = [];
      updateValues();
    }

    // Public methods
    return {
      init : function (domTarget) {

        domInput = domTarget;

        initTextarea();
        initAutocomplete();
        initMentionsOverlay();
        resetInput();

        if( settings.prefillMention ) {
          addMention( settings.prefillMention );
        }

      },

      val : function (callback) {
        if (!_.isFunction(callback)) {
          return;
        }

        var value = mentionsCollection.length ? elmInputBox.data('messageText') : getInputBoxValue();
        callback.call(this, value);
      },

      reset : function () {
        resetInput();
      },

      getMentions : function (callback) {
        if (!_.isFunction(callback)) {
          return;
        }

        callback.call(this, mentionsCollection);
      }
    };
  };

  $.fn.mentionsInput = function (method, settings) {

    var outerArguments = arguments;

    if (typeof method === 'object' || !method) {
      settings = $.extend(true, {}, defaultSettings, method);
    }

    return this.each(function () {
      var instance = $.data(this, 'mentionsInput') || $.data(this, 'mentionsInput', new MentionsInput(settings));

      if (_.isFunction(instance[method])) {
        return instance[method].apply(this, Array.prototype.slice.call(outerArguments, 1));

      } else if (typeof method === 'object' || !method) {
        return instance.init.call(this, this);

      } else {
        $.error('Method ' + method + ' does not exist');
      }

    });
  };

})(jQuery, _);<|endoftext|>


<commit_before>var yo = require('russell-view')
var csjs = require('csjs')
var style = require('./dialog_css.js')
module.exports = function dialog (state, globalstate, index) {
  if (globalstate.windowWidth > 900) {
    var width = '50%'
  } else {
    var width = '100%'
  }

  var color1 = '#175f8a'
  var color2 = '#f08030'

  var color = color1
  if (index % 2 === 0) {
    color = color2
  }

  return yo`

${state.img ? `<img style="width:${width}; padding:10px;" src="${state.img}" />` : ''}

Año ${state.title}

${state.body}

[Ver mas ...]
[Cerrar]

`
}
<commit_msg>Fix timeline link bug<commit_after>var yo = require('russell-view')
var csjs = require('csjs')
var style = require('./dialog_css.js')
module.exports = function dialog (state, globalstate, index) {
  if (globalstate.windowWidth > 900) {
    var width = '50%'
  } else {
    var width = '100%'
  }

  var color1 = '#175f8a'
  var color2 = '#f08030'

  var color = color1
  if (index % 2 === 0) {
    color = color2
  }

  return yo`

${state.img !== '' ? `<img style="width:${width}; padding:10px;" src="${state.img}" />` : ''}

Año ${state.title}

${state.body}

${state.url !== '' ? `[<a class="${style.btn}" href="${state.url}" target="_blank">Ver mas ...</a>]` : ''}
[Cerrar]

`
}
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var _ = require('lodash'),
    config = require('../config'),
    errorHandler = require('../../modules/core/server/controllers/errors.server.controller'),
    languages = require('../languages/languages.json'),
    express = require('express'),
    morgan = require('morgan'),
    bodyParser = require('body-parser'),
    session = require('express-session'),
    MongoStore = require('connect-mongo')(session),
    favicon = require('serve-favicon'),
    compress = require('compression'),
    methodOverride = require('method-override'),
    cookieParser = require('cookie-parser'),
    helmet = require('helmet'),
    flash = require('connect-flash'),
    consolidate = require('consolidate'),
    git = require('git-rev'),
    path = require('path'),
    paginate = require('express-paginate'),
    seo = require('mean-seo'),
    path = require('path'),
    Agenda = require('agenda');

/**
 * Initialize local variables
 */
module.exports.initLocalVariables = function (app) {
  // Setting application local variables
  app.locals.title = config.app.title;
  app.locals.description = config.app.description;
  app.locals.facebookAppId = config.facebook.clientID;
  app.locals.twitterUsername = config.twitter.username;
  app.locals.facebookPage = config.facebook.page;
  app.locals.googlePage = config.google.page;
  app.locals.googleAnalytics = config.googleAnalytics;
  app.locals.languages = languages;
  app.locals.appSettings = config.app;
  app.locals.appSettings.piwik = config.piwik;
  app.locals.appSettings.mapbox = config.mapbox;
  app.locals.appSettings.time = new Date().toISOString();
  app.locals.appSettings.https = config.https;
  app.locals.appSettings.maxUploadSize = config.maxUploadSize;

  app.locals.jsFiles = config.files.client.js;
  app.locals.cssFiles = _.map(config.files.client.css, function(file) { return file.replace('/client', ''); });

  // Get 'git rev-parse --short HEAD' (the latest git commit hash) to use as a cache buster
  // @link https://www.npmjs.com/package/git-rev
  git.short(function (str) {
    app.locals.appSettings.commit = str;
  });

  // Passing the request url to environment locals
  app.use(function (req, res, next) {

    // Determine if to use https. When proxying (e.g. with Nginx) to localhost
    // from https front, req.protocol would end up being http when it should be https.
    // @todo: sniff if behind proxy and otherwise rely req.protocol.
    var protocol = (config.https === true || req.protocol === 'https') ? 'https' : 'http';

    res.locals.hostPort = protocol + '://' + req.get('host');
    res.locals.host = protocol + '://' + req.hostname;
    res.locals.url = protocol + '://' + req.headers.host + req.originalUrl;
    next();
  });
};

/**
 * Initialize application middleware
 */
module.exports.initMiddleware = function (app) {
  // Showing stack errors
  app.set('showStackError', true);

  // Enable jsonp
  app.enable('jsonp callback');

  // Should be placed before express.static
  app.use(compress({
    filter: function (req, res) {
      return (/json|text|javascript|css|font|svg/).test(res.getHeader('Content-Type'));
    },
    level: 9
  }));

  // Initialize pagination middleware
  // Set Pagination default values (limit, max limit)
  app.use(paginate.middleware(20, 50));

  // Initialize favicon middleware
  app.use(favicon('public/favicon.ico'));

  // Environment dependent middleware
  if (process.env.NODE_ENV === 'development') {
    // Enable logger (morgan)
    app.use(morgan('dev'));

    // Disable views cache
    app.set('view cache', false);
  } else if (process.env.NODE_ENV === 'production') {
    app.locals.cache = 'memory';
  }

  // Request body parsing middleware should be above methodOverride
  app.use(bodyParser.urlencoded({
    extended: true
  }));
  app.use(bodyParser.json());
  app.use(methodOverride());

  // Add the cookie parser and flash middleware
  app.use(cookieParser());
  app.use(flash());

};

/**
 * Configure view engine
 */
module.exports.initViewEngine = function (app) {
  // Set swig as the template engine
  app.engine('server.view.html', consolidate.swig);

  // Set views path and view engine
  app.set('view engine', 'server.view.html');
  app.set('views', './');
};

/**
 * Configure Express session
 */
module.exports.initSession = function (app, db) {
  // Express MongoDB session storage
  // https://www.npmjs.com/package/express-session
  app.use(session({
    saveUninitialized: true,
    resave: true,
    secret: config.sessionSecret,
    cookie: {
      // If secure is true, and you access your site over HTTP, the cookie will not be set.
      secure: false,//config.https,

      // By default cookie.maxAge is null, meaning no "expires" parameter is
      // set so the cookie becomes a browser-session cookie. When the user
      // closes the browser the cookie (and session) will be removed.
      maxAge: 2419200000
    },
    store: new MongoStore({
      mongooseConnection: db.connection,
      collection: config.sessionCollection
    })
  }));
};

/**
 * Invoke modules server configuration
 */
module.exports.initModulesConfiguration = function (app, db) {
  config.files.server.configs.forEach(function (configPath) {
    require(path.resolve(configPath))(app, db);
  });
};

/**
 * Configure Helmet headers configuration
 */
module.exports.initHelmetHeaders = function (app) {
  // Use helmet to secure Express headers
  app.use(helmet.xframe());
  app.use(helmet.xssFilter());
  app.use(helmet.nosniff());
  app.use(helmet.ienoopen());
  app.disable('x-powered-by');
};

/**
 * Configure SEO rendering for `/?_escaped_fragment_=/pagename` -urls
 * This must come before client route configs
 * @link http://meanjs.org/modules.html#seo
 */
module.exports.initSEO = function (app) {
  app.use(seo({
    cacheClient: 'disk', // Can be 'disk' or 'redis'
    cacheDuration: 2 * 60 * 60 * 24 * 1000, // In milliseconds for disk cache
  }));
};

/**
 * Configure Agenda "Cron" jobs
 * @link https://www.npmjs.com/package/agenda
 */
module.exports.initAgenda = function (app, db) {

  // Don't launch Agenda on test environment
  // @todo: make it possible to launch this manually with very small interwalls for testing
  // @todo: similarly for testing purposes, write a stopAgenda() method
  if(process.env.NODE_ENV !== 'production') {
    return;
  }

  // Setup agenda
  var agendaWorker = new Agenda({
    db: {
      address: config.db.uri,
      collection: 'agendaJobs'
    }
  });

  agendaWorker.on('ready', function() {
    // Load jobs
    var messagesUnreadJob = require(path.resolve('./modules/messages/server/jobs/message-unread.server.job'));

    // Schedule job(s)
    messagesUnreadJob.checkUnreadMessages(agendaWorker);
    agendaWorker.every('5 minutes', 'check unread messages');

    // Start worker
    agendaWorker.start();
    console.log('Agenda started processing background jobs');
  });

  // Error reporting
  agendaWorker.on('fail', function(err, job) {
    console.error('Agenda job failed with error: %s', err.message);
  });
};

/**
 * Configure the modules static routes
 */
module.exports.initModulesClientRoutes = function (app) {
  // Setting the app router and static folder
  app.use('/', express.static(path.resolve('./public')));

  // Globbing static routing
  config.folders.client.forEach(function (staticPath) {
    app.use(staticPath.replace('/client', ''), express.static(path.resolve('./' + staticPath)));
  });

};

/**
 * Configure the modules ACL policies
 */
module.exports.initModulesServerPolicies = function (app) {
  // Globbing policy files
  config.files.server.policies.forEach(function (policyPath) {
    require(path.resolve(policyPath)).invokeRolesPolicies();
  });
};

/**
 * Configure the modules server routes
 */
module.exports.initModulesServerRoutes = function (app) {
  // Globbing routing files
  config.files.server.routes.forEach(function (routePath) {
    require(path.resolve(routePath))(app);
  });
};

/**
 * Configure error handling
 */
module.exports.initErrorRoutes = function (app) {
  app.use(errorHandler.errorResponse);
};

/**
 * Configure Socket.io
 */
/*
module.exports.configureSocketIO = function (app, db) {
  // Load the Socket.io configuration
  var server = require('./socket.io')(app, db);

  // Return server object
  return server;
};
*/

/**
 * Initialize the Express application
 */
module.exports.init = function (db) {
  // Initialize express app
  var app = express();

  // Initialize local variables
  this.initLocalVariables(app);

  // Initialize Express middleware
  this.initMiddleware(app);

  // Initialize Express view engine
  this.initViewEngine(app);

  // Initialize Helmet security headers
  this.initHelmetHeaders(app);

  // Initialize modules static client routes
  this.initModulesClientRoutes(app);

  // Initialize Express session
  this.initSession(app, db);

  // Initialize Modules configuration
  this.initModulesConfiguration(app);

  // Initialize modules server authorization policies
  this.initModulesServerPolicies(app);

  // Initialize SEO Modules
  this.initSEO(app);

  // Initialize modules server routes
  this.initModulesServerRoutes(app);

  // Initialize error routes
  this.initErrorRoutes(app);

  // Initialize Agenda ("cron" jobs)
  this.initAgenda(app, db);

  // Configure Socket.io
  //app = this.configureSocketIO(app, db);

  return app;
};
<commit_msg>Clean out piwik field from frontend settings<commit_after>'use strict';

/**
 * Module dependencies.
 */
var _ = require('lodash'),
    config = require('../config'),
    errorHandler = require('../../modules/core/server/controllers/errors.server.controller'),
    languages = require('../languages/languages.json'),
    express = require('express'),
    morgan = require('morgan'),
    bodyParser = require('body-parser'),
    session = require('express-session'),
    MongoStore = require('connect-mongo')(session),
    favicon = require('serve-favicon'),
    compress = require('compression'),
    methodOverride = require('method-override'),
    cookieParser = require('cookie-parser'),
    helmet = require('helmet'),
    flash = require('connect-flash'),
    consolidate = require('consolidate'),
    git = require('git-rev'),
    path = require('path'),
    paginate = require('express-paginate'),
    seo = require('mean-seo'),
    path = require('path'),
    Agenda = require('agenda');

/**
 * Initialize local variables
 */
module.exports.initLocalVariables = function (app) {
  // Setting application local variables
  app.locals.title = config.app.title;
  app.locals.description = config.app.description;
  app.locals.facebookAppId = config.facebook.clientID;
  app.locals.twitterUsername = config.twitter.username;
  app.locals.facebookPage = config.facebook.page;
  app.locals.googlePage = config.google.page;
  app.locals.googleAnalytics = config.googleAnalytics;
  app.locals.languages = languages;
  app.locals.appSettings = config.app;
  app.locals.appSettings.mapbox = config.mapbox;
  app.locals.appSettings.time = new Date().toISOString();
  app.locals.appSettings.https = config.https;
  app.locals.appSettings.maxUploadSize = config.maxUploadSize;

  app.locals.jsFiles = config.files.client.js;
  app.locals.cssFiles = _.map(config.files.client.css, function(file) { return file.replace('/client', ''); });

  // Get 'git rev-parse --short HEAD' (the latest git commit hash) to use as a cache buster
  // @link https://www.npmjs.com/package/git-rev
  git.short(function (str) {
    app.locals.appSettings.commit = str;
  });

  // Passing the request url to environment locals
  app.use(function (req, res, next) {

    // Determine if to use https. When proxying (e.g. with Nginx) to localhost
    // from https front, req.protocol would end up being http when it should be https.
    // @todo: sniff if behind proxy and otherwise rely req.protocol.
    var protocol = (config.https === true || req.protocol === 'https') ? 'https' : 'http';

    res.locals.hostPort = protocol + '://' + req.get('host');
    res.locals.host = protocol + '://' + req.hostname;
    res.locals.url = protocol + '://' + req.headers.host + req.originalUrl;
    next();
  });
};

/**
 * Initialize application middleware
 */
module.exports.initMiddleware = function (app) {
  // Showing stack errors
  app.set('showStackError', true);

  // Enable jsonp
  app.enable('jsonp callback');

  // Should be placed before express.static
  app.use(compress({
    filter: function (req, res) {
      return (/json|text|javascript|css|font|svg/).test(res.getHeader('Content-Type'));
    },
    level: 9
  }));

  // Initialize pagination middleware
  // Set Pagination default values (limit, max limit)
  app.use(paginate.middleware(20, 50));

  // Initialize favicon middleware
  app.use(favicon('public/favicon.ico'));

  // Environment dependent middleware
  if (process.env.NODE_ENV === 'development') {
    // Enable logger (morgan)
    app.use(morgan('dev'));

    // Disable views cache
    app.set('view cache', false);
  } else if (process.env.NODE_ENV === 'production') {
    app.locals.cache = 'memory';
  }

  // Request body parsing middleware should be above methodOverride
  app.use(bodyParser.urlencoded({
    extended: true
  }));
  app.use(bodyParser.json());
  app.use(methodOverride());

  // Add the cookie parser and flash middleware
  app.use(cookieParser());
  app.use(flash());

};

/**
 * Configure view engine
 */
module.exports.initViewEngine = function (app) {
  // Set swig as the template engine
  app.engine('server.view.html', consolidate.swig);

  // Set views path and view engine
  app.set('view engine', 'server.view.html');
  app.set('views', './');
};

/**
 * Configure Express session
 */
module.exports.initSession = function (app, db) {
  // Express MongoDB session storage
  // https://www.npmjs.com/package/express-session
  app.use(session({
    saveUninitialized: true,
    resave: true,
    secret: config.sessionSecret,
    cookie: {
      // If secure is true, and you access your site over HTTP, the cookie will not be set.
      secure: false,//config.https,

      // By default cookie.maxAge is null, meaning no "expires" parameter is
      // set so the cookie becomes a browser-session cookie. When the user
      // closes the browser the cookie (and session) will be removed.
      maxAge: 2419200000
    },
    store: new MongoStore({
      mongooseConnection: db.connection,
      collection: config.sessionCollection
    })
  }));
};

/**
 * Invoke modules server configuration
 */
module.exports.initModulesConfiguration = function (app, db) {
  config.files.server.configs.forEach(function (configPath) {
    require(path.resolve(configPath))(app, db);
  });
};

/**
 * Configure Helmet headers configuration
 */
module.exports.initHelmetHeaders = function (app) {
  // Use helmet to secure Express headers
  app.use(helmet.xframe());
  app.use(helmet.xssFilter());
  app.use(helmet.nosniff());
  app.use(helmet.ienoopen());
  app.disable('x-powered-by');
};

/**
 * Configure SEO rendering for `/?_escaped_fragment_=/pagename` -urls
 * This must come before client route configs
 * @link http://meanjs.org/modules.html#seo
 */
module.exports.initSEO = function (app) {
  app.use(seo({
    cacheClient: 'disk', // Can be 'disk' or 'redis'
    cacheDuration: 2 * 60 * 60 * 24 * 1000, // In milliseconds for disk cache
  }));
};

/**
 * Configure Agenda "Cron" jobs
 * @link https://www.npmjs.com/package/agenda
 */
module.exports.initAgenda = function (app, db) {

  // Don't launch Agenda on test environment
  // @todo: make it possible to launch this manually with very small interwalls for testing
  // @todo: similarly for testing purposes, write a stopAgenda() method
  if(process.env.NODE_ENV !== 'production') {
    return;
  }

  // Setup agenda
  var agendaWorker = new Agenda({
    db: {
      address: config.db.uri,
      collection: 'agendaJobs'
    }
  });

  agendaWorker.on('ready', function() {
    // Load jobs
    var messagesUnreadJob = require(path.resolve('./modules/messages/server/jobs/message-unread.server.job'));

    // Schedule job(s)
    messagesUnreadJob.checkUnreadMessages(agendaWorker);
    agendaWorker.every('5 minutes', 'check unread messages');

    // Start worker
    agendaWorker.start();
    console.log('Agenda started processing background jobs');
  });

  // Error reporting
  agendaWorker.on('fail', function(err, job) {
    console.error('Agenda job failed with error: %s', err.message);
  });
};

/**
 * Configure the modules static routes
 */
module.exports.initModulesClientRoutes = function (app) {
  // Setting the app router and static folder
  app.use('/', express.static(path.resolve('./public')));

  // Globbing static routing
  config.folders.client.forEach(function (staticPath) {
    app.use(staticPath.replace('/client', ''), express.static(path.resolve('./' + staticPath)));
  });

};

/**
 * Configure the modules ACL policies
 */
module.exports.initModulesServerPolicies = function (app) {
  // Globbing policy files
  config.files.server.policies.forEach(function (policyPath) {
    require(path.resolve(policyPath)).invokeRolesPolicies();
  });
};

/**
 * Configure the modules server routes
 */
module.exports.initModulesServerRoutes = function (app) {
  // Globbing routing files
  config.files.server.routes.forEach(function (routePath) {
    require(path.resolve(routePath))(app);
  });
};

/**
 * Configure error handling
 */
module.exports.initErrorRoutes = function (app) {
  app.use(errorHandler.errorResponse);
};

/**
 * Configure Socket.io
 */
/*
module.exports.configureSocketIO = function (app, db) {
  // Load the Socket.io configuration
  var server = require('./socket.io')(app, db);

  // Return server object
  return server;
};
*/

/**
 * Initialize the Express application
 */
module.exports.init = function (db) {
  // Initialize express app
  var app = express();

  // Initialize local variables
  this.initLocalVariables(app);

  // Initialize Express middleware
  this.initMiddleware(app);

  // Initialize Express view engine
  this.initViewEngine(app);

  // Initialize Helmet security headers
  this.initHelmetHeaders(app);

  // Initialize modules static client routes
  this.initModulesClientRoutes(app);

  // Initialize Express session
  this.initSession(app, db);

  // Initialize Modules configuration
  this.initModulesConfiguration(app);

  // Initialize modules server authorization policies
  this.initModulesServerPolicies(app);

  // Initialize SEO Modules
  this.initSEO(app);

  // Initialize modules server routes
  this.initModulesServerRoutes(app);

  // Initialize error routes
  this.initErrorRoutes(app);

  // Initialize Agenda ("cron" jobs)
  this.initAgenda(app, db);

  // Configure Socket.io
  //app = this.configureSocketIO(app, db);

  return app;
};
<|endoftext|>


<commit_before>/*global define, brackets */

/* Worst code ever... There has been no polish and little thought added to this what so ever! */

define(function (/* require, exports, module */) {

    "use strict";

    /*global $ */

    var CommandManager = brackets.getModule("command/CommandManager"),
        Menus = brackets.getModule("command/Menus"),
        Dialogs         = brackets.getModule("widgets/Dialogs");

    var getMatching = function(allCommands, input) {
        return allCommands.filter(function(s) {
            return (s.toLowerCase().indexOf(input.toLowerCase()) > -1);
        }).sort();
    };

    var getInput = function(allCommands, cb) {
        // Based on code from Patrick Edelman, but made worse!
        Dialogs.showModalDialogUsingTemplate([
            '
',
            '<input type="text" autofocus="true" id="jkfdasjrejj"/>
',
            '<select multiple="multiple" size="16">',
            '</select>',
            '
'
        ].join(' '));
        $('#jkfdasjrejj').keypress(function (e) {
            if (e.which === 13) {
                var _c = $('#jkfdasjrejj').val();
                e.preventDefault();

                if (_c === null) {
                    return;
                }
                $('.jkfdasjrejj').fadeOut(300);
                var t = $('.jkfdasjrejj select').find('option:first-child').text();
                Dialogs.cancelModalDialogIfOpen('jkfdasjrejj');
                cb(t);
            }
        });
        $('#jkfdasjrejj').keyup(function (e) {
            if (e.which === 13) {
                return;
            }
            $('.jkfdasjrejj').find('select').html('');
            var _c = $('#jkfdasjrejj').val();
            var newCommands = getMatching(allCommands, _c);
            for (var i=0; i<newCommands.length; i++) {
                $('.jkfdasjrejj select').append(
                    $('<option></option>').text(newCommands[i])
                );
            }
        });
    };

    function handleHelloWorld() {
        var allCommands = CommandManager.getAll();
        getInput(allCommands, function(input) {
           if (allCommands.indexOf(input) === -1) { return false;}
           CommandManager.get(input)._commandFn();
        });
    }

    // First, register a command - a UI-less object associating an id to a handler
    var MY_COMMAND_ID_A = "forbesmyester.run-menu-item";

    CommandManager.register(
        "Rubbish CtrlP Clone",
        MY_COMMAND_ID_A,
        handleHelloWorld.bind(this, '')
    );

    // Then create a menu item bound to the command
    // The label of the menu item is the name we gave the command (see above)
    var menu = Menus.getMenu(Menus.AppMenuBar.FILE_MENU);
    menu.addMenuItem(MY_COMMAND_ID_A);

    // We could also add a key binding at the same time:
    //menu.addMenuItem(MY_COMMAND_ID, "Ctrl-Alt-H");
    // (Note: "Ctrl" is automatically mapped to "Cmd" on Mac)
});
<commit_msg>Add basic short bindings<commit_after>/*global define, brackets */

/* Worst code ever... There has been no polish and little thought added to this what so ever! */

define(function (require, exports, module) {

    "use strict";

    /*global $ */

    var CommandManager = brackets.getModule("command/CommandManager"),
        Menus = brackets.getModule("command/Menus"),
        Dialogs         = brackets.getModule("widgets/Dialogs"),
		EditorManager = brackets.getModule("editor/EditorManager"),
		PreferencesManager = brackets.getModule("preferences/PreferencesManager"),
		fileMenu = Menus.getMenu(Menus.AppMenuBar.FILE_MENU),
		MY_COMMAND_ID_A = "forbesmyester.run-menu-item",
		MY_COMMAND_ID_B = "forbesmyester.run-menu-item-set-short-command",
		MY_COMMAND_ID_C = "forbesmyester.run-menu-item-run-short-command",
		_prefs = PreferencesManager.getPreferenceStorage(module);

    var getMatching = function(allCommands, input) {
		input = input.indexOf(' ') > -1 ? input.substr(0, input.indexOf(' ')).trim() : input;
        return allCommands.filter(function(s) {
			var p = s.indexOf(':');
			if (p > -1) {
				s = s.substr(0, p);
			}
            return (s.toLowerCase().indexOf(input.toLowerCase()) > -1);
        }).sort();
    };

    var getInput = function(showShortCodeInput, allCommands, cb) {
        // Based on code from Patrick Edelman, but made worse!
        Dialogs.showModalDialogUsingTemplate([
            '
',
            '<input type="text" autofocus="true" id="akl4kfklls"/>
',
			'<input type="text" autofocus="true" id="jkfdasjrejj"/>
',
            '<select multiple="multiple" size="16">',
            '</select>',
            '
'
        ].join(' '));
		if (!showShortCodeInput) {
			$('#akl4kfklls').hide();
		}
        $('#jkfdasjrejj').keypress(function (e) {
            if (e.which === 13) {
                var _c = $('#jkfdasjrejj').val();
                e.preventDefault();

                if (_c === null) {
                    return;
                }
                $('.jkfdasjrejj').fadeOut(300);
                var t = $('.jkfdasjrejj select').find('option:first-child').text();
				var shortCode = $('#akl4kfklls').val();
				var extraInput = $('#jkfdasjrejj').val().indexOf(' ') > -1 ?
					$('#jkfdasjrejj').val().substr(
							$('#jkfdasjrejj').val().indexOf(' ')
						).trim() :
					'';
                Dialogs.cancelModalDialogIfOpen('jkfdasjrejj');
                cb(t, shortCode, extraInput);
				EditorManager.focusEditor();
            }
        });
        $('#jkfdasjrejj').keyup(function (e) {
            if (e.which === 13) {
                return;
            }
            $('.jkfdasjrejj').find('select').html('');
            var _c = $('#jkfdasjrejj').val();
            var newCommands = getMatching(allCommands, _c);
            for (var i=0; i<newCommands.length; i++) {
                $('.jkfdasjrejj select').append(
                    $('<option></option>').text(newCommands[i])
                );
            }
        });
    };

    function runCommand() {
        var allCommands = CommandManager.getAll();
        getInput(false, allCommands, function(input) {
		if (allCommands.indexOf(input) === -1) { return false;}
			CommandManager.get(input)._commandFn();
        });
    }

	function setShortCommand() {
        var allCommands = CommandManager.getAll();
        getInput(true, allCommands, function(commandName, shortCode) {
			_prefs.setValue(shortCode, commandName);
        });
	}

	function runShortCommand() {
		var allCommands = CommandManager.getAll(),
			codeCommand = _prefs.getAllValues(),
			k,
			options = [],
			commandName;
		for (k in codeCommand) { if (codeCommand.hasOwnProperty(k)) {
			options.push(k + ': ' + codeCommand[k]);
		} }
        getInput(false, options, function(input, _, extraParams) {
			commandName = input.substr(input.indexOf(':') + 1).trim();
			if (allCommands.indexOf(commandName) === -1) { return false;}
			if (extraParams.length) {
				CommandManager.get(commandName)._commandFn(extraParams);
			} else {
				CommandManager.get(commandName)._commandFn();
			}
        });
	}

    CommandManager.register("Rubbish CtrlP Clone", MY_COMMAND_ID_A, runCommand);
    fileMenu.addMenuItem(MY_COMMAND_ID_A);
    CommandManager.register("Set Short Command", MY_COMMAND_ID_B, setShortCommand);
    fileMenu.addMenuItem(MY_COMMAND_ID_B);
    CommandManager.register("Run Short Command", MY_COMMAND_ID_C, runShortCommand);
    fileMenu.addMenuItem(MY_COMMAND_ID_C);

    // We could also add a key binding at the same time:
    //menu.addMenuItem(MY_COMMAND_ID, "Ctrl-Alt-H");
    // (Note: "Ctrl" is automatically mapped to "Cmd" on Mac)
});
<|endoftext|>


<commit_before>'use strict';

var isArray  = Array.isArray
  , map      = Array.prototype.map
  , slice    = Array.prototype.slice
  , apply    = Function.prototype.apply
  , toArray  = require('../../Array/from')
  , indexOf  = require('../../Array/prototype/e-index-of')
  , callable = require('../../Object/valid-callable')

  , resolve;

resolve = function (args) {
	return this.map(function (r, i) {
		return r ? r(args[i]) : args[i];
	}).concat(slice.call(args, this.length));
};

// Implementation details:
//
// Results are saved internally within array matrix:
// cache[0] -> Result of calling function with no arguments
// cache[1] -> Matrix that keeps results for one argument function calls
// cache[1][0] -> Array of different arguments with which
//                function have been called
// cache[1][1] -> Array of results that matches cache[1][0] arguments array
// cache[2] -> Matrix that keeps results for two argument function calls
// cache[2][0] -> Array of different first (of two) arguments with which
//                function have been called
// cache[2][1] -> Matrixes that keeps results for two arguments function calls
//                Each matrix matches first argument found in cache[2][0]
// cache[2][1][x][0] -> Array of different second arguments with which
//                      function have been called.
// cache[2][1][x][1] -> Array of results that matches cache[2][1][x][0]
//                      arguments array
// ...and so on

module.exports = function (length, resolvers) {
	var fn, cache, resolver, find, aset, rset, index, found, mfn;
	fn = callable(this);

	cache = [];
	if (isArray(length)) {
		resolvers = length;
		length = fn.length;
	} else if (length == null) {
		length = fn.length;
	} else if (length !== false) {
		length = length >>> 0;
	}

	if (resolvers != null) {
		resolvers = toArray(resolvers);
		resolvers.forEach(function (r) {
			(r == null) || callable(r);
		});
		resolver = resolve.bind(resolvers);
	}

	find =  function (args) {
		var limit, i, arg;

		i = 0;
		aset = found = false;
		index = limit = (length === false) ? args.length : length;
		rset = cache;

		if (limit === 0) {
			found = rset.hasOwnProperty(0);
		} else {
			while (i !== limit) {
				if (!rset[index]) {
					rset = (rset[index] = [[args[i]], []]);
					index = 0;
				} else if ((index =
						indexOf.call((rset = rset[index])[0], args[i])) === -1) {
					index = rset[0].push(args[i]) - 1;
					found = false;
				} else {
					found = rset[1].hasOwnProperty(index);
				}
				aset = rset[0];
				rset = rset[1];
				++i;
			}
		}
	};

	mfn = function () {
		var args, result;
		args = resolver ? resolver(arguments) : arguments;
		find(args);
		if (found) {
			result = rset[index];
		} else {
			mfn.args = arguments;
			result = (rset[index] = apply.call(fn, this, args));
			delete mfn.args;
		}
		return result
	};

	mfn.clearCache = function () {
		find(resolver ? resolver(arguments) : arguments);
		if (found) {
			if (aset) {
				aset.splice(index, 1);
				rset.splice(index, 1);
			} else {
				delete rset[index];
			}
		}
	};

	mfn.clearAllCache = function () {
		cache = [];
	};

	return mfn;
};
<commit_msg>Reorganize memoize algorithm<commit_after>'use strict';

var isArray  = Array.isArray
  , map      = Array.prototype.map
  , slice    = Array.prototype.slice
  , apply    = Function.prototype.apply
  , toArray  = require('../../Array/from')
  , indexOf  = require('../../Array/prototype/e-index-of')
  , callable = require('../../Object/valid-callable')

  , resolve;

resolve = function (args) {
	return this.map(function (r, i) {
		return r ? r(args[i]) : args[i];
	}).concat(slice.call(args, this.length));
};

// Implementation details:
//
// Results are saved internally within array matrix:
// cache[0] -> Result of calling function with no arguments
// cache[1] -> Matrix that keeps results for one argument function calls
// cache[1][0] -> Array of different arguments with which
//                function have been called
// cache[1][1] -> Array of results that matches cache[1][0] arguments array
// cache[2] -> Matrix that keeps results for two argument function calls
// cache[2][0] -> Array of different first (of two) arguments with which
//                function have been called
// cache[2][1] -> Matrixes that keeps results for two arguments function calls
//                Each matrix matches first argument found in cache[2][0]
// cache[2][1][x][0] -> Array of different second arguments with which
//                      function have been called.
// cache[2][1][x][1] -> Array of results that matches cache[2][1][x][0]
//                      arguments array
// ...and so on

module.exports = function (length, resolvers) {
	var fn, mfn, resolver, cache, find, save, clear
	  , value;

	fn = callable(this);
	if (isArray(length)) {
		resolvers = length;
		length = fn.length;
	} else if (length == null) {
		length = fn.length;
	} else if (length !== false) {
		length = length >>> 0;
	}
	if (resolvers != null) {
		resolvers = toArray(resolvers);
		resolvers.forEach(function (r) {
			(r == null) || callable(r);
		});
		resolver = resolve.bind(resolvers);
	}

	cache = [];

	find =  function (length, args) {
		var index = 0, rset = cache, i;

		if (length === 0) {
			value = rset[length];
			return rset.hasOwnProperty(length);
		} else if ((rset = rset[length])) {
			while (index < (length - 1)) {
				i = indexOf.call(rset[0], args[index]);
				if (i === -1) {
					return false;
				}
				rset = rset[1][i];
				++index;
			}
			i = indexOf.call(rset[0], args[index]);
			if (i === -1) {
				return false;
			}
			value = rset[1][i];
			return true;
		}
		return false;
	};

	save = function (length, args, value) {
		var index = 0, rset = cache, i;

		if (length === 0) {
			rset[length] = value;
		} else {
			if (!rset[length]) {
				rset[length] = [[], []];
			}
			rset = rset[length];
			while (index < (length - 1)) {
				i = indexOf.call(rset[0], args[index]);
				if (i === -1) {
					i = rset[0].push(args[index]) - 1;
					rset[1].push([[], []]);
				}
				rset = rset[1][i];
				++index;
			}
			i = indexOf.call(rset[0], args[index]);
			if (i === -1) {
				i = rset[0].push(args[index]) - 1;
			}
			rset[1][i] = value;
		}
	};

	clear = function (length, args) {
		var index = 0, rset = cache, i, path = [];

		if (length === 0) {
			delete rset[length];
		} else if ((rset = rset[length])) {
			while (index < (length - 1)) {
				i = indexOf.call(rset[0], args[index]);
				if (i === -1) {
					return;
				}
				path.push(rset, i);
				rset = rset[1][i];
				++index;
			}
			i = indexOf.call(rset[0], args[index]);
			if (i === -1) {
				return;
			}
			rset[0].splice(i, 1);
			rset[1].splice(i, 1);
			while (!rset[0].length && path.length) {
				i = path.pop();
				rset = path.pop();
				rset[0].splice(i, 1);
				rset[1].splice(i, 1);
			}
		}
	};

	mfn = function () {
		var args, alength;
		args = resolver ? resolver(arguments) : arguments;
		alength = (length === false) ? args.length : length;

		if (find(alength, args)) {
			return value;
		} else {
			mfn.args = arguments;
			mfn.preventCache = false;
			value = apply.call(fn, this, args);
			if (!mfn.preventCache) {
				save(alength, args, value);
			}
			delete mfn.args;
			return value;
		}
	};

	mfn.clearCache = function () {
		var args, alength;
		args = resolver ? resolver(arguments) : arguments;
		alength = (length === false) ? args.length : length;

		clear(alength, args);
	};

	mfn.clearAllCache = function () {
		cache = [];
	};

	return mfn;
};
<|endoftext|>


<commit_before>/* eslint-disable max-len */
import asyncComponent from 'utils/asyncComponent';

export const Home = asyncComponent(() => import(/* webpackChunkName: Home */ 'components/Home'));
export const NotFound = asyncComponent(() => import(/* webpackChunkName: NotFound */ 'components/NotFound'));
export const GettingStarted = asyncComponent(() => import(/* webpackChunkName: GettingStarted */ 'components/GettingStarted'));
export const Colors = asyncComponent(() => import(/* webpackChunkName: Colors */ 'components/Customization/Colors'));
export const Themes = asyncComponent(() => import(/* webpackChunkName: Themes */ 'components/Customization/Themes'));
export const ThemeBuilder = asyncComponent(() => import(/* webpackChunkName: ThemeBuilder */ 'components/Customization/ThemeBuilder'));
export const Typography = asyncComponent(() => import(/* webpackChunkName: Typography */ 'components/Customization/Typography'));
export const MediaQueries = asyncComponent(() => import(/* webpackChunkName: MediaQueries */ 'components/Customization/MediaQueries'));
export const MinimizingBundle = asyncComponent(() => import(/* webpackChunkName: MinimizingBundle */ 'components/Customization/MinimizingBundle'));
export const WhatsNew = asyncComponent(() => import(/* webpackChunkName: WhatsNew */ 'components/DiscoverMore/WhatsNew'));
export const UpgradeV030 = asyncComponent(() => import(/* webpackChunkName: UpgradeV030 */ 'components/DiscoverMore/UpgradeGuides/v0.3.0'));
export const UpgradeV100 = asyncComponent(() => import(/* webpackChunkName: UpgradeV100 */ 'components/DiscoverMore/UpgradeGuides/v1.0.0'));
export const UpgradeV110 = asyncComponent(() => import(/* webpackChunkName: UpgradeV110 */ 'components/DiscoverMore/UpgradeGuides/v1.1.0'));
export const Showcases = asyncComponent(() => import(/* webpackChunkName: Showcases */ 'components/DiscoverMore/Showcases'));
export const Community = asyncComponent(() => import(/* webpackChunkName: Community */ 'components/DiscoverMore/Community'));
export const Contributing = asyncComponent(() => import(/* webpackChunkName: Contributing */ 'components/DiscoverMore/Contributing'));
export const Testing = asyncComponent(() => import(/* webpackChunkName: Testing */ 'components/DiscoverMore/Testing'));

export const SassDocPage = asyncComponent(() => import(/* webpackChunkName: SassDocPage */ 'components/SassDocPage'));
export const PropTypesPage = asyncComponent(() => import(/* webpackChunkName: PropTypesPage */ 'components/PropTypesPage'));

// routing examples
export const BottomNavigationRouting = asyncComponent(() => import(/* webpackChunkName: BottomNavigationRouting */ 'components/Components/BottomNavigations/RoutingExample'));
export const DrawerRouting = asyncComponent(() => import(/* webpackChunkName: DrawerRouting */ 'components/Components/Drawers/RoutingExample'));
export const NavigationDrawerRouting = asyncComponent(() => import(/* webpackChunkName: NavigationDrawerRouting */ 'components/Components/NavigationDrawers/RoutingExample'));

// components
export const Autocompletes = asyncComponent(() => import(/* webpackChunkName: Autocompletes */ 'components/Components/Autocompletes'));
export const Avatars = asyncComponent(() => import(/* webpackChunkName: Avatars */ 'components/Components/Avatars'));
export const Badges = asyncComponent(() => import(/* webpackChunkName: Badges */ 'components/Components/Badges'));
export const BottomNavigations = asyncComponent(() => import(/* webpackChunkName: BottomNavigations */ 'components/Components/BottomNavigations'));
export const Buttons = asyncComponent(() => import(/* webpackChunkName: Buttons */ 'components/Components/Buttons'));
export const Cards = asyncComponent(() => import(/* webpackChunkName: Cards */ 'components/Components/Cards'));
export const Chips = asyncComponent(() => import(/* webpackChunkName: Chips */ 'components/Components/Chips'));
export const DataTables = asyncComponent(() => import(/* webpackChunkName: DataTables */ 'components/Components/DataTables'));
export const Dialogs = asyncComponent(() => import(/* webpackChunkName: Dialogs */ 'components/Components/Dialogs'));
export const Dividers = asyncComponent(() => import(/* webpackChunkName: Dividers */ 'components/Components/Dividers'));
export const Drawers = asyncComponent(() => import(/* webpackChunkName: Drawers */ 'components/Components/Drawers'));
export const ExpansionPanels = asyncComponent(() => import(/* webpackChunkName: ExpansionPanels */ 'components/Components/ExpansionPanels'));
export const FileInputs = asyncComponent(() => import(/* webpackChunkName: FileInputs */ 'components/Components/FileInputs'));
export const FontIcons = asyncComponent(() => import(/* webpackChunkName: FontIcons */ 'components/Components/FontIcons'));
export const Grids = asyncComponent(() => import(/* webpackChunkName: Grids */ 'components/Components/Grids'));
export const AccessibleFakeButtons = asyncComponent(() => import(/* webpackChunkName: AccessibleFakeButtons */ 'components/Components/Helpers/AccessibleFakeButtons'));
export const Collapses = asyncComponent(() => import(/* webpackChunkName: Collapses */ 'components/Components/Helpers/Collapses'));
export const FocusContainers = asyncComponent(() => import(/* webpackChunkName: FocusContainers */ 'components/Components/Helpers/FocusContainers'));
export const IconSeparators = asyncComponent(() => import(/* webpackChunkName: IconSeparators */ 'components/Components/Helpers/IconSeparators'));
export const Layovers = asyncComponent(() => import(/* webpackChunkName: Layovers */ 'components/Components/Helpers/Layovers'));
export const Portals = asyncComponent(() => import(/* webpackChunkName: Portals */ 'components/Components/Helpers/Portals'));
export const ResizeObservers = asyncComponent(() => import(/* webpackChunkName: ResizeObservers */ 'components/Components/Helpers/ResizeObservers'));
export const Inks = asyncComponent(() => import(/* webpackChunkName: Inks */ 'components/Components/Inks'));
export const Lists = asyncComponent(() => import(/* webpackChunkName: Lists */ 'components/Components/Lists'));
export const Media = asyncComponent(() => import(/* webpackChunkName: Media */ 'components/Components/Media'));
export const Menus = asyncComponent(() => import(/* webpackChunkName: Menus */ 'components/Components/Menus'));
export const NavigationDrawers = asyncComponent(() => import(/* webpackChunkName: NavigationDrawers */ 'components/Components/NavigationDrawers'));
export const Papers = asyncComponent(() => import(/* webpackChunkName: Papers */ 'components/Components/Papers'));
export const DatePickers = asyncComponent(() => import(/* webpackChunkName: DatePickers */ 'components/Components/Pickers/Date'));
export const TimePickers = asyncComponent(() => import(/* webpackChunkName: TimePickers */ 'components/Components/Pickers/Time'));
export const CircularProgress = asyncComponent(() => import(/* webpackChunkName: CircularProgress */ 'components/Components/Progress/Circular'));
export const LinearProgress = asyncComponent(() => import(/* webpackChunkName: LinearProgress */ 'components/Components/Progress/Linear'));
export const SelectFields = asyncComponent(() => import(/* webpackChunkName: SelectFields */ 'components/Components/SelectFields'));
export const SelectionControls = asyncComponent(() => import(/* webpackChunkName: SelectionControls */ 'components/Components/SelectionControls'));
export const Sliders = asyncComponent(() => import(/* webpackChunkName: Sliders */ 'components/Components/Sliders'));
export const Snackbars = asyncComponent(() => import(/* webpackChunkName: Snackbars */ 'components/Components/Snackbars'));
export const Subheaders = asyncComponent(() => import(/* webpackChunkName: Subheaders */ 'components/Components/Subheaders'));
export const SVGIcons = asyncComponent(() => import(/* webpackChunkName: SVGIcons */ 'components/Components/SVGIcons'));
export const Tabs = asyncComponent(() => import(/* webpackChunkName: Tabs */ 'components/Components/Tabs'));
export const TextFields = asyncComponent(() => import(/* webpackChunkName: TextFields */ 'components/Components/TextFields'));
export const Toolbars = asyncComponent(() => import(/* webpackChunkName: Toolbars */ 'components/Components/Toolbars'));
export const Tooltips = asyncComponent(() => import(/* webpackChunkName: Tooltips */ 'components/Components/Tooltips'));
<commit_msg>Fixed documentation chunk names<commit_after>/* eslint-disable max-len */
import asyncComponent from 'utils/asyncComponent';

export const Home = asyncComponent(() => import(/* webpackChunkName: "Home" */ 'components/Home'));
export const NotFound = asyncComponent(() => import(/* webpackChunkName: "NotFound" */ 'components/NotFound'));
export const GettingStarted = asyncComponent(() => import(/* webpackChunkName: "GettingStarted" */ 'components/GettingStarted'));
export const Colors = asyncComponent(() => import(/* webpackChunkName: "Colors" */ 'components/Customization/Colors'));
export const Themes = asyncComponent(() => import(/* webpackChunkName: "Themes" */ 'components/Customization/Themes'));
export const ThemeBuilder = asyncComponent(() => import(/* webpackChunkName: "ThemeBuilder" */ 'components/Customization/ThemeBuilder'));
export const Typography = asyncComponent(() => import(/* webpackChunkName: "Typography" */ 'components/Customization/Typography'));
export const MediaQueries = asyncComponent(() => import(/* webpackChunkName: "MediaQueries" */ 'components/Customization/MediaQueries'));
export const MinimizingBundle = asyncComponent(() => import(/* webpackChunkName: "MinimizingBundle" */ 'components/Customization/MinimizingBundle'));
export const WhatsNew = asyncComponent(() => import(/* webpackChunkName: "WhatsNew" */ 'components/DiscoverMore/WhatsNew'));
export const UpgradeV030 = asyncComponent(() => import(/* webpackChunkName: "UpgradeV030" */ 'components/DiscoverMore/UpgradeGuides/v0.3.0'));
export const UpgradeV100 = asyncComponent(() => import(/* webpackChunkName: "UpgradeV100" */ 'components/DiscoverMore/UpgradeGuides/v1.0.0'));
export const UpgradeV110 = asyncComponent(() => import(/* webpackChunkName: "UpgradeV110" */ 'components/DiscoverMore/UpgradeGuides/v1.1.0'));
export const Showcases = asyncComponent(() => import(/* webpackChunkName: "Showcases" */ 'components/DiscoverMore/Showcases'));
export const Community = asyncComponent(() => import(/* webpackChunkName: "Community" */ 'components/DiscoverMore/Community'));
export const Contributing = asyncComponent(() => import(/* webpackChunkName: "Contributing" */ 'components/DiscoverMore/Contributing'));
export const Testing = asyncComponent(() => import(/* webpackChunkName: "Testing" */ 'components/DiscoverMore/Testing'));

export const SassDocPage = asyncComponent(() => import(/* webpackChunkName: "SassDocPage" */ 'components/SassDocPage'));
export const PropTypesPage = asyncComponent(() => import(/* webpackChunkName: "PropTypesPage" */ 'components/PropTypesPage'));

// routing examples
export const BottomNavigationRouting = asyncComponent(() => import(/* webpackChunkName: "BottomNavigationRouting" */ 'components/Components/BottomNavigations/RoutingExample'));
export const DrawerRouting = asyncComponent(() => import(/* webpackChunkName: "DrawerRouting" */ 'components/Components/Drawers/RoutingExample'));
export const NavigationDrawerRouting = asyncComponent(() => import(/* webpackChunkName: "NavigationDrawerRouting" */ 'components/Components/NavigationDrawers/RoutingExample'));

// components
export const Autocompletes = asyncComponent(() => import(/* webpackChunkName: "Autocompletes" */ 'components/Components/Autocompletes'));
export const Avatars = asyncComponent(() => import(/* webpackChunkName: "Avatars" */ 'components/Components/Avatars'));
export const Badges = asyncComponent(() => import(/* webpackChunkName: "Badges" */ 'components/Components/Badges'));
export const BottomNavigations = asyncComponent(() => import(/* webpackChunkName: "BottomNavigations" */ 'components/Components/BottomNavigations'));
export const Buttons = asyncComponent(() => import(/* webpackChunkName: "Buttons" */ 'components/Components/Buttons'));
export const Cards = asyncComponent(() => import(/* webpackChunkName: "Cards" */ 'components/Components/Cards'));
export const Chips = asyncComponent(() => import(/* webpackChunkName: "Chips" */ 'components/Components/Chips'));
export const DataTables = asyncComponent(() => import(/* webpackChunkName: "DataTables" */ 'components/Components/DataTables'));
export const Dialogs = asyncComponent(() => import(/* webpackChunkName: "Dialogs" */ 'components/Components/Dialogs'));
export const Dividers = asyncComponent(() => import(/* webpackChunkName: "Dividers" */ 'components/Components/Dividers'));
export const Drawers = asyncComponent(() => import(/* webpackChunkName: "Drawers" */ 'components/Components/Drawers'));
export const ExpansionPanels = asyncComponent(() => import(/* webpackChunkName: "ExpansionPanels" */ 'components/Components/ExpansionPanels'));
export const FileInputs = asyncComponent(() => import(/* webpackChunkName: "FileInputs" */ 'components/Components/FileInputs'));
export const FontIcons = asyncComponent(() => import(/* webpackChunkName: "FontIcons" */ 'components/Components/FontIcons'));
export const Grids = asyncComponent(() => import(/* webpackChunkName: "Grids" */ 'components/Components/Grids'));
export const AccessibleFakeButtons = asyncComponent(() => import(/* webpackChunkName: "AccessibleFakeButtons" */ 'components/Components/Helpers/AccessibleFakeButtons'));
export const Collapses = asyncComponent(() => import(/* webpackChunkName: "Collapses" */ 'components/Components/Helpers/Collapses'));
export const FocusContainers = asyncComponent(() => import(/* webpackChunkName: "FocusContainers" */ 'components/Components/Helpers/FocusContainers'));
export const IconSeparators = asyncComponent(() => import(/* webpackChunkName: "IconSeparators" */ 'components/Components/Helpers/IconSeparators'));
export const Layovers = asyncComponent(() => import(/* webpackChunkName: "Layovers" */ 'components/Components/Helpers/Layovers'));
export const Portals = asyncComponent(() => import(/* webpackChunkName: "Portals" */ 'components/Components/Helpers/Portals'));
export const ResizeObservers = asyncComponent(() => import(/* webpackChunkName: "ResizeObservers" */ 'components/Components/Helpers/ResizeObservers'));
export const Inks = asyncComponent(() => import(/* webpackChunkName: "Inks" */ 'components/Components/Inks'));
export const Lists = asyncComponent(() => import(/* webpackChunkName: "Lists" */ 'components/Components/Lists'));
export const Media = asyncComponent(() => import(/* webpackChunkName: "Media" */ 'components/Components/Media'));
export const Menus = asyncComponent(() => import(/* webpackChunkName: "Menus" */ 'components/Components/Menus'));
export const NavigationDrawers = asyncComponent(() => import(/* webpackChunkName: "NavigationDrawers" */ 'components/Components/NavigationDrawers'));
export const Papers = asyncComponent(() => import(/* webpackChunkName: "Papers" */ 'components/Components/Papers'));
export const DatePickers = asyncComponent(() => import(/* webpackChunkName: "DatePickers" */ 'components/Components/Pickers/Date'));
export const TimePickers = asyncComponent(() => import(/* webpackChunkName: "TimePickers" */ 'components/Components/Pickers/Time'));
export const CircularProgress = asyncComponent(() => import(/* webpackChunkName: "CircularProgress" */ 'components/Components/Progress/Circular'));
export const LinearProgress = asyncComponent(() => import(/* webpackChunkName: "LinearProgress" */ 'components/Components/Progress/Linear'));
export const SelectFields = asyncComponent(() => import(/* webpackChunkName: "SelectFields" */ 'components/Components/SelectFields'));
export const SelectionControls = asyncComponent(() => import(/* webpackChunkName: "SelectionControls" */ 'components/Components/SelectionControls'));
export const Sliders = asyncComponent(() => import(/* webpackChunkName: "Sliders" */ 'components/Components/Sliders'));
export const Snackbars = asyncComponent(() => import(/* webpackChunkName: "Snackbars" */ 'components/Components/Snackbars'));
export const Subheaders = asyncComponent(() => import(/* webpackChunkName: "Subheaders" */ 'components/Components/Subheaders'));
export const SVGIcons = asyncComponent(() => import(/* webpackChunkName: "SVGIcons" */ 'components/Components/SVGIcons'));
export const Tabs = asyncComponent(() => import(/* webpackChunkName: "Tabs" */ 'components/Components/Tabs'));
export const TextFields = asyncComponent(() => import(/* webpackChunkName: "TextFields" */ 'components/Components/TextFields'));
export const Toolbars = asyncComponent(() => import(/* webpackChunkName: "Toolbars" */ 'components/Components/Toolbars'));
export const Tooltips = asyncComponent(() => import(/* webpackChunkName: "Tooltips" */ 'components/Components/Tooltips'));
<|endoftext|>