<commit_before>'use strict';

angular.module('lexicon.services', ['jsonRpc', 'bellows.services', 'sgw.ui.breadcrumb'])

// Lexicon Link Service
.service('lexLinkService', ['$location', 'sessionService', function($location, ss) {
  this.project = function project() {
    return '/app/lexicon/' + this.getProjectId();
  };

  this.projectView = function projectView(view) {
    return this.project() + '/' + view;
  };

  this.getProjectId = function getProjectId() {
    return ss.session.project.id;
  };
}])

// Lexicon Project Service
.service('lexProjectService', ['jsonRpc', 'sessionService', 'breadcrumbService', 'lexLinkService', '$location',
function(jsonRpc, ss, breadcrumbService, linkService, $location) {
  jsonRpc.connect('/api/sf');

  this.setBreadcrumbs = function setBreadcrumbs(view, label) {
    breadcrumbService.set('top', [{
      href: '/app/projects',
      label: 'My Projects'
    }, {
      href: linkService.project(),
      label: ss.session.project.projectName
    }, {
      href: linkService.projectView(view),
      label: label
    }]);
  };

  this.baseViewDto = function baseViewDto(view, label, callback) {
    var setBreadcrumbs = this.setBreadcrumbs;
    jsonRpc.call('lex_baseViewDto', [], function(result) {
      if (result.ok) {
        setBreadcrumbs(view, label);
      }
      callback(result);
    });
  };

  this.updateConfiguration = function updateConfiguration(config, optionlist, callback) {
    jsonRpc.call('lex_configuration_update', [config, optionlist], callback);
  };

  this.updateOptionList = function updateOptionList(optionList, callback) {
    jsonRpc.call('lex_optionlist_update', [optionList], callback);
  };

  this.readProject = function readProject(callback) {
    jsonRpc.call('lex_projectDto', [], callback);
  };

  this.updateProject = function updateProject(project, callback) {
    jsonRpc.call('lex_project_update', [project], callback);
  };
  this.updateSettings = function updateSettings(smsSettings, emailSettings, callback) {
    jsonRpc.call('project_updateSettings', [smsSettings, emailSettings], callback);
  };
  this.readSettings = function readSettings(callback) {
    jsonRpc.call('project_readSettings', [], callback);
  };
  this.users = function users(callback) {
    jsonRpc.call('project_usersDto', [], callback);
  };

  this.updateUserProfile = function updateUserProfile(user, callback) {
    jsonRpc.call('user_updateProfile', [user], callback);
  };

  this.removeMediaFile = function removeMediaFile(mediaType, fileName, callback) {
    jsonRpc.call('lex_project_removeMediaFile', [mediaType, fileName], callback);
  };

  this.getProjectId = function getProjectId() {
    return ss.session.project.id;
    // var parts = $location.path().split('/');
    // // strip off the "/p/"
    // return parts[2];
  };
}])

// Lexicon Comment Service
.service('lexCommentService', ['jsonRpc', function(jsonRpc) {
  jsonRpc.connect('/api/sf');

  this.update = function updateComment(comment, callback) {
    jsonRpc.call('lex_comment_update', [comment], callback);
  };

  this.updateReply = function updateReply(commentId, reply, callback) {
    jsonRpc.call('lex_commentReply_update', [commentId, reply], callback);
  };

  this.remove = function deleteComment(commentId, callback) {
    jsonRpc.call('lex_comment_delete', [commentId], callback);
  };

  this.deleteReply = function deleteReply(commentId, replyId, callback) {
    jsonRpc.call('lex_commentReply_delete', [commentId, replyId], callback);
  };

  this.plusOne = function plusOne(commentId, callback) {
    jsonRpc.call('lex_comment_plusOne', [commentId], callback);
  };

  this.updateStatus = function updateStatus(commentId, status, callback) {
    jsonRpc.call('lex_comment_updateStatus', [commentId, status], callback);
  };
}])

// Lexicon Configuration Service
.service('lexConfigService', ['sessionService', function(ss) {
  this.isTaskEnabled = function isTaskEnabled(taskName) {
    var config = ss.session.projectSettings.config,
      role = ss.session.projectSettings.currentUserRole,
      userId = ss.session.userId;
    if (angular.isDefined(config.userViews[userId])) {
      return config.userViews[userId].showTasks[taskName];
    } else {

      // fallback to role-based field config
      return config.roleViews[role].showTasks[taskName];
    }
  };

  this.getConfigForUser = function getConfigForUser() {
    var config = angular.copy(ss.session.projectSettings.config),
      userId = ss.session.userId,
      role = ss.session.projectSettings.currentUserRole,
      fieldsConfig;

    // copy option lists to config object
    config.optionlists = {};
    angular.forEach(ss.session.projectSettings.optionlists, function(optionlist) {
      config.optionlists[optionlist.code] = optionlist;
    });

    // use an user-based field config if defined
    if (angular.isDefined(config.userViews[userId])) {
      fieldsConfig = config.userViews[userId];
    } else {

      // fallback to role-based field config
      fieldsConfig = config.roleViews[role];
    }

    removeDisabledConfigFields(config.entry, fieldsConfig);
    removeDisabledConfigFields(config.entry.fields.senses, fieldsConfig);
    removeDisabledConfigFields(config.entry.fields.senses.fields.examples, fieldsConfig);

    return config;
  };

  this.fieldContainsData = function fieldContainsData(type, model) {
    var containsData = false;

    if (angular.isUndefined(model))
      return false;
    if (type == 'fields')
      return true;
    switch (type) {
      case 'multitext':
        angular.forEach(model, function(field) {
          if (field.value != '') {
            containsData = true;
          }
        });
        break;
      case 'optionlist':
        if (model.value != '') {
          containsData = true;
        }
        break;
      case 'multioptionlist':
        if (model.values.length > 0) {
          containsData = true;
        }
        break;
      case 'pictures':
        if (model.length > 0) {
          containsData = true;
        }
        break;
    }
    return containsData;
  };

  function removeDisabledConfigFields(config, fieldsConfig) {
    angular.forEach(config.fieldOrder, function(fieldName) {
      if (fieldName != 'senses' && fieldName != 'examples') {
        var fieldConfig = fieldsConfig.fields[fieldName];

        if (fieldConfig && fieldConfig.show) {
          // field is enabled

          // override input systems if specified
          if (fieldConfig.overrideInputSystems) {
            config.fields[fieldName].inputSystems = angular.copy(fieldConfig.inputSystems);
          }
        } else {
          // remove config field
          delete config.fields[fieldName];

          // remove field from fieldOrder array
          config.fieldOrder.splice(config.fieldOrder.indexOf(fieldName), 1);
        }
      }
    });
  }

  this.isCustomField = function isCustomField(fieldName) {
    return fieldName.search('customField_') === 0;
  };

  this.getFieldConfig = function getFieldConfig(fieldName) {
    var config = ss.session.projectSettings.config,
      search = config.entry.fields;

    if (angular.isDefined(search[fieldName])) {
      return search[fieldName];
    }

    search = config.entry.fields.senses.fields;
    if (angular.isDefined(search[fieldName])) {
      return search[fieldName];
    }

    search = config.entry.fields.senses.fields.examples.fields;
    if (angular.isDefined(search[fieldName])) {
      return search[fieldName];
    }
    return undefined;
  };

  /*
   * this.isFieldEnabled = function(fieldName, ws) {
   *
   * var config = ss.session.projectSettings.config; var userId =
   * ss.session.userId; var role = ss.session.projectSettings.currentUserRole;
   * var fieldConfig; // use an user-based field config if defined if
   * (angular.isDefined(config.userViews[userId])) { fieldConfig =
   * config.userViews[userId].fields[fieldName]; } else { // fallback to
   * role-based field config fieldConfig =
   * config.roleViews[role].fields[fieldName]; }
   *
   * if (!fieldConfig) { console.log(fieldName); } // field-level visibility var
   * show = fieldConfig.show; // input system level visibility if (ws &&
   * fieldConfig.show && fieldConfig.overrideInputSystems) { if
   * (fieldConfig.inputSystems.indexOf(ws) != -1) { show = true; } else { show =
   * false; } } return show; };
   *
   * this.isUncommonField = function isUncommonField(fieldName) { var
   * fieldConfig = getFieldConfig(fieldName); return fieldConfig.hideIfEmpty; };
   *
   *
   * this.isFieldVisible = function isFieldVisible(showUncommon, fieldName,
   * type, model) { if (type == 'fields') return true; var isVisible = true;
   *
   * if (!showUncommon && this.isUncommonField(fieldName)) { isVisible = false;
   * switch (type) { case 'multitext': angular.forEach(model, function(ws) { if
   * (model[ws].value != '') { isVisible = true; } }); break; case 'optionlist':
   * case 'multioptionlist': if (model.value != '') { isVisible = true; } break; } }
   *
   * return isVisible; };
   *
   */

}])

