<commit_before>(function() {
  'use strict';

  if (self.fetch) {
    return
  }

  function normalizeName(name) {
    if (typeof name !== 'string') {
      name = name.toString();
    }
    if (/[^a-z0-9\-#$%&'*+.\^_`|~]/i.test(name)) {
      throw new TypeError('Invalid character in header field name')
    }
    return name.toLowerCase()
  }

  function normalizeValue(value) {
    if (typeof value !== 'string') {
      value = value.toString();
    }
    return value
  }

  function Headers(headers) {
    this.map = {}

    var self = this
    if (headers instanceof Headers) {
      headers.forEach(function(name, values) {
        values.forEach(function(value) {
          self.append(name, value)
        })
      })

    } else if (headers) {
      Object.getOwnPropertyNames(headers).forEach(function(name) {
        self.append(name, headers[name])
      })
    }
  }

  Headers.prototype.append = function(name, value) {
    name = normalizeName(name)
    value = normalizeValue(value)
    var list = this.map[name]
    if (!list) {
      list = []
      this.map[name] = list
    }
    list.push(value)
  }

  Headers.prototype['delete'] = function(name) {
    delete this.map[normalizeName(name)]
  }

  Headers.prototype.get = function(name) {
    var values = this.map[normalizeName(name)]
    return values ? values[0] : null
  }

  Headers.prototype.getAll = function(name) {
    return this.map[normalizeName(name)] || []
  }

  Headers.prototype.has = function(name) {
    return this.map.hasOwnProperty(normalizeName(name))
  }

  Headers.prototype.set = function(name, value) {
    this.map[normalizeName(name)] = [normalizeValue(value)]
  }

  // Instead of iterable for now.
  Headers.prototype.forEach = function(callback) {
    var self = this
    Object.getOwnPropertyNames(this.map).forEach(function(name) {
      callback(name, self.map[name])
    })
  }

  function consumed(body) {
    if (body.bodyUsed) {
      return Promise.reject(new TypeError('Already read'))
    }
    body.bodyUsed = true
  }

  function fileReaderReady(reader) {
    return new Promise(function(resolve, reject) {
      reader.onload = function() {
        resolve(reader.result)
      }
      reader.onerror = function() {
        reject(reader.error)
      }
    })
  }

  function readBlobAsArrayBuffer(blob) {
    var reader = new FileReader()
    reader.readAsArrayBuffer(blob)
    return fileReaderReady(reader)
  }

  function readBlobAsText(blob) {
    var reader = new FileReader()
    reader.readAsText(blob)
    return fileReaderReady(reader)
  }

  var support = {
    blob: 'FileReader' in self && 'Blob' in self && (function() {
      try {
        new Blob();
        return true
      } catch(e) {
        return false
      }
    })(),
    formData: 'FormData' in self
  }

  function Body() {
    this.bodyUsed = false

    if (support.blob) {
      this._initBody = function(body) {
        this._bodyInit = body
        if (typeof body === 'string') {
          this._bodyText = body
        } else if (support.blob && Blob.prototype.isPrototypeOf(body)) {
          this._bodyBlob = body
        } else if (support.formData && FormData.prototype.isPrototypeOf(body)) {
          this._bodyFormData = body
        } else if (!body) {
          this._bodyText = ''
        } else {
          throw new Error('unsupported BodyInit type')
        }
      }

      this.blob = function() {
        var rejected = consumed(this)
        if (rejected) {
          return rejected
        }

        if (this._bodyBlob) {
          return Promise.resolve(this._bodyBlob)
        } else if (this._bodyFormData) {
          throw new Error('could not read FormData body as blob')
        } else {
          return Promise.resolve(new Blob([this._bodyText]))
        }
      }

      this.arrayBuffer = function() {
        return this.blob().then(readBlobAsArrayBuffer)
      }

      this.text = function() {
        var rejected = consumed(this)
        if (rejected) {
          return rejected
        }

        if (this._bodyBlob) {
          return readBlobAsText(this._bodyBlob)
        } else if (this._bodyFormData) {
          throw new Error('could not read FormData body as text')
        } else {
          return Promise.resolve(this._bodyText)
        }
      }
    } else {
      this._initBody = function(body) {
        this._bodyInit = body
        if (typeof body === 'string') {
          this._bodyText = body
        } else if (support.formData && FormData.prototype.isPrototypeOf(body)) {
          this._bodyFormData = body
        } else if (!body) {
          this._bodyText = ''
        } else {
          throw new Error('unsupported BodyInit type')
        }
      }

      this.text = function() {
        var rejected = consumed(this)
        return rejected ? rejected : Promise.resolve(this._bodyText)
      }
    }

    if (support.formData) {
      this.formData = function() {
        return this.text().then(decode)
      }
    }

    this.json = function() {
      return this.text().then(JSON.parse)
    }

    return this
  }

  // HTTP methods whose capitalization should be normalized
  var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']

  function normalizeMethod(method) {
    var upcased = method.toUpperCase()
    return (methods.indexOf(upcased) > -1) ? upcased : method
  }

  function Request(url, options) {
    options = options || {}
    this.url = url

    this.credentials = options.credentials || 'omit'
    this.headers = new Headers(options.headers)
    this.method = normalizeMethod(options.method || 'GET')
    this.mode = options.mode || null
    this.referrer = null

    if ((this.method === 'GET' || this.method === 'HEAD') && options.body) {
      throw new TypeError('Body not allowed for GET or HEAD requests')
    }
    this._initBody(options.body)
  }

  function decode(body) {
    var form = new FormData()
    body.trim().split('&').forEach(function(bytes) {
      if (bytes) {
        var split = bytes.split('=')
        var name = split.shift().replace(/\+/g, ' ')
        var value = split.join('=').replace(/\+/g, ' ')
        form.append(decodeURIComponent(name), decodeURIComponent(value))
      }
    })
    return form
  }

  function headers(xhr) {
    var head = new Headers()
    var pairs = xhr.getAllResponseHeaders().trim().split('\n')
    pairs.forEach(function(header) {
      var split = header.trim().split(':')
      var key = split.shift().trim()
      var value = split.join(':').trim()
      head.append(key, value)
    })
    return head
  }

  var noXhrPatch =
    typeof window !== 'undefined' && !!window.ActiveXObject &&
      !(window.XMLHttpRequest && (new XMLHttpRequest).dispatchEvent);

  Request.prototype.getXhr = function () {
    // from backbone.js 1.1.2
    // https://github.com/jashkenas/backbone/blob/1.1.2/backbone.js#L1181
    if (noXhrPatch && !(/^(get|post|head|put|delete|options)$/i.test(this.method))) {
      this.usingActiveXhr = true;
      return new ActiveXObject("Microsoft.XMLHTTP");
    }
    return new XMLHttpRequest();
  }

  Request.prototype.fetch = function() {
    var self = this

    return new Promise(function(resolve, reject) {
      var xhr = self.getXhr();
      if (self.credentials === 'cors') {
        xhr.withCredentials = true;
      }

      function responseURL() {
        if ('responseURL' in xhr) {
          return xhr.responseURL
        }

        // Avoid security warnings on getResponseHeader when not allowed by CORS
        if (/^X-Request-URL:/m.test(xhr.getAllResponseHeaders())) {
          return xhr.getResponseHeader('X-Request-URL')
        }

        return;
      }

      function onload() {
        if (xhr.readyState !== 4) {
          return
        }
        var status = (xhr.status === 1223) ? 204 : xhr.status
        if (status < 100 || status > 599) {
          reject(new TypeError('Network request failed'))
          return
        }
        var options = {
          status: status,
          statusText: xhr.statusText,
          headers: headers(xhr),
          url: responseURL()
        }
        var body = 'response' in xhr ? xhr.response : xhr.responseText;
        resolve(new Response(body, options))
      }
      xhr.onreadystatechange = onload;
      if (!self.usingActiveXhr) {
        xhr.onload = onload;
        xhr.onerror = function() {
          reject(new TypeError('Network request failed'))
        }
      }

      xhr.open(self.method, self.url, true)

      if ('responseType' in xhr && support.blob) {
        xhr.responseType = 'blob'
      }

      self.headers.forEach(function(name, values) {
        values.forEach(function(value) {
          xhr.setRequestHeader(name, value)
        })
      })

      xhr.send(typeof self._bodyInit === 'undefined' ? null : self._bodyInit)
    })
  }

  Body.call(Request.prototype)

  function Response(bodyInit, options) {
    if (!options) {
      options = {}
    }

    this._initBody(bodyInit)
    this.type = 'default'
    this.url = null
    this.status = options.status
    this.ok = this.status >= 200 && this.status < 300
    this.statusText = options.statusText
    this.headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers)
    this.url = options.url || ''
  }

  Body.call(Response.prototype)

  self.Headers = Headers;
  self.Request = Request;
  self.Response = Response;

  self.fetch = function (url, options) {
    return new Request(url, options).fetch()
  }
  self.fetch.polyfill = true
})();
<commit_msg>wrap JSON.parse to pass tests in Firefox 37<commit_after>(function() {
  'use strict';

  if (self.fetch) {
    return
  }

  function normalizeName(name) {
    if (typeof name !== 'string') {
      name = name.toString();
    }
    if (/[^a-z0-9\-#$%&'*+.\^_`|~]/i.test(name)) {
      throw new TypeError('Invalid character in header field name')
    }
    return name.toLowerCase()
  }

  function normalizeValue(value) {
    if (typeof value !== 'string') {
      value = value.toString();
    }
    return value
  }

  function Headers(headers) {
    this.map = {}

    var self = this
    if (headers instanceof Headers) {
      headers.forEach(function(name, values) {
        values.forEach(function(value) {
          self.append(name, value)
        })
      })

    } else if (headers) {
      Object.getOwnPropertyNames(headers).forEach(function(name) {
        self.append(name, headers[name])
      })
    }
  }

  Headers.prototype.append = function(name, value) {
    name = normalizeName(name)
    value = normalizeValue(value)
    var list = this.map[name]
    if (!list) {
      list = []
      this.map[name] = list
    }
    list.push(value)
  }

  Headers.prototype['delete'] = function(name) {
    delete this.map[normalizeName(name)]
  }

  Headers.prototype.get = function(name) {
    var values = this.map[normalizeName(name)]
    return values ? values[0] : null
  }

  Headers.prototype.getAll = function(name) {
    return this.map[normalizeName(name)] || []
  }

  Headers.prototype.has = function(name) {
    return this.map.hasOwnProperty(normalizeName(name))
  }

  Headers.prototype.set = function(name, value) {
    this.map[normalizeName(name)] = [normalizeValue(value)]
  }

  // Instead of iterable for now.
  Headers.prototype.forEach = function(callback) {
    var self = this
    Object.getOwnPropertyNames(this.map).forEach(function(name) {
      callback(name, self.map[name])
    })
  }

  function consumed(body) {
    if (body.bodyUsed) {
      return Promise.reject(new TypeError('Already read'))
    }
    body.bodyUsed = true
  }

  function fileReaderReady(reader) {
    return new Promise(function(resolve, reject) {
      reader.onload = function() {
        resolve(reader.result)
      }
      reader.onerror = function() {
        reject(reader.error)
      }
    })
  }

  function readBlobAsArrayBuffer(blob) {
    var reader = new FileReader()
    reader.readAsArrayBuffer(blob)
    return fileReaderReady(reader)
  }

  function readBlobAsText(blob) {
    var reader = new FileReader()
    reader.readAsText(blob)
    return fileReaderReady(reader)
  }

  var support = {
    blob: 'FileReader' in self && 'Blob' in self && (function() {
      try {
        new Blob();
        return true
      } catch(e) {
        return false
      }
    })(),
    formData: 'FormData' in self
  }

  function Body() {
    this.bodyUsed = false

    if (support.blob) {
      this._initBody = function(body) {
        this._bodyInit = body
        if (typeof body === 'string') {
          this._bodyText = body
        } else if (support.blob && Blob.prototype.isPrototypeOf(body)) {
          this._bodyBlob = body
        } else if (support.formData && FormData.prototype.isPrototypeOf(body)) {
          this._bodyFormData = body
        } else if (!body) {
          this._bodyText = ''
        } else {
          throw new Error('unsupported BodyInit type')
        }
      }

      this.blob = function() {
        var rejected = consumed(this)
        if (rejected) {
          return rejected
        }

        if (this._bodyBlob) {
          return Promise.resolve(this._bodyBlob)
        } else if (this._bodyFormData) {
          throw new Error('could not read FormData body as blob')
        } else {
          return Promise.resolve(new Blob([this._bodyText]))
        }
      }

      this.arrayBuffer = function() {
        return this.blob().then(readBlobAsArrayBuffer)
      }

      this.text = function() {
        var rejected = consumed(this)
        if (rejected) {
          return rejected
        }

        if (this._bodyBlob) {
          return readBlobAsText(this._bodyBlob)
        } else if (this._bodyFormData) {
          throw new Error('could not read FormData body as text')
        } else {
          return Promise.resolve(this._bodyText)
        }
      }
    } else {
      this._initBody = function(body) {
        this._bodyInit = body
        if (typeof body === 'string') {
          this._bodyText = body
        } else if (support.formData && FormData.prototype.isPrototypeOf(body)) {
          this._bodyFormData = body
        } else if (!body) {
          this._bodyText = ''
        } else {
          throw new Error('unsupported BodyInit type')
        }
      }

      this.text = function() {
        var rejected = consumed(this)
        return rejected ? rejected : Promise.resolve(this._bodyText)
      }
    }

    if (support.formData) {
      this.formData = function() {
        return this.text().then(decode)
      }
    }

    this.json = function() {
      return this.text().then(function (text) {
          return JSON.parse(text);
      });
    }

    return this
  }

  // HTTP methods whose capitalization should be normalized
  var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']

  function normalizeMethod(method) {
    var upcased = method.toUpperCase()
    return (methods.indexOf(upcased) > -1) ? upcased : method
  }

  function Request(url, options) {
    options = options || {}
    this.url = url

    this.credentials = options.credentials || 'omit'
    this.headers = new Headers(options.headers)
    this.method = normalizeMethod(options.method || 'GET')
    this.mode = options.mode || null
    this.referrer = null

    if ((this.method === 'GET' || this.method === 'HEAD') && options.body) {
      throw new TypeError('Body not allowed for GET or HEAD requests')
    }
    this._initBody(options.body)
  }

  function decode(body) {
    var form = new FormData()
    body.trim().split('&').forEach(function(bytes) {
      if (bytes) {
        var split = bytes.split('=')
        var name = split.shift().replace(/\+/g, ' ')
        var value = split.join('=').replace(/\+/g, ' ')
        form.append(decodeURIComponent(name), decodeURIComponent(value))
      }
    })
    return form
  }

  function headers(xhr) {
    var head = new Headers()
    var pairs = xhr.getAllResponseHeaders().trim().split('\n')
    pairs.forEach(function(header) {
      var split = header.trim().split(':')
      var key = split.shift().trim()
      var value = split.join(':').trim()
      head.append(key, value)
    })
    return head
  }

  var noXhrPatch =
    typeof window !== 'undefined' && !!window.ActiveXObject &&
      !(window.XMLHttpRequest && (new XMLHttpRequest).dispatchEvent);

  Request.prototype.getXhr = function () {
    // from backbone.js 1.1.2
    // https://github.com/jashkenas/backbone/blob/1.1.2/backbone.js#L1181
    if (noXhrPatch && !(/^(get|post|head|put|delete|options)$/i.test(this.method))) {
      this.usingActiveXhr = true;
      return new ActiveXObject("Microsoft.XMLHTTP");
    }
    return new XMLHttpRequest();
  }

  Request.prototype.fetch = function() {
    var self = this

    return new Promise(function(resolve, reject) {
      var xhr = self.getXhr();
      if (self.credentials === 'cors') {
        xhr.withCredentials = true;
      }

      function responseURL() {
        if ('responseURL' in xhr) {
          return xhr.responseURL
        }

        // Avoid security warnings on getResponseHeader when not allowed by CORS
        if (/^X-Request-URL:/m.test(xhr.getAllResponseHeaders())) {
          return xhr.getResponseHeader('X-Request-URL')
        }

        return;
      }

      function onload() {
        if (xhr.readyState !== 4) {
          return
        }
        var status = (xhr.status === 1223) ? 204 : xhr.status
        if (status < 100 || status > 599) {
          reject(new TypeError('Network request failed'))
          return
        }
        var options = {
          status: status,
          statusText: xhr.statusText,
          headers: headers(xhr),
          url: responseURL()
        }
        var body = 'response' in xhr ? xhr.response : xhr.responseText;
        resolve(new Response(body, options))
      }
      xhr.onreadystatechange = onload;
      if (!self.usingActiveXhr) {
        xhr.onload = onload;
        xhr.onerror = function() {
          reject(new TypeError('Network request failed'))
        }
      }

      xhr.open(self.method, self.url, true)

      if ('responseType' in xhr && support.blob) {
        xhr.responseType = 'blob'
      }

      self.headers.forEach(function(name, values) {
        values.forEach(function(value) {
          xhr.setRequestHeader(name, value)
        })
      })

      xhr.send(typeof self._bodyInit === 'undefined' ? null : self._bodyInit)
    })
  }

  Body.call(Request.prototype)

  function Response(bodyInit, options) {
    if (!options) {
      options = {}
    }

    this._initBody(bodyInit)
    this.type = 'default'
    this.url = null
    this.status = options.status
    this.ok = this.status >= 200 && this.status < 300
    this.statusText = options.statusText
    this.headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers)
    this.url = options.url || ''
  }

  Body.call(Response.prototype)

  self.Headers = Headers;
  self.Request = Request;
  self.Response = Response;

  self.fetch = function (url, options) {
    return new Request(url, options).fetch()
  }
  self.fetch.polyfill = true
})();
<|endoftext|>


