<commit_before>import ee from '../../shared/pub_sub';

const TALL_EDITORS = ['page_body'];

function configureWysiwyg(id, editorOptions = []) {
  const $editor = $('#' + id);
  if ($editor.length === 0) {
    return;
  }

  $editor.summernote({
    toolbar: editorOptions.length
      ? editorOptions
      : [
          ['style', ['bold', 'italic', 'underline', 'clear']],
          ['font', ['fontname', 'fontsize']],
          ['para', ['ul', 'ol', 'paragraph']],
          ['color', ['color']],
          ['insert', ['link', 'picture', 'video']],
          ['view', ['fullscreen', 'codeview', 'help']],
        ],
    height: TALL_EDITORS.indexOf(id) > -1 ? 280 : 120,
    fontSizes: ['8', '10', '11', '12', '14', '16', '20', '24', '36', '72'],
    codemirror: {
      theme: 'default',
      mode: 'text/html',
      lineNumbers: true,
      tabMode: 'indent',
      lineWrapping: true,
    },
  });
  const $contentField = $('#' + id + '_content');

  $editor.summernote('fontSize', '16'); // default

  $editor.summernote('code', $contentField.val());

  // In order to make an iframe size down with the containing column
  // or to fit on screen on mobile, you have to apply style to the iframe
  // and to the containing element. This adds a class to the containing element
  // that our CSS is looking for.
  const encapsulateIframes = function(html) {
    if (html.indexOf('iframe') === -1) {
      return html; // don't do anything if there's no iframe
    }
    const $html = $(html);
    // addClass is idempotent so we just call it every time we save
    $html
      .find('iframe')
      .parent()
      .addClass('iframe-responsive-container');
    // this little goof is just cause jquery doesn't have $el.outerHtml();
    return $('

')
      .append($html)
      .html();
  };

  const updateContentBeforeSave = function() {
    const content = encapsulateIframes($editor.summernote('code'));
    $contentField.val(content);
  };

  ee.on('wysiwyg:submit', updateContentBeforeSave);
}

ee.on('wysiwyg:setup', configureWysiwyg);
<commit_msg>Removed font family from editor (skip ci)<commit_after>import ee from '../../shared/pub_sub';

const TALL_EDITORS = ['page_body'];

function configureWysiwyg(id, editorOptions = []) {
  const $editor = $('#' + id);
  if ($editor.length === 0) {
    return;
  }

  $editor.summernote({
    toolbar: editorOptions.length
      ? editorOptions
      : [
          ['style', ['bold', 'italic', 'underline', 'clear']],
          ['font', ['fontsize']],
          ['para', ['ul', 'ol', 'paragraph']],
          ['color', ['color']],
          ['insert', ['link', 'picture', 'video']],
          ['view', ['fullscreen', 'codeview', 'help']],
        ],
    height: TALL_EDITORS.indexOf(id) > -1 ? 280 : 120,
    fontSizes: ['8', '10', '11', '12', '14', '16', '20', '24', '36', '72'],
    codemirror: {
      theme: 'default',
      mode: 'text/html',
      lineNumbers: true,
      tabMode: 'indent',
      lineWrapping: true,
    },
  });
  const $contentField = $('#' + id + '_content');

  $editor.summernote('fontSize', '16'); // default

  $editor.summernote('code', $contentField.val());

  // In order to make an iframe size down with the containing column
  // or to fit on screen on mobile, you have to apply style to the iframe
  // and to the containing element. This adds a class to the containing element
  // that our CSS is looking for.
  const encapsulateIframes = function(html) {
    if (html.indexOf('iframe') === -1) {
      return html; // don't do anything if there's no iframe
    }
    const $html = $(html);
    // addClass is idempotent so we just call it every time we save
    $html
      .find('iframe')
      .parent()
      .addClass('iframe-responsive-container');
    // this little goof is just cause jquery doesn't have $el.outerHtml();
    return $('

')
      .append($html)
      .html();
  };

  const updateContentBeforeSave = function() {
    const content = encapsulateIframes($editor.summernote('code'));
    $contentField.val(content);
  };

  ee.on('wysiwyg:submit', updateContentBeforeSave);
}

ee.on('wysiwyg:setup', configureWysiwyg);
<|endoftext|>


<commit_before>import Uploader from '../../shared/activestorage/uploader';
import ProgressBar from '../../shared/activestorage/progress-bar';
import { ajax, show, hide, toggle } from '@utils';

// Given a file input in a champ with a selected file, upload a file,
// then attach it to the dossier.
//
// On success, the champ is replaced by an HTML fragment describing the attachment.
// On error, a error message is displayed above the input.
export default class AutoUploadController {
  constructor(input, file) {
    this.input = input;
    this.file = file;
  }

  async start() {
    try {
      this._begin();

      // Sanity checks
      const autoAttachUrl = this.input.dataset.autoAttachUrl;
      if (!autoAttachUrl) {
        throw new Error('L’attribut "data-auto-attach-url" est manquant');
      }

      // Upload the file (using Direct Upload)
      let blobSignedId = await this._upload();

      // Attach the blob to the champ
      // (The request responds with Javascript, which displays the attachment HTML fragment).
      await this._attach(blobSignedId, autoAttachUrl);

      // Everything good: clear the original file input value
      this.input.value = null;
    } catch (error) {
      this._failed(error);
      throw error;
    } finally {
      this._done();
    }
  }

  _begin() {
    this.input.disabled = true;
    this._hideErrorMessage();
  }

  async _upload() {
    const uploader = new Uploader(
      this.input,
      this.file,
      this.input.dataset.directUploadUrl
    );
    return await uploader.start();
  }

  async _attach(blobSignedId, autoAttachUrl) {
    // Now that the upload is done, display a new progress bar
    // to show that the attachment request is still pending.
    const progressBar = new ProgressBar(
      this.input,
      `${this.input.id}-progress-bar`,
      this.file
    );
    progressBar.progress(100);
    progressBar.end();

    const attachmentRequest = {
      url: autoAttachUrl,
      type: 'PUT',
      data: `blob_signed_id=${blobSignedId}`
    };
    await ajax(attachmentRequest);

    // The progress bar has been destroyed by the attachment HTML fragment that replaced the input,
    // so no further cleanup is needed.
  }

  _failed(error) {
    if (!document.body.contains(this.input)) {
      return;
    }

    let progressBar = this.input.parentElement.querySelector('.direct-upload');
    if (progressBar) {
      progressBar.remove();
    }

    this._displayErrorMessage(error);
  }

  _done() {
    this.input.disabled = false;
  }

  _messageFromError(error) {
    if (
      error.xhr &&
      error.xhr.status == 422 &&
      error.response &&
      error.response.errors &&
      error.response.errors[0]
    ) {
      return {
        title: error.response.errors[0],
        description: '',
        retry: false
      };
    } else {
      return {
        title: 'Une erreur s’est produite pendant l’envoi du fichier.',
        description: error.message || error.toString(),
        retry: true
      };
    }
  }

  _displayErrorMessage(error) {
    let errorNode = this.input.parentElement.querySelector('.attachment-error');
    if (errorNode) {
      show(errorNode);
      let message = this._messageFromError(error);
      errorNode.querySelector('.attachment-error-title').textContent =
        message.title || '';
      errorNode.querySelector('.attachment-error-description').textContent =
        message.description || '';
      toggle(errorNode.querySelector('.attachment-error-retry'), message.retry);
    }
  }

  _hideErrorMessage() {
    let errorElement = this.input.parentElement.querySelector(
      '.attachment-error'
    );
    if (errorElement) {
      hide(errorElement);
    }
  }
}
<commit_msg>javascript: don't allow to retry on direct upload 422<commit_after>import Uploader from '../../shared/activestorage/uploader';
import ProgressBar from '../../shared/activestorage/progress-bar';
import { ajax, show, hide, toggle } from '@utils';

// Given a file input in a champ with a selected file, upload a file,
// then attach it to the dossier.
//
// On success, the champ is replaced by an HTML fragment describing the attachment.
// On error, a error message is displayed above the input.
export default class AutoUploadController {
  constructor(input, file) {
    this.input = input;
    this.file = file;
  }

  async start() {
    try {
      this._begin();

      // Sanity checks
      const autoAttachUrl = this.input.dataset.autoAttachUrl;
      if (!autoAttachUrl) {
        throw new Error('L’attribut "data-auto-attach-url" est manquant');
      }

      // Upload the file (using Direct Upload)
      let blobSignedId = await this._upload();

      // Attach the blob to the champ
      // (The request responds with Javascript, which displays the attachment HTML fragment).
      await this._attach(blobSignedId, autoAttachUrl);

      // Everything good: clear the original file input value
      this.input.value = null;
    } catch (error) {
      this._failed(error);
      throw error;
    } finally {
      this._done();
    }
  }

  _begin() {
    this.input.disabled = true;
    this._hideErrorMessage();
  }

  async _upload() {
    const uploader = new Uploader(
      this.input,
      this.file,
      this.input.dataset.directUploadUrl
    );
    return await uploader.start();
  }

  async _attach(blobSignedId, autoAttachUrl) {
    // Now that the upload is done, display a new progress bar
    // to show that the attachment request is still pending.
    const progressBar = new ProgressBar(
      this.input,
      `${this.input.id}-progress-bar`,
      this.file
    );
    progressBar.progress(100);
    progressBar.end();

    const attachmentRequest = {
      url: autoAttachUrl,
      type: 'PUT',
      data: `blob_signed_id=${blobSignedId}`
    };
    await ajax(attachmentRequest);

    // The progress bar has been destroyed by the attachment HTML fragment that replaced the input,
    // so no further cleanup is needed.
  }

  _failed(error) {
    if (!document.body.contains(this.input)) {
      return;
    }

    let progressBar = this.input.parentElement.querySelector('.direct-upload');
    if (progressBar) {
      progressBar.remove();
    }

    this._displayErrorMessage(error);
  }

  _done() {
    this.input.disabled = false;
  }

  _isError422(error) {
    // Ajax errors have an xhr attribute
    if (error && error.xhr && error.xhr.status == 422) return true;
    // Rails DirectUpload errors are returned as a String, e.g. 'Error creating Blob for "Demain.txt". Status: 422'
    if (error && error.toString().includes('422')) return true;

    return false;
  }

  _messageFromError(error) {
    let allowRetry = !this._isError422(error);

    if (
      error.xhr &&
      error.xhr.status == 422 &&
      error.response &&
      error.response.errors &&
      error.response.errors[0]
    ) {
      return {
        title: error.response.errors[0],
        description: '',
        retry: allowRetry
      };
    } else {
      return {
        title: 'Une erreur s’est produite pendant l’envoi du fichier.',
        description: error.message || error.toString(),
        retry: allowRetry
      };
    }
  }

  _displayErrorMessage(error) {
    let errorNode = this.input.parentElement.querySelector('.attachment-error');
    if (errorNode) {
      show(errorNode);
      let message = this._messageFromError(error);
      errorNode.querySelector('.attachment-error-title').textContent =
        message.title || '';
      errorNode.querySelector('.attachment-error-description').textContent =
        message.description || '';
      toggle(errorNode.querySelector('.attachment-error-retry'), message.retry);
    }
  }

  _hideErrorMessage() {
    let errorElement = this.input.parentElement.querySelector(
      '.attachment-error'
    );
    if (errorElement) {
      hide(errorElement);
    }
  }
}
<|endoftext|>


<commit_before>'use strict';

let angular = require('angular');

module.exports = angular
  .module('spinnaker.core.filterModel.service', [
    require('../utils/lodash.js'),
    require('angular-ui-router'),
  ])
.factory('filterModelService', function (_, $location, $state, $stateParams, $timeout) {

    function isFilterable(sortFilterModel) {
      return _.size(sortFilterModel) > 0 && _.any(sortFilterModel);
    }

    function getCheckValues(sortFilterModel) {
      return  _.reduce(sortFilterModel, function(acc, val, key) {
        if (val) {
          acc.push(key);
        }
        return acc;
      }, []).sort();
    }

    function checkAccountFilters(model) {
      return function(target) {
        if(isFilterable(model.sortFilter.account)) {
          var checkedAccounts = getCheckValues(model.sortFilter.account);
          return _.contains(checkedAccounts, target.account);
        } else {
          return true;
        }
      };
    }

    function checkRegionFilters(model) {
      return function(target) {
        if(isFilterable(model.sortFilter.region)) {
          var checkedRegions = getCheckValues(model.sortFilter.region);
          return _.contains(checkedRegions, target.region);
        } else {
          return true;
        }
      };
    }

    function checkStackFilters(model) {
      return function(target) {
        if (isFilterable(model.sortFilter.stack)) {
          var checkedStacks = getCheckValues(model.sortFilter.stack);
          return _.contains(checkedStacks, target.stack);
        } else {
          return true;
        }
      };
    }

    function checkStatusFilters(model) {
      return function(target) {
        if (isFilterable(model.sortFilter.status)) {
          var checkedStatus = getCheckValues(model.sortFilter.status);
          return _.contains(checkedStatus, 'Up') && target.downCount === 0 ||
            _.contains(checkedStatus, 'Down') && target.downCount > 0 ||
            _.contains(checkedStatus, 'OutOfService') && target.outOfServiceCount > 0 ||
            _.contains(checkedStatus, 'Starting') && target.startingCount > 0 ||
            _.contains(checkedStatus, 'Disabled') && target.isDisabled;
        }
        return true;
      };
    }

    function checkProviderFilters(model) {
      return function(target) {
        if (isFilterable(model.sortFilter.providerType)) {
          var checkedProviderTypes = getCheckValues(model.sortFilter.providerType);
          return _.contains(checkedProviderTypes, target.type) || _.contains(checkedProviderTypes, target.provider);
        } else {
          return true;
        }
      };
    }

    function getParamVal(property) {
      return $location.search()[property.param] || property.defaultValue;
    }

    function addTagsForSection(model, property) {
      var key = property.model,
          label = property.filterLabel || property.model,
          translator = property.filterTranslator || {},
          clearValue = property.clearValue;
      translator = translator || {};
      var tags = model.tags;
      var modelVal = model.sortFilter[key];
      if (property.type === 'object') {
        _.forOwn(modelVal, function (isActive, value) {
          if (isActive) {
            tags.push({
              key: key,
              label: label,
              value: translator[value] || value,
              clear: function () {
                delete model.sortFilter[key][value];
                model.applyParamsToUrl();
              }
            });
          }
        });
      } else {
        if (modelVal !== null && modelVal !== undefined && modelVal !== '' && modelVal !== false) {
          tags.push({
            key: key,
            label: label,
            value: translator[modelVal] || modelVal,
            clear: function () {
              model.sortFilter[key] = clearValue;
              model.applyParamsToUrl();
            }
          });
        }
      }
      return tags;
    }

    var converters = {
      'object': {
        toParam: function(filterModel, property) {
          var obj = filterModel.sortFilter[property.model];
          if (obj) {
            return _.chain(obj)
              .collect(function (val, key) {
                if (val) {
                  return key;
                }
              })
              .remove(undefined)
              .value()
              .sort()
              .join(',') || null;
          }
        },
        toModel: function(filterModel, property) {
          var paramList = getParamVal(property);
          if (paramList) {
            return _.reduce(paramList.split(','), function (acc, value) {
              acc[value] = true;
              return acc;
            }, {});
          } else {
            return {};
          }
        }
      },
      'string': {
        toParam: function(filterModel, property) {
          var val = filterModel.sortFilter[property.model];
          return val && val !== property.defaultValue ? val : null;
        },
        toModel: function(filterModel, property) {
          var val = getParamVal(property);
          return val ? val : '';
        }
      },
      'boolean': {
        toParam: function(filterModel, property) {
          var val = filterModel.sortFilter[property.model];
          return val ? val.toString() : null;
        },
        toModel: function(filterModel, property) {
          var val = getParamVal(property);
          return Boolean(val);
        }
      },
      'inverse-boolean': {
        toParam: function(filterModel, property) {
          var val = filterModel.sortFilter[property.model];
          return val ? null : 'true';
        },
        toModel: function(filterModel, property) {
          var val = getParamVal(property);
          return !Boolean(val);
        }
      },
      'number': {
        toParam: function(filterModel, property) {
          var val = filterModel.sortFilter[property.model];
          return isNaN(val) ? null : property.defaultValue === val ? null: val;
        },
        toModel: function(filterModel, property) {
          var val = getParamVal(property);
          return isNaN(val) ? null : Number(val);
        }
      },
      'sortKey': {
        toParam: function(filterModel, property) {
          var val = filterModel.sortFilter[property.model].key;
          return val === property.defaultValue ? null : val;
        },
        toModel: function(filterModel, property) {
          var val = getParamVal(property);
          return { key: val };
        }
      }
    };

    function configureFilterModel(filterModel, filterModelConfig) {
      filterModel.groups = [];
      filterModel.tags = [];
      filterModel.displayOptions = {};
      filterModel.savedState = {};
      filterModel.sortFilter = {};

      filterModelConfig.forEach(function (property) {
        property.param = property.param || property.model;
      });

      filterModel.addTags = function() {
        filterModel.tags.length = 0;
        filterModelConfig
          .filter(function (property) {
            return !property.displayOption;
          })
          .forEach(function (property) {
            addTagsForSection(filterModel, property);
          });
      };

      filterModel.saveState = function(state, params, filters) {
        if (params.application) {
          filters = filters || $location.search();
          filterModel.savedState[params.application] = {
            filters: angular.copy(filters),
            state: state,
            params: params,
          };
        }
      };

      filterModel.restoreState = function(toParams) {
        var application = toParams.application;
        var savedState = filterModel.savedState[application];
        if (savedState) {
          angular.copy(savedState.params, $stateParams);
          var currentParams = $location.search();
          // clear any shared params between states, e.g. previous state set 'acct', which this state also uses,
          // but this state does not have that field set, so angular.extend will not overwrite it
          _.forOwn(currentParams, function(val, key) {
            if (Object.hasOwnProperty(savedState.filters, key)) {
              delete currentParams[key];
            }
          });
          $timeout(function() {
            $location.search(angular.extend(currentParams, savedState.filters));
            filterModel.activate();
            $location.replace();
          });
        }
      };

      filterModel.hasSavedState = function(toParams) {
        var application = toParams.application;
        return filterModel.savedState[application] !== undefined && filterModel.savedState[application].params !== undefined;
      };

      filterModel.clearFilters = function () {
        filterModelConfig.forEach(function (property) {
          if (!property.displayOption) {
            filterModel.sortFilter[property.model] = property.clearValue;
          }
        });
      };

      filterModel.activate = function() {
        filterModelConfig.forEach(function (property) {
          filterModel.sortFilter[property.model] = converters[property.type].toModel(filterModel, property);
        });
      };

      filterModel.applyParamsToUrl = function() {
        filterModelConfig.forEach(function (property) {
          $location.search(property.param, converters[property.type].toParam(filterModel, property));
        });
      };
    }

    return {
      configureFilterModel: configureFilterModel,
      isFilterable: isFilterable,
      getCheckValues: getCheckValues,
      checkAccountFilters: checkAccountFilters,
      checkRegionFilters: checkRegionFilters,
      checkStackFilters: checkStackFilters,
      checkStatusFilters: checkStatusFilters,
      checkProviderFilters: checkProviderFilters
    };

  }).name;
<commit_msg>encode commas when storing as filter model objects in url<commit_after>'use strict';

let angular = require('angular');

module.exports = angular
  .module('spinnaker.core.filterModel.service', [
    require('../utils/lodash.js'),
    require('angular-ui-router'),
  ])
.factory('filterModelService', function (_, $location, $state, $stateParams, $timeout) {

    function isFilterable(sortFilterModel) {
      return _.size(sortFilterModel) > 0 && _.any(sortFilterModel);
    }

    function getCheckValues(sortFilterModel) {
      return  _.reduce(sortFilterModel, function(acc, val, key) {
        if (val) {
          acc.push(key);
        }
        return acc;
      }, []).sort();
    }

    function checkAccountFilters(model) {
      return function(target) {
        if(isFilterable(model.sortFilter.account)) {
          var checkedAccounts = getCheckValues(model.sortFilter.account);
          return _.contains(checkedAccounts, target.account);
        } else {
          return true;
        }
      };
    }

    function checkRegionFilters(model) {
      return function(target) {
        if(isFilterable(model.sortFilter.region)) {
          var checkedRegions = getCheckValues(model.sortFilter.region);
          return _.contains(checkedRegions, target.region);
        } else {
          return true;
        }
      };
    }

    function checkStackFilters(model) {
      return function(target) {
        if (isFilterable(model.sortFilter.stack)) {
          var checkedStacks = getCheckValues(model.sortFilter.stack);
          return _.contains(checkedStacks, target.stack);
        } else {
          return true;
        }
      };
    }

    function checkStatusFilters(model) {
      return function(target) {
        if (isFilterable(model.sortFilter.status)) {
          var checkedStatus = getCheckValues(model.sortFilter.status);
          return _.contains(checkedStatus, 'Up') && target.downCount === 0 ||
            _.contains(checkedStatus, 'Down') && target.downCount > 0 ||
            _.contains(checkedStatus, 'OutOfService') && target.outOfServiceCount > 0 ||
            _.contains(checkedStatus, 'Starting') && target.startingCount > 0 ||
            _.contains(checkedStatus, 'Disabled') && target.isDisabled;
        }
        return true;
      };
    }

    function checkProviderFilters(model) {
      return function(target) {
        if (isFilterable(model.sortFilter.providerType)) {
          var checkedProviderTypes = getCheckValues(model.sortFilter.providerType);
          return _.contains(checkedProviderTypes, target.type) || _.contains(checkedProviderTypes, target.provider);
        } else {
          return true;
        }
      };
    }

    function getParamVal(property) {
      return $location.search()[property.param] || property.defaultValue;
    }

    function addTagsForSection(model, property) {
      var key = property.model,
          label = property.filterLabel || property.model,
          translator = property.filterTranslator || {},
          clearValue = property.clearValue;
      translator = translator || {};
      var tags = model.tags;
      var modelVal = model.sortFilter[key];
      if (property.type === 'object') {
        _.forOwn(modelVal, function (isActive, value) {
          if (isActive) {
            tags.push({
              key: key,
              label: label,
              value: translator[value] || value,
              clear: function () {
                delete model.sortFilter[key][value];
                model.applyParamsToUrl();
              }
            });
          }
        });
      } else {
        if (modelVal !== null && modelVal !== undefined && modelVal !== '' && modelVal !== false) {
          tags.push({
            key: key,
            label: label,
            value: translator[modelVal] || modelVal,
            clear: function () {
              model.sortFilter[key] = clearValue;
              model.applyParamsToUrl();
            }
          });
        }
      }
      return tags;
    }

    var converters = {
      'object': {
        toParam: function(filterModel, property) {
          var obj = filterModel.sortFilter[property.model];
          if (obj) {
            return _.chain(obj)
              .collect(function (val, key) {
                if (val) {
                  // replace any commas in the string with their uri-encoded version ('%2c'), since
                  // we use commas as our separator in the URL
                  return key.replace(/,/g, '%2c');
                }
              })
              .remove(undefined)
              .value()
              .sort()
              .join(',') || null;
          }
        },
        toModel: function(filterModel, property) {
          var paramList = getParamVal(property);
          if (paramList) {
            return _.reduce(paramList.split(','), function (acc, value) {
              // replace any uri-encoded commas in the string ('%2c') with actual commas, since
              // we use commas as our separator in the URL
              acc[value.replace(/%2c/g, ',')] = true;
              return acc;
            }, {});
          } else {
            return {};
          }
        }
      },
      'string': {
        toParam: function(filterModel, property) {
          var val = filterModel.sortFilter[property.model];
          return val && val !== property.defaultValue ? val : null;
        },
        toModel: function(filterModel, property) {
          var val = getParamVal(property);
          return val ? val : '';
        }
      },
      'boolean': {
        toParam: function(filterModel, property) {
          var val = filterModel.sortFilter[property.model];
          return val ? val.toString() : null;
        },
        toModel: function(filterModel, property) {
          var val = getParamVal(property);
          return Boolean(val);
        }
      },
      'inverse-boolean': {
        toParam: function(filterModel, property) {
          var val = filterModel.sortFilter[property.model];
          return val ? null : 'true';
        },
        toModel: function(filterModel, property) {
          var val = getParamVal(property);
          return !Boolean(val);
        }
      },
      'number': {
        toParam: function(filterModel, property) {
          var val = filterModel.sortFilter[property.model];
          return isNaN(val) ? null : property.defaultValue === val ? null: val;
        },
        toModel: function(filterModel, property) {
          var val = getParamVal(property);
          return isNaN(val) ? null : Number(val);
        }
      },
      'sortKey': {
        toParam: function(filterModel, property) {
          var val = filterModel.sortFilter[property.model].key;
          return val === property.defaultValue ? null : val;
        },
        toModel: function(filterModel, property) {
          var val = getParamVal(property);
          return { key: val };
        }
      }
    };

    function configureFilterModel(filterModel, filterModelConfig) {
      filterModel.groups = [];
      filterModel.tags = [];
      filterModel.displayOptions = {};
      filterModel.savedState = {};
      filterModel.sortFilter = {};

      filterModelConfig.forEach(function (property) {
        property.param = property.param || property.model;
      });

      filterModel.addTags = function() {
        filterModel.tags.length = 0;
        filterModelConfig
          .filter(function (property) {
            return !property.displayOption;
          })
          .forEach(function (property) {
            addTagsForSection(filterModel, property);
          });
      };

      filterModel.saveState = function(state, params, filters) {
        if (params.application) {
          filters = filters || $location.search();
          filterModel.savedState[params.application] = {
            filters: angular.copy(filters),
            state: state,
            params: params,
          };
        }
      };

      filterModel.restoreState = function(toParams) {
        var application = toParams.application;
        var savedState = filterModel.savedState[application];
        if (savedState) {
          angular.copy(savedState.params, $stateParams);
          var currentParams = $location.search();
          // clear any shared params between states, e.g. previous state set 'acct', which this state also uses,
          // but this state does not have that field set, so angular.extend will not overwrite it
          _.forOwn(currentParams, function(val, key) {
            if (Object.hasOwnProperty(savedState.filters, key)) {
              delete currentParams[key];
            }
          });
          $timeout(function() {
            $location.search(angular.extend(currentParams, savedState.filters));
            filterModel.activate();
            $location.replace();
          });
        }
      };

      filterModel.hasSavedState = function(toParams) {
        var application = toParams.application;
        return filterModel.savedState[application] !== undefined && filterModel.savedState[application].params !== undefined;
      };

      filterModel.clearFilters = function () {
        filterModelConfig.forEach(function (property) {
          if (!property.displayOption) {
            filterModel.sortFilter[property.model] = property.clearValue;
          }
        });
      };

      filterModel.activate = function() {
        filterModelConfig.forEach(function (property) {
          filterModel.sortFilter[property.model] = converters[property.type].toModel(filterModel, property);
        });
      };

      filterModel.applyParamsToUrl = function() {
        filterModelConfig.forEach(function (property) {
          $location.search(property.param, converters[property.type].toParam(filterModel, property));
        });
      };
    }

    return {
      configureFilterModel: configureFilterModel,
      isFilterable: isFilterable,
      getCheckValues: getCheckValues,
      checkAccountFilters: checkAccountFilters,
      checkRegionFilters: checkRegionFilters,
      checkStackFilters: checkStackFilters,
      checkStatusFilters: checkStatusFilters,
      checkProviderFilters: checkProviderFilters
    };

  }).name;
<|endoftext|>


<commit_before>/**
 * Example of the most basic activity, implementing base properties and a
 * minimal template that uses an example component.
 *
 * @module activities/_examples/a-basic-activity
 *
 * FIXME: Update this activity description
 * FIXME: After copy this example, some paths to imported modules needs to be
 * updated by removing one parent path ('../')
 *
 * REMOVEME: Check other examples for more documentation and the Activity
 * class source code (is partially documented and annotated --we are in the process to
 * enhance that documentation and remove obsolete parts)
 */

// REMOVEME: We MUST explicitly load each component used directly at the
// template. Be aware that the example component we are loading register
// itself with the name `component-example` rather than the folder name, not
// following convention but done for simplicity of examples as commented
// on their kocomponents/_examples/README.md file.
import '../../../kocomponents/_examples/a-template-only';
import * as activities from '../index';
// REMOVEME: After migration of old activities into folders, the base class will
// move from this path into '../helpers/Activity', we will upgrade existent
// activities too.
import Activity from '../../../components/Activity';
import UserType from '../../../enums/UserType';
import template from './template.html';

const ROUTE_NAME = 'example-activity';

export default class ExampleActivity extends Activity {

    static get template() { return template; }

    /**
     * REMOVEME: No need to document standard behavior and parameters for the
     * activity, since usually is just copy&paste of base Activity class and
     * is redundant. But document with a jsdoc comment like this if some special
     * behavior is worth note it.
     * Use this constructor to set instance values for inherit and required
     * members and create new members (usually observables and computed) usually
     * needed at the template; methods needed at the template can be created
     * as class methods or defined at the constructor if there is need to access
     * some private/closure values or problems with the execution context ('bind')
     * @param {jQuery} $activity
     * @param {App} app
     */
    constructor($activity, app) {
        // REMOVEME: This set of parameters is being reviewed and can change/remove
        // in a future (specially the 'app' global instance, replacing by modules
        // explicitly imported for specific tasks).
        super($activity, app);

        // FIXME: REQUIRED: Define which users can access this activity filtering by
        // user type. Assign any valid UserType value.
        // You can set the value 'null' to allow any
        this.accessLevel = UserType.loggedUser;
        // FIXME: REQUIRED: Define the kind of activity navbar used and values
        // For now, next set-up is the usual for first-level activities (like
        // home, dashboard, cms, ...). Use Activity.createSubsectionNavBar
        // and accepted values for activities that are behind another in the
        // navigation hierarchy (check Activity class documentation)
        this.navBar = Activity.createSectionNavBar(null);
        this.navBar.rightAction(null);
        // FIXME: REQUIRED: Define the activity title, used at window/tab
        // and top title in the template
        // This value can be a string (then is a constant value for all the life
        // of the activity), an observable (dynamically changed depending
        // on the route or user interaction), a pureComputed (dynamically
        // changed depending on other activity observables --usually this is
        // recommended over an observable since it keeps all possible values
        // in one place)
        this.title = 'Example Activity';
    }

    /**
     * REMOVEME: If there is no parameters/state accepted by this activity,
     * there is no need to document here the standard behavior and parameters for the
     * show method, since usually is just copy&paste of base method and
     * is redundant. But document with a jsdoc comment like this if some special
     * behavior is worth note it and when specific state properties and values
     * are expected.
     * Replace this method only if need to execute some code when the activity
     * is being displayed and to read/analyze incoming state parameters (routing
     * internal to the activity, query-string parameters, communication between
     * activities through state properties).
     * Remove all this 'show' code if you don't need to do anything here
     * @param {Object} state
     */
    show(state) {
        super.show(state);
        // Check other examples for some code using 'state'
    }
}

activities.register(ROUTE_NAME, ExampleActivity);
<commit_msg>fixed paths to activity example to the correct ones AFTER copy it under activities folder to use as template<commit_after>/**
 * Example of the most basic activity, implementing base properties and a
 * minimal template that uses an example component.
 *
 * @module activities/_examples/a-basic-activity
 *
 * FIXME: Update this activity description
 * FIXME: After copy this example, some paths to imported modules needs to be
 * updated by removing one parent path ('../')
 *
 * REMOVEME: Check other examples for more documentation and the Activity
 * class source code (is partially documented and annotated --we are in the process to
 * enhance that documentation and remove obsolete parts)
 */

// REMOVEME: We MUST explicitly load each component used directly at the
// template. Be aware that the example component we are loading register
// itself with the name `component-example` rather than the folder name, not
// following convention but done for simplicity of examples as commented
// on their kocomponents/_examples/README.md file.
import '../../kocomponents/_examples/a-template-only';
import * as activities from '../index';
// REMOVEME: After migration of old activities into folders, the base class will
// move from this path into '../helpers/Activity', we will upgrade existent
// activities too.
import Activity from '../../components/Activity';
import UserType from '../../enums/UserType';
import template from './template.html';

const ROUTE_NAME = 'example-activity';

export default class ExampleActivity extends Activity {

    static get template() { return template; }

    /**
     * REMOVEME: No need to document standard behavior and parameters for the
     * activity, since usually is just copy&paste of base Activity class and
     * is redundant. But document with a jsdoc comment like this if some special
     * behavior is worth note it.
     * Use this constructor to set instance values for inherit and required
     * members and create new members (usually observables and computed) usually
     * needed at the template; methods needed at the template can be created
     * as class methods or defined at the constructor if there is need to access
     * some private/closure values or problems with the execution context ('bind')
     * @param {jQuery} $activity
     * @param {App} app
     */
    constructor($activity, app) {
        // REMOVEME: This set of parameters is being reviewed and can change/remove
        // in a future (specially the 'app' global instance, replacing by modules
        // explicitly imported for specific tasks).
        super($activity, app);

        // FIXME: REQUIRED: Define which users can access this activity filtering by
        // user type. Assign any valid UserType value.
        // You can set the value 'null' to allow any
        this.accessLevel = UserType.loggedUser;
        // FIXME: REQUIRED: Define the kind of activity navbar used and values
        // For now, next set-up is the usual for first-level activities (like
        // home, dashboard, cms, ...). Use Activity.createSubsectionNavBar
        // and accepted values for activities that are behind another in the
        // navigation hierarchy (check Activity class documentation)
        this.navBar = Activity.createSectionNavBar(null);
        this.navBar.rightAction(null);
        // FIXME: REQUIRED: Define the activity title, used at window/tab
        // and top title in the template
        // This value can be a string (then is a constant value for all the life
        // of the activity), an observable (dynamically changed depending
        // on the route or user interaction), a pureComputed (dynamically
        // changed depending on other activity observables --usually this is
        // recommended over an observable since it keeps all possible values
        // in one place)
        this.title = 'Example Activity';
    }

    /**
     * REMOVEME: If there is no parameters/state accepted by this activity,
     * there is no need to document here the standard behavior and parameters for the
     * show method, since usually is just copy&paste of base method and
     * is redundant. But document with a jsdoc comment like this if some special
     * behavior is worth note it and when specific state properties and values
     * are expected.
     * Replace this method only if need to execute some code when the activity
     * is being displayed and to read/analyze incoming state parameters (routing
     * internal to the activity, query-string parameters, communication between
     * activities through state properties).
     * Remove all this 'show' code if you don't need to do anything here
     * @param {Object} state
     */
    show(state) {
        super.show(state);
        // Check other examples for some code using 'state'
    }
}

activities.register(ROUTE_NAME, ExampleActivity);
<|endoftext|>


<commit_before>var app = angular.module("app")
    .service("utilityService",function() {

        var service =  {};

        /**
         * This function formats a timestamp and returns it into a simple date dd/mm/yyyy
         * @returns {*}
         */
        service.formatDate = function(dateString){
            var date = dateString.split("-").join("/");
            var date_object = new Date(date);
            var month = date_object.getMonth() + 1;
            var day = date_object.getDate();
            var year = date_object.getFullYear();
            var date_object_formatted = day + "/" + month + "/" + year;

            return date_object_formatted;
        };

        return service;
    });

<commit_msg>[#124]: remove microseconds. another try with safari and IE<commit_after>var app = angular.module("app")
    .service("utilityService",function() {

        var service =  {};

        /**
         * This function formats a timestamp and returns it into a simple date dd/mm/yyyy
         * @returns {*}
         */
        service.formatDate = function(dateString){
            var date = dateString.split("-").join("/").replace( /\.[0-9]+/g, '' );
            var date_object = new Date(date);
            var month = date_object.getMonth() + 1;
            var day = date_object.getDate();
            var year = date_object.getFullYear();
            var date_object_formatted = day + "/" + month + "/" + year;

            return date_object_formatted;
        };

        return service;
    });

<|endoftext|>


<commit_before>import React, { Component } from 'react'
import { Upload, Icon, message, Select } from 'antd';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import './ProjectData.scss';
import axios from 'axios';
const Dragger = Upload.Dragger;
const Option = Select.Option;

const plugin = require('client/plugin.js');

const importDataModule = {};

@connect(
  state => {
    // console.log(state);
    return {
      curCatid: -(-state.inter.curdata.catid),
      basePath: state.project.currProject.basepath
    }
  }, {

  }
)

class ProjectData extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectCatid: "",
      menuList: [],
      curImportType: null
    }
  }
  static propTypes = {
    match: PropTypes.object,
    curCatid: PropTypes.number,
    basePath: PropTypes.string
  }

  componentWillMount() {
    axios.get(`/api/interface/getCatMenu?project_id=${this.props.match.params.id}`).then((data) => {
      let menuList = data.data.data;
      this.setState({
        menuList: menuList
      })
    });
    plugin.emitHook('import_data', importDataModule, this.props);
  }
  selectChange(value) {
    this.setState({
      selectCatid: +value
    })
  }

  uploadChnange(info) {
    const status = info.file.status;
    if (status !== 'uploading') {
      console.log(info.file, info.fileList);
    }
    if (status === 'done') {
      message.success(`${info.file.name} 文件上传成功`);
    } else if (status === 'error') {
      message.error(`${info.file.name} 文件上传失败`);
    }
  }

  handleAddInterface(info) {
    if (!this.state.curImportType) {
      return message.error('请选择导入数据的方式');
    }
    if (this.state.selectCatid) {
      // let filename = info.file.name;
      // let filetype = filename.substr(filename.lastIndexOf(".")).toLowerCase();
      // console.log(filename,filetype);
      //if(filetype != ".json") return message.error("文件格式只能为json");
      let reader = new FileReader();
      reader.readAsText(info.file);
      reader.onload = (res) => {
        res = importDataModule[this.state.curImportType].run(res.target.result);
        res = res.apis;
        let len = res.length;
        let count = 0;
        let successNum = len;
        res.forEach(async (item) => {
          let data = {
            ...item,
            project_id: this.props.match.params.id,
            catid: this.state.selectCatid
          }
          if (this.props.basePath) {
            data.path = data.path.indexOf(this.props.basePath) === 0 ? data.path.substr(this.props.basePath.length) : data.path;
          }

          let result = await axios.post('/api/interface/add', data);
          count++;
          if (result.data.errcode) {
            successNum--;
          }
          if (count === len) {
            message.success(`成功导入接口 ${successNum} 个`);
          }

        })
      }
    } else {
      message.error("请选择上传的分类");
    }
  }

  handleImportType = (val) => {
    this.setState({
      curImportType: val
    })
  }

  /**
   *
   *
   * @returns
   * @memberof ProjectData
   */
  render() {
    const uploadMess = {
      name: 'interfaceData',
      multiple: true,
      showUploadList: false,
      action: '/api/interface/interUpload',
      customRequest: this.handleAddInterface.bind(this),
      onChange: this.uploadChnange.bind(this)
    }
    return (

数据导入 <Icon type="question-circle-o" />

                <Select placeholder="请选择导入数据的方式" onChange={this.handleImportType}>
                  {Object.keys(importDataModule).map((name) => {
                    return <Option key={name} value={name}>{importDataModule[name].name}</Option>
                  })}

                </Select>

                <Select
                  showSearch
                  style={{ width: '100%' }}
                  placeholder="请选择数据导入的接口分类"
                  optionFilterProp="children"
                  onChange={this.selectChange.bind(this)}
                  filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                >
                  {this.state.menuList.map((item, key) => {
                    return <Option key={key} value={item._id + ""}>{item.name}</Option>;
                  })}

                </Select>

                <Dragger {...uploadMess}>

                    <Icon type="inbox" />

点击或者拖拽文件到上传区域

{this.state.curImportType ? importDataModule[this.state.curImportType].desc : null}

                </Dragger>

    )
  }
}