// Lexicon Entry Service
.service('lexEntryService', ['jsonRpc', 'sessionService', 'lexProjectService', 'breadcrumbService', 'lexLinkService',
function(jsonRpc, ss, projectService, breadcrumbService, linkService) {
  jsonRpc.connect('/api/sf');

  /*
   * not currently used this.read = function readEntry(id, callback) {
   * jsonRpc.call('lex_entry_read', [id], callback); };
   */

  this.update = function updateEntry(entry, callback) {
    jsonRpc.call('lex_entry_update', [entry], callback);
  };

  this.remove = function(id, callback) {
    jsonRpc.call('lex_entry_remove', [id], callback);
  };

  this.dbeDto = function dbeDto(browserId, fullRefresh, callback) {
    if (fullRefresh) {
      jsonRpc.call('lex_dbeDtoFull', [browserId], function(result) {
        if (result.ok) {
          // todo move breadcrumbs back to controller - cjh 2014-07
          breadcrumbService.set('top', [{
            href: '/app/projects',
            label: 'My Projects'
          }, {
            href: linkService.project(),
            label: ss.session.project.projectName
          }, {
            href: linkService.projectView('dbe'),
            label: 'Browse And Edit'
          }]);
        }
        callback(result);
      });
    } else {
      jsonRpc.call('lex_dbeDtoUpdatesOnly', [browserId], callback);
    }
  };

  this.updateComment = function updateComment(comment, callback) {
    jsonRpc.call('lex_entry_updateComment', [comment], callback);
  };

}]).service('lexUtils', [function() {

  function getFirstField(config, node, fieldName) {
    var result = '', ws, field;
    if (node[fieldName] && config && config.fields && config.fields[fieldName] && config.fields[fieldName].inputSystems) {
      for (var i = 0; i < config.fields[fieldName].inputSystems.length; i++) {
        ws = config.fields[fieldName].inputSystems[i];
        field = node[fieldName][ws];
        if (angular.isDefined(field) && angular.isDefined(field.value) && field.value != '') {
          result = field.value;
          break;
        }
      }
    }
    return result;
  };

  function getFields(config, node, fieldName, delimiter) {
    var result = '';
    if (typeof(delimiter) === 'undefined') delimiter = ' ';
    if (node[fieldName] && config && config.fields && config.fields[fieldName] && config.fields[fieldName].inputSystems) {
      angular.forEach(config.fields[fieldName].inputSystems, function (inputSystem) {
        var field = node[fieldName][inputSystem];
        if (angular.isDefined(field) && angular.isDefined(field.value) && field.value != '') {
          if (result) {
            result += delimiter + field.value;
          } else {
            result = field.value;
          }
        }
      });
    }
    return result;
  };

  /**
   *
   * @param config - entry config obj
   * @param entry
   * @returns {string}
   */
  this.getLexeme = function getLexeme(config, entry) {
    return getFirstField(config, entry, 'lexeme');
  };
  this.getWords = function getWords(config, entry) {
    return getFields(config, entry, 'lexeme');
  };

  this.getCitationForms = function(config, entry) {
    var citation = '';
    var citationFormByInputSystem = {};
    if (angular.isDefined(config.fields.citationForm)) {
      angular.forEach(config.fields.citationForm.inputSystems, function(inputSystem) {
        if (angular.isDefined(entry.citationForm)) {
          var field = entry.citationForm[inputSystem];
          if (angular.isDefined(field) && angular.isDefined(field.value) && field.value != '') {
            citationFormByInputSystem[inputSystem] = field.value;
          }
        }
      });
    }
    angular.forEach(config.fields.lexeme.inputSystems, function(inputSystem) {
      var field = entry.lexeme[inputSystem];
      var valueToAppend = '';
      if (angular.isDefined(citationFormByInputSystem[inputSystem])) {
        valueToAppend = citationFormByInputSystem[inputSystem]
      } else if (angular.isDefined(field) && angular.isDefined(field.value)) {
        valueToAppend = field.value;
      }
      if (valueToAppend) {
        if (citation) {
          citation += ' ' + valueToAppend;
        } else {
          citation += valueToAppend;
        }
      }
    });
    return citation;
  };

  this.getDefinition = function getDefinition(config, sense) {
    return getFirstField(config, sense, 'definition');
  };
  this.getGloss = function getGloss(config, sense) {
    return getFirstField(config, sense, 'gloss');
  };
  this.getMeaning = function getMeaning(config, sense) {
    var meaning = '';
    meaning = this.getDefinition(config, sense);
    if (!meaning) {
      meaning = this.getGloss(config, sense);
    }
    return meaning;
  };
  this.getMeanings = function getMeanings(config, sense) {
    var meaning = '';
    meaning = getFields(config, sense, 'definition');
    if (!meaning) {
      meaning = getFields(config, sense, 'gloss');
    }
    return meaning;
  };

  this.getExampleSentence = function getExampleSentence(config, example) {
    return getFields(config, example, 'sentence');
  };

  this.getPartOfSpeechAbbreviation = function getPartOfSpeechAbbreviation(posModel, optionlists) {
    if (angular.isDefined(posModel)) {
      if (angular.isDefined(optionlists)) {
        var abbreviation = '';
        angular.forEach(optionlists, function(optionlist) {
          if (optionlist.code == 'partOfSpeech' || optionlist.code == 'grammatical-info') {
            angular.forEach(optionlist.items, function(item) {
              if (item.value == posModel.value) {
                abbreviation = item.abbreviation;
              }
            });
          }
        });
        if (abbreviation)
          return abbreviation;
      }

      // capture text inside parentheses
      var myRegexp = /\((.*)\)/;
      var match = myRegexp.exec(posModel.value);
      if (match && match.length > 1) {
        return match[1];
      } else if (! posModel.value) {
        return '';
      } else {
        return posModel.value.toLowerCase().substring(0, 5);
      }
    }
    return '';
  };

}]);
<commit_msg>fix HideIfEmpty on option lists<commit_after>'use strict';

angular.module('lexicon.services', ['jsonRpc', 'bellows.services', 'sgw.ui.breadcrumb'])

// Lexicon Link Service
.service('lexLinkService', ['$location', 'sessionService', function($location, ss) {
  this.project = function project() {
    return '/app/lexicon/' + this.getProjectId();
  };

  this.projectView = function projectView(view) {
    return this.project() + '/' + view;
  };

  this.getProjectId = function getProjectId() {
    return ss.session.project.id;
  };
}])

// Lexicon Project Service
.service('lexProjectService', ['jsonRpc', 'sessionService', 'breadcrumbService', 'lexLinkService', '$location',
function(jsonRpc, ss, breadcrumbService, linkService, $location) {
  jsonRpc.connect('/api/sf');

  this.setBreadcrumbs = function setBreadcrumbs(view, label) {
    breadcrumbService.set('top', [{
      href: '/app/projects',
      label: 'My Projects'
    }, {
      href: linkService.project(),
      label: ss.session.project.projectName
    }, {
      href: linkService.projectView(view),
      label: label
    }]);
  };

  this.baseViewDto = function baseViewDto(view, label, callback) {
    var setBreadcrumbs = this.setBreadcrumbs;
    jsonRpc.call('lex_baseViewDto', [], function(result) {
      if (result.ok) {
        setBreadcrumbs(view, label);
      }
      callback(result);
    });
  };

  this.updateConfiguration = function updateConfiguration(config, optionlist, callback) {
    jsonRpc.call('lex_configuration_update', [config, optionlist], callback);
  };

  this.updateOptionList = function updateOptionList(optionList, callback) {
    jsonRpc.call('lex_optionlist_update', [optionList], callback);
  };

  this.readProject = function readProject(callback) {
    jsonRpc.call('lex_projectDto', [], callback);
  };

  this.updateProject = function updateProject(project, callback) {
    jsonRpc.call('lex_project_update', [project], callback);
  };
  this.updateSettings = function updateSettings(smsSettings, emailSettings, callback) {
    jsonRpc.call('project_updateSettings', [smsSettings, emailSettings], callback);
  };
  this.readSettings = function readSettings(callback) {
    jsonRpc.call('project_readSettings', [], callback);
  };
  this.users = function users(callback) {
    jsonRpc.call('project_usersDto', [], callback);
  };

  this.updateUserProfile = function updateUserProfile(user, callback) {
    jsonRpc.call('user_updateProfile', [user], callback);
  };

  this.removeMediaFile = function removeMediaFile(mediaType, fileName, callback) {
    jsonRpc.call('lex_project_removeMediaFile', [mediaType, fileName], callback);
  };

  this.getProjectId = function getProjectId() {
    return ss.session.project.id;
    // var parts = $location.path().split('/');
    // // strip off the "/p/"
    // return parts[2];
  };
}])

// Lexicon Comment Service
.service('lexCommentService', ['jsonRpc', function(jsonRpc) {
  jsonRpc.connect('/api/sf');

  this.update = function updateComment(comment, callback) {
    jsonRpc.call('lex_comment_update', [comment], callback);
  };

  this.updateReply = function updateReply(commentId, reply, callback) {
    jsonRpc.call('lex_commentReply_update', [commentId, reply], callback);
  };

  this.remove = function deleteComment(commentId, callback) {
    jsonRpc.call('lex_comment_delete', [commentId], callback);
  };

  this.deleteReply = function deleteReply(commentId, replyId, callback) {
    jsonRpc.call('lex_commentReply_delete', [commentId, replyId], callback);
  };

  this.plusOne = function plusOne(commentId, callback) {
    jsonRpc.call('lex_comment_plusOne', [commentId], callback);
  };

  this.updateStatus = function updateStatus(commentId, status, callback) {
    jsonRpc.call('lex_comment_updateStatus', [commentId, status], callback);
  };
}])

// Lexicon Configuration Service
.service('lexConfigService', ['sessionService', function(ss) {
  this.isTaskEnabled = function isTaskEnabled(taskName) {
    var config = ss.session.projectSettings.config,
      role = ss.session.projectSettings.currentUserRole,
      userId = ss.session.userId;
    if (angular.isDefined(config.userViews[userId])) {
      return config.userViews[userId].showTasks[taskName];
    } else {

      // fallback to role-based field config
      return config.roleViews[role].showTasks[taskName];
    }
  };

  this.getConfigForUser = function getConfigForUser() {
    var config = angular.copy(ss.session.projectSettings.config),
      userId = ss.session.userId,
      role = ss.session.projectSettings.currentUserRole,
      fieldsConfig;

    // copy option lists to config object
    config.optionlists = {};
    angular.forEach(ss.session.projectSettings.optionlists, function(optionlist) {
      config.optionlists[optionlist.code] = optionlist;
    });

    // use an user-based field config if defined
    if (angular.isDefined(config.userViews[userId])) {
      fieldsConfig = config.userViews[userId];
    } else {

      // fallback to role-based field config
      fieldsConfig = config.roleViews[role];
    }

    removeDisabledConfigFields(config.entry, fieldsConfig);
    removeDisabledConfigFields(config.entry.fields.senses, fieldsConfig);
    removeDisabledConfigFields(config.entry.fields.senses.fields.examples, fieldsConfig);

    return config;
  };

  this.fieldContainsData = function fieldContainsData(type, model) {
    var containsData = false;

    if (angular.isUndefined(model))
      return false;
    if (type == 'fields')
      return true;
    switch (type) {
      case 'multitext':
        angular.forEach(model, function(field) {
          if (field.value && field.value != '') {
            containsData = true;
          }
        });
        break;
      case 'optionlist':
        if (model.value && model.value != '') {
          containsData = true;
        }
        break;
      case 'multioptionlist':
        if (model.values.length > 0) {
          containsData = true;
        }
        break;
      case 'pictures':
        if (model.length > 0) {
          containsData = true;
        }
        break;
    }
    return containsData;
  };

  function removeDisabledConfigFields(config, fieldsConfig) {
    angular.forEach(config.fieldOrder, function(fieldName) {
      if (fieldName != 'senses' && fieldName != 'examples') {
        var fieldConfig = fieldsConfig.fields[fieldName];

        if (fieldConfig && fieldConfig.show) {
          // field is enabled

          // override input systems if specified
          if (fieldConfig.overrideInputSystems) {
            config.fields[fieldName].inputSystems = angular.copy(fieldConfig.inputSystems);
          }
        } else {
          // remove config field
          delete config.fields[fieldName];

          // remove field from fieldOrder array
          config.fieldOrder.splice(config.fieldOrder.indexOf(fieldName), 1);
        }
      }
    });
  }

  this.isCustomField = function isCustomField(fieldName) {
    return fieldName.search('customField_') === 0;
  };

  this.getFieldConfig = function getFieldConfig(fieldName) {
    var config = ss.session.projectSettings.config,
      search = config.entry.fields;

    if (angular.isDefined(search[fieldName])) {
      return search[fieldName];
    }

    search = config.entry.fields.senses.fields;
    if (angular.isDefined(search[fieldName])) {
      return search[fieldName];
    }

    search = config.entry.fields.senses.fields.examples.fields;
    if (angular.isDefined(search[fieldName])) {
      return search[fieldName];
    }
    return undefined;
  };

  /*
   * this.isFieldEnabled = function(fieldName, ws) {
   *
   * var config = ss.session.projectSettings.config; var userId =
   * ss.session.userId; var role = ss.session.projectSettings.currentUserRole;
   * var fieldConfig; // use an user-based field config if defined if
   * (angular.isDefined(config.userViews[userId])) { fieldConfig =
   * config.userViews[userId].fields[fieldName]; } else { // fallback to
   * role-based field config fieldConfig =
   * config.roleViews[role].fields[fieldName]; }
   *
   * if (!fieldConfig) { console.log(fieldName); } // field-level visibility var
   * show = fieldConfig.show; // input system level visibility if (ws &&
   * fieldConfig.show && fieldConfig.overrideInputSystems) { if
   * (fieldConfig.inputSystems.indexOf(ws) != -1) { show = true; } else { show =
   * false; } } return show; };
   *
   * this.isUncommonField = function isUncommonField(fieldName) { var
   * fieldConfig = getFieldConfig(fieldName); return fieldConfig.hideIfEmpty; };
   *
   *
   * this.isFieldVisible = function isFieldVisible(showUncommon, fieldName,
   * type, model) { if (type == 'fields') return true; var isVisible = true;
   *
   * if (!showUncommon && this.isUncommonField(fieldName)) { isVisible = false;
   * switch (type) { case 'multitext': angular.forEach(model, function(ws) { if
   * (model[ws].value != '') { isVisible = true; } }); break; case 'optionlist':
   * case 'multioptionlist': if (model.value != '') { isVisible = true; } break; } }
   *
   * return isVisible; };
   *
   */

}])