<commit_before>'use strict';

// MODULES //

var betaln = require( '@stdlib/math/base/special/betaln');
var isnan = require( '@stdlib/math/base/utils/is-nan' );
var log1p = require( '@stdlib/math/base/special/log1p' );
var exp = require( '@stdlib/math/base/special/exp' );
var ln = require( '@stdlib/math/base/special/ln' );
var PINF = require( '@stdlib/math/constants/float64-pinf' );
var nan = require( './nan.js' );

// MAIN //

/**
* Returns a function for evaluating the probability density function (PDF) for a beta distribution with first shape parameter `alpha` and second shape parameter `beta`
*
* @param {PositiveNumber} alpha - first shape parameter
* @param {PositiveNumber} beta - second shape parameter
* @returns {Function} PDF
*
* @example
* var mypdf = factory( 0.5, 0.5 );
*
* var y = mypdf( 0.8 );
* // returns ~0.796
*
* y = mypdf( 0.3 );
* // returns ~0.695
*/
function factory( alpha, beta ) {
	var betalnAB;
	if ( isnan( alpha ) || isnan( beta ) ) {
		return nan;
	}
	if ( alpha <= 0.0 || beta <= 0.0 ) {
		return nan;
	}
	betalnAB = betaln( alpha, beta );
	return pdf;

	/**
	* Evaluates the probability density function (PDF) for a beta distribution.
	*
	* @private
	* @param {number} x - input value
	* @returns {number} evaluated PDF
	*
	* @example
	* var y = pdf( 0.3 );
	* // returns <number>
	*/
	function pdf( x ) {
		var lnl;
		if ( isnan( x ) ) {
			return NaN;
		}
		if ( x < 0.0 || x > 1.0 ) {
			// Support of the Beta distribution: [0,1]
			return 0.0;
		}
		else if ( x === 0.0 ) {
			if ( alpha < 1.0 ) {
				return PINF;
			}
			else if ( alpha > 1.0 ) {
				return 0.0;
			}
			return beta;
		}
		else if ( x === 1.0 ) {
			if ( beta < 1.0 ) {
				return PINF;
			}
			else if ( beta > 1.0 ) {
				return 0.0;
			}
			return alpha;
		}
		lnl = -betalnAB;
		lnl += ( alpha - 1.0 ) * ln( x );
		lnl += ( beta - 1.0 ) * log1p( -x );
		return exp( lnl );
	} // end FUNCTION pdf()
} // end FUNCTION factory()

// EXPORTS //

module.exports = factory;
<commit_msg>Add missing period<commit_after>'use strict';

// MODULES //

var betaln = require( '@stdlib/math/base/special/betaln');
var isnan = require( '@stdlib/math/base/utils/is-nan' );
var log1p = require( '@stdlib/math/base/special/log1p' );
var exp = require( '@stdlib/math/base/special/exp' );
var ln = require( '@stdlib/math/base/special/ln' );
var PINF = require( '@stdlib/math/constants/float64-pinf' );
var nan = require( './nan.js' );

// MAIN //

/**
* Returns a function for evaluating the probability density function (PDF) for a beta distribution with first shape parameter `alpha` and second shape parameter `beta`.
*
* @param {PositiveNumber} alpha - first shape parameter
* @param {PositiveNumber} beta - second shape parameter
* @returns {Function} PDF
*
* @example
* var mypdf = factory( 0.5, 0.5 );
*
* var y = mypdf( 0.8 );
* // returns ~0.796
*
* y = mypdf( 0.3 );
* // returns ~0.695
*/
function factory( alpha, beta ) {
	var betalnAB;
	if ( isnan( alpha ) || isnan( beta ) ) {
		return nan;
	}
	if ( alpha <= 0.0 || beta <= 0.0 ) {
		return nan;
	}
	betalnAB = betaln( alpha, beta );
	return pdf;

	/**
	* Evaluates the probability density function (PDF) for a beta distribution.
	*
	* @private
	* @param {number} x - input value
	* @returns {number} evaluated PDF
	*
	* @example
	* var y = pdf( 0.3 );
	* // returns <number>
	*/
	function pdf( x ) {
		var lnl;
		if ( isnan( x ) ) {
			return NaN;
		}
		if ( x < 0.0 || x > 1.0 ) {
			// Support of the Beta distribution: [0,1]
			return 0.0;
		}
		else if ( x === 0.0 ) {
			if ( alpha < 1.0 ) {
				return PINF;
			}
			else if ( alpha > 1.0 ) {
				return 0.0;
			}
			return beta;
		}
		else if ( x === 1.0 ) {
			if ( beta < 1.0 ) {
				return PINF;
			}
			else if ( beta > 1.0 ) {
				return 0.0;
			}
			return alpha;
		}
		lnl = -betalnAB;
		lnl += ( alpha - 1.0 ) * ln( x );
		lnl += ( beta - 1.0 ) * log1p( -x );
		return exp( lnl );
	} // end FUNCTION pdf()
} // end FUNCTION factory()