export default ProjectData;
<commit_msg>docs: 数据导入文档提示<commit_after>import React, { Component } from 'react'
import { Upload, Icon, message, Select } from 'antd';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import './ProjectData.scss';
import axios from 'axios';
const Dragger = Upload.Dragger;
const Option = Select.Option;

const plugin = require('client/plugin.js');

const importDataModule = {};

@connect(
  state => {
    // console.log(state);
    return {
      curCatid: -(-state.inter.curdata.catid),
      basePath: state.project.currProject.basepath
    }
  }, {

  }
)

class ProjectData extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectCatid: "",
      menuList: [],
      curImportType: null
    }
  }
  static propTypes = {
    match: PropTypes.object,
    curCatid: PropTypes.number,
    basePath: PropTypes.string
  }

  componentWillMount() {
    axios.get(`/api/interface/getCatMenu?project_id=${this.props.match.params.id}`).then((data) => {
      let menuList = data.data.data;
      this.setState({
        menuList: menuList
      })
    });
    plugin.emitHook('import_data', importDataModule, this.props);
  }
  selectChange(value) {
    this.setState({
      selectCatid: +value
    })
  }

  uploadChnange(info) {
    const status = info.file.status;
    if (status !== 'uploading') {
      console.log(info.file, info.fileList);
    }
    if (status === 'done') {
      message.success(`${info.file.name} 文件上传成功`);
    } else if (status === 'error') {
      message.error(`${info.file.name} 文件上传失败`);
    }
  }

  handleAddInterface(info) {
    if (!this.state.curImportType) {
      return message.error('请选择导入数据的方式');
    }
    if (this.state.selectCatid) {
      // let filename = info.file.name;
      // let filetype = filename.substr(filename.lastIndexOf(".")).toLowerCase();
      // console.log(filename,filetype);
      //if(filetype != ".json") return message.error("文件格式只能为json");
      let reader = new FileReader();
      reader.readAsText(info.file);
      reader.onload = (res) => {
        res = importDataModule[this.state.curImportType].run(res.target.result);
        res = res.apis;
        let len = res.length;
        let count = 0;
        let successNum = len;
        res.forEach(async (item) => {
          let data = {
            ...item,
            project_id: this.props.match.params.id,
            catid: this.state.selectCatid
          }
          if (this.props.basePath) {
            data.path = data.path.indexOf(this.props.basePath) === 0 ? data.path.substr(this.props.basePath.length) : data.path;
          }

          let result = await axios.post('/api/interface/add', data);
          count++;
          if (result.data.errcode) {
            successNum--;
          }
          if (count === len) {
            message.success(`成功导入接口 ${successNum} 个`);
          }

        })
      }
    } else {
      message.error("请选择上传的分类");
    }
  }

  handleImportType = (val) => {
    this.setState({
      curImportType: val
    })
  }

  /**
   *
   *
   * @returns
   * @memberof ProjectData
   */
  render() {
    const uploadMess = {
      name: 'interfaceData',
      multiple: true,
      showUploadList: false,
      action: '/api/interface/interUpload',
      customRequest: this.handleAddInterface.bind(this),
      onChange: this.uploadChnange.bind(this)
    }
    return (

数据导入 <Icon type="question-circle-o" />

                <Select placeholder="请选择导入数据的方式" onChange={this.handleImportType}>
                  {Object.keys(importDataModule).map((name) => {
                    return <Option key={name} value={name}>{importDataModule[name].name}</Option>
                  })}

                </Select>

                <Select
                  showSearch
                  style={{ width: '100%' }}
                  placeholder="请选择数据导入的接口分类"
                  optionFilterProp="children"
                  onChange={this.selectChange.bind(this)}
                  filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                >
                  {this.state.menuList.map((item, key) => {
                    return <Option key={key} value={item._id + ""}>{item.name}</Option>;
                  })}

                </Select>

                <Dragger {...uploadMess}>

                    <Icon type="inbox" />

点击或者拖拽文件到上传区域

{this.state.curImportType ? importDataModule[this.state.curImportType].desc : null}

                </Dragger>

    )
  }
}

