<commit_before>// eslint-disable-next-line
import When from 'when';
import autobahn from 'autobahn';
import eventify from './eventify';

/**
 * @param {Connection} connection
 * @param {string} method
 * @param {array} [args]
 * @return {When.Promise}
 */
function deferredSession(connection, method, args = []) {
  const d = connection.defer();
  debounceClose(connection, -1);
  connection.getSession().then((session) => {
    try {
      session[method](...args)
          .then(d.resolve, d.reject, d.notify)
          .finally(() => {
            debounceClose(connection);
          });
    } catch (e) {
      debounceClose(connection);
      d.reject(e);
    }
  }, (...args) => {
    debounceClose(connection);
    d.reject(...args);
  });
  return d.promise;
}

/**
 * @param {Connection} connection
 * @param {int} timeout
 */
function debounceClose(connection, timeout = 0) {
  if (timeout < 0) {
    if (connection._wampCloseTimeout) {
      clearTimeout(connection._wampCloseTimeout);
    }
    return;
  }
  if (timeout === 0) {
    timeout = connection._options.auto_close_timeout;
  }
  if (connection._wampCloseTimeout) {
    clearTimeout(connection._wampCloseTimeout);
  }
  if (timeout > 0) {
    connection._wampCloseTimeout = setTimeout(() => {
      connection.close();
    }, timeout);
  }
}

/**
 * Exposes session methods on autobahn connection
 */
class Connection extends autobahn.Connection {
  /**
   * @param {object} options
   */
  constructor(options) {
    super(options);
    eventify(this);

    this._wampSessionDefer = this.defer();
    this._wampCloseTimeout = null;

    let _lastStatus = {
      isConnected: false,
      isOpen: false,
      isRetrying: false,
    };

    const _statusUpdate = (details) => {
      const status = {
        isConnected: this.isConnected,
        isOpen: this.isOpen,
        isRetrying: this.isRetrying,
      };
      const e = {status, lastStatus: _lastStatus, details};
      this.emit('status', e);
      if (status.isOpen && !_lastStatus.isOpen) {
        this.emit('opened', e);
        if (!status.isRetrying && _lastStatus.isRetrying) {
          this.emit('reconnected', e);
        }
      } else if (!status.isOpen && _lastStatus.isOpen) {
        this.emit('closed', e);
      }
      if (status.isRetrying && !_lastStatus.isRetrying) {
        this.emit('retrying', e);
      }
      _lastStatus = status;
    };

    this.onopen = function(session, details) {
      if (this._wampSessionDefer) {
        this._wampSessionDefer.resolve(session);
      }
      this.emit('open', session, details);
      _statusUpdate(details);
    };

    this.onclose = function(reason, details) {
      if (this._wampSessionDefer) {
        this._wampSessionDefer.reject(reason || 'closed', details);
      }
      this._session = null;
      this._wampSessionDefer = this.defer();
      this.emit('close', reason, details);
      _statusUpdate(details);
    };

    _statusUpdate(null);
  }

  /**
   * Safe open
   */
  open() {
    if (!this._transport) {
      super.open();
    }
  }

  /**
   * Safe close
   * @param {string} [reason]
   * @param {string} [message]
   */
  close(reason, message) {
    if (this._transport || this._is_retrying) {
      super.close(reason || 'closed', message || '');
    }
  }

  /**
   * @return {When.Promise}
   */
  getSession() {
    if (!this._session) {
      setTimeout(() => this.open());
      return this._wampSessionDefer.promise;
    }
    if(!this._session.isOpen) {
      return this._wampSessionDefer.promise;
    }
    return When.Promise.resolve(this._session);
  }

  /**
   * @param {string} shortcut
   * @param {string} prefix
   * @return {When.Promise}
   */
  prefix(shortcut, prefix) {
    return deferredSession(this, 'prefix', [shortcut, prefix]);
  }

  /**
   * @param {string} procedure
   * @param {array} [args]
   * @param {object} [kwArgs]
   * @param {object} [options]
   * @return {When.Promise}
   */
  call(procedure, args = [], kwArgs = {}, options = {}) {
    return deferredSession(this, 'call', [procedure, args, kwArgs, options]);
  }

  /**
   * @param {string} procedure
   * @param {callback} endpoint
   * @param {object} [options]
   * @return {When.Promise}
   */
  register(procedure, endpoint, options = {}) {
    return deferredSession(this, 'register', [procedure, endpoint, options]);
  }

  /**
   * @param {autobahn.Registration} registration
   * @return {When.Promise}
   */
  unregister(registration) {
    return deferredSession(this, 'unregister', [registration]);
  }

  /**
   * @param {string} topic
   * @param {array} [args]
   * @param {object} [kwArgs]
   * @param {object} [options]
   * @return {When.Promise}
   */
  publish(topic, args = [], kwArgs = {}, options = {}) {
    options = {
      ...options,
      acknowledge: true,
    };
    return deferredSession(this, 'publish', [topic, args, kwArgs, options]);
  }

  /**
   * @param {string} topic
   * @param {callback} handler
   * @param {object} [options]
   * @return {When.Promise}
   */
  subscribe(topic, handler, options = {}) {
    return deferredSession(this, 'subscribe', [topic, handler, options]);
  }

  /**
   * @param {autobahn.Subscription} subscription
   * @return {When.Promise}
   */
  unsubscribe(subscription) {
    return deferredSession(this, 'unsubscribe', [subscription]);
  }
}

export default Connection;
<commit_msg>fix session access when already set but not yet open<commit_after>// eslint-disable-next-line
import When from 'when';
import autobahn from 'autobahn';
import eventify from './eventify';

/**
 * @param {Connection} connection
 * @param {string} method
 * @param {array} [args]
 * @return {When.Promise}
 */
function deferredSession(connection, method, args = []) {
  const d = connection.defer();
  debounceClose(connection, -1);
  connection.getSession().then((session) => {
    try {
      session[method](...args)
          .then(d.resolve, d.reject, d.notify)
          .finally(() => {
            debounceClose(connection);
          });
    } catch (e) {
      debounceClose(connection);
      d.reject(e);
    }
  }, (...args) => {
    debounceClose(connection);
    d.reject(...args);
  });
  return d.promise;
}

/**
 * @param {Connection} connection
 * @param {int} timeout
 */
function debounceClose(connection, timeout = 0) {
  if (timeout < 0) {
    if (connection._wampCloseTimeout) {
      clearTimeout(connection._wampCloseTimeout);
    }
    return;
  }
  if (timeout === 0) {
    timeout = connection._options.auto_close_timeout;
  }
  if (connection._wampCloseTimeout) {
    clearTimeout(connection._wampCloseTimeout);
  }
  if (timeout > 0) {
    connection._wampCloseTimeout = setTimeout(() => {
      connection.close();
    }, timeout);
  }
}

/**
 * Exposes session methods on autobahn connection
 */
class Connection extends autobahn.Connection {
  /**
   * @param {object} options
   */
  constructor(options) {
    super(options);
    eventify(this);

    this._wampSessionDefer = this.defer();
    this._wampCloseTimeout = null;

    let _lastStatus = {
      isConnected: false,
      isOpen: false,
      isRetrying: false,
    };

    const _statusUpdate = (details) => {
      const status = {
        isConnected: this.isConnected,
        isOpen: this.isOpen,
        isRetrying: this.isRetrying,
      };
      const e = {status, lastStatus: _lastStatus, details};
      this.emit('status', e);
      if (status.isOpen && !_lastStatus.isOpen) {
        this.emit('opened', e);
        if (!status.isRetrying && _lastStatus.isRetrying) {
          this.emit('reconnected', e);
        }
      } else if (!status.isOpen && _lastStatus.isOpen) {
        this.emit('closed', e);
      }
      if (status.isRetrying && !_lastStatus.isRetrying) {
        this.emit('retrying', e);
      }
      _lastStatus = status;
    };

    this.onopen = function(session, details) {
      if (this._wampSessionDefer) {
        this._wampSessionDefer.resolve(session);
      }
      this.emit('open', session, details);
      _statusUpdate(details);
    };

    this.onclose = function(reason, details) {
      if (this._wampSessionDefer) {
        this._wampSessionDefer.reject(reason || 'closed', details);
      }
      this._session = null;
      this._wampSessionDefer = this.defer();
      this.emit('close', reason, details);
      _statusUpdate(details);
    };

    _statusUpdate(null);
  }

  /**
   * Safe open
   */
  open() {
    if (!this._transport) {
      super.open();
    }
  }

  /**
   * Safe close
   * @param {string} [reason]
   * @param {string} [message]
   */
  close(reason, message) {
    if (this._transport || this._is_retrying) {
      super.close(reason || 'closed', message || '');
    }
  }

  /**
   * @return {When.Promise}
   */
  getSession() {
    if (!this._session) {
      setTimeout(() => this.open());
      return this._wampSessionDefer.promise;
    }
    if (!this._session.isOpen) {
      return this._wampSessionDefer.promise;
    }
    return When.Promise.resolve(this._session);
  }

  /**
   * @param {string} shortcut
   * @param {string} prefix
   * @return {When.Promise}
   */
  prefix(shortcut, prefix) {
    return deferredSession(this, 'prefix', [shortcut, prefix]);
  }

  /**
   * @param {string} procedure
   * @param {array} [args]
   * @param {object} [kwArgs]
   * @param {object} [options]
   * @return {When.Promise}
   */
  call(procedure, args = [], kwArgs = {}, options = {}) {
    return deferredSession(this, 'call', [procedure, args, kwArgs, options]);
  }

  /**
   * @param {string} procedure
   * @param {callback} endpoint
   * @param {object} [options]
   * @return {When.Promise}
   */
  register(procedure, endpoint, options = {}) {
    return deferredSession(this, 'register', [procedure, endpoint, options]);
  }

  /**
   * @param {autobahn.Registration} registration
   * @return {When.Promise}
   */
  unregister(registration) {
    return deferredSession(this, 'unregister', [registration]);
  }

  /**
   * @param {string} topic
   * @param {array} [args]
   * @param {object} [kwArgs]
   * @param {object} [options]
   * @return {When.Promise}
   */
  publish(topic, args = [], kwArgs = {}, options = {}) {
    options = {
      ...options,
      acknowledge: true,
    };
    return deferredSession(this, 'publish', [topic, args, kwArgs, options]);
  }

  /**
   * @param {string} topic
   * @param {callback} handler
   * @param {object} [options]
   * @return {When.Promise}
   */
  subscribe(topic, handler, options = {}) {
    return deferredSession(this, 'subscribe', [topic, handler, options]);
  }

  /**
   * @param {autobahn.Subscription} subscription
   * @return {When.Promise}
   */
  unsubscribe(subscription) {
    return deferredSession(this, 'unsubscribe', [subscription]);
  }
}

export default Connection;
<|endoftext|>