// Lexicon Entry Service
.service('lexEntryService', ['jsonRpc', 'sessionService', 'lexProjectService', 'breadcrumbService', 'lexLinkService',
function(jsonRpc, ss, projectService, breadcrumbService, linkService) {
  jsonRpc.connect('/api/sf');

  /*
   * not currently used this.read = function readEntry(id, callback) {
   * jsonRpc.call('lex_entry_read', [id], callback); };
   */

  this.update = function updateEntry(entry, callback) {
    jsonRpc.call('lex_entry_update', [entry], callback);
  };

  this.remove = function(id, callback) {
    jsonRpc.call('lex_entry_remove', [id], callback);
  };

  this.dbeDto = function dbeDto(browserId, fullRefresh, callback) {
    if (fullRefresh) {
      jsonRpc.call('lex_dbeDtoFull', [browserId], function(result) {
        if (result.ok) {
          // todo move breadcrumbs back to controller - cjh 2014-07
          breadcrumbService.set('top', [{
            href: '/app/projects',
            label: 'My Projects'
          }, {
            href: linkService.project(),
            label: ss.session.project.projectName
          }, {
            href: linkService.projectView('dbe'),
            label: 'Browse And Edit'
          }]);
        }
        callback(result);
      });
    } else {
      jsonRpc.call('lex_dbeDtoUpdatesOnly', [browserId], callback);
    }
  };

  this.updateComment = function updateComment(comment, callback) {
    jsonRpc.call('lex_entry_updateComment', [comment], callback);
  };

}]).service('lexUtils', [function() {

  function getFirstField(config, node, fieldName) {
    var result = '', ws, field;
    if (node[fieldName] && config && config.fields && config.fields[fieldName] && config.fields[fieldName].inputSystems) {
      for (var i = 0; i < config.fields[fieldName].inputSystems.length; i++) {
        ws = config.fields[fieldName].inputSystems[i];
        field = node[fieldName][ws];
        if (angular.isDefined(field) && angular.isDefined(field.value) && field.value != '') {
          result = field.value;
          break;
        }
      }
    }
    return result;
  };

  function getFields(config, node, fieldName, delimiter) {
    var result = '';
    if (typeof(delimiter) === 'undefined') delimiter = ' ';
    if (node[fieldName] && config && config.fields && config.fields[fieldName] && config.fields[fieldName].inputSystems) {
      angular.forEach(config.fields[fieldName].inputSystems, function (inputSystem) {
        var field = node[fieldName][inputSystem];
        if (angular.isDefined(field) && angular.isDefined(field.value) && field.value != '') {
          if (result) {
            result += delimiter + field.value;
          } else {
            result = field.value;
          }
        }
      });
    }
    return result;
  };

  /**
   *
   * @param config - entry config obj
   * @param entry
   * @returns {string}
   */
  this.getLexeme = function getLexeme(config, entry) {
    return getFirstField(config, entry, 'lexeme');
  };
  this.getWords = function getWords(config, entry) {
    return getFields(config, entry, 'lexeme');
  };

  this.getCitationForms = function(config, entry) {
    var citation = '';
    var citationFormByInputSystem = {};
    if (angular.isDefined(config.fields.citationForm)) {
      angular.forEach(config.fields.citationForm.inputSystems, function(inputSystem) {
        if (angular.isDefined(entry.citationForm)) {
          var field = entry.citationForm[inputSystem];
          if (angular.isDefined(field) && angular.isDefined(field.value) && field.value != '') {
            citationFormByInputSystem[inputSystem] = field.value;
          }
        }
      });
    }
    angular.forEach(config.fields.lexeme.inputSystems, function(inputSystem) {
      var field = entry.lexeme[inputSystem];
      var valueToAppend = '';
      if (angular.isDefined(citationFormByInputSystem[inputSystem])) {
        valueToAppend = citationFormByInputSystem[inputSystem]
      } else if (angular.isDefined(field) && angular.isDefined(field.value)) {
        valueToAppend = field.value;
      }
      if (valueToAppend) {
        if (citation) {
          citation += ' ' + valueToAppend;
        } else {
          citation += valueToAppend;
        }
      }
    });
    return citation;
  };

  this.getDefinition = function getDefinition(config, sense) {
    return getFirstField(config, sense, 'definition');
  };
  this.getGloss = function getGloss(config, sense) {
    return getFirstField(config, sense, 'gloss');
  };
  this.getMeaning = function getMeaning(config, sense) {
    var meaning = '';
    meaning = this.getDefinition(config, sense);
    if (!meaning) {
      meaning = this.getGloss(config, sense);
    }
    return meaning;
  };
  this.getMeanings = function getMeanings(config, sense) {
    var meaning = '';
    meaning = getFields(config, sense, 'definition');
    if (!meaning) {
      meaning = getFields(config, sense, 'gloss');
    }
    return meaning;
  };

  this.getExampleSentence = function getExampleSentence(config, example) {
    return getFields(config, example, 'sentence');
  };

  this.getPartOfSpeechAbbreviation = function getPartOfSpeechAbbreviation(posModel, optionlists) {
    if (angular.isDefined(posModel)) {
      if (angular.isDefined(optionlists)) {
        var abbreviation = '';
        angular.forEach(optionlists, function(optionlist) {
          if (optionlist.code == 'partOfSpeech' || optionlist.code == 'grammatical-info') {
            angular.forEach(optionlist.items, function(item) {
              if (item.value == posModel.value) {
                abbreviation = item.abbreviation;
              }
            });
          }
        });
        if (abbreviation)
          return abbreviation;
      }

      // capture text inside parentheses
      var myRegexp = /\((.*)\)/;
      var match = myRegexp.exec(posModel.value);
      if (match && match.length > 1) {
        return match[1];
      } else if (! posModel.value) {
        return '';
      } else {
        return posModel.value.toLowerCase().substring(0, 5);
      }
    }
    return '';
  };

}]);
<|endoftext|>


<commit_before>try {
    var reporter = require('nodeunit').reporters.default;
} catch(e) {
    console.log("Cannot find nodeunit module.");
    process.exit();
}

process.chdir(__dirname);
reporter.run(['test']);<commit_msg>changed runner.js to use a minimal interface<commit_after>try {
    var reporter = require('nodeunit').reporters.minimal;
} catch(e) {
    console.log("Cannot find nodeunit module.");
    process.exit();
}

process.chdir(__dirname);
reporter.run(['test']);
<|endoftext|>


<commit_before>/**
 * BxSlider v4.1.2 - Fully loaded, responsive content slider
 * http://bxslider.com
 *
 * Copyright 2014, Steven Wanderski - http://stevenwanderski.com - http://bxcreative.com
 * Written while drinking Belgian ales and listening to jazz
 *
 * Released under the MIT license - http://opensource.org/licenses/MIT
 */