export default ProjectData;
<|endoftext|>


<commit_before>"use strict";

define(['logManager', './AutoRouter', './Profiler'], function (logManager, AutoRouter, Profiler) {

    var ConnectionRouteManager3,
        DESIGNERITEM_SUBCOMPONENT_SEPARATOR = "_x_";

    ConnectionRouteManager3 = function (options) {
        this.logger = (options && options.logger) || logManager.create(((options && options.loggerName) || "ConnectionRouteManager3"));

        this.diagramDesigner = options ? options.diagramDesigner : null;

        if (this.diagramDesigner === undefined || this.diagramDesigner === null) {
            this.logger.error("Trying to initialize a ConnectionRouteManager3 without a canvas...");
            throw ("ConnectionRouteManager3 can not be created");
        }

        this.autorouter = new AutoRouter();

        this.logger.debug("ConnectionRouteManager3 ctor finished");
    };

    ConnectionRouteManager3.prototype.initialize = function () {
        this._initialized = false;
        this._clearGraph();

        //Adding event listeners
        var self = this;

        this._onComponentUpdate = function(_canvas, ID) {//Boxes and lines
            if( self.diagramDesigner.itemIds.indexOf( ID ) !== -1 ){

             if( self.diagramDesigner.items[ID].rotation !== self._autorouterBoxRotation[ID] ) //Item has been rotated
                self._resizeItem( ID );

            }else if( self.diagramDesigner.connectionIds.indexOf( ID ) !== -1 ){ //Segment points have been modified
                self.autorouter.setPathCustomPoints({
                        "path": self._autorouterPaths[ ID ],
                        "points": self.diagramDesigner.items[ ID ].segmentPoints
                        });
            }
       };
        this.diagramDesigner.addEventListener(this.diagramDesigner.events.ON_COMPONENT_UPDATE, this._onComponentUpdate);

        this._onComponentCreate = function(_canvas, ID) {//Boxes and lines
            if( self.diagramDesigner.itemIds.indexOf( ID ) !== -1 ){

                if( self._autorouterBoxes[ID] === undefined )
                    self.insertBox( ID );

            }else if( self.diagramDesigner.connectionIds.indexOf( ID ) !== -1 )
                self.insertConnection( ID );
        };
        this.diagramDesigner.addEventListener(this.diagramDesigner.events.ON_COMPONENT_CREATE, this._onComponentCreate);

        this._onComponentResize = function(_canvas, ID) {
            if( self._autorouterBoxes[ID.ID] )
                self._resizeItem( ID.ID );
            else
                self.insertBox( ID.ID );
        };
        this.diagramDesigner.addEventListener(this.diagramDesigner.events.ITEM_SIZE_CHANGED, this._onComponentResize);

        this._onComponentDelete = function(_canvas, ID) {//Boxes and lines
            self.deleteItem( ID );
        };
        this.diagramDesigner.addEventListener(this.diagramDesigner.events.ON_COMPONENT_DELETE, this._onComponentDelete);
        //ON_UNREGISTER_SUBCOMPONENT

        this._onItemPositionChanged = function(_canvas, eventArgs) {
            if( self._autorouterBoxes[eventArgs.ID] ){
                var x = self.diagramDesigner.items[eventArgs.ID].getBoundingBox().x,
                    y = self.diagramDesigner.items[eventArgs.ID].getBoundingBox().y;

                self.autorouter.move(self._autorouterBoxes[eventArgs.ID].box, { "x": x, "y": y });
            }
        };
        this.diagramDesigner.addEventListener(this.diagramDesigner.events.ITEM_POSITION_CHANGED, this._onItemPositionChanged);

        this._onClear = function(_canvas, eventArgs) {
            self._clearGraph();
        };
        this.diagramDesigner.addEventListener(this.diagramDesigner.events.ON_CLEAR, this._onClear);

    };

    ConnectionRouteManager3.prototype.destroy = function () {
        //removeEventListener(eventName, handler);
        this.diagramDesigner.removeEventListener(this.diagramDesigner.events.ON_COMPONENT_CREATE, this._onComponentCreate);
        this.diagramDesigner.removeEventListener(this.diagramDesigner.events.ON_COMPONENT_UPDATE, this._onComponentUpdate);
        this.diagramDesigner.removeEventListener(this.diagramDesigner.events.ITEM_SIZE_CHANGED, this._onComponentResize);
        this.diagramDesigner.removeEventListener(this.diagramDesigner.events.ON_COMPONENT_DELETE, this._onComponentDelete);
        this.diagramDesigner.removeEventListener(this.diagramDesigner.events.ITEM_POSITION_CHANGED, this._onItemPositionChanged);
        this.diagramDesigner.removeEventListener(this.diagramDesigner.events.ON_CLEAR, this._onClear);
    };

    ConnectionRouteManager3.prototype.redrawConnections = function (idList) {

        if( !this._initialized ){
            this._initializeGraph();
        }else{
            this._refreshConnData(idList);
        }

        this._updateConnectionPorts( idList );

        //no matter what, we want the id's of all the connections
        //not just the ones that explicitly needs rerouting
        idList = this.diagramDesigner.connectionIds.slice(0);

        var i = idList.length;

        //1 - autoroute
        this.autorouter.autoroute();

        //2 - Get the path points and redraw
        var pathPoints,
            realPathPoints;
        for (i = 0; i < idList.length; i += 1) {
            if( this._autorouterPaths[idList[i]] ){
                pathPoints = this.autorouter.getPathPoints(this._autorouterPaths[idList[i]]);
            }else{
                pathPoints = [];
            }

            realPathPoints = [];
            for(var j = 0; j < pathPoints.length; j++){
                realPathPoints.push({'x': pathPoints[j][0], 'y': pathPoints[j][1] });
            }

            this.diagramDesigner.items[idList[i]].setConnectionRenderData(realPathPoints);
        }

        //need to return the IDs of the connections that was really
        //redrawn or any other visual property changed (width, etc)

        return idList;
    };

    ConnectionRouteManager3.prototype._refreshConnData = function (idList) {
        //Clear connection data and paths then re-add them
        var i = idList.length;

        while(i--){
            this.autorouter.remove(this._autorouterPaths[idList[i]]);
            this._autorouterPaths[idList[i]] = undefined;
            this.insertConnection([idList[i]]);
        }

    };

    ConnectionRouteManager3.prototype._clearGraph = function () {
        this.autorouter.clear();
        this._autorouterBoxes = {};//Define container that will map obj+subID -> box
        this._autorouterPorts = {};//Maps boxIds to an array of port ids that have been mapped
        this._autorouterPaths = {};
        this._autorouterBoxRotation = {};//Define container that will map obj+subID -> rotation
        this.endpointConnectionAreaInfo = {};
    };

    ConnectionRouteManager3.prototype._initializeGraph = function () {
        /*
         * In this method, we will update the boxes using the canvas.itemIds list and
         * add any ports as needed (from the canvas.connectionIds)
         */
        var canvas = this.diagramDesigner,
            connIdList = canvas.connectionIds,
            itemIdList = canvas.itemIds,
            i = itemIdList.length,
            connId,
            srcObjId,
            srcSubCompId,
            dstObjId,
            dstSubCompId;

        while(i--){
            this.insertBox(itemIdList[i]);
        }

        i = connIdList.length;
        while( i-- ){
            this.insertConnection(connIdList[i]);
            if( canvas.items[connIdList[i]].segmentPoints.length > 0 )
                this.autorouter.setPathCustomPoints({
                        "path": this._autorouterPaths[ connIdList[i] ],
                        "points": canvas.items[ connIdList[i] ].segmentPoints
                        });
        }

        //Next, I will update the ports as necessary
        this._updateConnectionPorts(connIdList);

        this._initialized = true;

    };

    ConnectionRouteManager3.prototype.insertConnection = function (connId) {
        var canvas = this.diagramDesigner,
            srcObjId = canvas.connectionEndIDs[connId].srcObjId,
            srcSubCompId = canvas.connectionEndIDs[connId].srcSubCompId,
            dstObjId = canvas.connectionEndIDs[connId].dstObjId,
            dstSubCompId = canvas.connectionEndIDs[connId].dstSubCompId,
            sId = srcSubCompId ? srcObjId + DESIGNERITEM_SUBCOMPONENT_SEPARATOR + srcSubCompId : srcObjId,
            tId = dstSubCompId ? dstObjId + DESIGNERITEM_SUBCOMPONENT_SEPARATOR + dstSubCompId : dstObjId;

        this._updatePort(srcObjId, srcSubCompId);//Adding ports for connection
        this._updatePort(dstObjId, dstSubCompId);
        //If it has both a src and dst
        if( this._autorouterBoxes[sId].ports.length !== 0 && this._autorouterBoxes[tId].ports.length !== 0 ){
            this._autorouterPaths[connId] = this.autorouter.addPath({ "src": this._autorouterBoxes[sId],
                                                                               "dst": this._autorouterBoxes[tId] });
        }

     };

    ConnectionRouteManager3.prototype.insertBox = function (objId) {
        var canvas = this.diagramDesigner,
            designerItem,
            areas,
            bBox,
            boxdefinition,
            connectionMetaInfo,
            isEnd,
            j;

        designerItem = canvas.items[objId];
        bBox = designerItem.getBoundingBox();
        areas = designerItem.getConnectionAreas(objId, isEnd, connectionMetaInfo) || [];

        boxdefinition = {
            //BOX
            "x1": bBox.x,
            "y1": bBox.y,
            "x2": bBox.x2,
            "y2": bBox.y2,

            //PORTS
            "ConnectionAreas": []
        };

        j = areas.length;
        while (j--) {
            //Building up the ConnectionAreas object
            boxdefinition.ConnectionAreas.push([ [ areas[j].x1, areas[j].y1 ], [ areas[j].x2, areas[j].y2 ] ]);
        }

        this._autorouterBoxes[objId] = this.autorouter.addBox(boxdefinition);
        this._autorouterBoxRotation[objId] = canvas.items[objId].rotation;
    };

    ConnectionRouteManager3.prototype.deleteItem = function (objId) {
        //If I can query them from the objId, I can clear the entries with that info
        var item = this.diagramDesigner.items[objId],
            connIds = this.diagramDesigner.connectionIds,
            itemIds = this.diagramDesigner.itemIds;
        if(itemIds.indexOf(objId) !== -1){
            item = this._autorouterBoxes[objId];

            var i = this._autorouterPorts[objId] ? this._autorouterPorts[objId].length : 0;
            while( i-- ){
                var id = objId + DESIGNERITEM_SUBCOMPONENT_SEPARATOR + this._autorouterPorts[objId][i]; //ID of child port
                this._autorouterBoxes[id] = undefined;
            }

            this._autorouterBoxes[objId] = undefined;
        }else if(connIds.indexOf(objId) !== -1){
            item = this._autorouterPaths[objId];//If objId is a connection

        }
            this.autorouter.remove(item);

    };

    ConnectionRouteManager3.prototype._resizeItem = function (objId) {
        var canvas = this.diagramDesigner,
            isEnd = true,
            connectionMetaInfo,
            designerItem = canvas.items[objId],
            newCoord = designerItem.getBoundingBox(),
            newBox = { 'x1': newCoord.x,
                       'x2': newCoord.x2,
                       'y1': newCoord.y,
                       'y2': newCoord.y2,
          'ConnectionAreas': [] },
            connAreas = designerItem.getConnectionAreas(objId, isEnd, connectionMetaInfo),
            portIds = this._autorouterPorts[objId],
            i;

        //Create the new box connection areas
        i = connAreas.length;
        while (i--) {
            //Building up the ConnectionAreas obiect
            newBox.ConnectionAreas.push([ [ connAreas[i].x1, connAreas[i].y1 ], [ connAreas[i].x2, connAreas[i].y2 ] ]);
        }

        //Update Box
        this.autorouter.setBox(this._autorouterBoxes[objId], newBox);

        //Resize Ports Based on Connections
        i = portIds !== undefined ? portIds.length : 0;
        while( i-- ){
            this._updatePort( objId, portIds[i] );
        }

    };

    ConnectionRouteManager3.prototype._updateConnectionPorts = function (idList) {
        var canvas = this.diagramDesigner,
            connId,
            srcObjId,
            srcSubCompId,
            dstObjId,
            dstSubCompId,
            i = idList.length;

        while(i--){
            connId = idList[i];
            srcObjId = canvas.connectionEndIDs[connId].srcObjId;
            srcSubCompId = canvas.connectionEndIDs[connId].srcSubCompId;
            dstObjId = canvas.connectionEndIDs[connId].dstObjId;
            dstSubCompId = canvas.connectionEndIDs[connId].dstSubCompId;

            this._updatePort(srcObjId, srcSubCompId);
            this._updatePort(dstObjId, dstSubCompId);
        }
    };

    ConnectionRouteManager3.prototype._updatePort = function (objId, subCompId) {
        var longid = objId + DESIGNERITEM_SUBCOMPONENT_SEPARATOR + subCompId,
            canvas = this.diagramDesigner,
            connectionMetaInfo = null;

        this._autorouterPorts[objId] = this._autorouterPorts[objId] === undefined ? [] : this._autorouterPorts[objId];

        if( subCompId !== undefined /*&& this._autorouterBoxes[longid] === undefined */){
        //Add ports to our list of _autorouterBoxes and add the port to the respective box (if undefined, of course)
            var parentBox = this._autorouterBoxes[objId].box,
                portdefinition = [],
                res = canvas.items[objId].getConnectionAreas(subCompId, true, connectionMetaInfo) || [],
                j = res.length;

        while (j--) {
            portdefinition.push([ [ res[j].x1, res[j].y1 ], [ res[j].x2, res[j].y2 ] ]);
        }
            this._autorouterBoxes[longid] = { "ports": this.autorouter.addPort(parentBox, portdefinition) };
            this._autorouterPorts[objId].push(subCompId);
        }
     };

    return ConnectionRouteManager3;
});
<commit_msg>Small bug fixes relating to port addition/removal<commit_after>"use strict";