<commit_before>define(function(require) {
    var _injectmethod = function(name, method) {
        var injectwrapper = function($sources, $targets, opts) {
            // no $targets -> called as a jquery method
            // XXX: is it good to have that here?
            if ($targets === undefined) $targets = this;
            $targets = method($sources, $targets);

            opts = opts || {};
            opts.method = name;
            opts.$sources = $sources;
            $targets.trigger('inject', opts);
            return $targets;
        };
        return injectwrapper;
    };

    var methods = {};
    // temporary mark sources for injection
    var MARKER = "tmp-inject-marker";

    methods.content =  _injectmethod("content", function($sources, $targets) {
        $targets.each(function() {
            $(this).html($sources.html());
        });
        return $targets;
    });

    methods.replace = _injectmethod("replace", function($sources, $targets) {
        // XXX: consider removal of special case
        // this needs tests!
        if ($targets.length === 1) {
            $targets.replaceWith($sources);
            return $sources;
        }
        $targets.each(function() {
            $(this).replaceWith($sources.clone().addClass(MARKER));
        });
        return $("." + MARKER).removeClass(MARKER);
    });

    methods.replacetagwithcontent = _injectmethod("replacetagwithcontent", function($sources, $targets) {
        $targets.each(function() {
            var $tmp = $sources.clone().children().addClass(MARKER);
            $(this).replaceWith($tmp);
        });
        return $("." + MARKER).removeClass(MARKER);
    });

    // XXX: name under discussion
    methods.pre = _injectmethod("pre", function($sources, $targets) {
        $targets.each(function() {
            $(this).before($sources.clone().addClass(MARKER));
        });
        return $("." + MARKER).removeClass(MARKER);
    });

    // XXX: name under discussion
    methods.post = _injectmethod("post", function($sources, $targets) {
        $targets.each(function() {
            $(this).after($sources.clone().addClass(MARKER));
        });
        return $("." + MARKER).removeClass(MARKER);
    });

    // XXX: name under discussion
    methods.append = _injectmethod("append", function($sources, $targets) {
        $targets.each(function() {
            $(this).append($sources.clone().addClass(MARKER));
        });
        return $("." + MARKER).removeClass(MARKER);
    });

    methods.prepend = _injectmethod("prepend", function($sources, $targets) {
        $targets.each(function() {
            $(this).append($sources.clone().addClass(MARKER));
        });
        return $("." + MARKER).removeClass(MARKER);
    });

    return methods;
});

// jshint indent: 4, browser: true, jquery: true, quotmark: double
// vim: sw=4 expandtab
<commit_msg>readded lost comment from jshint until sure what to do about it<commit_after>// XXX: not sure whether this abstraction makes sense or whether it
// should be moved into the inject2 pattern
define(function(require) {
    var _injectmethod = function(name, method) {
        var injectwrapper = function($sources, $targets, opts) {
            // no $targets -> called as a jquery method
            // XXX: is it good to have that here?
            if ($targets === undefined) $targets = this;
            $targets = method($sources, $targets);

            opts = opts || {};
            opts.method = name;
            opts.$sources = $sources;
            $targets.trigger('inject', opts);
            return $targets;
        };
        return injectwrapper;
    };

    var methods = {};
    // temporary mark sources for injection
    var MARKER = "tmp-inject-marker";

    methods.content =  _injectmethod("content", function($sources, $targets) {
        $targets.each(function() {
            $(this).html($sources.html());
        });
        return $targets;
    });

    methods.replace = _injectmethod("replace", function($sources, $targets) {
        // XXX: consider removal of special case
        // this needs tests!
        if ($targets.length === 1) {
            $targets.replaceWith($sources);
            return $sources;
        }
        $targets.each(function() {
            $(this).replaceWith($sources.clone().addClass(MARKER));
        });
        return $("." + MARKER).removeClass(MARKER);
    });

    methods.replacetagwithcontent = _injectmethod("replacetagwithcontent", function($sources, $targets) {
        $targets.each(function() {
            var $tmp = $sources.clone().children().addClass(MARKER);
            $(this).replaceWith($tmp);
        });
        return $("." + MARKER).removeClass(MARKER);
    });

    // XXX: name under discussion
    methods.pre = _injectmethod("pre", function($sources, $targets) {
        $targets.each(function() {
            $(this).before($sources.clone().addClass(MARKER));
        });
        return $("." + MARKER).removeClass(MARKER);
    });

    // XXX: name under discussion
    methods.post = _injectmethod("post", function($sources, $targets) {
        $targets.each(function() {
            $(this).after($sources.clone().addClass(MARKER));
        });
        return $("." + MARKER).removeClass(MARKER);
    });

    // XXX: name under discussion
    methods.append = _injectmethod("append", function($sources, $targets) {
        $targets.each(function() {
            $(this).append($sources.clone().addClass(MARKER));
        });
        return $("." + MARKER).removeClass(MARKER);
    });

    methods.prepend = _injectmethod("prepend", function($sources, $targets) {
        $targets.each(function() {
            $(this).append($sources.clone().addClass(MARKER));
        });
        return $("." + MARKER).removeClass(MARKER);
    });

    return methods;
});

// jshint indent: 4, browser: true, jquery: true, quotmark: double
// vim: sw=4 expandtab
<|endoftext|>