// EXPORTS //

module.exports = factory;
<|endoftext|>


<commit_before>/**
 * Copyright 2014 aixigo AG
 * Released under the MIT license.
 * http://laxarjs.org/license
 */
define( [
   '../widget_adapters/angular_adapter',
   'angular',
   'angular-mocks',
   '../../../testing/portal_mocks',
   '../features_provider',
   '../../paths',
   './data/widget_data'
], function( angularWidgetAdapterModule, ng, ngMocks, portalMocks, features, paths, widgetData ) {
   'use strict';

   paths.WIDGETS = 'the_widgets';
   paths.THEMES = 'the_themes';

   var defaultCssAssetPath_ = 'the_themes/blue.theme/test/test_widget/css/test_widget.css';
   var themeCssAssetPath_ = 'the_themes/blue.theme/test/test_widget/css/test_widget.css';
   var htmlAssetPath_ = 'the_widgets/test/test_widget/default.theme/test_widget.html';
   var assets = {};
   assets[ themeCssAssetPath_ ] = 'h1 { color: blue }';
   assets[ defaultCssAssetPath_ ] = 'h1 { color: #ccc }';
   assets[ htmlAssetPath_ ] = '
hello there
';

   var widgetSpec_;
   var widgetConfiguration_;
   var widgetFeatures_;
   var widgetLoaderConfiguration_;
   var anchor_;

   var q_;
   var fileResourceProvider_;
   var widgetServices_;
   var fakeControllerScope_ = {};

   beforeEach( function() {

      widgetSpec_ = widgetData.specification;
      widgetConfiguration_ = widgetData.configuration;

      function throwError( msg ) { throw new Error( msg ); }
      widgetFeatures_ = features.featuresForWidget( widgetSpec_, widgetConfiguration_, throwError );

      widgetLoaderConfiguration_ = {
         theme: 'blue',
         'anchorScope': {
            '$new': jasmine.createSpy( 'anchorScope.$new' ).andCallFake( function() {
               return fakeControllerScope_;
            } )
         }
      };

      anchor_ = document.createElement( 'DIV' );

      q_ = portalMocks.mockQ();

      fileResourceProvider_ = portalMocks.mockFileResourceProvider( assets );

      widgetServices_ = {
         idGenerator: function() { return 'fake-id'; },
         eventBus: portalMocks.mockEventBus(),
         release: jasmine.createSpy( 'widgetServices.release' )
      };
   } );

   ///////////////////////////////////////////////////////////////////////////////////////////////////////////

   describe( 'An angular widget adapter module', function() {

      it( 'provides an AngularJS module representation', function() {
         expect( angularWidgetAdapterModule.module ).toBeDefined();
         expect( angularWidgetAdapterModule.module.name ).toBeDefined();
         expect( angularWidgetAdapterModule.create ).toBeDefined();
         expect( angularWidgetAdapterModule.create ).toEqual( jasmine.any( Function ) );
      } );

      ////////////////////////////////////////////////////////////////////////////////////////////////////////

      it( 'fails to create an adapter with missing dependencies', function() {
         var adapter = null;
         expect( function() {
            adapter = angularWidgetAdapterModule.create();
         } ).toThrow();
      } );

      ////////////////////////////////////////////////////////////////////////////////////////////////////////

      it( 'allows to create an adapter from dependencies', function() {
         var adapter = null;
         expect( function() {
            adapter = angularWidgetAdapterModule.create(
               q_, fileResourceProvider_, widgetSpec_, widgetFeatures_, widgetConfiguration_, anchor_
            );
         } ).not.toThrow();
         expect( adapter ).not.toBe( null );
         expect( adapter.createController ).toBeDefined();
      } );

   } );

   ///////////////////////////////////////////////////////////////////////////////////////////////////////////

   describe( 'An angular widget adapter', function() {

      var adapter_;
      var controllerScope_;
      var mockThemeManager_;
      var mockCssLoader_;

      var Controller_ = function( $scope ) {
         controllerScope_ = $scope;
      };

      // This mock will provide the non-themed HTML and the themed CSS.
      function mockThemeManager() {
         var provideSpy = jasmine.createSpy( 'urlProvider.provide' ).andCallFake( function( paths ) {
            var results = {};
            results[ 'test_widget.html' ] = htmlAssetPath_;
            results[ 'css/test_widget.css' ] = themeCssAssetPath_;
            return q_.when( paths.map( function( _ ) { return results[ _ ]; } ) );
         } );

         var urlProviderSpy = jasmine.createSpy( 'themeManager.urlProvider' ).andCallFake( function() {
            return {
               provide: provideSpy
            };
         } );

         return {
            urlProvider: urlProviderSpy
         };
      }

      function mockCssLoader() {
         return {
            load: jasmine.createSpy( 'cssLoader.load' )
         };
      }

      beforeEach( function() {
         // widgets.test.test_widget.Controller
         var widgetModule = ng.module( 'widgets.test.test_widget', [] );
         widgetModule.controller( 'widgets.test.test_widget.Controller', Controller_ );
         ngMocks.module( 'widgets.test.test_widget' );
         ngMocks.module( 'laxar.portal.angular_adapter' );
         ngMocks.module( function( $provide ) {
            mockThemeManager_ = mockThemeManager();
            $provide.service( 'ThemeManager', function() {
               return mockThemeManager_;
            } );
            mockCssLoader_ = mockCssLoader();
            $provide.service( 'CssLoader', function() {
               return mockCssLoader_;
            } );
         } );

         ngMocks.inject( function() {
            adapter_ = angularWidgetAdapterModule.create(
               q_, fileResourceProvider_, widgetSpec_, widgetFeatures_, widgetConfiguration_, anchor_
            );
         } );
      } );

      ////////////////////////////////////////////////////////////////////////////////////////////////////////

      describe( 'asked to instantiate a widget controller', function() {

         beforeEach( function() {
            adapter_.createController( widgetServices_, widgetLoaderConfiguration_ );
         } );

         /////////////////////////////////////////////////////////////////////////////////////////////////////

         it( 'instantiates the widget controller', function() {
            expect( controllerScope_ ).toEqual( fakeControllerScope_ );
            expect( controllerScope_.features ).toEqual( widgetFeatures_ );
         } );

      } );

      ////////////////////////////////////////////////////////////////////////////////////////////////////////

      describe( 'asked to prepare its DOM representation', function() {

         var resolveSpy = jasmine.createSpy( 'resolveSpy' );
         var rejectSpy = jasmine.createSpy( 'rejectSpy' );
         var promise_;

         beforeEach( function() {
            adapter_.createController( widgetServices_, widgetLoaderConfiguration_ );
            promise_ = adapter_.domPrepare().then( resolveSpy, rejectSpy );
            jasmine.Clock.tick( 0 );
         } );

         /////////////////////////////////////////////////////////////////////////////////////////////////////

         it( 'uses the correct search paths to resolve assets', function() {
            expect( promise_ ).toBeDefined();
            expect( mockThemeManager_.urlProvider ).toHaveBeenCalledWith(
               'the_themes/[theme]/widgets/test/test_widget',
               'the_widgets/test/test_widget/[theme]'
            );
         } );

         /////////////////////////////////////////////////////////////////////////////////////////////////////

         it( 'correctly resolves the CSS and HTML assets', function() {
            expect( promise_ ).toBeDefined();
            expect( mockThemeManager_.urlProvider().provide ).toHaveBeenCalled();
            expect( fileResourceProvider_.provide ).toHaveBeenCalledWith( htmlAssetPath_ );
            expect( mockCssLoader_.load ).toHaveBeenCalledWith( defaultCssAssetPath_ );

            expect( rejectSpy ).not.toHaveBeenCalled();
            expect( resolveSpy ).toHaveBeenCalled();
         } );

         /////////////////////////////////////////////////////////////////////////////////////////////////////

         it( 'fills its anchor dom node', function() {
            expect( anchor_.innerHTML.toLowerCase() ).toEqual( assets[ htmlAssetPath_ ] );
         } );

      } );

      ////////////////////////////////////////////////////////////////////////////////////////////////////////

      describe( 'asked to attach its DOM representation', function() {

         var mockAreaNode_;

         var elementThatWasAttached_;

         var resolveSpy = jasmine.createSpy( 'resolveSpy' ).andCallFake( function() {
            adapter_.domAttachTo( {
               appendChild: function( node ) {
               elementThatWasAttached_ = node;
            }
            } );
         } );
         var rejectSpy = jasmine.createSpy( 'rejectSpy' );
         var promise_;

         beforeEach( function() {
            mockAreaNode_= document.createElement( 'DIV' );
            adapter_.createController( widgetServices_, widgetLoaderConfiguration_ );
            promise_ = adapter_.domPrepare().then( function() {
               adapter_.domAttachTo( mockAreaNode_ );
            } );
            jasmine.Clock.tick( 0 );
         } );

         /////////////////////////////////////////////////////////////////////////////////////////////////////

         it( 'attaches its representation to the given widget area', function() {
            expect( mockAreaNode_.children.length ).toBe( 1 );
            expect( mockAreaNode_.children[ 0 ] ).toBe( anchor_ );
            // anchor class is (mostly) managed externally
            expect( anchor_.className ).toEqual( 'ng-scope' );
         } );

         /////////////////////////////////////////////////////////////////////////////////////////////////////

         describe( 'and then to detach it again', function() {

            beforeEach( function() {
               fakeControllerScope_.$destroy = jasmine.createSpy( '$destroy' );
               adapter_.domDetach();
            } );

            //////////////////////////////////////////////////////////////////////////////////////////////////

            it( 'detaches its dom node from the widget area', function() {
               expect( mockAreaNode_.children.length ).toBe( 0 );
            } );

            //////////////////////////////////////////////////////////////////////////////////////////////////

            it( 'retains its widget services and scope', function() {
               expect( widgetServices_.release ).not.toHaveBeenCalled();
               expect( fakeControllerScope_.$destroy ).not.toHaveBeenCalled();
            } );

         } );

         /////////////////////////////////////////////////////////////////////////////////////////////////////

         describe( 'and then to destroy itself', function() {

            beforeEach( function() {
               fakeControllerScope_.$destroy = jasmine.createSpy( '$destroy' );
               adapter_.destroy();
            } );

            //////////////////////////////////////////////////////////////////////////////////////////////////

            it( 'destroys the corresponding angular scope', function() {
               expect( fakeControllerScope_.$destroy ).toHaveBeenCalled();
            } );

            //////////////////////////////////////////////////////////////////////////////////////////////////

            it( 'releases its widget services', function() {
               adapter_.destroy();
               expect( widgetServices_.release ).toHaveBeenCalled();
            } );

         } );

      } );

   } );

} );<commit_msg>(#91) portal: make sure that widget DOM is attached when linking: specs<commit_after>/**
 * Copyright 2014 aixigo AG
 * Released under the MIT license.
 * http://laxarjs.org/license
 */
define( [
   '../widget_adapters/angular_adapter',
   'angular',
   'angular-mocks',
   '../../../testing/portal_mocks',
   '../features_provider',
   '../../paths',
   './data/widget_data'
], function( angularWidgetAdapterModule, ng, ngMocks, portalMocks, features, paths, widgetData ) {
   'use strict';

   paths.WIDGETS = 'the_widgets';
   paths.THEMES = 'the_themes';

   var defaultCssAssetPath_ = 'the_themes/blue.theme/test/test_widget/css/test_widget.css';
   var themeCssAssetPath_ = 'the_themes/blue.theme/test/test_widget/css/test_widget.css';
   var htmlAssetPath_ = 'the_widgets/test/test_widget/default.theme/test_widget.html';
   var assets = {};
   assets[ themeCssAssetPath_ ] = 'h1 { color: blue }';
   assets[ defaultCssAssetPath_ ] = 'h1 { color: #ccc }';
   assets[ htmlAssetPath_ ] = '
hello there
';

   var widgetSpec_;
   var widgetConfiguration_;
   var widgetFeatures_;
   var widgetLoaderConfiguration_;
   var anchor_;

   var q_;
   var fileResourceProvider_;
   var widgetServices_;
   var fakeControllerScope_ = {};

   beforeEach( function() {

      widgetSpec_ = widgetData.specification;
      widgetConfiguration_ = widgetData.configuration;

      function throwError( msg ) { throw new Error( msg ); }
      widgetFeatures_ = features.featuresForWidget( widgetSpec_, widgetConfiguration_, throwError );

      widgetLoaderConfiguration_ = {
         theme: 'blue',
         'anchorScope': {
            '$new': jasmine.createSpy( 'anchorScope.$new' ).andCallFake( function() {
               return fakeControllerScope_;
            } )
         }
      };

      anchor_ = document.createElement( 'DIV' );

      q_ = portalMocks.mockQ();

      fileResourceProvider_ = portalMocks.mockFileResourceProvider( assets );

      widgetServices_ = {
         idGenerator: function() { return 'fake-id'; },
         eventBus: portalMocks.mockEventBus(),
         release: jasmine.createSpy( 'widgetServices.release' )
      };
   } );

   ///////////////////////////////////////////////////////////////////////////////////////////////////////////

   describe( 'An angular widget adapter module', function() {

      it( 'provides an AngularJS module representation', function() {
         expect( angularWidgetAdapterModule.module ).toBeDefined();
         expect( angularWidgetAdapterModule.module.name ).toBeDefined();
         expect( angularWidgetAdapterModule.create ).toBeDefined();
         expect( angularWidgetAdapterModule.create ).toEqual( jasmine.any( Function ) );
      } );

      ////////////////////////////////////////////////////////////////////////////////////////////////////////

      it( 'fails to create an adapter with missing dependencies', function() {
         var adapter = null;
         expect( function() {
            adapter = angularWidgetAdapterModule.create();
         } ).toThrow();
      } );

      ////////////////////////////////////////////////////////////////////////////////////////////////////////

      it( 'allows to create an adapter from dependencies', function() {
         var adapter = null;
         expect( function() {
            adapter = angularWidgetAdapterModule.create(
               q_, fileResourceProvider_, widgetSpec_, widgetFeatures_, widgetConfiguration_, anchor_
            );
         } ).not.toThrow();
         expect( adapter ).not.toBe( null );
         expect( adapter.createController ).toBeDefined();
      } );

   } );

   ///////////////////////////////////////////////////////////////////////////////////////////////////////////

   describe( 'An angular widget adapter', function() {

      var adapter_;
      var controllerScope_;
      var mockThemeManager_;
      var mockCssLoader_;

      var Controller_ = function( $scope ) {
         controllerScope_ = $scope;
      };

      // This mock will provide the non-themed HTML and the themed CSS.
      function mockThemeManager() {
         var provideSpy = jasmine.createSpy( 'urlProvider.provide' ).andCallFake( function( paths ) {
            var results = {};
            results[ 'test_widget.html' ] = htmlAssetPath_;
            results[ 'css/test_widget.css' ] = themeCssAssetPath_;
            return q_.when( paths.map( function( _ ) { return results[ _ ]; } ) );
         } );

         var urlProviderSpy = jasmine.createSpy( 'themeManager.urlProvider' ).andCallFake( function() {
            return {
               provide: provideSpy
            };
         } );

         return {
            urlProvider: urlProviderSpy
         };
      }

      function mockCssLoader() {
         return {
            load: jasmine.createSpy( 'cssLoader.load' )
         };
      }

      beforeEach( function() {
         // widgets.test.test_widget.Controller
         var widgetModule = ng.module( 'widgets.test.test_widget', [] );
         widgetModule.controller( 'widgets.test.test_widget.Controller', Controller_ );
         ngMocks.module( 'widgets.test.test_widget' );
         ngMocks.module( 'laxar.portal.angular_adapter' );
         ngMocks.module( function( $provide ) {
            mockThemeManager_ = mockThemeManager();
            $provide.service( 'ThemeManager', function() {
               return mockThemeManager_;
            } );
            mockCssLoader_ = mockCssLoader();
            $provide.service( 'CssLoader', function() {
               return mockCssLoader_;
            } );
         } );

         ngMocks.inject( function() {
            adapter_ = angularWidgetAdapterModule.create(
               q_, fileResourceProvider_, widgetSpec_, widgetFeatures_, widgetConfiguration_, anchor_
            );
         } );
      } );

      ////////////////////////////////////////////////////////////////////////////////////////////////////////

      describe( 'asked to instantiate a widget controller', function() {

         beforeEach( function() {
            adapter_.createController( widgetServices_, widgetLoaderConfiguration_ );
         } );

         /////////////////////////////////////////////////////////////////////////////////////////////////////

         it( 'instantiates the widget controller', function() {
            expect( controllerScope_ ).toEqual( fakeControllerScope_ );
            expect( controllerScope_.features ).toEqual( widgetFeatures_ );
         } );

      } );

      ////////////////////////////////////////////////////////////////////////////////////////////////////////

      describe( 'asked to prepare its DOM representation', function() {

         var resolveSpy = jasmine.createSpy( 'resolveSpy' );
         var rejectSpy = jasmine.createSpy( 'rejectSpy' );
         var promise_;

         beforeEach( function() {
            adapter_.createController( widgetServices_, widgetLoaderConfiguration_ );
            promise_ = adapter_.domPrepare().then( resolveSpy, rejectSpy );
            jasmine.Clock.tick( 0 );
         } );

         /////////////////////////////////////////////////////////////////////////////////////////////////////

         it( 'uses the correct search paths to resolve assets', function() {
            expect( promise_ ).toBeDefined();
            expect( mockThemeManager_.urlProvider ).toHaveBeenCalledWith(
               'the_themes/[theme]/widgets/test/test_widget',
               'the_widgets/test/test_widget/[theme]'
            );
         } );

         /////////////////////////////////////////////////////////////////////////////////////////////////////

         it( 'correctly resolves the CSS and HTML assets', function() {
            expect( promise_ ).toBeDefined();
            expect( mockThemeManager_.urlProvider().provide ).toHaveBeenCalled();
            expect( fileResourceProvider_.provide ).toHaveBeenCalledWith( htmlAssetPath_ );
            expect( mockCssLoader_.load ).toHaveBeenCalledWith( defaultCssAssetPath_ );

            expect( rejectSpy ).not.toHaveBeenCalled();
            expect( resolveSpy ).toHaveBeenCalled();
         } );

         /////////////////////////////////////////////////////////////////////////////////////////////////////

         it( 'fills its anchor dom node', function() {
            expect( anchor_.innerHTML.toLowerCase() ).toEqual( assets[ htmlAssetPath_ ] );
         } );

         /////////////////////////////////////////////////////////////////////////////////////////////////////

         it( 'does not link its anchor dom node', function() {
            expect( ng.element( 'i', anchor_ ).length ).toEqual( 1 );
         } );

      } );

      ////////////////////////////////////////////////////////////////////////////////////////////////////////

      describe( 'asked to attach its DOM representation', function() {

         var mockAreaNode_;

         var elementThatWasAttached_;

         var resolveSpy = jasmine.createSpy( 'resolveSpy' ).andCallFake( function() {
            adapter_.domAttachTo( {
               appendChild: function( node ) {
               elementThatWasAttached_ = node;
            }
            } );
         } );
         var rejectSpy = jasmine.createSpy( 'rejectSpy' );
         var promise_;

         beforeEach( function() {
            mockAreaNode_= document.createElement( 'DIV' );
            adapter_.createController( widgetServices_, widgetLoaderConfiguration_ );
            promise_ = adapter_.domPrepare().then( function() {
               adapter_.domAttachTo( mockAreaNode_ );
            } );
            jasmine.Clock.tick( 0 );
         } );

         /////////////////////////////////////////////////////////////////////////////////////////////////////

         it( 'links the widget template', function() {
            expect( ng.element( 'i', anchor_ ).length ).toEqual( 0 );
         } );

         /////////////////////////////////////////////////////////////////////////////////////////////////////

         it( 'attaches its representation to the given widget area', function() {
            expect( mockAreaNode_.children.length ).toBe( 1 );
            expect( mockAreaNode_.children[ 0 ] ).toBe( anchor_ );
            // anchor class is (mostly) managed externally
            expect( anchor_.className ).toEqual( 'ng-scope' );

         } );

         /////////////////////////////////////////////////////////////////////////////////////////////////////

         describe( 'and then to detach it again', function() {

            beforeEach( function() {
               fakeControllerScope_.$destroy = jasmine.createSpy( '$destroy' );
               adapter_.domDetach();
            } );

            //////////////////////////////////////////////////////////////////////////////////////////////////

            it( 'detaches its dom node from the widget area', function() {
               expect( mockAreaNode_.children.length ).toBe( 0 );
            } );

            //////////////////////////////////////////////////////////////////////////////////////////////////

            it( 'retains its widget services and scope', function() {
               expect( widgetServices_.release ).not.toHaveBeenCalled();
               expect( fakeControllerScope_.$destroy ).not.toHaveBeenCalled();
            } );

         } );

         /////////////////////////////////////////////////////////////////////////////////////////////////////

         describe( 'and then to destroy itself', function() {

            beforeEach( function() {
               fakeControllerScope_.$destroy = jasmine.createSpy( '$destroy' );
               adapter_.destroy();
            } );

            //////////////////////////////////////////////////////////////////////////////////////////////////

            it( 'destroys the corresponding angular scope', function() {
               expect( fakeControllerScope_.$destroy ).toHaveBeenCalled();
            } );

            //////////////////////////////////////////////////////////////////////////////////////////////////

            it( 'releases its widget services', function() {
               adapter_.destroy();
               expect( widgetServices_.release ).toHaveBeenCalled();
            } );

         } );

      } );

   } );

} );<|endoftext|>


<commit_before>module.exports = {
  root: true,
  parser: 'babel-eslint',
  parserOptions: {
    ecmaVersion: 2018,
    sourceType: 'module',
    ecmaFeatures: {
      legacyDecorators: true,
    },
  },
  plugins: ['ember', 'ember-concurrency', 'prettier', 'import-helpers'],
  extends: [
    'eslint:recommended',
    'plugin:ember/recommended',
    'plugin:unicorn/recommended',
    'plugin:prettier/recommended',
  ],
  env: {
    browser: true,
  },
  rules: {
    // it's fine to use `return` without a value and rely on the implicit `undefined` return value
    'getter-return': 'off',

    // declaration sort is taken care of by `import-helpers/order-imports`
    'sort-imports': ['error', { ignoreDeclarationSort: true, ignoreCase: true }],

    'prettier/prettier': 'error',

    // disabled because we still use `this.set()` in a few places and it works just fine
    'ember/classic-decorator-no-classic-methods': 'off',
    'ember/no-classic-classes': 'error',
    // disabled because we still use quite a few CPs
    'ember/no-computed-properties-in-native-classes': 'off',
    'ember/no-empty-attrs': 'off',
    'ember/require-computed-property-dependencies': 'off',

    'ember-concurrency/no-perform-without-catch': 'warn',
    'ember-concurrency/require-task-name-suffix': 'error',

    'unicorn/explicit-length-check': ['error', { 'non-zero': 'not-equal' }],
    // disabled because we need `null` since JSON has no `undefined`
    'unicorn/no-null': 'off',
    // disabled because this rule conflicts with prettier
    'unicorn/no-nested-ternary': 'off',
    // disabled because of unfixable false positives
    'unicorn/prevent-abbreviations': 'off',
    // disabled because it seems unnecessary
    'unicorn/prefer-number-properties': 'off',
    // disabled because it seems unnecessary
    'unicorn/prefer-reflect-apply': 'off',
    // disabled because of false positives
    'unicorn/consistent-destructuring': 'off',
    'unicorn/filename-case': ['error', { case: 'kebabCase', ignore: ['^-'] }],

    'import-helpers/order-imports': [
      'error',
      {
        newlinesBetween: 'always',
        groups: [
          // Node.js built-in modules
          '/^(assert|async_hooks|buffer|child_process|cluster|console|constants|crypto|dgram|dns|domain|events|fs|http|http2|https|inspector|module|net|os|path|perf_hooks|process|punycode|querystring|readline|repl|stream|string_decoder|timers|tls|trace_events|tty|url|util|v8|vm|zli)/',
          // Testing modules
          ['/^(qunit|ember-qunit|@ember/test-helpers|ember-exam|htmlbars-inline-precompile)$/', '/^ember-exam\\//'],
          // Ember.js modules
          ['/^@(ember|ember-data|glimmer)\\//', '/^(ember|ember-data|rsvp)$/', '/^ember-data\\//'],
          ['module'],
          [`/^${require('./package.json').name}\\//`],
          ['parent', 'sibling', 'index'],
        ],
        alphabetize: { order: 'asc', ignoreCase: true },
      },
    ],
  },
  overrides: [
    // test files
    {
      files: ['tests/**/*.js'],
      rules: {
        // disabled because of our nested `prepare()` functions
        'unicorn/consistent-function-scoping': 'off',
      },
    },

    // mirage files
    {
      files: ['mirage/**/*.js'],
      rules: {
        // disabled because of different `.find()` meaning
        'unicorn/no-array-callback-reference': 'off',
      },
    },

    // node files
    {
      files: [
        '.eslintrc.js',
        '.template-lintrc.js',
        'ember-cli-build.js',
        'fastboot.js',
        'testem.js',
        'blueprints/*/index.js',
        'config/**/*.js',
        'lib/*/index.js',
        'server/**/*.js',
      ],
      parserOptions: {
        sourceType: 'script',
        ecmaVersion: 2018,
      },
      env: {
        browser: false,
        node: true,
      },
    },
  ],
};
<commit_msg>ESLint: Disable `unicorn/no-array-for-each` rule<commit_after>module.exports = {
  root: true,
  parser: 'babel-eslint',
  parserOptions: {
    ecmaVersion: 2018,
    sourceType: 'module',
    ecmaFeatures: {
      legacyDecorators: true,
    },
  },
  plugins: ['ember', 'ember-concurrency', 'prettier', 'import-helpers'],
  extends: [
    'eslint:recommended',
    'plugin:ember/recommended',
    'plugin:unicorn/recommended',
    'plugin:prettier/recommended',
  ],
  env: {
    browser: true,
  },
  rules: {
    // it's fine to use `return` without a value and rely on the implicit `undefined` return value
    'getter-return': 'off',

    // declaration sort is taken care of by `import-helpers/order-imports`
    'sort-imports': ['error', { ignoreDeclarationSort: true, ignoreCase: true }],

    'prettier/prettier': 'error',

    // disabled because we still use `this.set()` in a few places and it works just fine
    'ember/classic-decorator-no-classic-methods': 'off',
    'ember/no-classic-classes': 'error',
    // disabled because we still use quite a few CPs
    'ember/no-computed-properties-in-native-classes': 'off',
    'ember/no-empty-attrs': 'off',
    'ember/require-computed-property-dependencies': 'off',

    'ember-concurrency/no-perform-without-catch': 'warn',
    'ember-concurrency/require-task-name-suffix': 'error',

    'unicorn/explicit-length-check': ['error', { 'non-zero': 'not-equal' }],
    // disabled because of false positives related to `EmberArray`
    'unicorn/no-array-for-each': 'off',
    // disabled because we need `null` since JSON has no `undefined`
    'unicorn/no-null': 'off',
    // disabled because this rule conflicts with prettier
    'unicorn/no-nested-ternary': 'off',
    // disabled because of unfixable false positives
    'unicorn/prevent-abbreviations': 'off',
    // disabled because it seems unnecessary
    'unicorn/prefer-number-properties': 'off',
    // disabled because it seems unnecessary
    'unicorn/prefer-reflect-apply': 'off',
    // disabled because of false positives
    'unicorn/consistent-destructuring': 'off',
    'unicorn/filename-case': ['error', { case: 'kebabCase', ignore: ['^-'] }],

    'import-helpers/order-imports': [
      'error',
      {
        newlinesBetween: 'always',
        groups: [
          // Node.js built-in modules
          '/^(assert|async_hooks|buffer|child_process|cluster|console|constants|crypto|dgram|dns|domain|events|fs|http|http2|https|inspector|module|net|os|path|perf_hooks|process|punycode|querystring|readline|repl|stream|string_decoder|timers|tls|trace_events|tty|url|util|v8|vm|zli)/',
          // Testing modules
          ['/^(qunit|ember-qunit|@ember/test-helpers|ember-exam|htmlbars-inline-precompile)$/', '/^ember-exam\\//'],
          // Ember.js modules
          ['/^@(ember|ember-data|glimmer)\\//', '/^(ember|ember-data|rsvp)$/', '/^ember-data\\//'],
          ['module'],
          [`/^${require('./package.json').name}\\//`],
          ['parent', 'sibling', 'index'],
        ],
        alphabetize: { order: 'asc', ignoreCase: true },
      },
    ],
  },
  overrides: [
    // test files
    {
      files: ['tests/**/*.js'],
      rules: {
        // disabled because of our nested `prepare()` functions
        'unicorn/consistent-function-scoping': 'off',
      },
    },

    // mirage files
    {
      files: ['mirage/**/*.js'],
      rules: {
        // disabled because of different `.find()` meaning
        'unicorn/no-array-callback-reference': 'off',
      },
    },

    // node files
    {
      files: [
        '.eslintrc.js',
        '.template-lintrc.js',
        'ember-cli-build.js',
        'fastboot.js',
        'testem.js',
        'blueprints/*/index.js',
        'config/**/*.js',
        'lib/*/index.js',
        'server/**/*.js',
      ],
      parserOptions: {
        sourceType: 'script',
        ecmaVersion: 2018,
      },
      env: {
        browser: false,
        node: true,
      },
    },
  ],
};
<|endoftext|>


<commit_before>define([
    'jquery',
    'underscore',
    'oroui/js/app/views/base/view'
], function($, _, BaseView) {
    'use strict';

    return BaseView.extend({
        relatedCheckboxesSelector: null,

        events: {
            'change': '_onChange'
        },

        requiredOptions: [
            'relatedCheckboxesSelector'
        ],

        initialize: function(options) {
            if (!_.has(options, 'relatedCheckboxesSelector')) {
                throw new Error('Required option "relatedCheckboxesSelector" not found.');
            }

            this.relatedCheckboxesSelector = options.relatedCheckboxesSelector;
        },

        _onChange: function() {
            $(this.relatedCheckboxesSelector).prop('checked', this.$el.is(':checked'));
        }
    });
});
<commit_msg>BAP-9646: User Edit page is hung with a lot of IMAP folders<commit_after>define([
    'jquery',
    'underscore',
    'oroui/js/app/views/base/view'
], function($, _, BaseView) {
    'use strict';

    return BaseView.extend({
        relatedCheckboxesSelector: null,

        events: {
            'change': '_onChange'
        },

        initialize: function(options) {
            if (!_.has(options, 'relatedCheckboxesSelector')) {
                throw new Error('Required option "relatedCheckboxesSelector" not found.');
            }

            this.relatedCheckboxesSelector = options.relatedCheckboxesSelector;
        },

        _onChange: function() {
            $(this.relatedCheckboxesSelector).prop('checked', this.$el.is(':checked'));
        }
    });
});
<|endoftext|>


<commit_before>import Controller from '@ember/controller';
import { inject as service } from '@ember/service';

export default Controller.extend({
  store: service(),

  client: null,

  actions: {
    destroy() {
      this.set('client', this.model.get('client'));
      let self = this;
      this.store.findRecord("doi", this.model.get('id'), { backgroundReload: false }).then(function(doi) {
        doi.destroyRecord().then(function () {
          self.transitionToRoute('clients.show.dois', self.get('client'));
        });
      });
    },
    cancel() {
      this.transitionToRoute('clients.show.dois.show', this.model.get('client.id'), this.model);
    }
  }
});<commit_msg>set correct path for delete transition. #190<commit_after>import Controller from '@ember/controller';
import { inject as service } from '@ember/service';

export default Controller.extend({
  store: service(),

  client: null,

  actions: {
    destroy() {
      this.set('client', this.model.get('client'));
      let self = this;
      this.store.findRecord("doi", this.model.get('id'), { backgroundReload: false }).then(function(doi) {
        doi.destroyRecord().then(function () {
          self.transitionToRoute('clients.show.dois', self.get('client.id'));
        });
      });
    },
    cancel() {
      this.transitionToRoute('clients.show.dois.show', this.model.get('client.id'), this.model);
    }
  }
});<|endoftext|>


<commit_before>module.exports = {
  "parser": "babel-eslint",
  "env": {
    "es6": true
  },

  "ecmaFeatures": {
    "jsx": true
  },

  "extends": "airbnb",

  "plugins": [
    "react"
  ],

  "globals": {
    // flow
    "React$Element": false
  },

  "rules": {
    // resets
    "no-underscore-dangle": 0,
    "arrow-parens": 0,
    "no-use-before-define": 0,
    "import/extensions": 0,
    "import/no-unresolved": 0,
    "react/sort-comp": 0,
    "react/jsx-filename-extension": 0,
    "react/no-array-index-key": 0,
  }
};
<commit_msg>Update eslint config<commit_after>module.exports = {
  "parser": "babel-eslint",
  "env": {
    "es6": true
  },

  "extends": "airbnb",

  "plugins": [
    "react"
  ],

  "rules": {
    // resets
    "no-underscore-dangle": 0,
    "arrow-parens": 0,
    "no-use-before-define": 0,
    "import/extensions": 0,
    "import/no-unresolved": 0,
    "react/sort-comp": 0,
    "react/jsx-filename-extension": 0,
    "react/no-array-index-key": 0,
  }
};
<|endoftext|>


<commit_before>/**
 * @file TagField component
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import React, {Component} from 'react';
import PropTypes from 'prop-types';

import EditableField from '../EditableField';
import IconButton from '../IconButton';

import Util from '../_vendors/Util';
import Dom from '../_vendors/Dom';
import CharSize from '../_vendors/CharSize';
import Event from '../_vendors/Event';

export default class TagField extends Component {

    constructor(props, ...restArgs) {

        super(props, ...restArgs);

        this.inputSymbol = Symbol('input');

        this.state = {
            data: props.data,
            inputValue: props.inputValue,
            inputIndex: props.data.length,
            itemEditing: false,
            editingItemIndex: -1
        };

        this.removeItem = ::this.removeItem;
        this.calInputIndex = ::this.calInputIndex;
        this.mouseDownHandler = ::this.mouseDownHandler;
        this.inputChangeHandler = ::this.inputChangeHandler;
        this.inputKeyDownHandler = ::this.inputKeyDownHandler;
        this.insertInputValue = ::this.insertInputValue;
        this.itemChangeHandler = ::this.itemChangeHandler;
        this.itemEditStartHandler = ::this.itemEditStartHandler;
        this.itemEditEndHandler = ::this.itemEditEndHandler;
        this.clearHandler = ::this.clearHandler;

    }

    removeItem(index) {

        const {data} = this.state;

        if (!data || data.length < 1 || !(index in data)) {
            return;
        }

        data.splice(index, 1);

        this.setState({
            data
        }, () => {
            const {onChange} = this.props;
            onChange && onChange(data);
        });

    }

    calInputIndex(e) {

        const wrapperEl = this.refs.wrapper,
            offset = Dom.getOffset(wrapperEl),
            {left: minX} = offset,
            wrapperWidth = wrapperEl.getBoundingClientRect().width,
            maxX = minX + wrapperWidth;

        let x = e.clientX,
            y = e.clientY,
            inputIndex = -1;

        while (x >= minX) {

            const item = document.elementFromPoint(x, y),
                wrapperEl = Dom.findParentByClassName(item, 'tag-field-item-wrapper');

            if (wrapperEl) {
                inputIndex = +wrapperEl.dataset.index + 1;
                break;
            }

            x--;

        }

        if (inputIndex < 0) {
            while (x <= maxX) {

                const item = document.elementFromPoint(x, y),
                    wrapperEl = Dom.findParentByClassName(item, 'tag-field-item-wrapper');

                if (wrapperEl) {
                    inputIndex = +wrapperEl.dataset.index;
                    break;
                }

                x++;

            }
        }

        return inputIndex < 0 ? this.state.data.length : inputIndex;

    }

    mouseDownHandler(e) {

        if (this.props.disabled || Dom.findParentByClassName(e.target, 'tag-field-item-wrapper')
            || Dom.hasClass(e.target, 'tag-field-input')) {
            return;
        }

        const callback = (function (e) {

            return () => {

                if (Dom.findParentByClassName(e.target, 'tag-field') != this.refs.wrapper || this.state.itemEditing) {
                    this.setState({
                        inputIndex: this.state.data.length
                    });
                    return;
                }

                let x = e.clientX,
                    y = e.clientY;

                if (!x || !y) {
                    return;
                }

                const wrapperEl = this.refs.wrapper,
                    offset = Dom.getOffset(wrapperEl);

                if (!offset) {
                    return;
                }

                const inputIndex = this.calInputIndex(e);

                this.setState({
                    inputIndex
                }, () => {
                    setTimeout(() => {
                        this.refs.input.focus();
                        // wrapperEl.scrollLeft = 0;
                        // wrapperEl.scrollTop = 0;
                    }, 0);
                });

            };

        }.bind(this))(e);

        if (this.state.inputValue) {
            this.insertInputValue(callback);
        } else {
            callback();
        }

    }

    inputChangeHandler(e) {

        if (this.props.disabled) {
            return;
        }

        const inputValue = e.target.value;

        this.setState({
            inputValue
        }, () => {

            const width = CharSize.calculateStringWidth(inputValue, this.refs.test);
            this.refs.inputWrapper.style.width = `${width + 9}px`;

            const {onInputChange} = this.props;
            onInputChange && onInputChange(inputValue);

        });

    }

    inputKeyDownHandler(e) {

        if (this.props.disabled) {
            return;
        }

        if (e.keyCode === 13) {
            this.insertInputValue();
        }

    }

    insertInputValue(callback) {

        if (this.props.disabled) {
            return;
        }

        const {separator} = this.props,
            {data, inputValue, inputIndex} = this.state;

        if (!inputValue) {
            return;
        }

        const splitedValue = inputValue.split(separator);

        data.splice(inputIndex, 0, ...splitedValue);

        this.setState({
            data,
            inputValue: '',
            inputIndex: inputIndex + splitedValue.length
        }, () => {

            this.refs.inputWrapper.style.width = '9px';

            const {onChange} = this.props;
            onChange && onChange(data);

            callback && callback();

        });

    }

    itemChangeHandler(value, index) {

        if (this.props.disabled) {
            return;
        }

        const {separator} = this.props,
            {data} = this.state;

        if (value) {
            const splitedValue = value.split(separator).filter(item => item);
            data.splice(index, 1, ...splitedValue);
        } else {
            data.splice(index, 1);
        }

        this.setState({
            data
        }, () => {
            const {onChange} = this.props;
            onChange && onChange(data);
        });

    }

    itemEditStartHandler(editingItemIndex) {

        if (this.props.disabled) {
            return;
        }

        this.setState({
            itemEditing: true,
            editingItemIndex
        });

    }

    itemEditEndHandler() {

        if (this.props.disabled) {
            return;
        }

        this.setState({
            itemEditing: false
        });

    }

    clearHandler() {

        this.setState({
            data: [],
            inputValue: '',
            inputIndex: 0,
            itemEditing: false,
            editingItemIndex: -1
        }, () => {

            const {onChange, onInputChange} = this.props;

            onChange && onChange([]);
            onInputChange && onInputChange('');

        });

    }

    componentDidMount() {
        Event.addEvent(document, 'mousedown', this.mouseDownHandler);
    }

    componentWillReceiveProps(nextProps) {

        let state;

        if (nextProps.data !== this.state.data) {
            if (!state) {
                state = {};
            }
            state.data = nextProps.data;
        }

        if (nextProps.inputValue !== this.state.inputValue) {
            if (!state) {
                state = {};
            }
            state.inputValue = nextProps.inputValue;
        }

        this.setState(state);

    }

    componentWillUnmount() {
        Event.removeEvent(document, 'mousedown', this.mouseDownHandler);
    }

    render() {

        const {className, style, valueField, displayField, disabled, placeholder, clearButtonVisible} = this.props,
            {data, inputValue, inputIndex, itemEditing, editingItemIndex} = this.state,

            tagFieldClassName = (clearButtonVisible ? ' with-clear' : '') + (className ? ' ' + className : '');

        const indexData = Util.genIndexArray(data.length);
        indexData.splice(inputIndex, 0, this.inputSymbol);

        return (

 {
                     Event.wheelHandler(e, this.props);
                 }}>

                {
                    indexData.map(index => {
                        return index === this.inputSymbol ?
                            (
                                !disabled ?

                                        <input ref="input"
                                               className="tag-field-input"
                                               autoFocus="true"
                                               value={inputValue}
                                               placeholder={data.length < 1 && placeholder ? placeholder : ''}
                                               onChange={this.inputChangeHandler}
                                               onKeyDown={this.inputKeyDownHandler}/>

                                    :
                                    null
                            )
                            :
                            (

                                    <EditableField className="tag-field-item-field"
                                                   value={Util.getTextByDisplayField(data[index], displayField, valueField)}
                                                   disabled={disabled || (itemEditing && index !== editingItemIndex)}
                                                   onChange={(value) => {
                                                       this.itemChangeHandler(value, index);
                                                   }}
                                                   onEditStart={() => {
                                                       this.itemEditStartHandler(index);
                                                   }}
                                                   onEditEnd={this.itemEditEndHandler}>

                                        <IconButton className="tag-field-item-field-delete-button"
                                                    iconCls="fa fa-times"
                                                    disabled={disabled || (itemEditing && index !== editingItemIndex)}
                                                    onTouchTap={() => {
                                                        this.removeItem(index);
                                                    }}/>

                                    </EditableField>

                            );
                    })
                }

                {
                    clearButtonVisible ?
                        <IconButton className="tag-field-clear-button"
                                    iconCls="fa fa-trash"
                                    onTouchTap={this.clearHandler}/>
                        :
                        null
                }

        );

    }
};

TagField.propTypes = {

    /**
     * The CSS class name of the root element.
     */
    className: PropTypes.string,

    /**
     * Override the styles of the root element.
     */
    style: PropTypes.object,

    data: PropTypes.array,
    inputValue: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
    valueField: PropTypes.string,
    displayField: PropTypes.string,
    separator: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),

    disabled: PropTypes.bool,
    placeholder: PropTypes.string,
    clearButtonVisible: PropTypes.bool,
    shouldPreventContainerScroll: PropTypes.bool,

    onChange: PropTypes.func,
    onInputChange: PropTypes.func,

    /**
     * Callback function fired when wrapper wheeled.
     */
    onWheel: PropTypes.func

};