define(['logManager', './AutoRouter', './Profiler'], function (logManager, AutoRouter, Profiler) {

    var ConnectionRouteManager3,
        DESIGNERITEM_SUBCOMPONENT_SEPARATOR = "_x_";

    ConnectionRouteManager3 = function (options) {
        this.logger = (options && options.logger) || logManager.create(((options && options.loggerName) || "ConnectionRouteManager3"));

        this.diagramDesigner = options ? options.diagramDesigner : null;

        if (this.diagramDesigner === undefined || this.diagramDesigner === null) {
            this.logger.error("Trying to initialize a ConnectionRouteManager3 without a canvas...");
            throw ("ConnectionRouteManager3 can not be created");
        }

        this.autorouter = new AutoRouter();

        this.logger.debug("ConnectionRouteManager3 ctor finished");
    };

    ConnectionRouteManager3.prototype.initialize = function () {
        this._initialized = false;
        this._clearGraph();

        //Adding event listeners
        var self = this;

        this._onComponentUpdate = function(_canvas, ID) {//Boxes and lines
            if( self.diagramDesigner.itemIds.indexOf( ID ) !== -1 ){

             if( self.diagramDesigner.items[ID].rotation !== self._autorouterBoxRotation[ID] ) //Item has been rotated
                self._resizeItem( ID );

            }else if( self.diagramDesigner.connectionIds.indexOf( ID ) !== -1 ){ //Segment points have been modified
                self.autorouter.setPathCustomPoints({
                        "path": self._autorouterPaths[ ID ],
                        "points": self.diagramDesigner.items[ ID ].segmentPoints
                        });
            }
       };
        this.diagramDesigner.addEventListener(this.diagramDesigner.events.ON_COMPONENT_UPDATE, this._onComponentUpdate);

        this._onComponentCreate = function(_canvas, ID) {//Boxes and lines
            if( self.diagramDesigner.itemIds.indexOf( ID ) !== -1 ){

                if( self._autorouterBoxes[ID] === undefined )
                    self.insertBox( ID );

            }else if( self.diagramDesigner.connectionIds.indexOf( ID ) !== -1 )
                self.insertConnection( ID );
        };
        this.diagramDesigner.addEventListener(this.diagramDesigner.events.ON_COMPONENT_CREATE, this._onComponentCreate);

        this._onComponentResize = function(_canvas, ID) {
            if( self._autorouterBoxes[ID.ID] )
                self._resizeItem( ID.ID );
            else
                self.insertBox( ID.ID );
        };
        this.diagramDesigner.addEventListener(this.diagramDesigner.events.ITEM_SIZE_CHANGED, this._onComponentResize);

        this._onComponentDelete = function(_canvas, ID) {//Boxes and lines
            self.deleteItem( ID );
        };
        this.diagramDesigner.addEventListener(this.diagramDesigner.events.ON_COMPONENT_DELETE, this._onComponentDelete);
        //ON_UNREGISTER_SUBCOMPONENT

        this._onItemPositionChanged = function(_canvas, eventArgs) {
            if( self._autorouterBoxes[eventArgs.ID] ){
                var x = self.diagramDesigner.items[eventArgs.ID].getBoundingBox().x,
                    y = self.diagramDesigner.items[eventArgs.ID].getBoundingBox().y;

                self.autorouter.move(self._autorouterBoxes[eventArgs.ID].box, { "x": x, "y": y });
            }
        };
        this.diagramDesigner.addEventListener(this.diagramDesigner.events.ITEM_POSITION_CHANGED, this._onItemPositionChanged);

        this._onClear = function(_canvas, eventArgs) {
            self._clearGraph();
        };
        this.diagramDesigner.addEventListener(this.diagramDesigner.events.ON_CLEAR, this._onClear);

    };

    ConnectionRouteManager3.prototype.destroy = function () {
        //removeEventListener(eventName, handler);
        this.diagramDesigner.removeEventListener(this.diagramDesigner.events.ON_COMPONENT_CREATE, this._onComponentCreate);
        this.diagramDesigner.removeEventListener(this.diagramDesigner.events.ON_COMPONENT_UPDATE, this._onComponentUpdate);
        this.diagramDesigner.removeEventListener(this.diagramDesigner.events.ITEM_SIZE_CHANGED, this._onComponentResize);
        this.diagramDesigner.removeEventListener(this.diagramDesigner.events.ON_COMPONENT_DELETE, this._onComponentDelete);
        this.diagramDesigner.removeEventListener(this.diagramDesigner.events.ITEM_POSITION_CHANGED, this._onItemPositionChanged);
        this.diagramDesigner.removeEventListener(this.diagramDesigner.events.ON_CLEAR, this._onClear);
    };

    ConnectionRouteManager3.prototype.redrawConnections = function (idList) {

        if( !this._initialized ){
            this._initializeGraph();
        }else{
            this._refreshConnData(idList);
        }

        this._updateConnectionPorts( idList );

        //no matter what, we want the id's of all the connections
        //not just the ones that explicitly needs rerouting
        idList = this.diagramDesigner.connectionIds.slice(0);

        var i = idList.length;

        //1 - autoroute
        this.autorouter.autoroute();

        //2 - Get the path points and redraw
        var pathPoints,
            realPathPoints;
        for (i = 0; i < idList.length; i += 1) {
            if( this._autorouterPaths[idList[i]] ){
                pathPoints = this.autorouter.getPathPoints(this._autorouterPaths[idList[i]]);
            }else{
                pathPoints = [];
            }

            realPathPoints = [];
            for(var j = 0; j < pathPoints.length; j++){
                realPathPoints.push({'x': pathPoints[j][0], 'y': pathPoints[j][1] });
            }

            this.diagramDesigner.items[idList[i]].setConnectionRenderData(realPathPoints);
        }

        //need to return the IDs of the connections that was really
        //redrawn or any other visual property changed (width, etc)

        return idList;
    };

    ConnectionRouteManager3.prototype._refreshConnData = function (idList) {
        //Clear connection data and paths then re-add them
        var i = idList.length;

        while(i--){
            this.deleteItem(idList[i]);
            //this.autorouter.remove(this._autorouterPaths[idList[i]]);
            //this._autorouterPaths[idList[i]] = undefined;
            this.insertConnection([idList[i]]);
        }

    };

    ConnectionRouteManager3.prototype._clearGraph = function () {
        this.autorouter.clear();
        this._autorouterBoxes = {};//Define container that will map obj+subID -> box
        this._autorouterPorts = {};//Maps boxIds to an array of port ids that have been mapped
        this._autorouterPaths = {};
        this._autorouterBoxRotation = {};//Define container that will map obj+subID -> rotation
        this.endpointConnectionAreaInfo = {};
    };

    ConnectionRouteManager3.prototype._initializeGraph = function () {
        /*
         * In this method, we will update the boxes using the canvas.itemIds list and
         * add any ports as needed (from the canvas.connectionIds)
         */
        var canvas = this.diagramDesigner,
            connIdList = canvas.connectionIds,
            itemIdList = canvas.itemIds,
            i = itemIdList.length,
            connId,
            srcObjId,
            srcSubCompId,
            dstObjId,
            dstSubCompId;

        while(i--){
            this.insertBox(itemIdList[i]);
        }

        i = connIdList.length;
        while( i-- ){
            this.insertConnection(connIdList[i]);
            if( canvas.items[connIdList[i]].segmentPoints.length > 0 )
                this.autorouter.setPathCustomPoints({
                        "path": this._autorouterPaths[ connIdList[i] ],
                        "points": canvas.items[ connIdList[i] ].segmentPoints
                        });
        }

        //Next, I will update the ports as necessary
        this._updateConnectionPorts(connIdList);

        this._initialized = true;

    };

    ConnectionRouteManager3.prototype.insertConnection = function (connId) {
        var canvas = this.diagramDesigner,
            srcObjId = canvas.connectionEndIDs[connId].srcObjId,
            srcSubCompId = canvas.connectionEndIDs[connId].srcSubCompId,
            dstObjId = canvas.connectionEndIDs[connId].dstObjId,
            dstSubCompId = canvas.connectionEndIDs[connId].dstSubCompId,
            sId = srcSubCompId ? srcObjId + DESIGNERITEM_SUBCOMPONENT_SEPARATOR + srcSubCompId : srcObjId,
            tId = dstSubCompId ? dstObjId + DESIGNERITEM_SUBCOMPONENT_SEPARATOR + dstSubCompId : dstObjId;

        this._updatePort(srcObjId, srcSubCompId);//Adding ports for connection
        this._updatePort(dstObjId, dstSubCompId);
        //If it has both a src and dst
        if( this._autorouterBoxes[sId].ports.length !== 0 && this._autorouterBoxes[tId].ports.length !== 0 ){
            this._autorouterPaths[connId] = this.autorouter.addPath({ "src": this._autorouterBoxes[sId],
                                                                               "dst": this._autorouterBoxes[tId] });
        }

     };

    ConnectionRouteManager3.prototype.insertBox = function (objId) {
        var canvas = this.diagramDesigner,
            designerItem,
            areas,
            bBox,
            boxdefinition,
            connectionMetaInfo,
            isEnd,
            j;

        designerItem = canvas.items[objId];
        bBox = designerItem.getBoundingBox();
        areas = designerItem.getConnectionAreas(objId, isEnd, connectionMetaInfo) || [];

        boxdefinition = {
            //BOX
            "x1": bBox.x,
            "y1": bBox.y,
            "x2": bBox.x2,
            "y2": bBox.y2,

            //PORTS
            "ConnectionAreas": []
        };

        j = areas.length;
        while (j--) {
            //Building up the ConnectionAreas object
            boxdefinition.ConnectionAreas.push([ [ areas[j].x1, areas[j].y1 ], [ areas[j].x2, areas[j].y2 ] ]);
        }

        this._autorouterBoxes[objId] = this.autorouter.addBox(boxdefinition);
        this._autorouterBoxRotation[objId] = canvas.items[objId].rotation;
    };

    ConnectionRouteManager3.prototype.deleteItem = function (objId) {
        //If I can query them from the objId, I can clear the entries with that info
        var item = this.diagramDesigner.items[objId],
            connIds = this.diagramDesigner.connectionIds,
            itemIds = this.diagramDesigner.itemIds;
        if(itemIds.indexOf(objId) !== -1){
            item = this._autorouterBoxes[objId];

            var i = this._autorouterPorts[objId] ? this._autorouterPorts[objId].length : 0;
            while( i-- ){
                var id = objId + DESIGNERITEM_SUBCOMPONENT_SEPARATOR + this._autorouterPorts[objId][i]; //ID of child port
                this._autorouterBoxes[id] = undefined;
            }

            this._autorouterBoxes[objId] = undefined;
        }else if(connIds.indexOf(objId) !== -1){
            item = this._autorouterPaths[objId];//If objId is a connection

        }
            this.autorouter.remove(item);

    };

    ConnectionRouteManager3.prototype._resizeItem = function (objId) {
        var canvas = this.diagramDesigner,
            isEnd = true,
            connectionMetaInfo,
            designerItem = canvas.items[objId],
            newCoord = designerItem.getBoundingBox(),
            newBox = { 'x1': newCoord.x,
                       'x2': newCoord.x2,
                       'y1': newCoord.y,
                       'y2': newCoord.y2,
          'ConnectionAreas': [] },
            connAreas = designerItem.getConnectionAreas(objId, isEnd, connectionMetaInfo),
            portIds = this._autorouterPorts[objId],
            i;

        //Create the new box connection areas
        i = connAreas.length;
        while (i--) {
            //Building up the ConnectionAreas obiect
            newBox.ConnectionAreas.push([ [ connAreas[i].x1, connAreas[i].y1 ], [ connAreas[i].x2, connAreas[i].y2 ] ]);
        }

        //Update Box
        this.autorouter.setBox(this._autorouterBoxes[objId], newBox);

        //Resize Ports Based on Connections
        i = portIds !== undefined ? portIds.length : 0;
        while( i-- ){
            this._updatePort( objId, portIds[i] );
        }

    };

    ConnectionRouteManager3.prototype._updateConnectionPorts = function (idList) {
        var canvas = this.diagramDesigner,
            connId,
            srcObjId,
            srcSubCompId,
            dstObjId,
            dstSubCompId,
            i = idList.length;

        while(i--){
            connId = idList[i];
            srcObjId = canvas.connectionEndIDs[connId].srcObjId;
            srcSubCompId = canvas.connectionEndIDs[connId].srcSubCompId;
            dstObjId = canvas.connectionEndIDs[connId].dstObjId;
            dstSubCompId = canvas.connectionEndIDs[connId].dstSubCompId;

            this._updatePort(srcObjId, srcSubCompId);
            this._updatePort(dstObjId, dstSubCompId);
        }
    };

    ConnectionRouteManager3.prototype._updatePort = function (objId, subCompId) {
        var longid = objId + DESIGNERITEM_SUBCOMPONENT_SEPARATOR + subCompId,
            canvas = this.diagramDesigner,
            connectionMetaInfo = null;

        this._autorouterPorts[objId] = this._autorouterPorts[objId] === undefined ? [] : this._autorouterPorts[objId];

        if( subCompId !== undefined /*&& this._autorouterBoxes[longid] === undefined */){
        //Add ports to our list of _autorouterBoxes and add the port to the respective box (if undefined, of course)
            var parentBox = this._autorouterBoxes[objId].box,
                portdefinition = [],
                res = canvas.items[objId].getConnectionAreas(subCompId, true, connectionMetaInfo) || [],
                j = res.length;

        while (j--) {
            portdefinition.push([ [ res[j].x1, res[j].y1 ], [ res[j].x2, res[j].y2 ] ]);
        }
            this._autorouterBoxes[longid] = { "ports": this.autorouter.addPort(parentBox, portdefinition) };

            if(this._autorouterPorts[objId].indexOf(subCompId) === -1)
                this._autorouterPorts[objId].push(subCompId);
        }
     };

    return ConnectionRouteManager3;
});
<|endoftext|>