<commit_before>/** @lends TagsEditorView */
define(function(require) {
    'use strict';

    /**
     * Tags-select content editor. Please note that it requires column data format
     * corresponding to tags-cell.
     *
     * ### Column configuration samples:
     * ``` yml
     * datagrid:
     *   {grid-uid}:
     *     inline_editing:
     *       enable: true
     *     # <grid configuration> goes here
     *     columns:
     *       # Sample 1. Full configuration
     *       {column-name-1}:
     *         inline_editing:
     *           editor:
     *             view: orodatagrid/js/app/views/editor/tags-editor-view
     *             view_options:
     *               placeholder: '<placeholder>'
     *               css_class_name: '<class-name>'
     *               maximumSelectionLength: 3
     *           validation_rules:
     *             NotBlank: true
     * ```
     *
     * ### Options in yml:
     *
     * Column option name                                  | Description
     * :---------------------------------------------------|:-----------
     * inline_editing.editor.view_options.placeholder      | Optional. Placeholder translation key for an empty element
     * inline_editing.editor.view_options.placeholder_raw  | Optional. Raw placeholder value
     * inline_editing.editor.view_options.css_class_name   | Optional. Additional css class name for editor view DOM el
     * inline_editing.editor.view_options.maximumSelectionLength | Optional. Maximum selection length
     * inline_editing.editor.validation_rules | Optional. Validation rules. See [documentation](https://goo.gl/j9dj4Y)
     *
     * ### Constructor parameters
     *
     * @class
     * @param {Object} options - Options container
     * @param {Object} options.model - Current row model
     * @param {string} options.fieldName - Field name to edit in model
     * @param {string} options.metadata - Editor metadata
     * @param {string} options.placeholder - Placeholder translation key for an empty element
     * @param {string} options.placeholder_raw - Raw placeholder value. It overrides placeholder translation key
     * @param {string} options.maximumSelectionLength - Maximum selection length
     * @param {Object} options.validationRules - Validation rules. See [documentation here](https://goo.gl/j9dj4Y)
     *
     * @augments [AbstractRelationEditorView](./abstract-relation-editor-view.md)
     * @exports TagsEditorView
     */
    var TagsEditorView;
    var AbstractRelationEditorView = require('oroform/js/app/views/editor/abstract-relation-editor-view');
    var _ = require('underscore');
    var $ = require('jquery');

    TagsEditorView = AbstractRelationEditorView.extend(/** @exports TagsEditorView.prototype */{
        className: 'tags-select-editor',
        DEFAULT_PER_PAGE: 20,
        initialize: function(options) {
            TagsEditorView.__super__.initialize.apply(this, arguments);
        },

        getInitialResultItem: function() {
            return this.getModelValue().map(function(item) {
                return {
                    id: item.id,
                    label: item.name
                };
            });
        },

        getSelect2Options: function() {
            var _this = this;
            _this.currentData = null;
            _this.firstPageData = {
                results: [],
                more: false,
                isDummy: true
            };
            return {
                placeholder: this.placeholder || ' ',
                allowClear: true,
                openOnEnter: false,
                selectOnBlur: false,
                multiple: true,
                id: 'label',
                formatSelection: function(item) {
                    return item.label;
                },
                formatResult: function(item) {
                    return item.label;
                },
                initSelection: function(element, callback) {
                    callback(_this.getInitialResultItem());
                },
                query: function(options) {
                    _this.currentTerm = options.term;
                    _this.currentPage = options.page;
                    _this.currentCallback = options.callback;
                    if (options.page === 1) {
                        // immediately show first item
                        _this.showResults();
                    }
                    options.callback = function(data) {
                        _this.currentData = data;
                        if (data.page === 1) {
                            _this.firstPageData = data;
                        }
                        _this.showResults();
                    };
                    if (_this.currentRequest && _this.currentRequest.term !== '' &&
                        _this.currentRequest.state() !== 'resolved') {
                        _this.currentRequest.abort();
                    }
                    var autoCompleteUrlParameters = _.extend(_this.model.toJSON(), {
                        term: options.term,
                        page: options.page,
                        per_page: _this.perPage
                    });
                    if (options.term !== '' &&
                        !_this.autocompleteApiAccessor.isCacheExistsFor(autoCompleteUrlParameters)) {
                        _this.debouncedMakeRequest(options, autoCompleteUrlParameters);
                    } else {
                        _this.makeRequest(options, autoCompleteUrlParameters);
                    }
                }
            };
        },

        showResults: function() {
            var data;
            if (this.currentPage === 1) {
                data = $.extend({}, this.firstPageData);
                data.results = this.filterTermFromResults(this.currentTerm, data.results);
                if (this.currentPage === 1) {
                    if (this.isValidTerm(this.currentTerm)) {
                        data.results.unshift({
                            id: this.currentTerm,
                            label: this.currentTerm
                        });
                    } else {
                        if (this.firstPageData.isDummy) {
                            // do not update list until choices will be loaded
                            return;
                        }
                    }
                }
                data.results.sort(_.bind(this.tagSortCallback, this));
            } else {
                data = $.extend({}, this.currentData);
                data.results = this.filterTermFromResults(this.currentTerm, data.results);
            }
            this.currentCallback(data);
        },

        filterTermFromResults: function(term, results) {
            results = _.clone(results);
            for (var i = 0; i < results.length; i++) {
                var result = results[i];
                if (result.label === term) {
                    results.splice(i, 1);
                    break;
                }
            }
            return results;
        },

        tagSortCallback: function(a, b) {
            return this.getTermSimilarity(a.label) - this.getTermSimilarity(b.label);
        },

        getTermSimilarity: function(term) {
            var lowerCaseTerm = term.toLowerCase();
            var index = lowerCaseTerm.indexOf(this.currentTerm.toLowerCase());
            if (index === -1) {
                return 1000;
            }
            return index;
        },

        isValidTerm: function(term) {
            return _.isString(term) && term.length > 0;
        },

        getModelValue: function() {
            return this.model.get(this.fieldName) || [];
        },

        getFormattedValue: function() {
            return this.getModelValue().map(function(item) {
                return item.id;
            }).join(',');
        },

        getServerUpdateData: function() {
            var data = {};
            var select2Data = this.$('.select2-container').select2('data');
            data[this.fieldName] = select2Data.map(function(item) {
                return {
                    name: item.label
                };
            });
            return data;
        },

        getModelUpdateData: function() {
            var data = {};
            var select2Data = this.$('.select2-container').select2('data');
            data[this.fieldName] = select2Data.map(function(item) {
                return {
                    id: item.id,
                    name: item.label
                };
            });
            return data;
        }
    }, {
        processMetadata: AbstractRelationEditorView.processMetadata
    });

    return TagsEditorView;
});
<commit_msg>CRM-4660 fix isChanged function for tags<commit_after>/** @lends TagsEditorView */
define(function(require) {
    'use strict';

    /**
     * Tags-select content editor. Please note that it requires column data format
     * corresponding to tags-cell.
     *
     * ### Column configuration samples:
     * ``` yml
     * datagrid:
     *   {grid-uid}:
     *     inline_editing:
     *       enable: true
     *     # <grid configuration> goes here
     *     columns:
     *       # Sample 1. Full configuration
     *       {column-name-1}:
     *         inline_editing:
     *           editor:
     *             view: orodatagrid/js/app/views/editor/tags-editor-view
     *             view_options:
     *               placeholder: '<placeholder>'
     *               css_class_name: '<class-name>'
     *               maximumSelectionLength: 3
     *           validation_rules:
     *             NotBlank: true
     * ```
     *
     * ### Options in yml:
     *
     * Column option name                                  | Description
     * :---------------------------------------------------|:-----------
     * inline_editing.editor.view_options.placeholder      | Optional. Placeholder translation key for an empty element
     * inline_editing.editor.view_options.placeholder_raw  | Optional. Raw placeholder value
     * inline_editing.editor.view_options.css_class_name   | Optional. Additional css class name for editor view DOM el
     * inline_editing.editor.view_options.maximumSelectionLength | Optional. Maximum selection length
     * inline_editing.editor.validation_rules | Optional. Validation rules. See [documentation](https://goo.gl/j9dj4Y)
     *
     * ### Constructor parameters
     *
     * @class
     * @param {Object} options - Options container
     * @param {Object} options.model - Current row model
     * @param {string} options.fieldName - Field name to edit in model
     * @param {string} options.metadata - Editor metadata
     * @param {string} options.placeholder - Placeholder translation key for an empty element
     * @param {string} options.placeholder_raw - Raw placeholder value. It overrides placeholder translation key
     * @param {string} options.maximumSelectionLength - Maximum selection length
     * @param {Object} options.validationRules - Validation rules. See [documentation here](https://goo.gl/j9dj4Y)
     *
     * @augments [AbstractRelationEditorView](./abstract-relation-editor-view.md)
     * @exports TagsEditorView
     */
    var TagsEditorView;
    var AbstractRelationEditorView = require('oroform/js/app/views/editor/abstract-relation-editor-view');
    var _ = require('underscore');
    var $ = require('jquery');

    TagsEditorView = AbstractRelationEditorView.extend(/** @exports TagsEditorView.prototype */{
        className: 'tags-select-editor',
        DEFAULT_PER_PAGE: 20,
        initialize: function(options) {
            TagsEditorView.__super__.initialize.apply(this, arguments);
        },

        getInitialResultItem: function() {
            return this.getModelValue().map(function(item) {
                return {
                    id: item.id,
                    label: item.name
                };
            });
        },

        getSelect2Options: function() {
            var _this = this;
            _this.currentData = null;
            _this.firstPageData = {
                results: [],
                more: false,
                isDummy: true
            };
            return {
                placeholder: this.placeholder || ' ',
                allowClear: true,
                openOnEnter: false,
                selectOnBlur: false,
                multiple: true,
                id: 'label',
                formatSelection: function(item) {
                    return item.label;
                },
                formatResult: function(item) {
                    return item.label;
                },
                initSelection: function(element, callback) {
                    callback(_this.getInitialResultItem());
                },
                query: function(options) {
                    _this.currentTerm = options.term;
                    _this.currentPage = options.page;
                    _this.currentCallback = options.callback;
                    if (options.page === 1) {
                        // immediately show first item
                        _this.showResults();
                    }
                    options.callback = function(data) {
                        _this.currentData = data;
                        if (data.page === 1) {
                            _this.firstPageData = data;
                        }
                        _this.showResults();
                    };
                    if (_this.currentRequest && _this.currentRequest.term !== '' &&
                        _this.currentRequest.state() !== 'resolved') {
                        _this.currentRequest.abort();
                    }
                    var autoCompleteUrlParameters = _.extend(_this.model.toJSON(), {
                        term: options.term,
                        page: options.page,
                        per_page: _this.perPage
                    });
                    if (options.term !== '' &&
                        !_this.autocompleteApiAccessor.isCacheExistsFor(autoCompleteUrlParameters)) {
                        _this.debouncedMakeRequest(options, autoCompleteUrlParameters);
                    } else {
                        _this.makeRequest(options, autoCompleteUrlParameters);
                    }
                }
            };
        },

        showResults: function() {
            var data;
            if (this.currentPage === 1) {
                data = $.extend({}, this.firstPageData);
                data.results = this.filterTermFromResults(this.currentTerm, data.results);
                if (this.currentPage === 1) {
                    if (this.isValidTerm(this.currentTerm)) {
                        data.results.unshift({
                            id: this.currentTerm,
                            label: this.currentTerm
                        });
                    } else {
                        if (this.firstPageData.isDummy) {
                            // do not update list until choices will be loaded
                            return;
                        }
                    }
                }
                data.results.sort(_.bind(this.tagSortCallback, this));
            } else {
                data = $.extend({}, this.currentData);
                data.results = this.filterTermFromResults(this.currentTerm, data.results);
            }
            this.currentCallback(data);
        },

        filterTermFromResults: function(term, results) {
            results = _.clone(results);
            for (var i = 0; i < results.length; i++) {
                var result = results[i];
                if (result.label === term) {
                    results.splice(i, 1);
                    break;
                }
            }
            return results;
        },

        tagSortCallback: function(a, b) {
            return this.getTermSimilarity(a.label) - this.getTermSimilarity(b.label);
        },

        getTermSimilarity: function(term) {
            var lowerCaseTerm = term.toLowerCase();
            var index = lowerCaseTerm.indexOf(this.currentTerm.toLowerCase());
            if (index === -1) {
                return 1000;
            }
            return index;
        },

        isValidTerm: function(term) {
            return _.isString(term) && term.length > 0;
        },

        getModelValue: function() {
            return this.model.get(this.fieldName) || [];
        },

        getFormattedValue: function() {
            return this.getModelValue().map(function(item) {
                return item.id;
            }).join(',');
        },

        isChanged: function() {
            return this.getValue() !== this.getModelValue().map(function(item) {
                return item.id;
            }).join(',');
        },

        getServerUpdateData: function() {
            var data = {};
            var select2Data = this.$('.select2-container').select2('data');
            data[this.fieldName] = select2Data.map(function(item) {
                return {
                    name: item.label
                };
            });
            return data;
        },

        getModelUpdateData: function() {
            var data = {};
            var select2Data = this.$('.select2-container').select2('data');
            data[this.fieldName] = select2Data.map(function(item) {
                return {
                    id: item.id,
                    name: item.label
                };
            });
            return data;
        }
    }, {
        processMetadata: AbstractRelationEditorView.processMetadata
    });

    return TagsEditorView;
});
<|endoftext|>


<commit_before>/*
 * Class: FlightDeck
 * Initializes all needed functionality
 */

var FlightDeck = new Class({
	Implements: [Options, Events],
	options: {
		menu_el: 'UI_Editor_Menu',
		try_in_browser_class: 'XPI_test'
		//user: ''
	},
	initialize: function() {
		this.uri = new URI();
		if (this.uri.getData('redirect','fragment')) {
			window.location.href = this.uri.getData('redirect', 'fragment');
		}
		this.warning = this.error = this.message = {
			'alert': function(title, message) {
				alert(title+"\n"+message);
			}
		};
		this.editors = [];

		this.tips = new Tips({
			fixed: false,
			className: 'UI_tooltip',
			offset: {
				x: 0,
				y: 16
			}
		});

		$$('div.UI_tooltip_source').each(function(tipSource){
			tipSource.hide();
			var target = $(tipSource.get('data-tooltip-for'));
			target.set('title', '');
			target.store('tip:title', tipSource.get('data-tooltip-title'));
			target.store('tip:text', tipSource.get('html'));
			this.tips.attach(target);
		}, this);

		this.createActionSections();
	},
	setURIRedirect: function(url) {
		// change the URL add #/path/to/saved/revision
		if (this.uri.get('directory') != url) {
			this.uri.setData({'redirect': url}, false, 'fragment');
			this.uri.go();
		}
	},
	/*
	 * Method: testXPI
	 */
	testXPI: function(response) {
		if (response.stderr) {
			fd.error.alert('Error in building Add-on XPI', response.stderr);
			return;
		}
		this.rm_xpi_url = response.rm_xpi_url;
		this.installXPI(response.test_xpi_url);
	},
	/*
	 * Method: hideEditors
	 */
	hideEditors: function() {
		this.editors.each(function(ed){ ed.hide(); });
	},
	/*
	 * Method: installXPI
	 */
	installXPI: function(url) {
		if (fd.alertIfNoAddOn()) {
			window.mozFlightDeck.send({cmd: "install", path: url});
		}
	},
	/*
	 * Method: enableMenuButtons
	 */
	enableMenuButtons: function() {
		$$('.' + this.options.menu_el + ' li').each(function(menuItem){
			if (menuItem.hasClass('disabled')){
				menuItem.removeClass('disabled');
			}
		});
	},
	/*
	 * Method: alertIfNoAddOn
	 */
	alertIfNoAddOn: function(text, title) {
		if (window.mozFlightDeck) return true;
		text = $pick(text, "Please install FlightDeck Add On");
		title = $pick(title, "Add on not installed");
		fd.warning.alert(title, text);
		return false;
	},
	/*
	 * Method: createActionSections
	 */
	createActionSections: function(){
		$$('.UI_Editor_Menu_Separator').each(function(separator){
			separator.getPrevious('li').addClass('UI_Section_Close');
			separator.getNext('li').addClass('UI_Section_Open');
		});

		var UI_Editor_Menu_Button = $$('.UI_Editor_Menu_Button');

		if (UI_Editor_Menu_Button.length <= 1){
			UI_Editor_Menu_Button[0].addClass('UI_Single');
		}
	}
});

/*
 * Default onFailure in all Requests
 */

Request = Class.refactor(Request, {
	options: {
		onFailure: function(xhr) {
			fd.error.alert(
				'Error {status}'.substitute(xhr),
				'{statusText}
{responseText}'.substitute(xhr)
				);
		}
	}
});

/*
 * Inspired by
 * http://github.com/jeresig/sizzle/commit/7631f9c3f85e5fa72ac51532399cb593c2cdc71f
 * and this http://github.com/jeresig/sizzle/commit/5716360040a440041da19823964f96d025ca734b
 * and then http://dev.jquery.com/ticket/4512
 */

Element.implement({

	isHidden: function(){
		var w = this.offsetWidth, h = this.offsetHeight,
		force = (this.tagName.toLowerCase() === 'tr');
		return (w===0 && h===0 && !force)
			? true
			: (w!==0 && h!==0 && !force) ? false : this.getStyle('display') === 'none';
	},
	isVisible: function(){
		return !this.isHidden();
	},
	getSiblings: function(match,nocache) {
		return this.getParent().getChildren(match,nocache).erase(this);
	}

});

/*
	Add $name mutator - specifies the type of the created Class
	Usage:
		var C = new Class({$name = 'sometype', inititate: function() {}});
		var c = new C();
		alert($type(c)); // 'sometype'
 */