TagField.defaultProps = {

    className: '',
    style: null,

    data: [],
    inputValue: '',

    valueField: 'value',
    displayField: 'text',
    separator: /\s*,\s*/,

    disabled: false,

    placeholder: '',
    clearButtonVisible: true,
    shouldPreventContainerScroll: true

};<commit_msg>update TagField<commit_after>/**
 * @file TagField component
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import React, {Component} from 'react';
import PropTypes from 'prop-types';

import EditableField from '../EditableField';
import IconButton from '../IconButton';

import Util from '../_vendors/Util';
import Dom from '../_vendors/Dom';
import CharSize from '../_vendors/CharSize';
import Event from '../_vendors/Event';

export default class TagField extends Component {

    static propTypes = {

        /**
         * The CSS class name of the root element.
         */
        className: PropTypes.string,

        /**
         * Override the styles of the root element.
         */
        style: PropTypes.object,

        data: PropTypes.array,
        inputValue: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
        valueField: PropTypes.string,
        displayField: PropTypes.string,
        separator: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),

        disabled: PropTypes.bool,
        placeholder: PropTypes.string,
        clearButtonVisible: PropTypes.bool,
        shouldPreventContainerScroll: PropTypes.bool,

        onChange: PropTypes.func,
        onInputChange: PropTypes.func,

        /**
         * Callback function fired when wrapper wheeled.
         */
        onWheel: PropTypes.func

    };

    static defaultProps = {

        className: '',
        style: null,

        data: [],
        inputValue: '',

        valueField: 'value',
        displayField: 'text',
        separator: /\s*,\s*/,

        disabled: false,

        placeholder: '',
        clearButtonVisible: true,
        shouldPreventContainerScroll: true

    };

    constructor(props, ...restArgs) {

        super(props, ...restArgs);

        this.inputSymbol = Symbol('input');

        this.state = {
            data: props.data,
            inputValue: props.inputValue,
            inputIndex: props.data.length,
            itemEditing: false,
            editingItemIndex: -1
        };

        this.removeItem = ::this.removeItem;
        this.calInputIndex = ::this.calInputIndex;
        this.mouseDownHandler = ::this.mouseDownHandler;
        this.inputChangeHandler = ::this.inputChangeHandler;
        this.inputKeyDownHandler = ::this.inputKeyDownHandler;
        this.insertInputValue = ::this.insertInputValue;
        this.itemChangeHandler = ::this.itemChangeHandler;
        this.itemEditStartHandler = ::this.itemEditStartHandler;
        this.itemEditEndHandler = ::this.itemEditEndHandler;
        this.clearHandler = ::this.clearHandler;

    }

    removeItem(index) {

        const {data} = this.state;

        if (!data || data.length < 1 || !(index in data)) {
            return;
        }

        data.splice(index, 1);

        this.setState({
            data
        }, () => {
            const {onChange} = this.props;
            onChange && onChange(data);
        });

    }

    calInputIndex(e) {

        const wrapperEl = this.refs.wrapper,
            offset = Dom.getOffset(wrapperEl),
            {left: minX} = offset,
            wrapperWidth = wrapperEl.getBoundingClientRect().width,
            maxX = minX + wrapperWidth;

        let x = e.clientX,
            y = e.clientY,
            inputIndex = -1;

        while (x >= minX) {

            const item = document.elementFromPoint(x, y),
                wrapperEl = Dom.findParentByClassName(item, 'tag-field-item-wrapper');

            if (wrapperEl) {
                inputIndex = +wrapperEl.dataset.index + 1;
                break;
            }

            x--;

        }

        if (inputIndex < 0) {
            while (x <= maxX) {

                const item = document.elementFromPoint(x, y),
                    wrapperEl = Dom.findParentByClassName(item, 'tag-field-item-wrapper');

                if (wrapperEl) {
                    inputIndex = +wrapperEl.dataset.index;
                    break;
                }

                x++;

            }
        }

        return inputIndex < 0 ? this.state.data.length : inputIndex;

    }

    mouseDownHandler(e) {

        if (this.props.disabled || Dom.findParentByClassName(e.target, 'tag-field-item-wrapper')
            || Dom.hasClass(e.target, 'tag-field-input')) {
            return;
        }

        const callback = (function (e) {

            return () => {

                if (Dom.findParentByClassName(e.target, 'tag-field') != this.refs.wrapper || this.state.itemEditing) {
                    this.setState({
                        inputIndex: this.state.data.length
                    });
                    return;
                }

                let x = e.clientX,
                    y = e.clientY;

                if (!x || !y) {
                    return;
                }

                const wrapperEl = this.refs.wrapper,
                    offset = Dom.getOffset(wrapperEl);

                if (!offset) {
                    return;
                }

                const inputIndex = this.calInputIndex(e);

                this.setState({
                    inputIndex
                }, () => {
                    setTimeout(() => {
                        this.refs.input.focus();
                        // wrapperEl.scrollLeft = 0;
                        // wrapperEl.scrollTop = 0;
                    }, 0);
                });

            };

        }.bind(this))(e);

        if (this.state.inputValue) {
            this.insertInputValue(callback);
        } else {
            callback();
        }

    }

    inputChangeHandler(e) {

        if (this.props.disabled) {
            return;
        }

        const inputValue = e.target.value;

        this.setState({
            inputValue
        }, () => {

            const width = CharSize.calculateStringWidth(inputValue, this.refs.test);
            this.refs.inputWrapper.style.width = `${width + 9}px`;

            const {onInputChange} = this.props;
            onInputChange && onInputChange(inputValue);

        });

    }

    inputKeyDownHandler(e) {

        if (this.props.disabled) {
            return;
        }

        if (e.keyCode === 13) {
            this.insertInputValue();
        }

    }

    insertInputValue(callback) {

        if (this.props.disabled) {
            return;
        }

        const {separator} = this.props,
            {data, inputValue, inputIndex} = this.state;

        if (!inputValue) {
            return;
        }

        const splitedValue = inputValue.split(separator);

        data.splice(inputIndex, 0, ...splitedValue);

        this.setState({
            data,
            inputValue: '',
            inputIndex: inputIndex + splitedValue.length
        }, () => {

            this.refs.inputWrapper.style.width = '9px';

            const {onChange} = this.props;
            onChange && onChange(data);

            callback && callback();

        });

    }

    itemChangeHandler(value, index) {

        if (this.props.disabled) {
            return;
        }

        const {separator} = this.props,
            {data} = this.state;

        if (value) {
            const splitedValue = value.split(separator).filter(item => item);
            data.splice(index, 1, ...splitedValue);
        } else {
            data.splice(index, 1);
        }

        this.setState({
            data
        }, () => {
            const {onChange} = this.props;
            onChange && onChange(data);
        });

    }

    itemEditStartHandler(editingItemIndex) {

        if (this.props.disabled) {
            return;
        }

        this.setState({
            itemEditing: true,
            editingItemIndex
        });

    }

    itemEditEndHandler() {

        if (this.props.disabled) {
            return;
        }

        this.setState({
            itemEditing: false
        });

    }

    clearHandler() {

        this.setState({
            data: [],
            inputValue: '',
            inputIndex: 0,
            itemEditing: false,
            editingItemIndex: -1
        }, () => {

            const {onChange, onInputChange} = this.props;

            onChange && onChange([]);
            onInputChange && onInputChange('');

        });

    }

    componentDidMount() {
        Event.addEvent(document, 'mousedown', this.mouseDownHandler);
    }

    componentWillReceiveProps(nextProps) {

        let state;

        if (nextProps.data !== this.state.data) {
            if (!state) {
                state = {};
            }
            state.data = nextProps.data;
        }

        if (nextProps.inputValue !== this.state.inputValue) {
            if (!state) {
                state = {};
            }
            state.inputValue = nextProps.inputValue;
        }

        this.setState(state);

    }

    componentWillUnmount() {
        Event.removeEvent(document, 'mousedown', this.mouseDownHandler);
    }

    render() {

        const {className, style, valueField, displayField, disabled, placeholder, clearButtonVisible} = this.props,
            {data, inputValue, inputIndex, itemEditing, editingItemIndex} = this.state,

            tagFieldClassName = (clearButtonVisible ? ' with-clear' : '') + (className ? ' ' + className : '');

        const indexData = Util.genIndexArray(data.length);
        indexData.splice(inputIndex, 0, this.inputSymbol);

        return (

 {
                     Event.wheelHandler(e, this.props);
                 }}>

                {
                    indexData.map(index => {
                        return index === this.inputSymbol ?
                            (
                                !disabled ?

                                        <input ref="input"
                                               className="tag-field-input"
                                               autoFocus="true"
                                               value={inputValue}
                                               placeholder={data.length < 1 && placeholder ? placeholder : ''}
                                               onChange={this.inputChangeHandler}
                                               onKeyDown={this.inputKeyDownHandler}/>

                                    :
                                    null
                            )
                            :
                            (

                                    <EditableField className="tag-field-item-field"
                                                   value={Util.getTextByDisplayField(data[index], displayField, valueField)}
                                                   disabled={disabled || (itemEditing && index !== editingItemIndex)}
                                                   onChange={(value) => {
                                                       this.itemChangeHandler(value, index);
                                                   }}
                                                   onEditStart={() => {
                                                       this.itemEditStartHandler(index);
                                                   }}
                                                   onEditEnd={this.itemEditEndHandler}>

                                        <IconButton className="tag-field-item-field-delete-button"
                                                    iconCls="fa fa-times"
                                                    disabled={disabled || (itemEditing && index !== editingItemIndex)}
                                                    onTouchTap={() => {
                                                        this.removeItem(index);
                                                    }}/>

                                    </EditableField>

                            );
                    })
                }

                {
                    clearButtonVisible ?
                        <IconButton className="tag-field-clear-button"
                                    iconCls="fa fa-trash"
                                    onTouchTap={this.clearHandler}/>
                        :
                        null
                }

        );

    }
};<|endoftext|>