<commit_before>'use strict';

app.filter('componentFilter', function()  {
  var allChecked = function(collection) {
    var none = _.every(collection, function(item) {
      return (item.checked === false);
    });
    var all = _.every(collection, function(item) {
      return (item.checked === true);
    });
    return (none || all);
  };

  return function (input, filters) {
    var out = null;
    out = _.filter(input, function(item) {  // if value passes with true it remains
      return _.every(filters, function(filter) {  //we return true if it passes all of these filters
        var collection = filter.collection;
        var key = filter.key;
        // if the filter isn't being used, or all are checked, we know its true
        if (!allChecked(collection)) {
          // otherwise we return true if it passes some portion of the filter
          return _.some(collection, function(checkedFilter) {
            if (checkedFilter.checked === true) {
              var check = _.pluck(item[key], 'code');
              // if the filter is checked, we need to check the item
              return _.contains(check, checkedFilter.code);
            } else {
              // if it isn't checked we default to false
              return false;
            }
          });
        } else {
          return true;
        }
      });
    });
    return out;
  };
});
<commit_msg>Added comments to the filter for future use.<commit_after>'use strict';

/*******************************************************************************
* This filter requires that you pass in the filters ;) it is an array of objects
* in this format:
*[
*  {
*    "name": "Types",
*    "key": "type",   // The key for the attribute in the object you're looking for
*    "collection": [
*      {
*        "code": "APPS",  // the value of the attribute in the object you wish to find
*        "type": "Application", // periferal information
*        "desc": "Applications are ...",
*        "src": "images/icon/pastel/locationOfFilterImage.png",
*        "checked": true // whether or not this portion of the filter defaults to checked (implemented) or not
*      },
*      {
*        "code": "WIDGET",
*        "type": "Widget",
*        "desc": "Filter description",
*        "src": "images/icon/pastel/locationOfFilterImage.png",
*        "checked": false
*      }
*      ...
*    ]
*  },
*  {
*    "name": "Categories",
*    "key": "categories",
*    "collection": [
*      {
*        "code": "MDATA",
*        "type": "Data Management",
*        "desc": "Data management is......",
*        "src": "images/icon/pastel/locationOfFilterImage.png",
*        "checked": false
*      },
*      ...
*    ]
*  }
*]
*******************************************************************************/
/*******************************************************************************
* The object you're looking for must be in a format similar to this:
*{
*  "id": 34,
*  "guid": "6482B5F8-CB71-E00D-8FA4-16529549EC22",
*  "type": [
*  {
*    "code": "APPS"
*  },
*  {
*    "code": "TOOLS"
*  }
*  ]
*  "categories": [
*  {
*    "code": "MDATA"
*  },
*  {
*    "code": "COLLECTION"
*  }
*  ]
*}
*******************************************************************************/
app.filter('componentFilter', function()  {
  var allChecked = function(collection) {
    var none = _.every(collection, function(item) {
      return (item.checked === false);
    });
    var all = _.every(collection, function(item) {
      return (item.checked === true);
    });
    return (none || all);
  };

  return function (input, filters) {
    var out = null;
    out = _.filter(input, function(item) {  // if value passes with true it remains
      return _.every(filters, function(filter) {  //we return true if it passes all of these filters
        var collection = filter.collection;
        var key = filter.key;
        // if the filter isn't being used, or all are checked, we know its true
        if (!allChecked(collection)) {
          // otherwise we return true if it passes some portion of the filter
          return _.some(collection, function(checkedFilter) {
            if (checkedFilter.checked === true) {
              var check = _.pluck(item[key], 'code');
              // if the filter is checked, we need to check the item
              return _.contains(check, checkedFilter.code);
            } else {
              // if it isn't checked we default to false
              return false;
            }
          });
        } else {
          return true;
        }
      });
    });
    return out;
  };
});
<|endoftext|>