Class.Mutators.$name = function(name){ this.implement('$family', {name: name}); };

/*
	Listen to an event fired when Extension is installed
 */
window.addEvent('load', function() {
	if (window.mozFlightDeck) {
		window.mozFlightDeck.whenMessaged(function(data) {
			// This gets called when one of our extensions has been installed
			// successfully, or failed somehow.
			fd.message.alert('Add-ons Builder', 'Add-on {msg}'.substitute(data));
			// log to console result of isInstalled command
			$log('sending isInstalled to window.mozFlightDeck');
			$log(window.mozFlightDeck.send({cmd:'isInstalled'}));
		});
	}
});
<commit_msg>- Small fix to the Action Menu<commit_after>/*
 * Class: FlightDeck
 * Initializes all needed functionality
 */

var FlightDeck = new Class({
	Implements: [Options, Events],
	options: {
		menu_el: 'UI_Editor_Menu',
		try_in_browser_class: 'XPI_test'
		//user: ''
	},
	initialize: function() {
		this.uri = new URI();
		if (this.uri.getData('redirect','fragment')) {
			window.location.href = this.uri.getData('redirect', 'fragment');
		}
		this.warning = this.error = this.message = {
			'alert': function(title, message) {
				alert(title+"\n"+message);
			}
		};
		this.editors = [];

		this.tips = new Tips({
			fixed: false,
			className: 'UI_tooltip',
			offset: {
				x: 0,
				y: 16
			}
		});

		$$('div.UI_tooltip_source').each(function(tipSource){
			tipSource.hide();
			var target = $(tipSource.get('data-tooltip-for'));
			target.set('title', '');
			target.store('tip:title', tipSource.get('data-tooltip-title'));
			target.store('tip:text', tipSource.get('html'));
			this.tips.attach(target);
		}, this);

		this.createActionSections();
	},
	setURIRedirect: function(url) {
		// change the URL add #/path/to/saved/revision
		if (this.uri.get('directory') != url) {
			this.uri.setData({'redirect': url}, false, 'fragment');
			this.uri.go();
		}
	},
	/*
	 * Method: testXPI
	 */
	testXPI: function(response) {
		if (response.stderr) {
			fd.error.alert('Error in building Add-on XPI', response.stderr);
			return;
		}
		this.rm_xpi_url = response.rm_xpi_url;
		this.installXPI(response.test_xpi_url);
	},
	/*
	 * Method: hideEditors
	 */
	hideEditors: function() {
		this.editors.each(function(ed){ ed.hide(); });
	},
	/*
	 * Method: installXPI
	 */
	installXPI: function(url) {
		if (fd.alertIfNoAddOn()) {
			window.mozFlightDeck.send({cmd: "install", path: url});
		}
	},
	/*
	 * Method: enableMenuButtons
	 */
	enableMenuButtons: function() {
		$$('.' + this.options.menu_el + ' li').each(function(menuItem){
			if (menuItem.hasClass('disabled')){
				menuItem.removeClass('disabled');
			}
		});
	},
	/*
	 * Method: alertIfNoAddOn
	 */
	alertIfNoAddOn: function(text, title) {
		if (window.mozFlightDeck) return true;
		text = $pick(text, "Please install FlightDeck Add On");
		title = $pick(title, "Add on not installed");
		fd.warning.alert(title, text);
		return false;
	},
	/*
	 * Method: createActionSections
	 */
	createActionSections: function(){
		$$('.UI_Editor_Menu_Separator').each(function(separator){
			separator.getPrevious('li').addClass('UI_Section_Close');
			separator.getNext('li').addClass('UI_Section_Open');
		});

		var UI_Editor_Menu_Button = $$('.UI_Editor_Menu_Button');

		if (UI_Editor_Menu_Button.length === 1){
			UI_Editor_Menu_Button[0].addClass('UI_Single');
		}
	}
});

/*
 * Default onFailure in all Requests
 */

Request = Class.refactor(Request, {
	options: {
		onFailure: function(xhr) {
			fd.error.alert(
				'Error {status}'.substitute(xhr),
				'{statusText}
{responseText}'.substitute(xhr)
				);
		}
	}
});

/*
 * Inspired by
 * http://github.com/jeresig/sizzle/commit/7631f9c3f85e5fa72ac51532399cb593c2cdc71f
 * and this http://github.com/jeresig/sizzle/commit/5716360040a440041da19823964f96d025ca734b
 * and then http://dev.jquery.com/ticket/4512
 */

Element.implement({

	isHidden: function(){
		var w = this.offsetWidth, h = this.offsetHeight,
		force = (this.tagName.toLowerCase() === 'tr');
		return (w===0 && h===0 && !force)
			? true
			: (w!==0 && h!==0 && !force) ? false : this.getStyle('display') === 'none';
	},
	isVisible: function(){
		return !this.isHidden();
	},
	getSiblings: function(match,nocache) {
		return this.getParent().getChildren(match,nocache).erase(this);
	}

});

/*
	Add $name mutator - specifies the type of the created Class
	Usage:
		var C = new Class({$name = 'sometype', inititate: function() {}});
		var c = new C();
		alert($type(c)); // 'sometype'
 */
Class.Mutators.$name = function(name){ this.implement('$family', {name: name}); };

/*
	Listen to an event fired when Extension is installed
 */
window.addEvent('load', function() {
	if (window.mozFlightDeck) {
		window.mozFlightDeck.whenMessaged(function(data) {
			// This gets called when one of our extensions has been installed
			// successfully, or failed somehow.
			fd.message.alert('Add-ons Builder', 'Add-on {msg}'.substitute(data));
			// log to console result of isInstalled command
			$log('sending isInstalled to window.mozFlightDeck');
			$log(window.mozFlightDeck.send({cmd:'isInstalled'}));
		});
	}
});
<|endoftext|>


<commit_before>(function() {
  var BrowserSync, browserSync, bsExists, bsPath, fs, http, log, mkdirp, path, version;

  fs = require('fs');

  log = require('de-logger');

  http = require('http');

  path = require('path');

  mkdirp = require('mkdirp');

  browserSync = require('browser-sync');

  version = null;

  bsExists = null;

  bsPath = path.resolve(__dirname, '../../../node_modules/browser-sync');

  fs.exists(bsPath, function(exists) {
    var ref;
    bsExists = exists;
    if (bsExists) {
      return ref = require('../../../node_modules/browser-sync/package.json'), version = ref.version, ref;
    } else {
      return log.warn('browser-sync not found');
    }
  });

  BrowserSync = (function() {
    function BrowserSync(server) {
      this.server = server;
      this.load();
    }

    BrowserSync.prototype.load = function() {
      this.filePath = path.resolve(__dirname, '../../../build/browser-sync.js');
      this.bs = browserSync.create();
      this.config = {
        ui: {
          port: 9000
        },
        port: 9001,
        logLevel: 'silent',
        logFileChanges: false
      };
      return this.bs.init(this.config, (function(_this) {
        return function(err, bs) {
          if (err) {
            return log.error('LDE - BrowserSync', 'Couldn\'t start BrowserSync \n\n', err);
          }
          return _this.code();
        };
      })(this));
    };

    BrowserSync.prototype.reload = function(path) {
      log.info('LDE - BrowserSync', "Reload", path.replace(this.server.options.root + "/", ''));
      return this.bs.reload(path);
    };

    BrowserSync.prototype.code = function() {
      log.info('LDE - BrowserSync', "BrowserSync server started");
      return this.download("http://localhost:" + this.config.port + "/browser-sync/browser-sync-client." + version + ".js", (function(_this) {
        return function(err) {
          if (err) {
            return log.error('LDE - BrowserSync', "Unable to get browser-sync .js file", err);
          }
          log.info('LDE - BrowserSync', "Ready at localhost:" + _this.config.ui.port);
          if (_this.server.options.browserSync.enabled) {
            _this.server.browserify.w.require('socket.io-client', {
              expose: 'socket.io-client'
            });
            _this.server.browserify.w.add(path.resolve(__dirname, '../../helper/socket.io-client'));
            _this.server.browserify.w.add(_this.filePath);
          }
          _this.ready = true;
          return _this.server.watch.browserify();
        };
      })(this));
    };

    BrowserSync.prototype.download = function(url, cb) {
      return mkdirp(path.dirname(this.filePath), (function(_this) {
        return function(err) {
          _this.file = fs.createWriteStream(_this.filePath);
          return http.get(url, function(response) {
            return response.pipe(_this.file).on('error', function(err) {
              fs.unlink(_this.file);
              return cb(err);
            }).on('finish', function() {
              return _this.file.close(cb);
            });
          });
        };
      })(this));
    };

    return BrowserSync;

  })();

  module.exports = BrowserSync;

}).call(this);
<commit_msg>small fix<commit_after>(function() {
  var BrowserSync, browserSync, bsExists, bsPath, fs, http, log, mkdirp, path, version;

  fs = require('fs');

  log = require('de-logger');

  http = require('http');

  path = require('path');

  mkdirp = require('mkdirp');

  browserSync = require('browser-sync');

  version = null;

  bsExists = null;

  bsPath = path.resolve(__dirname, '../../../node_modules/browser-sync');

  fs.exists(bsPath, function(exists) {
    var ref;
    bsExists = exists;
    if (bsExists) {
      return ref = require('../../../node_modules/browser-sync/package.json'), version = ref.version, ref;
    } else {
      return log.warn('browser-sync not found');
    }
  });

  BrowserSync = (function() {
    function BrowserSync(server) {
      this.server = server;
      this.load();
    }

    BrowserSync.prototype.load = function() {
      this.filePath = path.resolve(__dirname, '../../../build/browser-sync.js');
      this.bs = browserSync.create();
      this.config = {
        ui: {
          port: 9000
        },
        port: 9001,
        logLevel: 'silent',
        logFileChanges: false
      };
      return this.bs.init(this.config, (function(_this) {
        return function(err) {
          if (err) {
            return log.error('LDE - BrowserSync', 'Couldn\'t start BrowserSync \n\n', err);
          }
          return _this.code();
        };
      })(this));
    };

    BrowserSync.prototype.reload = function(path) {
      log.info('LDE - BrowserSync', "Reload", path.replace(this.server.options.root + "/", ''));
      return this.bs.reload(path);
    };

    BrowserSync.prototype.code = function() {
      log.info('LDE - BrowserSync', "BrowserSync server started");
      return this.download("http://localhost:" + this.config.port + "/browser-sync/browser-sync-client." + version + ".js", (function(_this) {
        return function(err) {
          if (err) {
            return log.error('LDE - BrowserSync', "Unable to get browser-sync .js file", err);
          }
          log.info('LDE - BrowserSync', "Ready at localhost:" + _this.config.ui.port);
          if (_this.server.options.browserSync.enabled) {
            _this.server.browserify.w.require('socket.io-client', {
              expose: 'socket.io-client'
            });
            _this.server.browserify.w.add(path.resolve(__dirname, '../../helper/socket.io-client'));
            _this.server.browserify.w.add(_this.filePath);
          }
          _this.ready = true;
          return _this.server.watch.browserify();
        };
      })(this));
    };

    BrowserSync.prototype.download = function(url, cb) {
      return mkdirp(path.dirname(this.filePath), (function(_this) {
        return function() {
          _this.file = fs.createWriteStream(_this.filePath);
          return http.get(url, function(response) {
            return response.pipe(_this.file).on('error', function(err) {
              fs.unlink(_this.file);
              return cb(err);
            }).on('finish', function() {
              return _this.file.close(cb);
            });
          });
        };
      })(this));
    };

    return BrowserSync;

  })();

  module.exports = BrowserSync;

}).call(this);
<|endoftext|>