<commit_before>module.exports = {
  extends: [
    'airbnb',
    'plugin:flowtype/recommended',
    'prettier',
    'prettier/flowtype',
    'prettier/react',
  ],
  parser: 'babel-eslint',
  plugins: ['flowtype', 'relay'],
  // Some rules can be too strict. Feel free to relax them. Explain.
  rules: {
    'import/first': 0, // Too strict.
    'no-shadow': 0, // // Shadow is nice language feature.
    'react/jsx-filename-extension': 0, // JavaScript belong to .js
    'react/prop-types': 0, // Flow checks it.
    'react/self-closing-comp': 0, // <Text> </Text> is fine.s
    'react/prefer-stateless-function': 0, // PureComponents ftw.
    'arrow-body-style': 0, // Too strict.
    'prefer-destructuring': 0, // Flow casting can need it.
    'import/extensions': 0, // Flow checks it.
    'no-alert': 0, // Too strict.
    'react/require-default-props': 0, // Flow checks it.
    'react/destructuring-assignment': 0, // Too strict.
    'import/order': 0, // Too strict.
    'lines-between-class-members': 0, // Too strict.
    'import/no-cycle': 0, // Too strict.
    'spaced-comment': ['error', 'always', { markers: ['::', ':'] }], // Flow comments.
    'consistent-return': 0, // Flow checks it.
    'default-case': 0, // Flow checks it.
    'react/no-unused-prop-types': 0, // Too brittle.
    // Must be explicitly enabled.
    'relay/graphql-syntax': 'error',
    'relay/compat-uses-vars': 'error',
    'relay/graphql-naming': 'error',
    'relay/generated-flow-types': 'error',
    'relay/unused-fields': 'error',
  },
};
<commit_msg>Add relay/no-future-added-value eslint rule<commit_after>module.exports = {
  extends: [
    'airbnb',
    'plugin:flowtype/recommended',
    'prettier',
    'prettier/flowtype',
    'prettier/react',
  ],
  parser: 'babel-eslint',
  plugins: ['flowtype', 'relay'],
  // Some rules can be too strict. Feel free to relax them. Explain.
  rules: {
    'import/first': 0, // Too strict.
    'no-shadow': 0, // // Shadow is nice language feature.
    'react/jsx-filename-extension': 0, // JavaScript belong to .js
    'react/prop-types': 0, // Flow checks it.
    'react/self-closing-comp': 0, // <Text> </Text> is fine.s
    'react/prefer-stateless-function': 0, // PureComponents ftw.
    'arrow-body-style': 0, // Too strict.
    'prefer-destructuring': 0, // Flow casting can need it.
    'import/extensions': 0, // Flow checks it.
    'no-alert': 0, // Too strict.
    'react/require-default-props': 0, // Flow checks it.
    'react/destructuring-assignment': 0, // Too strict.
    'import/order': 0, // Too strict.
    'lines-between-class-members': 0, // Too strict.
    'import/no-cycle': 0, // Too strict.
    'spaced-comment': ['error', 'always', { markers: ['::', ':'] }], // Flow comments.
    'consistent-return': 0, // Flow checks it.
    'default-case': 0, // Flow checks it.
    'react/no-unused-prop-types': 0, // Too brittle.
    // Must be explicitly enabled.
    'relay/graphql-syntax': 'error',
    'relay/compat-uses-vars': 'error',
    'relay/graphql-naming': 'error',
    'relay/generated-flow-types': 'error',
    'relay/unused-fields': 'error',
    'relay/no-future-added-value': 'error',
  },
};
<|endoftext|>