<commit_before>var dealReplyLink = function(name, reply_to_id){
    document.getElementById('reply_to_id').value = reply_to_id;
    document.getElementById('reply_to_user').value = "" + name;
    //var node=document.createTextNode("reply to " + name);
    var linkNode = document.createElement('a')
    linkNode.setAttribute('id', 'cancel_link')
    linkNode.addEventListener('click', function(event){
        var p = document.getElementById('reply_info')
        document.getElementById('reply_to_id').value = "";
        document.getElementById('reply_to_user').value = "";
        // p.removeChild(document.getElegnmentById('cancel_link'));
        p.innerHTML = "";
    });
    var link_txt = document.createTextNode('取消回复该用户')
    linkNode.appendChild(link_txt)
    //document.getElementById('reply_info').appendChild(node)
    document.getElementById('reply_info').innerHTML = "reply to " + name
    document.getElementById('reply_info').appendChild(linkNode)
}

var markdownPreview = function(){
    document.getElementById('preview').innerHTML =
      marked(document.getElementById('context').value);
}

function setCookie(url, hasViewed, expiretime)
{
var exdate=new Date()
exdate.setTime(exdate.getTime()+expiretime)
//console.log(exdate.toGMTString());
document.cookie=url+ "=" +escape(hasViewed)+
((expiretime==null) ? "" : ";expires="+exdate.toGMTString())
}