<commit_before>import React from 'react';

class PostFilter extends React.Component {
  constructor() {
    super();

    this.change = this.change.bind(this);
  }

  change(event) {
    this.props.onChange(event.target.value);
  }

  render() {
    return (

Post Filter

              <select onChange={(event) => this.change(event)}>
                  <option value="accepted">Accepted</option>
                  <option value="pending">Pending</option>
                  <option value="rejected">Rejected</option>
                  <option value="good-photo">Good Photo</option>
                  <option value="good-quote">Good Quote</option>
                  <option value="hide-in-gallery">Hide In Gallery 👻</option>
                  <option value="good-for-sponsor">Good For Sponsor</option>
                  <option value="good-for-storytelling">Good For Storytelling</option>
              </select>

    )
  }
}

export default PostFilter;
<commit_msg>adds comment to make a filter component<commit_after>import React from 'react';

class PostFilter extends React.Component {
  constructor() {
    super();

    this.change = this.change.bind(this);
  }

  change(event) {
    this.props.onChange(event.target.value);
  }

  render() {
    return (

Post Filter

          {/* @TODO create a <Filter> component that takes in an array of value/labels and renders the select list and handles the change event.*/}
              <select onChange={(event) => this.change(event)}>
                  <option value="accepted">Accepted</option>
                  <option value="pending">Pending</option>
                  <option value="rejected">Rejected</option>
                  <option value="good-photo">Good Photo</option>
                  <option value="good-quote">Good Quote</option>
                  <option value="hide-in-gallery">Hide In Gallery 👻</option>
                  <option value="good-for-sponsor">Good For Sponsor</option>
                  <option value="good-for-storytelling">Good For Storytelling</option>
              </select>

    )
  }
}

export default PostFilter;
<|endoftext|>