<commit_before>module.exports = {
    "extends": "eslint:recommended",
    "installedESLint": true,
    "plugins": [
        "standard",
        "promise"
    ],
    "env": {
      "es6": true,
      "browser": true
    },
    "parserOptions": {
        "ecmaVersion": 6,
        "sourceType": "module",
    },
    "rules": {
      "semi": ["error", "always"]
    }
};
<commit_msg>fix eslint<commit_after>module.exports = {
    "extends": "eslint:recommended",
    "plugins": [
        "standard",
        "promise"
    ],
    "env": {
      "es6": true,
      "browser": true
    },
    "parserOptions": {
        "ecmaVersion": 6,
        "sourceType": "module",
    },
    "rules": {
      "semi": ["error", "always"]
    }
};
<|endoftext|>


<commit_before>module.exports = {
    env: {
        es6: true
    },
    extends: 'eslint:recommended',
    parserOptions: {
        ecmaVersion: 2017,
        sourceType: 'module'
    },
    rules: {
        'strict': [ 'error', 'global' ],
        'indent': [ 'error', 4 ],
        'linebreak-style': [ 'error', 'unix' ],
        'quotes': [ 'error', 'single' ],
        'semi': [ 'error', 'always' ]
    }
};<commit_msg>Updated ESLint rules.<commit_after>module.exports = {
    env: {
        es6: true
    },
    extends: 'eslint:recommended',
    parserOptions: {
        ecmaVersion: 2017,
        sourceType: 'module'
    },
    rules: {
        'brace-style': [ 2, 'stroustrup', { allowSingleLine: true } ],
        'comma-dangle': [ 'error', 'never' ],
        'eqeqeq': [ 'error', 'always' ],
        'indent': [ 'error', 4, { SwitchCase: 1 } ],
        'keyword-spacing': [ 'error', { before: true, after: true } ],
        'linebreak-style': [ 'error', 'unix' ],
        'no-cond-assign': [ 'error', 'always' ],
        'no-unneeded-ternary': [ 'error', { defaultAssignment: false } ],
        'no-var': 'error',
        'quotes': [ 'error', 'single' ],
        'semi': [ 'error', 'always' ],
        'space-before-blocks': [ 'error', 'always' ],
        'strict': [ 'error', 'global' ],
        'yoda': [ 'error', 'never' ]
    }
};<|endoftext|>