function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=")
  if (c_start!=-1)
    {
    c_start=c_start + c_name.length+1
    c_end=document.cookie.indexOf(";",c_start)
    if (c_end==-1) c_end=document.cookie.length
    return unescape(document.cookie.substring(c_start,c_end))
    }
  }
return ""
}

function checkCookie(url){
    hasViewed = getCookie(url)
    console.log(hasViewed)
    return hasViewed
}

function addLoadEvent(func){
    var oldonload = window.onload;
    if(typeof window.onload != 'function'){
	window.onload=func;
    }
    else {
	window.onload = function(){
		oldonload();
		func();
	}
	}
}

function addViewed(){
    url = window.location.href;
    get_url = url + "/addview"
    var xmlHttp = null;
	try{
	xmlHttp = new XMLHttpRequest();
	}catch(e){
	try{
	   xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
	}catch(e){
	xmlHttp = new ActiveXObject("Microsoft.XMLHttp");	}
	}
    if (!checkCookie(url)) {

	xmlHttp.open("GET", get_url, true)
	xmlHttp.send()
	console.log(xmlHttp.responseText)
	setCookie(url, true, 3600*100)
	}
    }

addLoadEvent(addViewed)

<commit_msg>change cookies expire duration to 1 hour<commit_after>var dealReplyLink = function(name, reply_to_id){
    document.getElementById('reply_to_id').value = reply_to_id;
    document.getElementById('reply_to_user').value = "" + name;
    //var node=document.createTextNode("reply to " + name);
    var linkNode = document.createElement('a')
    linkNode.setAttribute('id', 'cancel_link')
    linkNode.addEventListener('click', function(event){
        var p = document.getElementById('reply_info')
        document.getElementById('reply_to_id').value = "";
        document.getElementById('reply_to_user').value = "";
        // p.removeChild(document.getElegnmentById('cancel_link'));
        p.innerHTML = "";
    });
    var link_txt = document.createTextNode('取消回复该用户')
    linkNode.appendChild(link_txt)
    //document.getElementById('reply_info').appendChild(node)
    document.getElementById('reply_info').innerHTML = "reply to " + name
    document.getElementById('reply_info').appendChild(linkNode)
}