<commit_before>module.exports = function(grunt, config, parameters, done) {
	var workFolder = parameters.releaseWorkFolder || './release/source/web';

	var remove = {
		file: {
			byName: [
				'.coveralls.yml',
				'.DS_Store',
				'.gitattributes',
				'.gitignore',
				'.gitmodules',
				'.php_cs',
				'.scrutinizer.yml',
				'.travis.yml',
				'build.properties.dev',
				'composer.lock',
			],
			byPath: [
				'/concrete/vendor/dapphp/securimage/example_form.ajax.php',
				'/concrete/vendor/dapphp/securimage/example_form.php',
				'/concrete/vendor/doctrine/migrations/package.php',
				'/concrete/vendor/doctrine/migrations/phar-cli-stub.php',
				'/concrete/vendor/htmlawed/htmlawed/htmLawedTest.php',
				'/concrete/vendor/imagine/imagine/lib/Imagine/resources/Adobe/Color Profile Bundling License_10.15.08.pdf',
				'/concrete/vendor/imagine/imagine/lib/Imagine/resources/Adobe/Profile Information.pdf',
				'/concrete/vendor/kertz/twitteroauth/callback.php',
				'/concrete/vendor/kertz/twitteroauth/clearsessions.php',
				'/concrete/vendor/kertz/twitteroauth/config-sample.php',
				'/concrete/vendor/kertz/twitteroauth/connect.php',
				'/concrete/vendor/kertz/twitteroauth/html.inc',
				'/concrete/vendor/kertz/twitteroauth/index.php',
				'/concrete/vendor/kertz/twitteroauth/redirect.php',
				'/concrete/vendor/kertz/twitteroauth/test.php',
				'/concrete/vendor/league/flysystem/phpunit.php',
				'/concrete/vendor/nesbot/carbon/readme.php',
				'/concrete/vendor/simplepie/simplepie/db.sql',
				'/concrete/vendor/tedivm/jshrink/package.xml',
				'/concrete/vendor/voku/urlify/INSTALL',
				'/INSTALL\.md',
			],
			byRX: [
				/^\/concrete\/vendor\/.*\/(changelog|change_log|upgrade|upgrading|readme|contributing|history|roadmap)(\.(font|src))?\.(md|mdown|markdown|txt)$/i,
				/^\/concrete\/vendor\/.*\/composer\.json(\.hhvm)?$/,
				/^\/concrete\/vendor\/.*\/phpunit\.(xml|xml\.dist|dist\.xml)(\.hhvm)?$/,
				/^\/concrete\/vendor\/.*\/build\.(xml|properties)(\.dist)?$/,
				/^\/concrete\/vendor\/.*\/UPGRADE_TO_\w+$/,
				/^\/concrete\/vendor\/.*\/UPGRADE$/i,
				/^\/concrete\/vendor\/htmlawed\/htmlawed\/htmLawed_[README|TESTCASE]/,
				/^\/concrete\/vendor\/.*\.(sh|bash|bat|exe|cmd|dll)$/i,
			]
		},
		dir: {
			byName: [
				'.easymin',
				'.git',
			],
			byPath: [
				'/concrete/vendor/anahkiasen/html-object/examples',
				'/concrete/vendor/anahkiasen/html-object/tests',
				'/concrete/vendor/bin',
				'/concrete/vendor/dapphp/securimage/examples',
				'/concrete/vendor/doctrine/annotations/tests',
				'/concrete/vendor/doctrine/cache/tests',
				'/concrete/vendor/doctrine/collections/tests',
				'/concrete/vendor/doctrine/common/tests',
				'/concrete/vendor/doctrine/dbal/bin',
				'/concrete/vendor/doctrine/inflector/tests',
				'/concrete/vendor/doctrine/migrations/tests',
				'/concrete/vendor/doctrine/orm/bin',
				'/concrete/vendor/doctrine/orm/docs',
				'/concrete/vendor/egulias/email-validator/documentation',
				'/concrete/vendor/egulias/email-validator/tests',
				'/concrete/vendor/facebook/php-sdk/examples',
				'/concrete/vendor/facebook/php-sdk/tests',
				'/concrete/vendor/filp/whoops/docs',
				'/concrete/vendor/filp/whoops/examples',
				'/concrete/vendor/filp/whoops/tests',
				'/concrete/vendor/guzzle/guzzle/docs',
				'/concrete/vendor/guzzle/guzzle/tests',
				'/concrete/vendor/hautelook/phpass/lib',
				'/concrete/vendor/hautelook/phpass/Tests',
				'/concrete/vendor/imagine/imagine/docs',
				'/concrete/vendor/imagine/imagine/lib/Imagine/Test',
				'/concrete/vendor/imagine/imagine/tests',
				'/concrete/vendor/league/flysystem/tests',
				'/concrete/vendor/mobiledetect/mobiledetectlib/examples',
				'/concrete/vendor/mobiledetect/mobiledetectlib/tests',
				'/concrete/vendor/monolog/monolog/doc',
				'/concrete/vendor/monolog/monolog/tests',
				'/concrete/vendor/nesbot/carbon/tests',
				'/concrete/vendor/oyejorge/less.php/bin',
				'/concrete/vendor/oyejorge/less.php/test',
				'/concrete/vendor/pagerfanta/pagerfanta/tests',
				'/concrete/vendor/psr/log/Psr/Log/Test',
				'/concrete/vendor/punic/punic/bin',
				'/concrete/vendor/punic/punic/tests',
				'/concrete/vendor/simplepie/simplepie/build',
				'/concrete/vendor/simplepie/simplepie/compatibility_test',
				'/concrete/vendor/simplepie/simplepie/demo',
				'/concrete/vendor/simplepie/simplepie/tests',
				'/concrete/vendor/sunra/php-simple-html-dom-parser/Src/Sunra/PhpSimple/simplehtmldom_1_5/app',
				'/concrete/vendor/sunra/php-simple-html-dom-parser/Src/Sunra/PhpSimple/simplehtmldom_1_5/example',
				'/concrete/vendor/sunra/php-simple-html-dom-parser/Src/Sunra/PhpSimple/simplehtmldom_1_5/manual',
				'/concrete/vendor/sunra/php-simple-html-dom-parser/Src/Sunra/PhpSimple/simplehtmldom_1_5/testcase',
				'/concrete/vendor/symfony/class-loader/Symfony/Component/ClassLoader/Tests',
				'/concrete/vendor/symfony/console/Symfony/Component/Console/Tests',
				'/concrete/vendor/symfony/debug/Symfony/Component/Debug/Tests',
				'/concrete/vendor/symfony/event-dispatcher/Symfony/Component/EventDispatcher/Tests',
				'/concrete/vendor/symfony/finder/Symfony/Component/Finder/Tests',
				'/concrete/vendor/symfony/http-foundation/Symfony/Component/HttpFoundation/Tests',
				'/concrete/vendor/symfony/http-kernel/Symfony/Component/HttpKernel/Tests',
				'/concrete/vendor/symfony/routing/Symfony/Component/Routing/Tests',
				'/concrete/vendor/symfony/serializer/Symfony/Component/Serializer/Tests',
				'/concrete/vendor/tedivm/jshrink/tests',
				'/concrete/vendor/tedivm/stash/tests',
				'/concrete/vendor/voku/urlify/tests',
			],
			byRX: [
			]
		}
	};
	function shouldRemove(kind, rel, name) {
		if(remove[kind].byName.indexOf(name) >= 0) {
			return true;
		}
		if(remove[kind].byPath.indexOf(rel) >= 0) {
			return true;
		}
		for(var i = 0; i < remove[kind].byRX.length; i++) {
			if(remove[kind].byRX[i].test(rel)) {
				return true;
			}
		}
		return false;
	}
	function endForError(e) {
		process.stderr.write(e.message || e);
		done(false);
	}
	try {
		var c5fs = require('../../libraries/fs'),
			fs = require('fs'),
			shell = require('shelljs'),
			path = require('path');
		var parser = new c5fs.directoryParser(workFolder);
		parser.excludeDirectoriesByName = [];
		parser.excludeFilesByName = [];
		parser.onDirectory = function(cb, abs, rel, name) {
			var skipContents = false;
			if(shouldRemove('dir', rel, name)) {
				process.stdout.write('Removing directory ' + rel + '\n');
				shell.rm('-rf', abs);
				if(c5fs.fileExists(abs)) {
					throw new Error('Unable to remove ' + abs);
				}
				skipContents = true;
			}
			cb(skipContents);
		};
		parser.onFile = function(cb, abs, rel, name) {
			if(shouldRemove('file', rel, name)) {
				process.stdout.write('Removing file ' + rel + '\n');
				shell.rm('-f', abs);
				if(c5fs.fileExists(abs)) {
					throw new Error('Unable to remove ' + abs);
				}
			}
			cb();
		};
		parser.start(function(error) {
			if(error) {
				endForError(error);
				return;
			}
			var classmapFile = path.join(workFolder, 'concrete/vendor/composer/autoload_classmap.php');
			if(c5fs.isFile(classmapFile)) {
				process.stdout.write('Removing lines from Composer classmap:\n');
				var classmapLines = fs.readFileSync(classmapFile, 'utf8').replace(/\r\n/g, '\n').replace(/\r/g, '\n').split('\n'),
					linesRemoved = 0;
				remove.dir.byPath.forEach(function(dir) {
					var m = dir.match(/^\/concrete\/vendor\/(.+)$/);
					if(!m) {
						return;
					}
					var removeLinesWith = '=> $vendorDir . \'/' + m[1] + '/';
					for(i = classmapLines.length - 1; i >= 0; i--) {
						if((classmapLines[i].indexOf(removeLinesWith) >= 0) && /^\s*'[^']+' => \$vendorDir . '/.test(classmapLines[i])) {
							process.stdout.write(classmapLines[i] + '\n');
							classmapLines.splice(i, 1);
							linesRemoved++;
						}
					}
				});
				if(linesRemoved > 0) {
					fs.writeFileSync(classmapFile, classmapLines.join('\n'), 'utf8');
				}
			}
			done();
		});
	}
	catch(e) {
		endForError(e);
		return;
	}
};<commit_msg>Keep concrete5 composer.lock<commit_after>module.exports = function(grunt, config, parameters, done) {
	var workFolder = parameters.releaseWorkFolder || './release/source/web';

	var remove = {
		file: {
			byName: [
				'.coveralls.yml',
				'.DS_Store',
				'.gitattributes',
				'.gitignore',
				'.gitmodules',
				'.php_cs',
				'.scrutinizer.yml',
				'.travis.yml',
				'build.properties.dev',
			],
			byPath: [
				'/concrete/vendor/dapphp/securimage/example_form.ajax.php',
				'/concrete/vendor/dapphp/securimage/example_form.php',
				'/concrete/vendor/doctrine/migrations/package.php',
				'/concrete/vendor/doctrine/migrations/phar-cli-stub.php',
				'/concrete/vendor/htmlawed/htmlawed/htmLawedTest.php',
				'/concrete/vendor/imagine/imagine/lib/Imagine/resources/Adobe/Color Profile Bundling License_10.15.08.pdf',
				'/concrete/vendor/imagine/imagine/lib/Imagine/resources/Adobe/Profile Information.pdf',
				'/concrete/vendor/kertz/twitteroauth/callback.php',
				'/concrete/vendor/kertz/twitteroauth/clearsessions.php',
				'/concrete/vendor/kertz/twitteroauth/config-sample.php',
				'/concrete/vendor/kertz/twitteroauth/connect.php',
				'/concrete/vendor/kertz/twitteroauth/html.inc',
				'/concrete/vendor/kertz/twitteroauth/index.php',
				'/concrete/vendor/kertz/twitteroauth/redirect.php',
				'/concrete/vendor/kertz/twitteroauth/test.php',
				'/concrete/vendor/league/flysystem/phpunit.php',
				'/concrete/vendor/nesbot/carbon/readme.php',
				'/concrete/vendor/simplepie/simplepie/db.sql',
				'/concrete/vendor/tedivm/jshrink/package.xml',
				'/concrete/vendor/voku/urlify/INSTALL',
				'/INSTALL\.md',
			],
			byRX: [
				/^\/concrete\/vendor\/.*\/(changelog|change_log|upgrade|upgrading|readme|contributing|history|roadmap)(\.(font|src))?\.(md|mdown|markdown|txt)$/i,
				/^\/concrete\/vendor\/.*\/composer\.(lock|json)(\.hhvm)?$/,
				/^\/concrete\/vendor\/.*\/phpunit\.(xml|xml\.dist|dist\.xml)(\.hhvm)?$/,
				/^\/concrete\/vendor\/.*\/build\.(xml|properties)(\.dist)?$/,
				/^\/concrete\/vendor\/.*\/UPGRADE_TO_\w+$/,
				/^\/concrete\/vendor\/.*\/UPGRADE$/i,
				/^\/concrete\/vendor\/htmlawed\/htmlawed\/htmLawed_[README|TESTCASE]/,
				/^\/concrete\/vendor\/.*\.(sh|bash|bat|exe|cmd|dll)$/i,
			]
		},
		dir: {
			byName: [
				'.easymin',
				'.git',
			],
			byPath: [
				'/concrete/vendor/anahkiasen/html-object/examples',
				'/concrete/vendor/anahkiasen/html-object/tests',
				'/concrete/vendor/bin',
				'/concrete/vendor/dapphp/securimage/examples',
				'/concrete/vendor/doctrine/annotations/tests',
				'/concrete/vendor/doctrine/cache/tests',
				'/concrete/vendor/doctrine/collections/tests',
				'/concrete/vendor/doctrine/common/tests',
				'/concrete/vendor/doctrine/dbal/bin',
				'/concrete/vendor/doctrine/inflector/tests',
				'/concrete/vendor/doctrine/migrations/tests',
				'/concrete/vendor/doctrine/orm/bin',
				'/concrete/vendor/doctrine/orm/docs',
				'/concrete/vendor/egulias/email-validator/documentation',
				'/concrete/vendor/egulias/email-validator/tests',
				'/concrete/vendor/facebook/php-sdk/examples',
				'/concrete/vendor/facebook/php-sdk/tests',
				'/concrete/vendor/filp/whoops/docs',
				'/concrete/vendor/filp/whoops/examples',
				'/concrete/vendor/filp/whoops/tests',
				'/concrete/vendor/guzzle/guzzle/docs',
				'/concrete/vendor/guzzle/guzzle/tests',
				'/concrete/vendor/hautelook/phpass/lib',
				'/concrete/vendor/hautelook/phpass/Tests',
				'/concrete/vendor/imagine/imagine/docs',
				'/concrete/vendor/imagine/imagine/lib/Imagine/Test',
				'/concrete/vendor/imagine/imagine/tests',
				'/concrete/vendor/league/flysystem/tests',
				'/concrete/vendor/mobiledetect/mobiledetectlib/examples',
				'/concrete/vendor/mobiledetect/mobiledetectlib/tests',
				'/concrete/vendor/monolog/monolog/doc',
				'/concrete/vendor/monolog/monolog/tests',
				'/concrete/vendor/nesbot/carbon/tests',
				'/concrete/vendor/oyejorge/less.php/bin',
				'/concrete/vendor/oyejorge/less.php/test',
				'/concrete/vendor/pagerfanta/pagerfanta/tests',
				'/concrete/vendor/psr/log/Psr/Log/Test',
				'/concrete/vendor/punic/punic/bin',
				'/concrete/vendor/punic/punic/tests',
				'/concrete/vendor/simplepie/simplepie/build',
				'/concrete/vendor/simplepie/simplepie/compatibility_test',
				'/concrete/vendor/simplepie/simplepie/demo',
				'/concrete/vendor/simplepie/simplepie/tests',
				'/concrete/vendor/sunra/php-simple-html-dom-parser/Src/Sunra/PhpSimple/simplehtmldom_1_5/app',
				'/concrete/vendor/sunra/php-simple-html-dom-parser/Src/Sunra/PhpSimple/simplehtmldom_1_5/example',
				'/concrete/vendor/sunra/php-simple-html-dom-parser/Src/Sunra/PhpSimple/simplehtmldom_1_5/manual',
				'/concrete/vendor/sunra/php-simple-html-dom-parser/Src/Sunra/PhpSimple/simplehtmldom_1_5/testcase',
				'/concrete/vendor/symfony/class-loader/Symfony/Component/ClassLoader/Tests',
				'/concrete/vendor/symfony/console/Symfony/Component/Console/Tests',
				'/concrete/vendor/symfony/debug/Symfony/Component/Debug/Tests',
				'/concrete/vendor/symfony/event-dispatcher/Symfony/Component/EventDispatcher/Tests',
				'/concrete/vendor/symfony/finder/Symfony/Component/Finder/Tests',
				'/concrete/vendor/symfony/http-foundation/Symfony/Component/HttpFoundation/Tests',
				'/concrete/vendor/symfony/http-kernel/Symfony/Component/HttpKernel/Tests',
				'/concrete/vendor/symfony/routing/Symfony/Component/Routing/Tests',
				'/concrete/vendor/symfony/serializer/Symfony/Component/Serializer/Tests',
				'/concrete/vendor/tedivm/jshrink/tests',
				'/concrete/vendor/tedivm/stash/tests',
				'/concrete/vendor/voku/urlify/tests',
			],
			byRX: [
			]
		}
	};
	function shouldRemove(kind, rel, name) {
		if(remove[kind].byName.indexOf(name) >= 0) {
			return true;
		}
		if(remove[kind].byPath.indexOf(rel) >= 0) {
			return true;
		}
		for(var i = 0; i < remove[kind].byRX.length; i++) {
			if(remove[kind].byRX[i].test(rel)) {
				return true;
			}
		}
		return false;
	}
	function endForError(e) {
		process.stderr.write(e.message || e);
		done(false);
	}
	try {
		var c5fs = require('../../libraries/fs'),
			fs = require('fs'),
			shell = require('shelljs'),
			path = require('path');
		var parser = new c5fs.directoryParser(workFolder);
		parser.excludeDirectoriesByName = [];
		parser.excludeFilesByName = [];
		parser.onDirectory = function(cb, abs, rel, name) {
			var skipContents = false;
			if(shouldRemove('dir', rel, name)) {
				process.stdout.write('Removing directory ' + rel + '\n');
				shell.rm('-rf', abs);
				if(c5fs.fileExists(abs)) {
					throw new Error('Unable to remove ' + abs);
				}
				skipContents = true;
			}
			cb(skipContents);
		};
		parser.onFile = function(cb, abs, rel, name) {
			if(shouldRemove('file', rel, name)) {
				process.stdout.write('Removing file ' + rel + '\n');
				shell.rm('-f', abs);
				if(c5fs.fileExists(abs)) {
					throw new Error('Unable to remove ' + abs);
				}
			}
			cb();
		};
		parser.start(function(error) {
			if(error) {
				endForError(error);
				return;
			}
			var classmapFile = path.join(workFolder, 'concrete/vendor/composer/autoload_classmap.php');
			if(c5fs.isFile(classmapFile)) {
				process.stdout.write('Removing lines from Composer classmap:\n');
				var classmapLines = fs.readFileSync(classmapFile, 'utf8').replace(/\r\n/g, '\n').replace(/\r/g, '\n').split('\n'),
					linesRemoved = 0;
				remove.dir.byPath.forEach(function(dir) {
					var m = dir.match(/^\/concrete\/vendor\/(.+)$/);
					if(!m) {
						return;
					}
					var removeLinesWith = '=> $vendorDir . \'/' + m[1] + '/';
					for(i = classmapLines.length - 1; i >= 0; i--) {
						if((classmapLines[i].indexOf(removeLinesWith) >= 0) && /^\s*'[^']+' => \$vendorDir . '/.test(classmapLines[i])) {
							process.stdout.write(classmapLines[i] + '\n');
							classmapLines.splice(i, 1);
							linesRemoved++;
						}
					}
				});
				if(linesRemoved > 0) {
					fs.writeFileSync(classmapFile, classmapLines.join('\n'), 'utf8');
				}
			}
			done();
		});
	}
	catch(e) {
		endForError(e);
		return;
	}
};<|endoftext|>