<commit_before>//{namespace name="backend/connect/view/main"}
//{block name="backend/article/controller/connect"}
Ext.define('Shopware.apps.Article.controller.Connect', {
    /**
     * The parent class that this class extends.
     * @string
     */
    extend:'Ext.app.Controller',

    refs: [
          { ref: 'connectForm', selector: 'article-connect-form' },
          { ref: 'articleDetailWindow', selector: 'article-detail-window' },
      ],

    /**
     * A template method that is called when your application boots.
     * It is called before the Application's launch function is executed
     * so gives a hook point to run any code before your Viewport is created.
     *
     * @return Ext.window.Window
     */
    init: function () {
        var me = this,
            mainWindow = me.subApplication.articleWindow;

        me.control({
            'article-detail-window': {
                connectTabActivated: me.onConnectStoreReloadNeeded,
                connectStoreReloadNeeded: me.onConnectStoreReloadNeeded,
                saveArticle: me.onSaveArticle
            }
        });

        mainWindow.on('storesLoaded', me.onStoresLoaded, me);

        me.callParent(arguments);
    },

    enableTab: function() {
        var me = this,
            detailWindow = me.getArticleDetailWindow();

        detailWindow.connectTab.setDisabled(false);
    },

    onStoresLoaded: function() {
        var me = this;

    },

    onSaveArticle: function(win, article, options) {
        var me = this,
            connectForm = me.getConnectForm();

        if (!me.subApplication.article || !me.subApplication.article.get('id')) {
            return;
        }

        connectForm.getForm().updateRecord(article);

        article.save({
                failure: function(record, operation) {
                    var rawData = record.getProxy().getReader().rawData,
                        message = rawData.message;

                    Shopware.Notification.createGrowlMessage('{s name=connect/error}error{/s}', message, 'connect');
                }
        });
    },

    /**
     * Callback function for the "connectStoreReloadNeeded" event
     */
    onConnectStoreReloadNeeded: function() {
        var me = this;

        me.doReloadConnectStore();
    },

    /**
     * Actually do reload the connect store
     */
    doReloadConnectStore: function() {
        var me = this,
            connectForm = me.getConnectForm();

        if (!me.subApplication.article || !me.subApplication.article.get('id')) {
            return;
        }

        me.connectStore.load({
            callback: function(records, operation) {
                if (!operation.wasSuccessful()) {
                    return;
                }
                if (records.length > 0) {
                    me.record = records[0];
                    connectForm.loadRecord(me.record);

                    me.manageFields();
                }
            }
        });

    },

    /**
     * Manage some fields which needs to be disabled for remote products
     */
    manageFields: function() {
        var me = this,
            connectForm = me.getConnectForm(),
            settingsFieldSet = me.subApplication.articleWindow.down('article-settings-field-set'),
            pricesFieldSet = me.subApplication.articleWindow.down('article-prices-field-set'),
            basePriceColumn = me.subApplication.articleWindow.down('article-prices-field-set numbercolumn[dataIndex=basePrice]'),
            shippingField, inStockField,
            isPriceLocked;

        // Unit fields
        var contentLabel = me.getArticleDetailWindow().snippets.basePrice.content;
        var contentField = me.getArticleDetailWindow().down('numberfield[fieldLabel=' + contentLabel + ']');
        var basicUnitLabel = me.getArticleDetailWindow().snippets.basePrice.basicUnit;
        var basicField = me.getArticleDetailWindow().down('numberfield[fieldLabel=' + basicUnitLabel + ']');
        me.getArticleDetailWindow().unitComboBox.setReadOnly(me.record.get('shopId') > 0);
        contentField.setReadOnly(me.record.get('shopId') > 0);
        basicField.setReadOnly(me.record.get('shopId') > 0);

        if (me.record.get('shopId') > 0) {
            connectForm.connectFixedPrice.setReadOnly(true);
        } else if (isFixedPriceAllowed == false) {
            connectForm.connectFixedPriceFieldset.setVisible(false);
        }

        if (settingsFieldSet) {
            shippingField = settingsFieldSet.down('checkboxfield[fieldLabel=' + settingsFieldSet.snippets.shippingFree.field + ']');
            inStockField = settingsFieldSet.down('numberfield[fieldLabel=' + settingsFieldSet.snippets.stock + ']');

            if (shippingField) {
                shippingField.setReadOnly(me.record.get('shopId') > 0);
            }
            if (inStockField) {
                inStockField.setReadOnly(me.record.get('shopId') > 0);
            }
        }

        if (pricesFieldSet) {
            isPriceLocked = me.record.get('fixedPrice') && me.record.get('shopId') > 0;
            pricesFieldSet.tabPanel.setDisabled(isPriceLocked);
            pricesFieldSet.connectLabel.setVisible(isPriceLocked);
        }

        if (basePriceColumn) {
            if (me.record.get('shopId') > 0) {
                basePriceColumn.setEditor(false);
            }
        }
    }

});
//{/block}
<commit_msg>NTR Rever saveArticle changes<commit_after>//{namespace name="backend/connect/view/main"}
//{block name="backend/article/controller/connect"}
Ext.define('Shopware.apps.Article.controller.Connect', {
    /**
     * The parent class that this class extends.
     * @string
     */
    extend:'Ext.app.Controller',

    refs: [
          { ref: 'connectForm', selector: 'article-connect-form' },
          { ref: 'articleDetailWindow', selector: 'article-detail-window' },
      ],

    /**
     * A template method that is called when your application boots.
     * It is called before the Application's launch function is executed
     * so gives a hook point to run any code before your Viewport is created.
     *
     * @return Ext.window.Window
     */
    init: function () {
        var me = this,
            mainWindow = me.subApplication.articleWindow;

        me.control({
            'article-detail-window': {
                connectTabActivated: me.onConnectStoreReloadNeeded,
                connectStoreReloadNeeded: me.onConnectStoreReloadNeeded,
                saveArticle: me.onSaveArticle
            }
        });

        mainWindow.on('storesLoaded', me.onStoresLoaded, me);

        me.callParent(arguments);
    },

    enableTab: function() {
        var me = this,
            detailWindow = me.getArticleDetailWindow();

        detailWindow.connectTab.setDisabled(false);
    },

    onStoresLoaded: function() {
        var me = this;

    },

    onSaveArticle: function(win, article, options) {
        var me = this,
            connectForm = me.getConnectForm();

        if (!me.subApplication.article || !me.subApplication.article.get('id')) {
            return;
        }

        connectForm.getForm().updateRecord(me.record);

        me.record.save({
                failure: function(record, operation) {
                    var rawData = record.getProxy().getReader().rawData,
                        message = rawData.message;

                    Shopware.Notification.createGrowlMessage('{s name=connect/error}error{/s}', message, 'connect');
                }
        });
    },

    /**
     * Callback function for the "connectStoreReloadNeeded" event
     */
    onConnectStoreReloadNeeded: function() {
        var me = this;

        me.doReloadConnectStore();
    },

    /**
     * Actually do reload the connect store
     */
    doReloadConnectStore: function() {
        var me = this,
            connectForm = me.getConnectForm();

        if (!me.subApplication.article || !me.subApplication.article.get('id')) {
            return;
        }

        me.connectStore.load({
            callback: function(records, operation) {
                if (!operation.wasSuccessful()) {
                    return;
                }
                if (records.length > 0) {
                    me.record = records[0];
                    connectForm.loadRecord(me.record);

                    me.manageFields();
                }
            }
        });

    },

    /**
     * Manage some fields which needs to be disabled for remote products
     */
    manageFields: function() {
        var me = this,
            connectForm = me.getConnectForm(),
            settingsFieldSet = me.subApplication.articleWindow.down('article-settings-field-set'),
            pricesFieldSet = me.subApplication.articleWindow.down('article-prices-field-set'),
            basePriceColumn = me.subApplication.articleWindow.down('article-prices-field-set numbercolumn[dataIndex=basePrice]'),
            shippingField, inStockField,
            isPriceLocked;

        // Unit fields
        var contentLabel = me.getArticleDetailWindow().snippets.basePrice.content;
        var contentField = me.getArticleDetailWindow().down('numberfield[fieldLabel=' + contentLabel + ']');
        var basicUnitLabel = me.getArticleDetailWindow().snippets.basePrice.basicUnit;
        var basicField = me.getArticleDetailWindow().down('numberfield[fieldLabel=' + basicUnitLabel + ']');
        me.getArticleDetailWindow().unitComboBox.setReadOnly(me.record.get('shopId') > 0);
        contentField.setReadOnly(me.record.get('shopId') > 0);
        basicField.setReadOnly(me.record.get('shopId') > 0);

        if (me.record.get('shopId') > 0) {
            connectForm.connectFixedPrice.setReadOnly(true);
        } else if (isFixedPriceAllowed == false) {
            connectForm.connectFixedPriceFieldset.setVisible(false);
        }

        if (settingsFieldSet) {
            shippingField = settingsFieldSet.down('checkboxfield[fieldLabel=' + settingsFieldSet.snippets.shippingFree.field + ']');
            inStockField = settingsFieldSet.down('numberfield[fieldLabel=' + settingsFieldSet.snippets.stock + ']');

            if (shippingField) {
                shippingField.setReadOnly(me.record.get('shopId') > 0);
            }
            if (inStockField) {
                inStockField.setReadOnly(me.record.get('shopId') > 0);
            }
        }

        if (pricesFieldSet) {
            isPriceLocked = me.record.get('fixedPrice') && me.record.get('shopId') > 0;
            pricesFieldSet.tabPanel.setDisabled(isPriceLocked);
            pricesFieldSet.connectLabel.setVisible(isPriceLocked);
        }

        if (basePriceColumn) {
            if (me.record.get('shopId') > 0) {
                basePriceColumn.setEditor(false);
            }
        }
    }

});
//{/block}
<|endoftext|>