!function(t){var e={},s={mode:"horizontal",slideSelector:"",infiniteLoop:!0,hideControlOnEnd:!1,speed:500,easing:null,slideMargin:0,startSlide:0,randomStart:!1,captions:!1,ticker:!1,tickerHover:!1,adaptiveHeight:!1,adaptiveHeightSpeed:500,video:!1,useCSS:!0,preloadImages:"visible",responsive:!0,slideZIndex:50,touchEnabled:!0,swipeThreshold:50,oneToOneTouch:!0,preventDefaultSwipeX:!0,preventDefaultSwipeY:!1,pager:!0,pagerType:"full",pagerShortSeparator:" / ",pagerSelector:null,buildPager:null,pagerCustom:null,controls:!0,nextText:"Next",prevText:"Prev",nextSelector:null,prevSelector:null,autoControls:!1,startText:"Start",stopText:"Stop",autoControlsCombine:!1,autoControlsSelector:null,auto:!1,pause:4e3,autoStart:!0,autoDirection:"next",autoHover:!1,autoDelay:0,minSlides:1,maxSlides:1,moveSlides:0,slideWidth:0,onSliderLoad:function(){},onSlideBefore:function(){},onSlideAfter:function(){},onSlideNext:function(){},onSlidePrev:function(){},onSliderResize:function(){}};t.fn.bxSlider=function(n){if(0==this.length)return this;if(this.length>1)return this.each(function(){t(this).bxSlider(n)}),this;var o={},r=this;e.el=this;var a=t(window).width(),l=t(window).height(),d=function(){o.settings=t.extend({},s,n),o.settings.slideWidth=parseInt(o.settings.slideWidth),o.children=r.children(o.settings.slideSelector),o.children.length<o.settings.minSlides&&(o.settings.minSlides=o.children.length),o.children.length<o.settings.maxSlides&&(o.settings.maxSlides=o.children.length),o.settings.randomStart&&(o.settings.startSlide=Math.floor(Math.random()*o.children.length)),o.active={index:o.settings.startSlide},o.carousel=o.settings.minSlides>1||o.settings.maxSlides>1,o.carousel&&(o.settings.preloadImages="all"),o.minThreshold=o.settings.minSlides*o.settings.slideWidth+(o.settings.minSlides-1)*o.settings.slideMargin,o.maxThreshold=o.settings.maxSlides*o.settings.slideWidth+(o.settings.maxSlides-1)*o.settings.slideMargin,o.working=!1,o.controls={},o.interval=null,o.animProp="vertical"==o.settings.mode?"top":"left",o.usingCSS=o.settings.useCSS&&"fade"!=o.settings.mode&&function(){var t=document.createElement("div"),e=["WebkitPerspective","MozPerspective","OPerspective","msPerspective"];for(var i in e)if(void 0!==t.style[e[i]])return o.cssPrefix=e[i].replace("Perspective","").toLowerCase(),o.animProp="-"+o.cssPrefix+"-transform",!0;return!1}(),"vertical"==o.settings.mode&&(o.settings.maxSlides=o.settings.minSlides),r.data("origStyle",r.attr("style")),r.children(o.settings.slideSelector).each(function(){t(this).data("origStyle",t(this).attr("style"))}),c()},c=function(){r.wrap('

'),o.viewport=r.parent(),o.loader=t('
'),o.viewport.prepend(o.loader),r.css({width:"horizontal"==o.settings.mode?100*o.children.length+215+"%":"auto",position:"relative"}),o.usingCSS&&o.settings.easing?r.css("-"+o.cssPrefix+"-transition-timing-function",o.settings.easing):o.settings.easing||(o.settings.easing="swing"),f(),o.viewport.css({width:"100%",overflow:"hidden",position:"relative"}),o.viewport.parent().css({maxWidth:p()}),o.settings.pager||o.viewport.parent().css({margin:"0 auto 0px"}),o.children.css({"float":"horizontal"==o.settings.mode?"left":"none",listStyle:"none",position:"relative"}),o.children.css("width",u()),"horizontal"==o.settings.mode&&o.settings.slideMargin>0&&o.children.css("marginRight",o.settings.slideMargin),"vertical"==o.settings.mode&&o.settings.slideMargin>0&&o.children.css("marginBottom",o.settings.slideMargin),"fade"==o.settings.mode&&(o.children.css({position:"absolute",zIndex:0,display:"none"}),o.children.eq(o.settings.startSlide).css({zIndex:o.settings.slideZIndex,display:"block"})),o.controls.el=t('
'),o.settings.captions&&P(),o.active.last=o.settings.startSlide==x()-1,o.settings.video&&r.fitVids();var e=o.children.eq(o.settings.startSlide);"all"==o.settings.preloadImages&&(e=o.children),o.settings.ticker?o.settings.pager=!1:(o.settings.pager&&T(),o.settings.controls&&C(),o.settings.auto&&o.settings.autoControls&&E(),(o.settings.controls||o.settings.autoControls||o.settings.pager)&&o.viewport.after(o.controls.el)),g(e,h)},g=function(e,i){var s=e.find("img, iframe").length;if(0==s)return i(),void 0;var n=0;e.find("img, iframe").each(function(){t(this).one("load",function(){++n==s&&i()}).each(function(){this.complete&&t(this).load()})})},h=function(){if(o.settings.infiniteLoop&&"fade"!=o.settings.mode&&!o.settings.ticker){var e="vertical"==o.settings.mode?o.settings.minSlides:o.settings.maxSlides,i=o.children.slice(0,e).clone().addClass("bx-clone"),s=o.children.slice(-e).clone().addClass("bx-clone");r.append(i).prepend(s)}o.loader.remove(),S(),"vertical"==o.settings.mode&&(o.settings.adaptiveHeight=!0),o.viewport.height(v()),r.redrawSlider(),o.settings.onSliderLoad(o.active.index),o.initialized=!0,o.settings.responsive&&t(window).bind("resize",Z),o.settings.auto&&o.settings.autoStart&&H(),o.settings.ticker&&L(),o.settings.pager&&q(o.settings.startSlide),o.settings.controls&&W(),o.settings.touchEnabled&&!o.settings.ticker&&O()},v=function(){var e=0,s=t();if("vertical"==o.settings.mode||o.settings.adaptiveHeight)if(o.carousel){var n=1==o.settings.moveSlides?o.active.index:o.active.index*m();for(s=o.children.eq(n),i=1;i<=o.settings.maxSlides-1;i++)s=n+i>=o.children.length?s.add(o.children.eq(i-1)):s.add(o.children.eq(n+i))}else s=o.children.eq(o.active.index);else s=o.children;return"vertical"==o.settings.mode?(s.each(function(){e+=t(this).outerHeight()}),o.settings.slideMargin>0&&(e+=o.settings.slideMargin*(o.settings.minSlides-1))):e=Math.max.apply(Math,s.map(function(){return t(this).outerHeight(!1)}).get()),e},p=function(){var t="100%";return o.settings.slideWidth>0&&(t="horizontal"==o.settings.mode?o.settings.maxSlides*o.settings.slideWidth+(o.settings.maxSlides-1)*o.settings.slideMargin:o.settings.slideWidth),t},u=function(){var t=o.settings.slideWidth,e=o.viewport.width();return 0==o.settings.slideWidth||o.settings.slideWidth>e&&!o.carousel||"vertical"==o.settings.mode?t=e:o.settings.maxSlides>1&&"horizontal"==o.settings.mode&&(e>o.maxThreshold||e<o.minThreshold&&(t=(e-o.settings.slideMargin*(o.settings.minSlides-1))/o.settings.minSlides)),t},f=function(){var t=1;if("horizontal"==o.settings.mode&&o.settings.slideWidth>0)if(o.viewport.width()<o.minThreshold)t=o.settings.minSlides;else if(o.viewport.width()>o.maxThreshold)t=o.settings.maxSlides;else{var e=o.children.first().width();t=Math.floor(o.viewport.width()/e)}else"vertical"==o.settings.mode&&(t=o.settings.minSlides);return t},x=function(){var t=0;if(o.settings.moveSlides>0)if(o.settings.infiniteLoop)t=o.children.length/m();else for(var e=0,i=0;e<o.children.length;)++t,e=i+f(),i+=o.settings.moveSlides<=f()?o.settings.moveSlides:f();else t=Math.ceil(o.children.length/f());return t},m=function(){return o.settings.moveSlides>0&&o.settings.moveSlides<=f()?o.settings.moveSlides:f()},S=function(){if(o.children.length>o.settings.maxSlides&&o.active.last&&!o.settings.infiniteLoop){if("horizontal"==o.settings.mode){var t=o.children.last(),e=t.position();b(-(e.left-(o.viewport.width()-t.width())),"reset",0)}else if("vertical"==o.settings.mode){var i=o.children.length-o.settings.minSlides,e=o.children.eq(i).position();b(-e.top,"reset",0)}}else{var e=o.children.eq(o.active.index*m()).position();o.active.index==x()-1&&(o.active.last=!0),void 0!=e&&("horizontal"==o.settings.mode?b(-e.left,"reset",0):"vertical"==o.settings.mode&&b(-e.top,"reset",0))}},b=function(t,e,i,s){if(o.usingCSS){var n="vertical"==o.settings.mode?"translate3d(0, "+t+"px, 0)":"translate3d("+t+"px, 0, 0)";r.css("-"+o.cssPrefix+"-transition-duration",i/1e3+"s"),"slide"==e?(r.css(o.animProp,n),r.bind("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd",function(){r.unbind("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd"),D()})):"reset"==e?r.css(o.animProp,n):"ticker"==e&&(r.css("-"+o.cssPrefix+"-transition-timing-function","linear"),r.css(o.animProp,n),r.bind("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd",function(){r.unbind("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd"),b(s.resetValue,"reset",0),N()}))}else{var a={};a[o.animProp]=t,"slide"==e?r.animate(a,i,o.settings.easing,function(){D()}):"reset"==e?r.css(o.animProp,t):"ticker"==e&&r.animate(a,speed,"linear",function(){b(s.resetValue,"reset",0),N()})}},w=function(){for(var e="",i=x(),s=0;i>s;s++){var n="";o.settings.buildPager&&t.isFunction(o.settings.buildPager)?(n=o.settings.buildPager(s),o.pagerEl.addClass("bx-custom-pager")):(n=s+1,o.pagerEl.addClass("bx-default-pager")),e+='
'+n+"
"}o.pagerEl.html(e)},T=function(){o.settings.pagerCustom?o.pagerEl=t(o.settings.pagerCustom):(o.pagerEl=t('
'),o.settings.pagerSelector?t(o.settings.pagerSelector).html(o.pagerEl):o.controls.el.addClass("bx-has-pager").append(o.pagerEl),w()),o.pagerEl.on("click","a",I)},C=function(){o.controls.next=t(''+o.settings.nextText+""),o.controls.prev=t(''+o.settings.prevText+""),o.controls.next.bind("click",y),o.controls.prev.bind("click",z),o.settings.nextSelector&&t(o.settings.nextSelector).append(o.controls.next),o.settings.prevSelector&&t(o.settings.prevSelector).append(o.controls.prev),o.settings.nextSelector||o.settings.prevSelector||(o.controls.directionEl=t('
'),o.controls.directionEl.append(o.controls.prev).append(o.controls.next),o.controls.el.addClass("bx-has-controls-direction").append(o.controls.directionEl))},E=function(){o.controls.start=t('
'+o.settings.startText+"
"),o.controls.stop=t('
'+o.settings.stopText+"
"),o.controls.autoEl=t('
'),o.controls.autoEl.on("click",".bx-start",k),o.controls.autoEl.on("click",".bx-stop",M),o.settings.autoControlsCombine?o.controls.autoEl.append(o.controls.start):o.controls.autoEl.append(o.controls.start).append(o.controls.stop),o.settings.autoControlsSelector?t(o.settings.autoControlsSelector).html(o.controls.autoEl):o.controls.el.addClass("bx-has-controls-auto").append(o.controls.autoEl),A(o.settings.autoStart?"stop":"start")},P=function(){o.children.each(function(){var e=t(this).find("img:first").attr("title");void 0!=e&&(""+e).length&&t(this).append('
'+e+"
")})},y=function(t){o.settings.auto&&r.stopAuto(),r.goToNextSlide(),t.preventDefault()},z=function(t){o.settings.auto&&r.stopAuto(),r.goToPrevSlide(),t.preventDefault()},k=function(t){r.startAuto(),t.preventDefault()},M=function(t){r.stopAuto(),t.preventDefault()},I=function(e){o.settings.auto&&r.stopAuto();var i=t(e.currentTarget),s=parseInt(i.attr("data-slide-index"));s!=o.active.index&&r.goToSlide(s),e.preventDefault()},q=function(e){var i=o.children.length;return"short"==o.settings.pagerType?(o.settings.maxSlides>1&&(i=Math.ceil(o.children.length/o.settings.maxSlides)),o.pagerEl.html(e+1+o.settings.pagerShortSeparator+i),void 0):(o.pagerEl.find("a").removeClass("active"),o.pagerEl.each(function(i,s){t(s).find("a").eq(e).addClass("active")}),void 0)},D=function(){if(o.settings.infiniteLoop){var t="";0==o.active.index?t=o.children.eq(0).position():o.active.index==x()-1&&o.carousel?t=o.children.eq((x()-1)*m()).position():o.active.index==o.children.length-1&&(t=o.children.eq(o.children.length-1).position()),t&&("horizontal"==o.settings.mode?b(-t.left,"reset",0):"vertical"==o.settings.mode&&b(-t.top,"reset",0))}o.working=!1,o.settings.onSlideAfter(o.children.eq(o.active.index),o.oldIndex,o.active.index)},A=function(t){o.settings.autoControlsCombine?o.controls.autoEl.html(o.controls[t]):(o.controls.autoEl.find("a").removeClass("active"),o.controls.autoEl.find("a:not(.bx-"+t+")").addClass("active"))},W=function(){1==x()?(o.controls.prev.addClass("disabled"),o.controls.next.addClass("disabled")):!o.settings.infiniteLoop&&o.settings.hideControlOnEnd&&(0==o.active.index?(o.controls.prev.addClass("disabled"),o.controls.next.removeClass("disabled")):o.active.index==x()-1?(o.controls.next.addClass("disabled"),o.controls.prev.removeClass("disabled")):(o.controls.prev.removeClass("disabled"),o.controls.next.removeClass("disabled")))},H=function(){o.settings.autoDelay>0?setTimeout(r.startAuto,o.settings.autoDelay):r.startAuto(),o.settings.autoHover&&r.hover(function(){o.interval&&(r.stopAuto(!0),o.autoPaused=!0)},function(){o.autoPaused&&(r.startAuto(!0),o.autoPaused=null)})},L=function(){var e=0;if("next"==o.settings.autoDirection)r.append(o.children.clone().addClass("bx-clone"));else{r.prepend(o.children.clone().addClass("bx-clone"));var i=o.children.first().position();e="horizontal"==o.settings.mode?-i.left:-i.top}b(e,"reset",0),o.settings.pager=!1,o.settings.controls=!1,o.settings.autoControls=!1,o.settings.tickerHover&&!o.usingCSS&&o.viewport.hover(function(){r.stop()},function(){var e=0;o.children.each(function(){e+="horizontal"==o.settings.mode?t(this).outerWidth(!0):t(this).outerHeight(!0)});var i=o.settings.speed/e,s="horizontal"==o.settings.mode?"left":"top",n=i*(e-Math.abs(parseInt(r.css(s))));N(n)}),N()},N=function(t){speed=t?t:o.settings.speed;var e={left:0,top:0},i={left:0,top:0};"next"==o.settings.autoDirection?e=r.find(".bx-clone").first().position():i=o.children.first().position();var s="horizontal"==o.settings.mode?-e.left:-e.top,n="horizontal"==o.settings.mode?-i.left:-i.top,a={resetValue:n};b(s,"ticker",speed,a)},O=function(){o.touch={start:{x:0,y:0},end:{x:0,y:0}},o.viewport.bind("touchstart",X)},X=function(t){if(o.working)t.preventDefault();else{o.touch.originalPos=r.position();var e=t.originalEvent;o.touch.start.x=e.changedTouches[0].pageX,o.touch.start.y=e.changedTouches[0].pageY,o.viewport.bind("touchmove",Y),o.viewport.bind("touchend",V)}},Y=function(t){var e=t.originalEvent,i=Math.abs(e.changedTouches[0].pageX-o.touch.start.x),s=Math.abs(e.changedTouches[0].pageY-o.touch.start.y);if(3*i>s&&o.settings.preventDefaultSwipeX?t.preventDefault():3*s>i&&o.settings.preventDefaultSwipeY&&t.preventDefault(),"fade"!=o.settings.mode&&o.settings.oneToOneTouch){var n=0;if("horizontal"==o.settings.mode){var r=e.changedTouches[0].pageX-o.touch.start.x;n=o.touch.originalPos.left+r}else{var r=e.changedTouches[0].pageY-o.touch.start.y;n=o.touch.originalPos.top+r}b(n,"reset",0)}},V=function(t){o.viewport.unbind("touchmove",Y);var e=t.originalEvent,i=0;if(o.touch.end.x=e.changedTouches[0].pageX,o.touch.end.y=e.changedTouches[0].pageY,"fade"==o.settings.mode){var s=Math.abs(o.touch.start.x-o.touch.end.x);s>=o.settings.swipeThreshold&&(o.touch.start.x>o.touch.end.x?r.goToNextSlide():r.goToPrevSlide(),r.stopAuto())}else{var s=0;"horizontal"==o.settings.mode?(s=o.touch.end.x-o.touch.start.x,i=o.touch.originalPos.left):(s=o.touch.end.y-o.touch.start.y,i=o.touch.originalPos.top),!o.settings.infiniteLoop&&(0==o.active.index&&s>0||o.active.last&&0>s)?b(i,"reset",200):Math.abs(s)>=o.settings.swipeThreshold?(0>s?r.goToNextSlide():r.goToPrevSlide(),r.stopAuto()):b(i,"reset",200)}o.viewport.unbind("touchend",V)},Z=function(){var e=t(window).width(),i=t(window).height();(a!=e||l!=i)&&(a=e,l=i,r.redrawSlider(),o.settings.onSliderResize.call(r,o.active.index))};return r.goToSlide=function(e,i){if(!o.working&&o.active.index!=e)if(o.working=!0,o.oldIndex=o.active.index,o.active.index=0>e?x()-1:e>=x()?0:e,o.settings.onSlideBefore(o.children.eq(o.active.index),o.oldIndex,o.active.index),"next"==i?o.settings.onSlideNext(o.children.eq(o.active.index),o.oldIndex,o.active.index):"prev"==i&&o.settings.onSlidePrev(o.children.eq(o.active.index),o.oldIndex,o.active.index),o.active.last=o.active.index>=x()-1,o.settings.pager&&q(o.active.index),o.settings.controls&&W(),"fade"==o.settings.mode)o.settings.adaptiveHeight&&o.viewport.height()!=v()&&o.viewport.animate({height:v()},o.settings.adaptiveHeightSpeed),o.children.filter(":visible").fadeOut(o.settings.speed).css({zIndex:0}),o.children.eq(o.active.index).css("zIndex",o.settings.slideZIndex+1).fadeIn(o.settings.speed,function(){t(this).css("zIndex",o.settings.slideZIndex),D()});else{o.settings.adaptiveHeight&&o.viewport.height()!=v()&&o.viewport.animate({height:v()},o.settings.adaptiveHeightSpeed);var s=0,n={left:0,top:0};if(!o.settings.infiniteLoop&&o.carousel&&o.active.last)if("horizontal"==o.settings.mode){var a=o.children.eq(o.children.length-1);n=a.position(),s=o.viewport.width()-a.outerWidth()}else{var l=o.children.length-o.settings.minSlides;n=o.children.eq(l).position()}else if(o.carousel&&o.active.last&&"prev"==i){var d=1==o.settings.moveSlides?o.settings.maxSlides-m():(x()-1)*m()-(o.children.length-o.settings.maxSlides),a=r.children(".bx-clone").eq(d);n=a.position()}else if("next"==i&&0==o.active.index)n=r.find("> .bx-clone").eq(o.settings.maxSlides).position(),o.active.last=!1;else if(e>=0){var c=e*m();n=o.children.eq(c).position()}if("undefined"!=typeof n){var g="horizontal"==o.settings.mode?-(n.left-s):-n.top;b(g,"slide",o.settings.speed)}}},r.goToNextSlide=function(){if(o.settings.infiniteLoop||!o.active.last){var t=parseInt(o.active.index)+1;r.goToSlide(t,"next")}},r.goToPrevSlide=function(){if(o.settings.infiniteLoop||0!=o.active.index){var t=parseInt(o.active.index)-1;r.goToSlide(t,"prev")}},r.startAuto=function(t){o.interval||(o.interval=setInterval(function(){"next"==o.settings.autoDirection?r.goToNextSlide():r.goToPrevSlide()},o.settings.pause),o.settings.autoControls&&1!=t&&A("stop"))},r.stopAuto=function(t){o.interval&&(clearInterval(o.interval),o.interval=null,o.settings.autoControls&&1!=t&&A("start"))},r.getCurrentSlide=function(){return o.active.index},r.getCurrentSlideElement=function(){return o.children.eq(o.active.index)},r.getSlideCount=function(){return o.children.length},r.redrawSlider=function(){o.children.add(r.find(".bx-clone")).outerWidth(u()),o.viewport.css("height",v()),o.settings.ticker||S(),o.active.last&&(o.active.index=x()-1),o.active.index>=x()&&(o.active.last=!0),o.settings.pager&&!o.settings.pagerCustom&&(w(),q(o.active.index))},r.destroySlider=function(){o.initialized&&(o.initialized=!1,t(".bx-clone",this).remove(),o.children.each(function(){void 0!=t(this).data("origStyle")?t(this).attr("style",t(this).data("origStyle")):t(this).removeAttr("style")}),void 0!=t(this).data("origStyle")?this.attr("style",t(this).data("origStyle")):t(this).removeAttr("style"),t(this).unwrap().unwrap(),o.controls.el&&o.controls.el.remove(),o.controls.next&&o.controls.next.remove(),o.controls.prev&&o.controls.prev.remove(),o.pagerEl&&o.settings.controls&&o.pagerEl.remove(),t(".bx-caption",this).remove(),o.controls.autoEl&&o.controls.autoEl.remove(),clearInterval(o.interval),o.settings.responsive&&t(window).unbind("resize",Z))},r.reloadSlider=function(t){void 0!=t&&(n=t),r.destroySlider(),d()},d(),this}}(jQuery);<commit_msg>remove bxslider js<commit_after><|endoftext|>


<commit_before>/*
 * patternlab-node - v1.2.0 - 2016
 *
 * Brian Muenzenmeyer, Geoffrey Pursell, and the web community.
 * Licensed under the MIT license.
 *
 * Many thanks to Brad Frost and Dave Olsen for inspiration, encouragement, and advice.
 *
 */

"use strict";

var path = require('path');
var fs = require('fs-extra');

// PRIVATE FUNCTIONS

function addToPatternPaths(patternlab, bucketName, pattern) {
  //this is messy, could use a refactor.
  patternlab.patternPaths[bucketName][pattern.patternName] = pattern.subdir.replace(/\\/g, '/') + "/" + pattern.fileName;
}

//todo: refactor this as a method on the pattern object itself once we merge dev with pattern-engines branch
function isPatternExcluded(pattern) {
  // returns whether or not the first character of the pattern filename is an underscore, or excluded
  return pattern.fileName.charAt(0) === '_';
}

// Returns the array of patterns to be rendered in the styleguide view and
// linked to in the pattern navigation. Checks if patterns are excluded.
function assembleStyleguidePatterns(patternlab) {
  var styleguideExcludes = patternlab.config.styleGuideExcludes;
  var styleguidePatterns = [];

  if (styleguideExcludes && styleguideExcludes.length) {
    for (var i = 0; i < patternlab.patterns.length; i++) {

      // skip underscore-prefixed files
      if (isPatternExcluded(patternlab.patterns[i])) {
        if (patternlab.config.debug) {
          console.log('Omitting ' + patternlab.patterns[i].key + " from styleguide pattern exclusion.");
        }
        continue;
      }

      var key = patternlab.patterns[i].key;
      var typeKey = key.substring(0, key.indexOf('-'));
      var isExcluded = (styleguideExcludes.indexOf(typeKey) > -1);
      if (!isExcluded) {
        styleguidePatterns.push(patternlab.patterns[i]);
      }
    }
  } else {
    styleguidePatterns = patternlab.patterns;
  }

  return styleguidePatterns;
}

// MAIN BUILDER FUNCTION

function buildViewAllPages(mainPageHead, mainPageFoot, mainPageHeadHtml, mainPageFootHtml, pattern_assembler, patternlab) {
  var paths = patternlab.config.paths;
  var prevSubdir = '';
  var prevGroup = '';
  var i;

  for (i = 0; i < patternlab.patterns.length; i++) {
    // skip underscore-prefixed files
    if (isPatternExcluded(patternlab.patterns[i])) {
      if (patternlab.config.debug) {
        console.log('Omitting ' + patternlab.patterns[i].key + " from view all rendering.");
      }
      continue;
    }

    var pattern = patternlab.patterns[i];

    //create the view all for the section
    // check if the current section is different from the previous one
    if (pattern.patternGroup !== prevGroup) {
      prevGroup = pattern.patternGroup;

      var viewAllPatterns = [];
      var patternPartial = "viewall-" + pattern.patternGroup;
      var j;

      for (j = 0; j < patternlab.patterns.length; j++) {
        if (patternlab.patterns[j].patternGroup === pattern.patternGroup) {
          //again, skip any sibling patterns to the current one that may have underscores
          if (isPatternExcluded(patternlab.patterns[j])) {
            if (patternlab.config.debug) {
              console.log('Omitting ' + patternlab.patterns[j].key + " from view all sibling rendering.");
            }
            continue;
          }

          viewAllPatterns.push(patternlab.patterns[j]);
        }
      }

      var viewAllTemplate = fs.readFileSync(path.resolve(paths.source.patternlabFiles, 'templates/viewall.mustache'), 'utf8');
      var viewAllHtml = pattern_assembler.renderPattern(viewAllTemplate, {partials: viewAllPatterns, patternPartial: patternPartial, cacheBuster: patternlab.cacheBuster });
      fs.outputFileSync(paths.public.patterns + pattern.subdir.slice(0, pattern.subdir.indexOf(pattern.patternGroup) + pattern.patternGroup.length) + '/index.html', mainPageHead + viewAllHtml + mainPageFoot);
    }

    //create the view all for the subsection
    // check if the current sub section is different from the previous one
    if (pattern.subdir !== prevSubdir) {
      prevSubdir = pattern.subdir;

      viewAllPatterns = [];
      patternPartial = "viewall-" + pattern.patternGroup + "-" + pattern.patternSubGroup;

      for (j = 0; j < patternlab.patterns.length; j++) {
        if (patternlab.patterns[j].subdir === pattern.subdir) {
          //again, skip any sibling patterns to the current one that may have underscores
          if (isPatternExcluded(patternlab.patterns[j])) {
            if (patternlab.config.debug) {
              console.log('Omitting ' + patternlab.patterns[j].key + " from view all sibling rendering.");
            }
            continue;
          }

          viewAllPatterns.push(patternlab.patterns[j]);
        }
      }

      var viewAllTemplate = fs.readFileSync(path.resolve(paths.source.patternlabFiles, 'templates/viewall.mustache'), 'utf8');
      var viewAllHtml = pattern_assembler.renderPattern(viewAllTemplate, {partials: viewAllPatterns, patternPartial: patternPartial, cacheBuster: patternlab.cacheBuster});
      fs.outputFileSync(paths.public.patterns + pattern.flatPatternPath + '/index.html', mainPageHeadHtml + viewAllHtml + mainPageFootHtml);
    }
  }
}

function buildFrontEnd(patternlab) {
  var pa = require('./pattern_assembler');
  var of = require('./object_factory');
  var mh = require('./media_hunter');
  var pattern_assembler = new pa();
  var media_hunter = new mh();
  var styleguidePatterns = [];
  var paths = patternlab.config.paths;
  var i;

  patternlab.buckets = [];
  patternlab.bucketIndex = [];
  patternlab.patternPaths = {};
  patternlab.viewAllPaths = {};

  //sort all patterns explicitly.
  patternlab.patterns = patternlab.patterns.sort(function (a, b) {
    if (a.name > b.name) {
      return 1;
    }
    if (a.name < b.name) {
      return -1;
    }

    // a must be equal to b
    return 0;
  });

  //find mediaQueries
  media_hunter.find_media_queries('./source/css', patternlab);

  // check if patterns are excluded, if not add them to styleguidePatterns
  styleguidePatterns = assembleStyleguidePatterns(patternlab);

  //also add the cachebuster value. slight chance this could collide with a user that has defined cacheBuster as a value
  patternlab.data.cacheBuster = patternlab.cacheBuster;

  //get the main page head and foot
  var mainPageHead = patternlab.userHead.extendedTemplate.replace('{% pattern-lab-head %}', patternlab.header);
  var mainPageHeadHtml = pattern_assembler.renderPattern(mainPageHead, patternlab.data);
  var mainPageFoot = patternlab.userFoot.extendedTemplate.replace('{% pattern-lab-foot %}', patternlab.footer);
  var mainPageFootHtml = pattern_assembler.renderPattern(mainPageFoot, patternlab.data);

  //build the styleguide
  var styleguideTemplate = fs.readFileSync(path.resolve(paths.source.patternlabFiles, 'templates/styleguide.mustache'), 'utf8');
  var styleguideHtml = pattern_assembler.renderPattern(styleguideTemplate, {partials: styleguidePatterns, cacheBuster: patternlab.cacheBuster});

  fs.outputFileSync(path.resolve(paths.public.styleguide, 'html/styleguide.html'), mainPageHeadHtml + styleguideHtml + mainPageFootHtml);

  //build the viewall pages
  buildViewAllPages(mainPageHead, mainPageFoot, mainPageHeadHtml, mainPageFootHtml, pattern_assembler, patternlab);

  //build the patternlab website
  var patternlabSiteTemplate = fs.readFileSync(path.resolve(paths.source.patternlabFiles, 'templates/index.mustache'), 'utf8');

  //loop through all patterns.to build the navigation
  //todo: refactor this someday
  for (i = 0; i < patternlab.patterns.length; i++) {

    var pattern = patternlab.patterns[i];
    var bucketName = pattern.name.replace(/\\/g, '-').split('-')[1];

    //check if the bucket already exists
    var bucketIndex = patternlab.bucketIndex.indexOf(bucketName);
    if (bucketIndex === -1) {

      // skip underscore-prefixed files. don't create a bucket on account of an underscored pattern
      if (isPatternExcluded(pattern)) {
        continue;
      }

      //add the bucket
      var bucket = new of.oBucket(bucketName);

      //add patternPath and viewAllPath
      patternlab.patternPaths[bucketName] = {};
      patternlab.viewAllPaths[bucketName] = {};

      //get the navItem
      var navItemName = pattern.subdir.split('/').pop();
      navItemName = navItemName.replace(/(\d).(-)/g, '');

      //get the navSubItem
      var navSubItemName = pattern.patternName.replace(/-/g, ' ');

      //test whether the pattern struture is flat or not - usually due to a template or page
      var flatPatternItem = false;
      if (navItemName === bucketName) {
        flatPatternItem = true;
      }

      //assume the navItem does not exist.
      var navItem = new of.oNavItem(navItemName);

      //assume the navSubItem does not exist.
      var navSubItem = new of.oNavSubItem(navSubItemName);
      navSubItem.patternPath = pattern.patternLink;
      navSubItem.patternPartial = bucketName + "-" + pattern.patternName; //add the hyphenated name

      //add the patternState if it exists
      if (pattern.patternState) {
        navSubItem.patternState = pattern.patternState;
      }

      //if it is flat - we should not add the pattern to patternPaths
      if (flatPatternItem) {

        bucket.patternItems.push(navSubItem);

        //add to patternPaths
        addToPatternPaths(patternlab, bucketName, pattern);

      } else {

        bucket.navItems.push(navItem);
        bucket.navItemsIndex.push(navItemName);
        navItem.navSubItems.push(navSubItem);
        navItem.navSubItemsIndex.push(navSubItemName);

        //add to patternPaths
        addToPatternPaths(patternlab, bucketName, pattern);

        //add the navViewAllItem
        var navViewAllItem = new of.oNavSubItem("View All");
        navViewAllItem.patternPath = pattern.subdir.slice(0, pattern.subdir.indexOf(pattern.patternGroup) + pattern.patternGroup.length) + "/index.html";
        navViewAllItem.patternPartial = "viewall-" + pattern.patternGroup;

        bucket.patternItems.push(navViewAllItem);
        patternlab.viewAllPaths[bucketName].viewall = pattern.subdir.slice(0, pattern.subdir.indexOf(pattern.patternGroup) + pattern.patternGroup.length);

      }

      //add the bucket.
      patternlab.buckets.push(bucket);
      patternlab.bucketIndex.push(bucketName);

      //done

    } else {
      //find the bucket
      bucket = patternlab.buckets[bucketIndex];

      //get the navItem
      //if there is one or more slashes in the subdir, get everything after
      //the last slash. if no slash, get the whole subdir string and strip
      //any numeric + hyphen prefix
      navItemName = pattern.subdir.split('/').pop().replace(/^\d*\-/, '');

      //get the navSubItem
      navSubItemName = pattern.patternName.replace(/-/g, ' ');

      //assume the navSubItem does not exist.
      navSubItem = new of.oNavSubItem(navSubItemName);
      navSubItem.patternPath = pattern.patternLink;
      navSubItem.patternPartial = bucketName + "-" + pattern.patternName; //add the hyphenated name

      //add the patternState if it exists
      if (pattern.patternState) {
        navSubItem.patternState = pattern.patternState;
      }

      //test whether the pattern struture is flat or not - usually due to a template or page
      flatPatternItem = false;
      if (navItemName === bucketName) {
        flatPatternItem = true;
      }

      //if it is flat - we should not add the pattern to patternPaths
      if (flatPatternItem) {

        // skip underscore-prefixed files
        if (isPatternExcluded(pattern)) {
          continue;
        }

        //add the navItem to patternItems
        bucket.patternItems.push(navSubItem);

        //add to patternPaths
        addToPatternPaths(patternlab, bucketName, pattern);

      } else {

        // only do this if pattern is included
        if (!isPatternExcluded(pattern)) {
          //check to see if navItem exists
          var navItemIndex = bucket.navItemsIndex.indexOf(navItemName);
          if (navItemIndex === -1) {
            navItem = new of.oNavItem(navItemName);

            //add the navItem and navSubItem
            navItem.navSubItems.push(navSubItem);
            navItem.navSubItemsIndex.push(navSubItemName);
            bucket.navItems.push(navItem);
            bucket.navItemsIndex.push(navItemName);

          } else {
            //add the navSubItem
            navItem = bucket.navItems[navItemIndex];
            navItem.navSubItems.push(navSubItem);
            navItem.navSubItemsIndex.push(navSubItemName);
          }
        }

        //check if we are moving to a new sub section in the next loop
        if (!patternlab.patterns[i + 1] || pattern.patternSubGroup !== patternlab.patterns[i + 1].patternSubGroup) {

          //add the navViewAllSubItem
          var navViewAllSubItem = new of.oNavSubItem("");
          navViewAllSubItem.patternName = "View All";
          navViewAllSubItem.patternPath = pattern.flatPatternPath + "/index.html";
          navViewAllSubItem.patternPartial = "viewall-" + pattern.patternGroup + "-" + pattern.patternSubGroup;

          navItem.navSubItems.push(navViewAllSubItem);
          navItem.navSubItemsIndex.push("View All");
        }

        // just add to patternPaths
        addToPatternPaths(patternlab, bucketName, pattern);
      }
    }

    patternlab.viewAllPaths[bucketName][pattern.patternSubGroup] = pattern.flatPatternPath;
  }

  //the patternlab site requires a lot of partials to be rendered.
  //patternNav
  var patternNavTemplate = fs.readFileSync(path.resolve(paths.source.patternlabFiles, 'templates/partials/patternNav.mustache'), 'utf8');
  var patternNavPartialHtml = pattern_assembler.renderPattern(patternNavTemplate, patternlab);

  //ishControls
  var ishControlsTemplate = fs.readFileSync(path.resolve(paths.source.patternlabFiles, 'templates/partials/ishControls.mustache'), 'utf8');
  patternlab.config.mqs = patternlab.mediaQueries;
  var ishControlsPartialHtml = pattern_assembler.renderPattern(ishControlsTemplate, patternlab.config);

  //patternPaths
  var patternPathsTemplate = fs.readFileSync(path.resolve(paths.source.patternlabFiles, 'templates/partials/patternPaths.mustache'), 'utf8');
  var patternPathsPartialHtml = pattern_assembler.renderPattern(patternPathsTemplate, {'patternPaths': JSON.stringify(patternlab.patternPaths)});

  //viewAllPaths
  var viewAllPathsTemplate = fs.readFileSync(path.resolve(paths.source.patternlabFiles, 'templates/partials/viewAllPaths.mustache'), 'utf8');
  var viewAllPathsPartialHtml = pattern_assembler.renderPattern(viewAllPathsTemplate, {'viewallpaths': JSON.stringify(patternlab.viewAllPaths)});

  //render the patternlab template, with all partials
  var patternlabSiteHtml = pattern_assembler.renderPattern(patternlabSiteTemplate, {
    defaultPattern: patternlab.config.defaultPattern || 'all',
    cacheBuster: patternlab.cacheBuster
  }, {
    'ishControls': ishControlsPartialHtml,
    'patternNav': patternNavPartialHtml,
    'patternPaths': patternPathsPartialHtml,
    'viewAllPaths': viewAllPathsPartialHtml
  });
  fs.outputFileSync(path.resolve(paths.public.root, 'index.html'), patternlabSiteHtml);
}

module.exports = buildFrontEnd;
<commit_msg>factor out buildNavigation()<commit_after>/*
 * patternlab-node - v1.2.0 - 2016
 *
 * Brian Muenzenmeyer, Geoffrey Pursell, and the web community.
 * Licensed under the MIT license.
 *
 * Many thanks to Brad Frost and Dave Olsen for inspiration, encouragement, and advice.
 *
 */

"use strict";

var path = require('path');
var fs = require('fs-extra');
var of = require('./object_factory');

// PRIVATE FUNCTIONS

function addToPatternPaths(patternlab, bucketName, pattern) {
  //this is messy, could use a refactor.
  patternlab.patternPaths[bucketName][pattern.patternName] = pattern.subdir.replace(/\\/g, '/') + "/" + pattern.fileName;
}

//todo: refactor this as a method on the pattern object itself once we merge dev with pattern-engines branch
function isPatternExcluded(pattern) {
  // returns whether or not the first character of the pattern filename is an underscore, or excluded
  return pattern.fileName.charAt(0) === '_';
}

// Returns the array of patterns to be rendered in the styleguide view and
// linked to in the pattern navigation. Checks if patterns are excluded.
function assembleStyleguidePatterns(patternlab) {
  var styleguideExcludes = patternlab.config.styleGuideExcludes;
  var styleguidePatterns = [];

  if (styleguideExcludes && styleguideExcludes.length) {
    for (var i = 0; i < patternlab.patterns.length; i++) {

      // skip underscore-prefixed files
      if (isPatternExcluded(patternlab.patterns[i])) {
        if (patternlab.config.debug) {
          console.log('Omitting ' + patternlab.patterns[i].key + " from styleguide pattern exclusion.");
        }
        continue;
      }

      var key = patternlab.patterns[i].key;
      var typeKey = key.substring(0, key.indexOf('-'));
      var isExcluded = (styleguideExcludes.indexOf(typeKey) > -1);
      if (!isExcluded) {
        styleguidePatterns.push(patternlab.patterns[i]);
      }
    }
  } else {
    styleguidePatterns = patternlab.patterns;
  }

  return styleguidePatterns;
}

function buildNavigation(patternlab) {
  for (var i = 0; i < patternlab.patterns.length; i++) {

    var pattern = patternlab.patterns[i];
    var bucketName = pattern.name.replace(/\\/g, '-').split('-')[1];

    //check if the bucket already exists
    var bucketIndex = patternlab.bucketIndex.indexOf(bucketName);
    if (bucketIndex === -1) {

      // skip underscore-prefixed files. don't create a bucket on account of an underscored pattern
      if (isPatternExcluded(pattern)) {
        continue;
      }

      //add the bucket
      var bucket = new of.oBucket(bucketName);

      //add patternPath and viewAllPath
      patternlab.patternPaths[bucketName] = {};
      patternlab.viewAllPaths[bucketName] = {};

      //get the navItem
      var navItemName = pattern.subdir.split('/').pop();
      navItemName = navItemName.replace(/(\d).(-)/g, '');

      //get the navSubItem
      var navSubItemName = pattern.patternName.replace(/-/g, ' ');

      //test whether the pattern struture is flat or not - usually due to a template or page
      var flatPatternItem = false;
      if (navItemName === bucketName) {
        flatPatternItem = true;
      }

      //assume the navItem does not exist.
      var navItem = new of.oNavItem(navItemName);

      //assume the navSubItem does not exist.
      var navSubItem = new of.oNavSubItem(navSubItemName);
      navSubItem.patternPath = pattern.patternLink;
      navSubItem.patternPartial = bucketName + "-" + pattern.patternName; //add the hyphenated name

      //add the patternState if it exists
      if (pattern.patternState) {
        navSubItem.patternState = pattern.patternState;
      }

      //if it is flat - we should not add the pattern to patternPaths
      if (flatPatternItem) {

        bucket.patternItems.push(navSubItem);

        //add to patternPaths
        addToPatternPaths(patternlab, bucketName, pattern);

      } else {

        bucket.navItems.push(navItem);
        bucket.navItemsIndex.push(navItemName);
        navItem.navSubItems.push(navSubItem);
        navItem.navSubItemsIndex.push(navSubItemName);

        //add to patternPaths
        addToPatternPaths(patternlab, bucketName, pattern);

        //add the navViewAllItem
        var navViewAllItem = new of.oNavSubItem("View All");
        navViewAllItem.patternPath = pattern.subdir.slice(0, pattern.subdir.indexOf(pattern.patternGroup) + pattern.patternGroup.length) + "/index.html";
        navViewAllItem.patternPartial = "viewall-" + pattern.patternGroup;

        bucket.patternItems.push(navViewAllItem);
        patternlab.viewAllPaths[bucketName].viewall = pattern.subdir.slice(0, pattern.subdir.indexOf(pattern.patternGroup) + pattern.patternGroup.length);

      }

      //add the bucket.
      patternlab.buckets.push(bucket);
      patternlab.bucketIndex.push(bucketName);

      //done

    } else {
      //find the bucket
      bucket = patternlab.buckets[bucketIndex];

      //get the navItem
      //if there is one or more slashes in the subdir, get everything after
      //the last slash. if no slash, get the whole subdir string and strip
      //any numeric + hyphen prefix
      navItemName = pattern.subdir.split('/').pop().replace(/^\d*\-/, '');

      //get the navSubItem
      navSubItemName = pattern.patternName.replace(/-/g, ' ');

      //assume the navSubItem does not exist.
      navSubItem = new of.oNavSubItem(navSubItemName);
      navSubItem.patternPath = pattern.patternLink;
      navSubItem.patternPartial = bucketName + "-" + pattern.patternName; //add the hyphenated name

      //add the patternState if it exists
      if (pattern.patternState) {
        navSubItem.patternState = pattern.patternState;
      }

      //test whether the pattern struture is flat or not - usually due to a template or page
      flatPatternItem = false;
      if (navItemName === bucketName) {
        flatPatternItem = true;
      }

      //if it is flat - we should not add the pattern to patternPaths
      if (flatPatternItem) {

        // skip underscore-prefixed files
        if (isPatternExcluded(pattern)) {
          continue;
        }

        //add the navItem to patternItems
        bucket.patternItems.push(navSubItem);

        //add to patternPaths
        addToPatternPaths(patternlab, bucketName, pattern);

      } else {

        // only do this if pattern is included
        if (!isPatternExcluded(pattern)) {
          //check to see if navItem exists
          var navItemIndex = bucket.navItemsIndex.indexOf(navItemName);
          if (navItemIndex === -1) {
            navItem = new of.oNavItem(navItemName);

            //add the navItem and navSubItem
            navItem.navSubItems.push(navSubItem);
            navItem.navSubItemsIndex.push(navSubItemName);
            bucket.navItems.push(navItem);
            bucket.navItemsIndex.push(navItemName);

          } else {
            //add the navSubItem
            navItem = bucket.navItems[navItemIndex];
            navItem.navSubItems.push(navSubItem);
            navItem.navSubItemsIndex.push(navSubItemName);
          }
        }

        //check if we are moving to a new sub section in the next loop
        if (!patternlab.patterns[i + 1] || pattern.patternSubGroup !== patternlab.patterns[i + 1].patternSubGroup) {

          //add the navViewAllSubItem
          var navViewAllSubItem = new of.oNavSubItem("");
          navViewAllSubItem.patternName = "View All";
          navViewAllSubItem.patternPath = pattern.flatPatternPath + "/index.html";
          navViewAllSubItem.patternPartial = "viewall-" + pattern.patternGroup + "-" + pattern.patternSubGroup;

          navItem.navSubItems.push(navViewAllSubItem);
          navItem.navSubItemsIndex.push("View All");
        }

        // just add to patternPaths
        addToPatternPaths(patternlab, bucketName, pattern);
      }
    }

    patternlab.viewAllPaths[bucketName][pattern.patternSubGroup] = pattern.flatPatternPath;
  }
  return bucketIndex;
}

// MAIN BUILDER FUNCTION

function buildViewAllPages(mainPageHead, mainPageFoot, mainPageHeadHtml, mainPageFootHtml, pattern_assembler, patternlab) {
  var paths = patternlab.config.paths;
  var prevSubdir = '';
  var prevGroup = '';
  var i;

  for (i = 0; i < patternlab.patterns.length; i++) {
    // skip underscore-prefixed files
    if (isPatternExcluded(patternlab.patterns[i])) {
      if (patternlab.config.debug) {
        console.log('Omitting ' + patternlab.patterns[i].key + " from view all rendering.");
      }
      continue;
    }

    var pattern = patternlab.patterns[i];

    //create the view all for the section
    // check if the current section is different from the previous one
    if (pattern.patternGroup !== prevGroup) {
      prevGroup = pattern.patternGroup;

      var viewAllPatterns = [];
      var patternPartial = "viewall-" + pattern.patternGroup;
      var j;

      for (j = 0; j < patternlab.patterns.length; j++) {
        if (patternlab.patterns[j].patternGroup === pattern.patternGroup) {
          //again, skip any sibling patterns to the current one that may have underscores
          if (isPatternExcluded(patternlab.patterns[j])) {
            if (patternlab.config.debug) {
              console.log('Omitting ' + patternlab.patterns[j].key + " from view all sibling rendering.");
            }
            continue;
          }

          viewAllPatterns.push(patternlab.patterns[j]);
        }
      }

      var viewAllTemplate = fs.readFileSync(path.resolve(paths.source.patternlabFiles, 'templates/viewall.mustache'), 'utf8');
      var viewAllHtml = pattern_assembler.renderPattern(viewAllTemplate, {partials: viewAllPatterns, patternPartial: patternPartial, cacheBuster: patternlab.cacheBuster });
      fs.outputFileSync(paths.public.patterns + pattern.subdir.slice(0, pattern.subdir.indexOf(pattern.patternGroup) + pattern.patternGroup.length) + '/index.html', mainPageHead + viewAllHtml + mainPageFoot);
    }

    //create the view all for the subsection
    // check if the current sub section is different from the previous one
    if (pattern.subdir !== prevSubdir) {
      prevSubdir = pattern.subdir;

      viewAllPatterns = [];
      patternPartial = "viewall-" + pattern.patternGroup + "-" + pattern.patternSubGroup;

      for (j = 0; j < patternlab.patterns.length; j++) {
        if (patternlab.patterns[j].subdir === pattern.subdir) {
          //again, skip any sibling patterns to the current one that may have underscores
          if (isPatternExcluded(patternlab.patterns[j])) {
            if (patternlab.config.debug) {
              console.log('Omitting ' + patternlab.patterns[j].key + " from view all sibling rendering.");
            }
            continue;
          }

          viewAllPatterns.push(patternlab.patterns[j]);
        }
      }

      var viewAllTemplate = fs.readFileSync(path.resolve(paths.source.patternlabFiles, 'templates/viewall.mustache'), 'utf8');
      var viewAllHtml = pattern_assembler.renderPattern(viewAllTemplate, {partials: viewAllPatterns, patternPartial: patternPartial, cacheBuster: patternlab.cacheBuster});
      fs.outputFileSync(paths.public.patterns + pattern.flatPatternPath + '/index.html', mainPageHeadHtml + viewAllHtml + mainPageFootHtml);
    }
  }
}

function buildFrontEnd(patternlab) {
  var pa = require('./pattern_assembler');
  var mh = require('./media_hunter');
  var pattern_assembler = new pa();
  var media_hunter = new mh();
  var styleguidePatterns = [];
  var paths = patternlab.config.paths;

  patternlab.buckets = [];
  patternlab.bucketIndex = [];
  patternlab.patternPaths = {};
  patternlab.viewAllPaths = {};

  //sort all patterns explicitly.
  patternlab.patterns = patternlab.patterns.sort(function (a, b) {
    if (a.name > b.name) {
      return 1;
    }
    if (a.name < b.name) {
      return -1;
    }

    // a must be equal to b
    return 0;
  });

  //find mediaQueries
  media_hunter.find_media_queries('./source/css', patternlab);

  // check if patterns are excluded, if not add them to styleguidePatterns
  styleguidePatterns = assembleStyleguidePatterns(patternlab);

  //also add the cachebuster value. slight chance this could collide with a user that has defined cacheBuster as a value
  patternlab.data.cacheBuster = patternlab.cacheBuster;

  //get the main page head and foot
  var mainPageHead = patternlab.userHead.extendedTemplate.replace('{% pattern-lab-head %}', patternlab.header);
  var mainPageHeadHtml = pattern_assembler.renderPattern(mainPageHead, patternlab.data);
  var mainPageFoot = patternlab.userFoot.extendedTemplate.replace('{% pattern-lab-foot %}', patternlab.footer);
  var mainPageFootHtml = pattern_assembler.renderPattern(mainPageFoot, patternlab.data);

  //build the styleguide
  var styleguideTemplate = fs.readFileSync(path.resolve(paths.source.patternlabFiles, 'templates/styleguide.mustache'), 'utf8');
  var styleguideHtml = pattern_assembler.renderPattern(styleguideTemplate, {partials: styleguidePatterns, cacheBuster: patternlab.cacheBuster});

  fs.outputFileSync(path.resolve(paths.public.styleguide, 'html/styleguide.html'), mainPageHeadHtml + styleguideHtml + mainPageFootHtml);

  //build the viewall pages
  buildViewAllPages(mainPageHead, mainPageFoot, mainPageHeadHtml, mainPageFootHtml, pattern_assembler, patternlab);

  //build the patternlab website
  var patternlabSiteTemplate = fs.readFileSync(path.resolve(paths.source.patternlabFiles, 'templates/index.mustache'), 'utf8');

  //loop through all patterns.to build the navigation
  //todo: refactor this someday
  buildNavigation(patternlab);

  //the patternlab site requires a lot of partials to be rendered.
  //patternNav
  var patternNavTemplate = fs.readFileSync(path.resolve(paths.source.patternlabFiles, 'templates/partials/patternNav.mustache'), 'utf8');
  var patternNavPartialHtml = pattern_assembler.renderPattern(patternNavTemplate, patternlab);

  //ishControls
  var ishControlsTemplate = fs.readFileSync(path.resolve(paths.source.patternlabFiles, 'templates/partials/ishControls.mustache'), 'utf8');
  patternlab.config.mqs = patternlab.mediaQueries;
  var ishControlsPartialHtml = pattern_assembler.renderPattern(ishControlsTemplate, patternlab.config);

  //patternPaths
  var patternPathsTemplate = fs.readFileSync(path.resolve(paths.source.patternlabFiles, 'templates/partials/patternPaths.mustache'), 'utf8');
  var patternPathsPartialHtml = pattern_assembler.renderPattern(patternPathsTemplate, {'patternPaths': JSON.stringify(patternlab.patternPaths)});

  //viewAllPaths
  var viewAllPathsTemplate = fs.readFileSync(path.resolve(paths.source.patternlabFiles, 'templates/partials/viewAllPaths.mustache'), 'utf8');
  var viewAllPathsPartialHtml = pattern_assembler.renderPattern(viewAllPathsTemplate, {'viewallpaths': JSON.stringify(patternlab.viewAllPaths)});

  //render the patternlab template, with all partials
  var patternlabSiteHtml = pattern_assembler.renderPattern(patternlabSiteTemplate, {
    defaultPattern: patternlab.config.defaultPattern || 'all',
    cacheBuster: patternlab.cacheBuster
  }, {
    'ishControls': ishControlsPartialHtml,
    'patternNav': patternNavPartialHtml,
    'patternPaths': patternPathsPartialHtml,
    'viewAllPaths': viewAllPathsPartialHtml
  });
  fs.outputFileSync(path.resolve(paths.public.root, 'index.html'), patternlabSiteHtml);
}

module.exports = buildFrontEnd;
<|endoftext|>


<commit_before>/**
 * 承诺 promise
 * 1. 后面的then注册的函数会覆盖前面注册的
 * 2. 如果resolve之后再注册then,则得不到值
 **/

//这件事情是一个需要延迟处理的事情
var Defer = function(){
	var status = 'pending';//初始态
	var value;//异步操作的最终的值
	var callbacks = [];//异步操作成功后的回调
	return {
		//当调用resolve的时候就表示成功了
		//异步操作完成之后调用，表示操作成功了
		resolve:function(_value){
			value = _value;
			status = 'resolve';
			callbacks.forEach(function(callback){
				callback(value);
			});
			callbacks = undefined;
		},
		reject:function(){

		},
		//就是承诺的对象,它会返回给客户端
		promise:{
			then:function(_callback_){
				if(callbacks){
					callbacks.push(_callback_);
				}else{
					_callback_(value);
				}
			},
			catch:function(){

			}
		}
	}
}

var defer = Defer();
var fs = require('fs');
fs.readFile('11.txt','utf8',function(err,data){
	//defer.resolve(data);//读取文件完成后调用resolve把状态改为成功
	defer.reject(err);
})

var promise = defer.promise;
//defer给你一个承诺，当异步操作完成之后我会调用你传给我回调函数
promise.then(function(data){
	console.log(1,data);
});
//当出错的时候进行的回调
promise.catch(function(errr){
	console.log(err);
});<commit_msg>promise update<commit_after>/**
 * 承诺 promise
 * 1. 后面的then注册的函数会覆盖前面注册的
 * 2. 如果resolve之后再注册then,则得不到值
 **/

//这件事情是一个需要延迟处理的事情
var Defer = function(){
	var status = 'pending';//初始态
	var value;//异步操作的最终的值
	var callbacks = [];//异步操作成功后的回调
	var reject_cbs = [];
	var reject_val;
	return {
		//当调用resolve的时候就表示成功了
		//异步操作完成之后调用，表示操作成功了
		resolve:function(_value){
			value = _value;
			status = 'resolved';
			callbacks.forEach(function(callback){
				callback(value);
			});
			callbacks = undefined;
		},
		reject:function(_value){
			reject_val = _value;
			status = 'rejected';
			reject_cbs.forEach(function(callback){
				callback(reject_val);
			});
			reject_cbs = undefined;
		},
		//就是承诺的对象,它会返回给客户端
		promise:{
			then:function(_callback_){
				if(callbacks){
					callbacks.push(_callback_);
				}else{
					_callback_(value);
				}
			},
			catch:function(_callback_){
				if(reject_cbs){
					reject_cbs.push(_callback_);
				}else{
					_callback_(reject_val);
				}
			}
		}
	}
}

var defer = Defer();
var fs = require('fs');
fs.readFile('11.txt','utf8',function(err,data){
	//defer.resolve(data);//读取文件完成后调用resolve把状态改为"成功"
	defer.reject(err);
})

var promise = defer.promise;
//defer给你一个承诺，当异步操作完成之后我会调用你传给我回调函数
promise.then(function(data){
	console.log(1,data);
});
//当出错的时候进行的回调
promise.catch(function(err){
	console.log(err);
});<|endoftext|>