<commit_before>describe('Mini test', function() {
  it('should work', function () {
    cy.visit("https://lga-1543-install-and-integra.staging.checklegalaid.service.gov.uk/start")

    cy.contains('Choose the area you most need help with')
    cy.contains('Debt').click()

    cy.contains('Choose the option that best describes your debt problem')
    cy.get(':nth-child(1) > .cla-scope-options-list-item-link').click()

    cy.contains('Legal aid is available for this type of problem')
    cy.contains('Check if you qualify financially').click()

    // About you form
    cy.setRadioInput('have_partner', 'No')
    cy.setRadioInput('on_benefits', 'Yes')
    cy.setRadioInput('have_children', 'Yes')
    cy.setTextInput('num_children', '4')
    cy.setRadioInput('have_dependants', 'No')
    cy.setRadioInput('own_property', 'Yes')
    cy.setRadioInput('is_employed', 'No')
    cy.setRadioInput('is_self_employed', 'No')
    cy.setRadioInput('aged_60_or_over', 'No')
    cy.setRadioInput('have_savings', 'Yes')
    cy.setRadioInput('have_valuables', 'No')
    cy.get("#submit-button").click();

    // Which benefits do you receive form
    cy.setCheckboxInput('benefits-5')
    cy.setCheckboxInput('benefits-6')
    cy.get("#submit-button").click();

  });
})
<commit_msg>Completed happy path for Your additional benefits form<commit_after>describe('Mini test', function() {
  it('should work', function () {
    cy.visit("https://lga-1543-install-and-integra.staging.checklegalaid.service.gov.uk/start")

    cy.contains('Choose the area you most need help with')
    cy.contains('Debt').click()

    cy.contains('Choose the option that best describes your debt problem')
    cy.get(':nth-child(1) > .cla-scope-options-list-item-link').click()

    cy.contains('Legal aid is available for this type of problem')
    cy.contains('Check if you qualify financially').click()

    // About you form
    cy.setRadioInput('have_partner', 'No')
    cy.setRadioInput('on_benefits', 'Yes')
    cy.setRadioInput('have_children', 'Yes')
    cy.setTextInput('num_children', '4')
    cy.setRadioInput('have_dependants', 'No')
    cy.setRadioInput('own_property', 'Yes')
    cy.setRadioInput('is_employed', 'No')
    cy.setRadioInput('is_self_employed', 'No')
    cy.setRadioInput('aged_60_or_over', 'No')
    cy.setRadioInput('have_savings', 'Yes')
    cy.setRadioInput('have_valuables', 'No')
    cy.get("#submit-button").click();

    // Which benefits do you receive form
    cy.setCheckboxInput('benefits-5')
    cy.setCheckboxInput('benefits-6')
    cy.get("#submit-button").click();

    // Your additional benefits form
    cy.setCheckboxInput('benefits-6')
    cy.setCheckboxInput('benefits-10')
    cy.setRadioInput('other_benefits', 'No')
    cy.get("#submit-button").click();

  });
})
<|endoftext|>


<commit_before>import axios from 'axios'
import store from '@/store'
// import { Spin } from 'iview'
const addErrorLog = errorInfo => {
  const { statusText, status, request: { responseURL } } = errorInfo
  let info = {
    type: 'ajax',
    code: status,
    mes: statusText,
    url: responseURL
  }
  if (!responseURL.includes('save_error_logger')) store.dispatch('addErrorLog', info)
}

class HttpRequest {
  constructor (baseUrl = baseURL) {
    this.baseUrl = baseUrl
    this.queue = {}
  }
  getInsideConfig () {
    const config = {
      baseURL: this.baseUrl,
      headers: {
        //
      }
    }
    return config
  }
  destroy (url) {
    delete this.queue[url]
    if (!Object.keys(this.queue).length) {
      // Spin.hide()
    }
  }
  interceptors (instance, url) {
    // 请求拦截
    instance.interceptors.request.use(config => {
      // 添加全局的loading...
      if (!Object.keys(this.queue).length) {
        // Spin.show() // 不建议开启，因为界面不友好
      }
      this.queue[url] = true
      return config
    }, error => {
      return Promise.reject(error)
    })
    // 响应拦截
    instance.interceptors.response.use(res => {
      this.destroy(url)
      const { data, status } = res
      return { data, status }
    }, error => {
      this.destroy(url)
      addErrorLog(error.response)
      return Promise.reject(error)
    })
  }
  request (options) {
    const instance = axios.create()
    options = Object.assign(this.getInsideConfig(), options)
    this.interceptors(instance, options.url)
    return instance(options)
  }
}
export default HttpRequest
<commit_msg>优化api请求的错误收集<commit_after>import axios from 'axios'
import store from '@/store'
// import { Spin } from 'iview'
const addErrorLog = errorInfo => {
  const { statusText, status, request: { responseURL } } = errorInfo
  let info = {
    type: 'ajax',
    code: status,
    mes: statusText,
    url: responseURL
  }
  if (!responseURL.includes('save_error_logger')) store.dispatch('addErrorLog', info)
}

class HttpRequest {
  constructor (baseUrl = baseURL) {
    this.baseUrl = baseUrl
    this.queue = {}
  }
  getInsideConfig () {
    const config = {
      baseURL: this.baseUrl,
      headers: {
        //
      }
    }
    return config
  }
  destroy (url) {
    delete this.queue[url]
    if (!Object.keys(this.queue).length) {
      // Spin.hide()
    }
  }
  interceptors (instance, url) {
    // 请求拦截
    instance.interceptors.request.use(config => {
      // 添加全局的loading...
      if (!Object.keys(this.queue).length) {
        // Spin.show() // 不建议开启，因为界面不友好
      }
      this.queue[url] = true
      return config
    }, error => {
      return Promise.reject(error)
    })
    // 响应拦截
    instance.interceptors.response.use(res => {
      this.destroy(url)
      const { data, status } = res
      return { data, status }
    }, error => {
      this.destroy(url)
      let errorInfo = error.response
      if (!errorInfo) {
        const { request: { statusText, status }, config } = JSON.parse(JSON.stringify(error))
        errorInfo = {
          statusText,
          status,
          request: { responseURL: config.url }
        }
      }
      addErrorLog(errorInfo)
      return Promise.reject(error)
    })
  }
  request (options) {
    const instance = axios.create()
    options = Object.assign(this.getInsideConfig(), options)
    this.interceptors(instance, options.url)
    return instance(options)
  }
}
export default HttpRequest
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2013 salesforce.com, inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
({
    /**
     * Verify that server created iteration components will actively respond to
     * underlying value changes on which expressions depend.
     */
    _testServerItemActive: {
        test: [function(component){
            // get collection of buttons
            var btns = component.find("aButton");
            // Verify initial state of components
            $A.test.assertStartsWith("isClose-false Server 0", $A.util.getText(btns[0].getElement()));
            $A.test.assertStartsWith("isClose-false Server 1", $A.util.getText(btns[1].getElement()));
            $A.test.assertStartsWith("isClose-false Server 2", $A.util.getText(btns[2].getElement()));
            // press the first button,  changing what the expression is dependent on
        	component.find("aButton")[0].get("myButton").get("e.press").fire();
        }, function(component){
        	var btns = component.find("aButton");
            $A.test.assertStartsWith("isClosed-true Server 0", $A.util.getText(btns[0].getElement()));
        }]
    },
    /**
     * Verify that a combination of client and server iteration components will actively respond to
     * underlying value changes on which expressions depend
     */
    _testClientItemActive: {
        test: [function(component){
            // add one item to iteration from client using button
            component.get("addItem").get("e.press").fire();
        }, function(component){
            // get collection of buttons
            var btns = component.find("aButton");

            // verify initial component state
            $A.test.assertStartsWith("isClose-false Client", $A.util.getText(btns[3].getElement()));
            $A.test.assertStartsWith("isClose-false Server 0", $A.util.getText(btns[0].getElement()));
            // press the first button,  changing what the expression is dependent on
        	component.find("aButton")[3].get("myButton").get("e.press").fire();
        	component.find("aButton")[0].get("myButton").get("e.press").fire();
        }, function(component){
        	var btns = component.find("aButton");
            // verify underlying data change is picked up
            $A.test.assertStartsWith("isClosed-true Client", $A.util.getText(btns[3].getElement()));
            $A.test.assertStartsWith("isClosed-true Server 0", $A.util.getText(btns[0].getElement()));
        }]
    }
})<commit_msg>Tests are now working, re-enable.<commit_after>/*
 * Copyright (C) 2013 salesforce.com, inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
({
    /**
     * Verify that server created iteration components will actively respond to
     * underlying value changes on which expressions depend.
     */
    testServerItemActive: {
        test: [function(component){
            // get collection of buttons
            var btns = component.find("aButton");
            // Verify initial state of components
            $A.test.assertStartsWith("isClose-false Server 0", $A.util.getText(btns[0].getElement()));
            $A.test.assertStartsWith("isClose-false Server 1", $A.util.getText(btns[1].getElement()));
            $A.test.assertStartsWith("isClose-false Server 2", $A.util.getText(btns[2].getElement()));
            // press the first button,  changing what the expression is dependent on
        	component.find("aButton")[0].find("myButton").get("e.press").fire();
        }, function(component){
        	var btns = component.find("aButton");
            $A.test.assertStartsWith("isClosed-true Server 0", $A.util.getText(btns[0].getElement()));
        }]
    },

    /**
     * Verify that a combination of client and server iteration components will actively respond to
     * underlying value changes on which expressions depend
     */
    testClientItemActive: {
        test: [function(component){
            // add one item to iteration from client using button
            component.find("addItem").get("e.press").fire();
        }, function(component){
            // get collection of buttons
            var btns = component.find("aButton");

            // verify initial component state
            $A.test.assertStartsWith("isClose-false Client", $A.util.getText(btns[3].getElement()));
            $A.test.assertStartsWith("isClose-false Server 0", $A.util.getText(btns[0].getElement()));
            // press the first button,  changing what the expression is dependent on
        	component.find("aButton")[3].find("myButton").get("e.press").fire();
        	component.find("aButton")[0].find("myButton").get("e.press").fire();
        }, function(component){
        	var btns = component.find("aButton");
            // verify underlying data change is picked up
            $A.test.assertStartsWith("isClosed-true Client", $A.util.getText(btns[3].getElement()));
            $A.test.assertStartsWith("isClosed-true Server 0", $A.util.getText(btns[0].getElement()));
        }]
    }
})<|endoftext|>


<commit_before>{% include "api/CallPowerForm.js" with context %}