var markdownPreview = function(){
    document.getElementById('preview').innerHTML =
      marked(document.getElementById('context').value);
}

function setCookie(url, hasViewed, expiretime)
{
var exdate=new Date()
exdate.setTime(exdate.getTime()+expiretime*1000)
//console.log(exdate.toGMTString());
document.cookie=url+ "=" +escape(hasViewed)+
((expiretime==null) ? "" : ";expires="+exdate.toGMTString())
}

function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=")
  if (c_start!=-1)
    {
    c_start=c_start + c_name.length+1
    c_end=document.cookie.indexOf(";",c_start)
    if (c_end==-1) c_end=document.cookie.length
    return unescape(document.cookie.substring(c_start,c_end))
    }
  }
return ""
}

function checkCookie(url){
    hasViewed = getCookie(url)
    console.log(hasViewed)
    return hasViewed
}

function addLoadEvent(func){
    var oldonload = window.onload;
    if(typeof window.onload != 'function'){
	window.onload=func;
    }
    else {
	window.onload = function(){
		oldonload();
		func();
	}
	}
}

function addViewed(){
    url = window.location.href;
    get_url = url + "/addview"
    var xmlHttp = null;
	try{
	xmlHttp = new XMLHttpRequest();
	}catch(e){
	try{
	   xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
	}catch(e){
	xmlHttp = new ActiveXObject("Microsoft.XMLHttp");	}
	}
    if (!checkCookie(url)) {

	xmlHttp.open("GET", get_url, true)
	xmlHttp.send()
	console.log(xmlHttp.responseText)
	setCookie(url, true, 3600)
	}
    }

addLoadEvent(addViewed)

<|endoftext|>


<commit_before>var should = require('should');
var ViewDb = require('../..');
var ViewDbTimestampPlugin = require('../..').plugins.TimestampPlugin;
var ViewDBVersioningPlugin = require('../..').plugins.VersioningPlugin;

describe('Viewdb timestamp plugin', function () {
  it('should add changeDateTime and createDateTime timestamp on insert', function (done) {
    var viewDb = new ViewDb();
    new ViewDbTimestampPlugin(viewDb);
    new ViewDBVersioningPlugin(viewDb);
    var obj = { id: '123' };
    var collection = viewDb.collection('test');
    var currentTime = (new Date().valueOf());

    // wait 1ms until update operation to check for lastModified updated
    setTimeout(function () {
      collection.insert(obj);
      collection.find({ id: '123' }).toArray(function (err, objects) {
        var object = objects[0];
        should.exists(object.createDateTime);
        if (currentTime < object.createDateTime) {
          done();
        } else {
          done(new Error('Timestamp was not renewed'))
        }
      });
    }, 1);
  });

  it('should update changeDateTime on save', function (done) {
    var viewDb = new ViewDb();
    new ViewDbTimestampPlugin(viewDb);
    new ViewDBVersioningPlugin(viewDb);
    var obj = { id: '123' };
    var insertTime;
    var collection = viewDb.collection('test');

    collection.insert(obj);
    collection.find({ id: '123' }).toArray(function (err, objects) {
      var object = objects[0];
      insertTime = object.createDateTime;
    });

    // wait 1ms until update operation to check for changeDateTime updated
    setTimeout(function () {
      obj.name = 'Pelle';
      collection.save(obj);
      collection.find({ id: '123' }).toArray(function (err, objects) {
        var object = objects[0];
        object.createDateTime.should.equal(insertTime);
        object.changeDateTime.should.greaterThan(insertTime);
        console.log('object', object);
        done();
      });
    }, 1)
  });

  it('should work together with version plugin', function (done) {
    var viewDb = new ViewDb();
    new ViewDbTimestampPlugin(viewDb);
    new ViewDBVersioningPlugin(viewDb);
    var obj = { id: '123' };
    var collection = viewDb.collection('test');
    collection.insert(obj);
    obj.name = 'Pelle';
    obj.version = undefined;
    collection.save(obj);
    collection.find({ id: '123' }).toArray(function (err, objects) {
      var object = objects[0];
      object.version.should.equal(0);
      object.name.should.equal('Pelle');
      should.exists(object.createDateTime);
      should.exists(object.changeDateTime);
      done();
    });
  });
});
<commit_msg>remove log in test<commit_after>var should = require('should');
var ViewDb = require('../..');
var ViewDbTimestampPlugin = require('../..').plugins.TimestampPlugin;
var ViewDBVersioningPlugin = require('../..').plugins.VersioningPlugin;

describe('Viewdb timestamp plugin', function () {
  it('should add changeDateTime and createDateTime timestamp on insert', function (done) {
    var viewDb = new ViewDb();
    new ViewDbTimestampPlugin(viewDb);
    new ViewDBVersioningPlugin(viewDb);
    var obj = { id: '123' };
    var collection = viewDb.collection('test');
    var currentTime = (new Date().valueOf());

    // wait 1ms until update operation to check for lastModified updated
    setTimeout(function () {
      collection.insert(obj);
      collection.find({ id: '123' }).toArray(function (err, objects) {
        var object = objects[0];
        should.exists(object.createDateTime);
        if (currentTime < object.createDateTime) {
          done();
        } else {
          done(new Error('Timestamp was not renewed'))
        }
      });
    }, 1);
  });

  it('should update changeDateTime on save', function (done) {
    var viewDb = new ViewDb();
    new ViewDbTimestampPlugin(viewDb);
    new ViewDBVersioningPlugin(viewDb);
    var obj = { id: '123' };
    var insertTime;
    var collection = viewDb.collection('test');

    collection.insert(obj);
    collection.find({ id: '123' }).toArray(function (err, objects) {
      var object = objects[0];
      insertTime = object.createDateTime;
    });

    // wait 1ms until update operation to check for changeDateTime updated
    setTimeout(function () {
      obj.name = 'Pelle';
      collection.save(obj);
      collection.find({ id: '123' }).toArray(function (err, objects) {
        var object = objects[0];
        object.createDateTime.should.equal(insertTime);
        object.changeDateTime.should.greaterThan(insertTime);
        done();
      });
    }, 1)
  });

  it('should work together with version plugin', function (done) {
    var viewDb = new ViewDb();
    new ViewDbTimestampPlugin(viewDb);
    new ViewDBVersioningPlugin(viewDb);
    var obj = { id: '123' };
    var collection = viewDb.collection('test');
    collection.insert(obj);
    obj.name = 'Pelle';
    obj.version = undefined;
    collection.save(obj);
    collection.find({ id: '123' }).toArray(function (err, objects) {
      var object = objects[0];
      object.version.should.equal(0);
      object.name.should.equal('Pelle');
      should.exists(object.createDateTime);
      should.exists(object.changeDateTime);
      done();
    });
  });
});
<|endoftext|>