var main = function($) {
  {% if campaign.embed %}
    callPowerForm = new CallPowerForm('{{campaign.embed.get("form_sel","#call_form")}}', $);
    {% if campaign.embed.get('script_display') == 'overlay' %}
      $.getScript("{{ url_for('static', filename='embed/overlay.js', _external=True) }}");
      $('head').append('<link rel="stylesheet" href="{{ url_for("static", filename="embed/overlay.css", _external=True) }}" />');
    {% endif %}
  {% endif %}
  {# check javascript context also, in case it is defined in templates but not this campaign #}
  if (window.CallPowerOptions.scriptDisplay === 'overlay' && !$.overlay) {
    $.getScript("{{ url_for('static', filename='embed/overlay.js', _external=True) }}");
    $('head').append('<link rel="stylesheet" href="{{ url_for("static", filename="embed/overlay.css", _external=True) }}" />');
  }
}

// from substack/semver-compare
// license MIT
function versionCmp (a, b) {
    var pa = a.split('.');
    var pb = b.split('.');
    for (var i = 0; i < 3; i++) {
        var na = Number(pa[i]);
        var nb = Number(pb[i]);
        if (na > nb) return 1;
        if (nb > na) return -1;
        if (!isNaN(na) && isNaN(nb)) return 1;
        if (isNaN(na) && !isNaN(nb)) return -1;
    }
    return 0;
};

// from https://css-tricks.com/snippets/jquery/load-jquery-only-if-not-present/
function getScript(url, success) {
    var script = document.createElement('script');
    script.src = url;

    var head = document.getElementsByTagName('head')[0],
    done = false;

    // Attach handlers for all browsers
    script.onload = script.onreadystatechange = function() {
      if (!done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) {

      done = true;
      // callback function provided as param
      success();
      script.onload = script.onreadystatechange = null;
      head.removeChild(script);
    };
  };
  head.appendChild(script);
};

if (typeof window.jQuery === 'undefined') {
  // load jQuery from cloudflare
  getScript('//cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.js', function() {
    return main(jQuery);
  });
} else if (versionCmp(window.jQuery.fn.jquery, '1.7.0') < 0) {
  console.log('jQuery is really old', jQuery.fn.jquery);
  getScript('//cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js', function() {
    // make sure new version of jQuery plays nice with existing one
    jQuery.noConflict();
    return main(jQuery);
  });
} else {
  // in-page jQuery is sufficient, carry on
  jQuery(document).ready(main);
}
<commit_msg>Embed default fallback<commit_after>{% include "api/CallPowerForm.js" with context %}

var main = function($) {
  {% if campaign.embed %}
    callPowerForm = new CallPowerForm('{{campaign.embed.get("form_sel","#call_form")}}', $);
    {% if campaign.embed.get('script_display') == 'overlay' %}
      $.getScript("{{ url_for('static', filename='embed/overlay.js', _external=True) }}");
      $('head').append('<link rel="stylesheet" href="{{ url_for("static", filename="embed/overlay.css", _external=True) }}" />');
    {% endif %}
  {% else %}
    {# if embed not defined, try to attach to the first form we see #}
    callPowerForm = new CallPowerForm('form', $);
  {% endif %}
  {# check javascript context also, in case script display is defined in templates but not this campaign #}
  if (window.CallPowerOptions && window.CallPowerOptions.scriptDisplay === 'overlay' && !$.overlay) {
    $.getScript("{{ url_for('static', filename='embed/overlay.js', _external=True) }}");
    $('head').append('<link rel="stylesheet" href="{{ url_for("static", filename="embed/overlay.css", _external=True) }}" />');
  }
}

// from substack/semver-compare
// license MIT
function versionCmp (a, b) {
    var pa = a.split('.');
    var pb = b.split('.');
    for (var i = 0; i < 3; i++) {
        var na = Number(pa[i]);
        var nb = Number(pb[i]);
        if (na > nb) return 1;
        if (nb > na) return -1;
        if (!isNaN(na) && isNaN(nb)) return 1;
        if (isNaN(na) && !isNaN(nb)) return -1;
    }
    return 0;
};

// from https://css-tricks.com/snippets/jquery/load-jquery-only-if-not-present/
function getScript(url, success) {
    var script = document.createElement('script');
    script.src = url;

    var head = document.getElementsByTagName('head')[0],
    done = false;

    // Attach handlers for all browsers
    script.onload = script.onreadystatechange = function() {
      if (!done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) {

      done = true;
      // callback function provided as param
      success();
      script.onload = script.onreadystatechange = null;
      head.removeChild(script);
    };
  };
  head.appendChild(script);
};

if (typeof window.jQuery === 'undefined') {
  // load jQuery from cloudflare
  getScript('//cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.js', function() {
    return main(jQuery);
  });
} else if (versionCmp(window.jQuery.fn.jquery, '1.7.0') < 0) {
  console.log('jQuery is really old', jQuery.fn.jquery);
  getScript('//cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js', function() {
    // make sure new version of jQuery plays nice with existing one
    jQuery.noConflict();
    return main(jQuery);
  });
} else {
  // in-page jQuery is sufficient, carry on
  jQuery(document).ready(main);
}
<|endoftext|>


<commit_before>// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

window.addEventListener('DOMContentLoaded', (event) => {
  if (document.getElementById('map')) {
    createMap();
  }
});

let _map;
let _center;

/** Creates a map and adds it to the page. */
function createMap() {
  _center = new google.maps.LatLng(40.7128, -74.0060);
  _map = new google.maps.Map(document.getElementById('map'), {
    center: _center,
    zoom: 15,
    styles: [
      {elementType: 'geometry', stylers: [{color: '#242f3e'}]},
      {elementType: 'labels.text.stroke', stylers: [{color: '#242f3e'}]},
      {elementType: 'labels.text.fill', stylers: [{color: '#746855'}]},
      {
          featureType: 'administrative.locality',
          elementType: 'labels.text.fill',
          stylers: [{color: '#d59563'}]
      },
      {
          featureType: 'poi',
          elementType: 'labels.text.fill',
          stylers: [{color: '#d59563'}]
      },
      {
          featureType: 'poi.park',
          elementType: 'geometry',
          stylers: [{color: '#263c3f'}]
      },
      {
          featureType: 'poi.park',
          elementType: 'labels.text.fill',
          stylers: [{color: '#6b9a76'}]
      },
      {
          featureType: 'road',
          elementType: 'geometry',
          stylers: [{color: '#38414e'}]
      },
      {
          featureType: 'road',
          elementType: 'geometry.stroke',
          stylers: [{color: '#212a37'}]
      },
      {
          featureType: 'road',
          elementType: 'labels.text.fill',
          stylers: [{color: '#9ca5b3'}]
      },
      {
          featureType: 'road.highway',
          elementType: 'geometry',
          stylers: [{color: '#746855'}]
      },
      {
          featureType: 'road.highway',
          elementType: 'geometry.stroke',
          stylers: [{color: '#1f2835'}]
      },
      {
          featureType: 'road.highway',
          elementType: 'labels.text.fill',
          stylers: [{color: '#f3d19c'}]
      },
      {
          featureType: 'transit',
          elementType: 'geometry',
          stylers: [{color: '#2f3948'}]
      },
      {
          featureType: 'transit.station',
          elementType: 'labels.text.fill',
          stylers: [{color: '#d59563'}]
      },
      {
          featureType: 'water',
          elementType: 'geometry',
          stylers: [{color: '#17263c'}]
      },
      {
          featureType: 'water',
          elementType: 'labels.text.fill',
          stylers: [{color: '#515c6d'}]
      },
      {
          featureType: 'water',
          elementType: 'labels.text.stroke',
          stylers: [{color: '#17263c'}]
      }
    ]
  });
  getSearchResults();
}

function getSearchResults() {
  var request = {
    location: _center,
    radius: 10000,
    types: ["restaurant", "food"]
  };
  service = new google.maps.places.PlacesService(_map);
  service.nearbySearch(request, callback);
}

function callback(results, status) {
  if (status == google.maps.places.PlacesServiceStatus.OK) {
    for (var i = 0; i < results.length; i++) {
      // TODO: change condition to check if matches filter
      if (true) {
        setMarker(results[i]);
      }
    }
  }
}

function setMarker(place) {
  console.log(place);
  const marker = new google.maps.Marker({
    map: _map,
    position: place.geometry.location,
    animation: google.maps.Animation.DROP,
  });
  google.maps.event.addListener(marker, "click", () => {
    displayPanel(place.name);
  });
}

function displayPanel(name) {
  document.getElementById("map").style.width = "75%";
  document.getElementById("panel").style.display = "block";
  document.getElementById("restaurant-info").innerHTML = name;
}
<commit_msg>linked issue to todo<commit_after>// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

window.addEventListener('DOMContentLoaded', (event) => {
  if (document.getElementById('map')) {
    createMap();
  }
});

let _map;
let _center;

/** Creates a map and adds it to the page. */
function createMap() {
  _center = new google.maps.LatLng(40.7128, -74.0060);
  _map = new google.maps.Map(document.getElementById('map'), {
    center: _center,
    zoom: 15,
    styles: [
      {elementType: 'geometry', stylers: [{color: '#242f3e'}]},
      {elementType: 'labels.text.stroke', stylers: [{color: '#242f3e'}]},
      {elementType: 'labels.text.fill', stylers: [{color: '#746855'}]},
      {
          featureType: 'administrative.locality',
          elementType: 'labels.text.fill',
          stylers: [{color: '#d59563'}]
      },
      {
          featureType: 'poi',
          elementType: 'labels.text.fill',
          stylers: [{color: '#d59563'}]
      },
      {
          featureType: 'poi.park',
          elementType: 'geometry',
          stylers: [{color: '#263c3f'}]
      },
      {
          featureType: 'poi.park',
          elementType: 'labels.text.fill',
          stylers: [{color: '#6b9a76'}]
      },
      {
          featureType: 'road',
          elementType: 'geometry',
          stylers: [{color: '#38414e'}]
      },
      {
          featureType: 'road',
          elementType: 'geometry.stroke',
          stylers: [{color: '#212a37'}]
      },
      {
          featureType: 'road',
          elementType: 'labels.text.fill',
          stylers: [{color: '#9ca5b3'}]
      },
      {
          featureType: 'road.highway',
          elementType: 'geometry',
          stylers: [{color: '#746855'}]
      },
      {
          featureType: 'road.highway',
          elementType: 'geometry.stroke',
          stylers: [{color: '#1f2835'}]
      },
      {
          featureType: 'road.highway',
          elementType: 'labels.text.fill',
          stylers: [{color: '#f3d19c'}]
      },
      {
          featureType: 'transit',
          elementType: 'geometry',
          stylers: [{color: '#2f3948'}]
      },
      {
          featureType: 'transit.station',
          elementType: 'labels.text.fill',
          stylers: [{color: '#d59563'}]
      },
      {
          featureType: 'water',
          elementType: 'geometry',
          stylers: [{color: '#17263c'}]
      },
      {
          featureType: 'water',
          elementType: 'labels.text.fill',
          stylers: [{color: '#515c6d'}]
      },
      {
          featureType: 'water',
          elementType: 'labels.text.stroke',
          stylers: [{color: '#17263c'}]
      }
    ]
  });
  getSearchResults();
}

function getSearchResults() {
  var request = {
    location: _center,
    radius: 10000,
    types: ["restaurant", "food"]
  };
  service = new google.maps.places.PlacesService(_map);
  service.nearbySearch(request, callback);
}

function callback(results, status) {
  if (status == google.maps.places.PlacesServiceStatus.OK) {
    for (var i = 0; i < results.length; i++) {
      // TODO(#15): change condition to check if matches filter
      if (true) {
        setMarker(results[i]);
      }
    }
  }
}

function setMarker(place) {
  console.log(place);
  const marker = new google.maps.Marker({
    map: _map,
    position: place.geometry.location,
    animation: google.maps.Animation.DROP,
  });
  google.maps.event.addListener(marker, "click", () => {
    displayPanel(place.name);
  });
}

function displayPanel(name) {
  document.getElementById("map").style.width = "75%";
  document.getElementById("panel").style.display = "block";
  document.getElementById("restaurant-info").innerHTML = name;
}
<|endoftext|>