<commit_before>
function wew(WEW){
	'use strict';
	this.uid = new Date;
	this.appid = WEW.opts.appID;
	this.ttl = WEW.opts.ttl;
	(this.storage = window.localStorage).setItem(this.uid, this.uid);
}

wew.prototype.getSet = function (setName,callback){
	'use strict';
	var storageKey = setName || "";
	console.log("setName: "+setName);

	var cached=this.inCache(storageKey);
	if(!cached){
		this.askCloud('http://'+this.appid+'.wew.io/ddr/cset/',storageKey, callback);
	}else{
		callback(cached);
	}
},

wew.prototype.getCap = function(capabilityName, callback) {
	'use strict';
	var storageKey = capabilityName;
	var capability ="";
	console.log("capabilityName: "+capabilityName);

	var cached=this.inCache(storageKey);
	if(!cached){
		this.askCloud('http://'+this.appid+'.wew.io/ddr/c/'+capabilityName,storageKey, callback);
	}else{
		callback(cached);
	}
},

wew.prototype.inCache = function(storageKey) {
	capability =0;
	if(this.storage && this.storage.getItem(storageKey) && JSON.parse && JSON) {
		try {
			capability = JSON.parse(this.storage.getItem(storageKey));
			var now = new Date();
			var age = new Date(capability.ts);
			if( (now.getTime() - age.getTime()) > this.ttl) {
				this.storage.removeItem(storageKey);
				capability=0;
			} else {
				return capability;
			}
		} catch(e) {

		}
	}else{
		return capability;
	}
},

wew.prototype.askCloud = function (url,storageKey,callback) {
		var http = this.httpObj();
		var storage = this.storage;
		http.open('GET', url, true);
		http.onreadystatechange = function (){
			if (http.status == 200 && http.readyState == 4) {
	    		if(storage) {
	    			var capability = JSON.parse(http.responseText);
	    			var i =0;
	    			for (key in capability) {
						try{
							capability['ts'] = new Date();
							if(i<1){
								storage.setItem(storageKey, JSON.stringify(capability));
							}
							var jsn={};
							jsn[key] = capability[key];
							jsn['ts'] = capability['ts'];
							storage.setItem(key, JSON.stringify(jsn));
							console.log("stored");
						}catch (e){
							console.log("Could not store");
							console.log(e);
						}
						i++;
		 			}
				}
	    		callback(JSON.parse(http.responseText));
	    	}
		};
		http.send();
},

wew.prototype.httpObj = function () {
	var xmlhttpmethod = false,
		attempts = [
			function () { return new XMLHttpRequest(); },
			function () { return new ActiveXObject("Microsoft.XMLHTTP"); },
			function () { return new XDomainRequest; },
			function () { return new ActiveXObject("MSXML2.XMLHTTP.3.0"); }
		],
		al = attempts.length;
	while (al--) {
	    try {
	        xmlhttpmethod = attempts[al]();
	    }
	    catch (e) {
	        continue;
	    }
	    break;
	}
	return xmlhttpmethod;
}<commit_msg>added more params to service<commit_after>
function wew(WEW){
	'use strict';
	this.uid = new Date;
	this.appid = WEW.opts.appID;
	this.ttl = WEW.opts.ttl;
	(this.storage = window.localStorage).setItem(this.uid, this.uid);
}

wew.prototype.getSet = function (setName,callback){
	'use strict';
	var storageKey = setName || "";
	console.log("setName: "+setName);

	var cached=this.inCache(storageKey);
	if(!cached){
		this.askCloud('http://'+this.appid+'.wew.io/ddr/cset/',storageKey, callback);
	}else{
		callback(cached);
	}
},

wew.prototype.getCap = function(capabilityName, callback) {
	'use strict';
	var storageKey = capabilityName;
	var capability ="";
	console.log("capabilityName: "+capabilityName);

	var cached=this.inCache(storageKey);
	if(!cached){
		this.askCloud('http://'+this.appid+'.wew.io/ddr/c/'+capabilityName,storageKey, callback);
	}else{
		callback(cached);
	}
},

wew.prototype.inCache = function(storageKey) {
	capability =0;
	if(this.storage && this.storage.getItem(storageKey) && JSON.parse && JSON) {
		try {
			capability = JSON.parse(this.storage.getItem(storageKey));
			var now = new Date();
			var age = new Date(capability.ts);
			if( (now.getTime() - age.getTime()) > this.ttl) {
				this.storage.removeItem(storageKey);
				capability=0;
			} else {
				return capability;
			}
		} catch(e) {

		}
	}else{
		return capability;
	}
},

wew.prototype.askCloud = function (url,storageKey,callback) {
		var http = this.httpObj();
		var storage = this.storage;
		var orientation = window.orientation || "";
		var height = screen.height || "";
		var width = screen.width || "";
		var pixelratio = window.devicePixelRatio || "";
		url = url +"?o="+orientation+"&h="+height+"&w="+width+"&p="+pixelratio;
		console.log(url);
		http.open('GET', url, true);
		http.onreadystatechange = function (){
			if (http.status == 200 && http.readyState == 4) {
	    		if(storage) {
	    			var capability = JSON.parse(http.responseText);
	    			var i =0;
	    			for (key in capability) {
						try{
							capability['ts'] = new Date();
							if(i<1){
								storage.setItem(storageKey, JSON.stringify(capability));
							}
							var jsn={};
							jsn[key] = capability[key];
							jsn['ts'] = capability['ts'];
							storage.setItem(key, JSON.stringify(jsn));
							console.log("stored");
						}catch (e){
							console.log("Could not store");
							console.log(e);
						}
						i++;
		 			}
				}
	    		callback(JSON.parse(http.responseText));
	    	}
		};
		http.send();
},

wew.prototype.httpObj = function () {
	var xmlhttpmethod = false,
		attempts = [
			function () { return new XMLHttpRequest(); },
			function () { return new ActiveXObject("Microsoft.XMLHTTP"); },
			function () { return new XDomainRequest; },
			function () { return new ActiveXObject("MSXML2.XMLHTTP.3.0"); }
		],
		al = attempts.length;
	while (al--) {
	    try {
	        xmlhttpmethod = attempts[al]();
	    }
	    catch (e) {
	        continue;
	    }
	    break;
	}
	return xmlhttpmethod;
}<|endoftext|>


<commit_before>/**
 * A speculative API for creating Django-style declarative models using
 * Concur for inheritance and __meta__ for pre-processing prototype
 * properties.
 */

function fmt = function(s) {
  var i = 0, args = Array.prototype.slice.call(arguments, 1)
  return s.replace(/%s/g, function() { return args[i++] })
}

// Dummy field and relationship objects
var Field = Concur.extend()
var CharField = Field.extend()
var TextField = Field.extend()
var DateField = Field.extend()
var ImageField = Field.extend()

var Rel = Concur.extend()
var ModelRel = Rel.extend()

/**
 * Meta-info about a model.
 */
function ModelOptions(meta) {
  this.meta = meta
  this.name = meta.name
  this.displayName = meta.displayName || meta.name
  this.displayNamePlural = meta.displayNamePlural || this.displayName + 's'
  this.fields = []
  this.ordering = meta.ordering || []
)

var Model = Concur.extend({
  /**
   * Prepares a ModelOptions for the extended Model and places it in a
   * _meta property on the prototype and constructor.
   */
  __meta__: function(prototypeProps, constructorProps) {
    if (typeof prototypeProps.Meta == 'undefined' ||
        typeof prototypeProps.Meta.name == 'undefined') {
      throw new Error('Objects extending Model must provide a name via a Meta object.')
    }
    var options = new ModelOptions(prototypeProps.Meta)
    delete prototypeProps.Meta

    for (var prop in prototypeProps) {
      if (prototypeProps.hasOwnProperty(prop)) {
        var field = prototypeProps[prop]
        if (field instanceof Field || field instanceof Rel) {
          field.name = prop
          options.fields.push(field)
          delete prototypeProps[prop]
        }
      }
    }

    prototypeProps._meta = constructorProps._meta = options
  }

, constructor: function(props) {
    Concur.cp(this, props)
  }

, get: function() {
    // Pretend you're looking at something which introspects this._meta
    // and does some really clever stuff.
    var args = Array.prototype.slice.call(arguments)
    return args.pop().apply(this, args)
  }
})

var Game = Model.extend({
  name        : CharField({max_length: 255})
, series      : ModelRel(Series, {nullable: true, relatedName: 'games'})
, genre       : ModelRel(Genre, {nullable: true, relatedName: 'games'})
, publisher   : ModelRel(Company, {relatedName: 'publishedGames'})
, developer   : ModelRel(Company, {relatedName: 'developedGames'})
, description : TextField({blank: true})

, Meta: { name: 'Game'
        , ordering: ['name']
        }

, toString: function(fn) {
    fn(this.name)
  }
})

var GameRelease = Model.extend({
  game        : ModelRel(Game, {relatedName: 'releases'})
, name        : CharField({maxLength: 255, blank: true})
, platform    : ModelRel(Platform, {relatedName: 'gameReleases'})
, region      : ModelRel(Region, {relatedName: 'gameReleases'})
, publisher   : ModelRel(Company, {nullable: true, blank: true, relatedName: 'publishedReleases'})
, date        : DateField()
, cover       : ImageField({uploadTo: 'covers', blank: true})
, description : TextField({blank: true})

, Meta: { name: 'GameRelease'
        , verboseName: 'Game Release'
        }

, toString: function(fn) {
    this.get('game', 'region', 'publisher', function(g, r, p) {
      fn(fmt('%s (%s, %s)', g, r, p))
    })
  }
})
<commit_msg>Update models example to remove use of an old API function and fix creation of Fields<commit_after>/**
 * A speculative API for creating Django-style declarative models using
 * Concur for inheritance and __meta__ for pre-processing prototype
 * properties.
 */
function fmt = function(s) {
  var i = 0, args = Array.prototype.slice.call(arguments, 1)
  return s.replace(/%s/g, function() { return args[i++] })
}

// Dummy field and relationship objects
var Field = Concur.extend()
var CharField = Field.extend()
var TextField = Field.extend()
var DateField = Field.extend()
var ImageField = Field.extend()

var Rel = Concur.extend()
var ModelRel = Rel.extend()

/**
 * Meta-info about a model.
 */
function ModelOptions(meta) {
  this.meta = meta
  this.name = meta.name
  this.displayName = meta.displayName || meta.name
  this.displayNamePlural = meta.displayNamePlural || this.displayName + 's'
  this.fields = []
  this.ordering = meta.ordering || []
)

var Model = Concur.extend({
  /**
   * Prepares a ModelOptions for the extended Model and places it in a
   * _meta property on the prototype and constructor.
   */
  __meta__: function(prototypeProps, constructorProps) {
    if (typeof prototypeProps.Meta == 'undefined' ||
        typeof prototypeProps.Meta.name == 'undefined') {
      throw new Error('When extending Model, you must provide a name via a Meta object.')
    }

    var options = new ModelOptions(prototypeProps.Meta)
    delete prototypeProps.Meta

    for (var prop in prototypeProps) {
      if (prototypeProps.hasOwnProperty(prop)) {
        var field = prototypeProps[prop]
        if (field instanceof Field || field instanceof Rel) {
          field.name = prop
          options.fields.push(field)
          delete prototypeProps[prop]
        }
      }
    }

    prototypeProps._meta = constructorProps._meta = options
  }

, constructor: function(props) {
    for (var prop in props)
      if (prop.hasOwnProperty(prop))
        this[prop] = props[prop]
  }

, get: function() {
    // Pretend you're looking at something which introspects this._meta
    // and does some really clever stuff as per the usage in GameRelease's
    // toString()
    var args = Array.prototype.slice.call(arguments)
    return args.pop().apply(this, args)
  }
})

var Game = Model.extend({
  name        : new CharField({max_length: 255})
, series      : new ModelRel(Series, {nullable: true, relatedName: 'games'})
, genre       : new ModelRel(Genre, {nullable: true, relatedName: 'games'})
, publisher   : new ModelRel(Company, {relatedName: 'publishedGames'})
, developer   : new ModelRel(Company, {relatedName: 'developedGames'})
, description : new TextField({blank: true})

, Meta: { name: 'Game'
        , ordering: ['name']
        }

, toString: function(fn) {
    fn(this.name)
  }
})

var GameRelease = Model.extend({
  game        : new ModelRel(Game, {relatedName: 'releases'})
, name        : new CharField({maxLength: 255, blank: true})
, platform    : new ModelRel(Platform, {relatedName: 'gameReleases'})
, region      : new ModelRel(Region, {relatedName: 'gameReleases'})
, publisher   : new ModelRel(Company, {nullable: true, blank: true, relatedName: 'publishedReleases'})
, date        : new DateField()
, cover       : new ImageField({uploadTo: 'covers', blank: true})
, description : new TextField({blank: true})

, Meta: { name: 'GameRelease'
        , verboseName: 'Game Release'
        }

, toString: function(fn) {
    this.get('game', 'region', 'publisher', function(g, r, p) {
      fn(fmt('%s (%s, %s)', g, r, p))
    })
  }
})
<|endoftext|>


<commit_before>/***
 * Copyright (c) 2016, 2017 Alex Grant (@localnerve), LocalNerve LLC
 * Copyrights licensed under the BSD License. See the accompanying LICENSE file for terms.
 */
/* global before, beforeEach, after, afterEach, describe, it */
import { expect } from 'chai';
import React from 'react';
import { domStart, domStop, mockStart, mockEnd } from '../utils/testdom';
import { Simple, setMockReporter } from '../fixtures/Simple';
import createSizeReporter from '../../lib';

describe('sizeReporter', () => {
  let testUtils;

  before('sizeReporter', () => {
    domStart();
  });

  after('sizeReporter', () => {
    domStop();
  });

  describe('structure', () => {
    it('should report and have expected report items with correct types',
    (done) => {
      const reporter = createSizeReporter('.nothing', (data) => {
        expect(typeof data.width).to.equal('number');
        expect(typeof data.height).to.equal('number');
        expect(typeof data.top).to.equal('number');
        expect(typeof data.accumulate).to.equal('boolean');
        done();
      }, {
        reportWidth: true,
        reportHeight: true,
        reportTop: true
      });

      reporter();
    });
  });

  describe('bad args', () => {
    it('should throw if no selector supplied', () => {
      expect(function () {
        createSizeReporter('', () => {});
      }).to.throw(Error);
    });

    it('should throw if no reporter function supplied', () => {
      expect(function () {
        createSizeReporter('.nothing', 'bad');
      }).to.throw(Error);
    });
  });

  describe('react', () => {
    let testUtils;

    before('react', () => {
      testUtils = require('react-addons-test-utils');
    });

    beforeEach(() => {
      // Clear the group trackers
      createSizeReporter(null, null, {
        _clearTrackers: true
      });
    });

    afterEach(() => {
      setMockReporter(null);
    });

    it('should render and execute action', (done) => {
      const element = React.createElement(Simple);
      const component = testUtils.renderIntoDocument(element);
      const result = testUtils.findRenderedDOMComponentWithClass(
        component, 'contained'
      );

      // Render test
      expect(result.textContent).to.match(/Simple Test/);

      setTimeout(function () {
        // Action test. Executes on componentDidMount so action should've run.
        expect(result.textContent).to.match(/Action/);
        done();
      }, 0);
    });

    it('should accumulate if multiple reporters in same group', (done) => {
      const reporters = 2;
      let reportCall = 0;

      /**
       * @param {Object} data - the report data from size reporter under test.
       */
      function handleReport (data) {
        if (reportCall === 0) {
          // First time, you want to overwrite the data.
          expect(data.accumulate).to.be.false;
        } else {
          // After that, you're accumulating.
          expect(data.accumulate).to.be.true;
        }

        reportCall++;
        if (reportCall === reporters) {
          done();
        }
      }

      setMockReporter(handleReport);

      const children = [Simple, Simple].map((childClass, index) => {
        return React.createElement(childClass, { key: index });
      });

      testUtils.renderIntoDocument(React.createElement('div', {}, children));
    });
  });

  describe('mocked tests', () => {
    const top = 202.2, right = 600, bottom = 600, left = 202.2,
      pageYOffset = 200;
    let domProps;

    function mockQuerySelector () {
      return {
        getBoundingClientRect: function () {
          return {
            top,
            right,
            bottom,
            left
          };
        }
      };
    }

    before('mocks', () => {
      domProps = mockStart({
        querySelector: mockQuerySelector,
        pageYOffset
      });
    });

    after('mocks', () => {
      mockEnd();
    });

    beforeEach(() => {
      // Clear the group trackers
      createSizeReporter(null, null, {
        _clearTrackers: true
      });
    });

    it('should compute values as expected', (done) => {
      const reporter = createSizeReporter('.mock', (data) => {
        expect(data.width).to.equal(Math.round(right - left));
        expect(data.height).to.equal(Math.round(bottom - top));
        expect(data.top).to.equal(Math.round(
          top + (pageYOffset - domProps.clientTop)
        ));
        expect(data.accumulate).to.equal(false);
        done();
      }, {
        reportWidth: true,
        reportHeight: true,
        reportTop: true
      });

      reporter();
    });

    it('should grow width on multiple as expected', (done) => {
      const multiple = 10;

      const reporter = createSizeReporter('.mock', (data) => {
        expect(data.width).to.equal(
          Math.ceil((right - left)/multiple) * multiple
        );
        done();
      }, {
        reportWidth: true,
        grow: {
          width: multiple
        }
      });

      reporter();
    });

    it('should grow top on multiple as expected', (done) => {
      const multiple = 10;

      const reporter = createSizeReporter('.mock', (data) => {
        expect(data.top).to.equal(
          Math.floor((top + (pageYOffset - domProps.clientTop))/multiple) * multiple
        );
        expect(data.top - (pageYOffset - domProps.clientTop)).to.be.below(top);
        done();
      }, {
        reportTop: true,
        grow: {
          top: multiple
        }
      });

      reporter();
    });

    it('should handle missing grow option with round', (done) => {
      const reporter = createSizeReporter('.mock', (data) => {
        expect(data.width).to.equal(
          Math.round(right - left)
        );
        done();
      }, {
        reportWidth: true
      });

      reporter();
    });

    it('should handle missing grow option prop without round', (done) => {
      const reporter = createSizeReporter('.mock', (data) => {
        expect(data.width).to.equal(
          Math.ceil(right - left)
        );
        done();
      }, {
        reportWidth: true,
        grow: {}
      });

      reporter();
    });
  });
});
<commit_msg>update react test util reference<commit_after>/***
 * Copyright (c) 2016, 2017 Alex Grant (@localnerve), LocalNerve LLC
 * Copyrights licensed under the BSD License. See the accompanying LICENSE file for terms.
 */
/* global before, beforeEach, after, afterEach, describe, it */
import { expect } from 'chai';
import React from 'react';
import { domStart, domStop, mockStart, mockEnd } from '../utils/testdom';
import { Simple, setMockReporter } from '../fixtures/Simple';
import createSizeReporter from '../../lib';

describe('sizeReporter', () => {
  let testUtils;

  before('sizeReporter', () => {
    domStart();
  });

  after('sizeReporter', () => {
    domStop();
  });

  describe('structure', () => {
    it('should report and have expected report items with correct types',
    (done) => {
      const reporter = createSizeReporter('.nothing', (data) => {
        expect(typeof data.width).to.equal('number');
        expect(typeof data.height).to.equal('number');
        expect(typeof data.top).to.equal('number');
        expect(typeof data.accumulate).to.equal('boolean');
        done();
      }, {
        reportWidth: true,
        reportHeight: true,
        reportTop: true
      });

      reporter();
    });
  });

  describe('bad args', () => {
    it('should throw if no selector supplied', () => {
      expect(function () {
        createSizeReporter('', () => {});
      }).to.throw(Error);
    });

    it('should throw if no reporter function supplied', () => {
      expect(function () {
        createSizeReporter('.nothing', 'bad');
      }).to.throw(Error);
    });
  });

  describe('react', () => {
    let testUtils;

    before('react', () => {
      testUtils = require('react-dom/test-utils');
    });

    beforeEach(() => {
      // Clear the group trackers
      createSizeReporter(null, null, {
        _clearTrackers: true
      });
    });

    afterEach(() => {
      setMockReporter(null);
    });

    it('should render and execute action', (done) => {
      const element = React.createElement(Simple);
      const component = testUtils.renderIntoDocument(element);
      const result = testUtils.findRenderedDOMComponentWithClass(
        component, 'contained'
      );

      // Render test
      expect(result.textContent).to.match(/Simple Test/);

      setTimeout(function () {
        // Action test. Executes on componentDidMount so action should've run.
        expect(result.textContent).to.match(/Action/);
        done();
      }, 0);
    });

    it('should accumulate if multiple reporters in same group', (done) => {
      const reporters = 2;
      let reportCall = 0;

      /**
       * @param {Object} data - the report data from size reporter under test.
       */
      function handleReport (data) {
        if (reportCall === 0) {
          // First time, you want to overwrite the data.
          expect(data.accumulate).to.be.false;
        } else {
          // After that, you're accumulating.
          expect(data.accumulate).to.be.true;
        }

        reportCall++;
        if (reportCall === reporters) {
          done();
        }
      }

      setMockReporter(handleReport);

      const children = [Simple, Simple].map((childClass, index) => {
        return React.createElement(childClass, { key: index });
      });

      testUtils.renderIntoDocument(React.createElement('div', {}, children));
    });
  });

  describe('mocked tests', () => {
    const top = 202.2, right = 600, bottom = 600, left = 202.2,
      pageYOffset = 200;
    let domProps;

    function mockQuerySelector () {
      return {
        getBoundingClientRect: function () {
          return {
            top,
            right,
            bottom,
            left
          };
        }
      };
    }

    before('mocks', () => {
      domProps = mockStart({
        querySelector: mockQuerySelector,
        pageYOffset
      });
    });

    after('mocks', () => {
      mockEnd();
    });

    beforeEach(() => {
      // Clear the group trackers
      createSizeReporter(null, null, {
        _clearTrackers: true
      });
    });

    it('should compute values as expected', (done) => {
      const reporter = createSizeReporter('.mock', (data) => {
        expect(data.width).to.equal(Math.round(right - left));
        expect(data.height).to.equal(Math.round(bottom - top));
        expect(data.top).to.equal(Math.round(
          top + (pageYOffset - domProps.clientTop)
        ));
        expect(data.accumulate).to.equal(false);
        done();
      }, {
        reportWidth: true,
        reportHeight: true,
        reportTop: true
      });

      reporter();
    });

    it('should grow width on multiple as expected', (done) => {
      const multiple = 10;

      const reporter = createSizeReporter('.mock', (data) => {
        expect(data.width).to.equal(
          Math.ceil((right - left)/multiple) * multiple
        );
        done();
      }, {
        reportWidth: true,
        grow: {
          width: multiple
        }
      });

      reporter();
    });

    it('should grow top on multiple as expected', (done) => {
      const multiple = 10;

      const reporter = createSizeReporter('.mock', (data) => {
        expect(data.top).to.equal(
          Math.floor((top + (pageYOffset - domProps.clientTop))/multiple) * multiple
        );
        expect(data.top - (pageYOffset - domProps.clientTop)).to.be.below(top);
        done();
      }, {
        reportTop: true,
        grow: {
          top: multiple
        }
      });

      reporter();
    });

    it('should handle missing grow option with round', (done) => {
      const reporter = createSizeReporter('.mock', (data) => {
        expect(data.width).to.equal(
          Math.round(right - left)
        );
        done();
      }, {
        reportWidth: true
      });

      reporter();
    });

    it('should handle missing grow option prop without round', (done) => {
      const reporter = createSizeReporter('.mock', (data) => {
        expect(data.width).to.equal(
          Math.ceil(right - left)
        );
        done();
      }, {
        reportWidth: true,
        grow: {}
      });

      reporter();
    });
  });
});
<|endoftext|>


<commit_before>import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';

import icBEM from '@ichef/gypcrete/lib/utils/icBEM';
import prefixClass from '@ichef/gypcrete/lib/utils/prefixClass';

import AvatarEditor from 'react-avatar-editor';
import EditorPlaceholder from './EditorPlaceholder';

import getInitScale from './utils/getInitScale';
import getInitPosition from './utils/getInitPosition';

import './styles/index.scss';

const DEFAULT_SCALE = 1;

export const COMPONENT_NAME = prefixClass('image-editor');
const ROOT_BEM = icBEM(COMPONENT_NAME);
export const BEM = {
    root: ROOT_BEM,
    canvas: ROOT_BEM.element('canvas'),
    control: ROOT_BEM.element('control'),
    slider: ROOT_BEM.element('slider'),
    placeholder: ROOT_BEM.element('placeholder'),
};

/**
 * <ImageEditor>
 * =============
 * This component is built upon `mosch/react-avatar-editor`, offering pre-configured
 * scale slider, no-image placeholder and a loading indicator mode. It also supports
 * setting an initial cropping rectangle via `initCropRect` prop.
 *
 * This component passes unknown props to the inner `<AvatarEditor>`.
 * Plase refer to: https://git.io/vxhT8, for a full list of supported props.
 *
 * ### Appearance configs
 * - `control`: toggles the scale slider
 * - `autoMargin`: adds `auto` to both left and right CSS margin.
 * - `readOnly`: prevent the editor from modifing the crop.
 * - `loading`: put the editor into a loading indicator mode.
 *
 * ### Notable <AvatarEditor> props
 * - `onLoadSuccess`: called with `imgInfo` when image finishes loading
 *
 */
class ImageEditor extends PureComponent {
    static propTypes = {
        initCropRect: PropTypes.shape({
            x: PropTypes.number,
            y: PropTypes.number,
            width: PropTypes.number,
            height: PropTypes.number,
        }),
        onCropChange: PropTypes.func,
        // appearance configs
        control: PropTypes.bool,
        autoMargin: PropTypes.bool,
        readOnly: PropTypes.bool,
        loading: PropTypes.bool,
        // props for <AvatarEditor>
        image: AvatarEditor.propTypes.image,
        width: AvatarEditor.propTypes.width,
        height: AvatarEditor.propTypes.height,
        onImageChange: AvatarEditor.propTypes.onImageChange,
        onPositionChange: AvatarEditor.propTypes.onPositionChange,
    };

    static defaultProps = {
        initCropRect: undefined,
        onCropChange: () => {},
        control: false,
        autoMargin: false,
        readOnly: false,
        loading: false,
        // props for <AvatarEditor>
        image: AvatarEditor.defaultProps.image,
        width: AvatarEditor.defaultProps.width,
        height: AvatarEditor.defaultProps.height,
        onImageChange: AvatarEditor.defaultProps.onImageChange,
        onPositionChange: AvatarEditor.defaultProps.onPositionChange,
    };

    state = {
        scale: getInitScale(this.props.initCropRect) || DEFAULT_SCALE,
        position: getInitPosition(this.props.initCropRect),
    };

    componentWillReceiveProps(nextProps) {
        // Consider current `scale`, `position` and `initCropRect` outdated when image changes
        if (nextProps.image !== this.props.image) {
            this.setState({
                scale: DEFAULT_SCALE,
                position: undefined,
            });
        }
    }

    /**
     * When maintaining ref with inline arrow function, it sometimes receives
     * mystery `null` during canvas drag. This blocks accessing cropping rect
     * via `onImageChange()` callback.
     *
     * Setting ref with instance method doesn't break. It's just MAGIC.
     */
    setCanvasRef = (ref) => {
        this.canvasRef = ref;
    }

    handleSliderChange = (event) => {
        const newScale = Number(event.target.value);

        this.setState({ scale: newScale });
    }

    handleCanvasPosChange = (newPos) => {
        if (!this.props.readOnly) {
            this.setState({ position: newPos });
        }

        // Proxies original `onPositionChange()` prop for `<AvatarEditor>`
        this.props.onPositionChange(newPos);
    }

    handleCanvasImageChange = () => {
        const newCropRect = this.canvasRef.getCroppingRect();
        this.props.onCropChange(newCropRect);

        // Proxies original `onImageChange()` prop for `<AvatarEditor>`
        this.props.onImageChange();
    }

    renderControl() {
        if (!this.props.control) {
            return null;
        }

        const { image, readOnly, loading } = this.props;
        const shouldDisable = readOnly || !image || loading;

        return (

                <input
                    ref={(ref) => { this.sliderRef = ref; }}
                    type="range"
                    value={this.state.scale}
                    className={BEM.slider.toString()}
                    disabled={shouldDisable}
                    step="0.1"
                    min="0.5"
                    max="5"
                    onChange={this.handleSliderChange} />

        );
    }

    render() {
        const {
            initCropRect,
            control,
            autoMargin,
            readOnly,
            loading,
            // props for <AvatarEditor>
            image,
            width,
            height,
            onImageChange,
            onPositionChange,
            // react props
            className,
            style,
            ...avatarEditorProps,
        } = this.props;

        const wraperBEM = BEM.root
            .modifier('auto-margin', autoMargin)
            .modifier('readonly', readOnly)
            .toString();

        const wrapperClass = classNames(className, wraperBEM);
        const wrapperStyle = { ...style, width };

        const shouldShowPlaceholder = (!image || loading);

        const placeholder = (
            <EditorPlaceholder
                loading={loading}
                className={BEM.placeholder.toString()}
                canvasHeight={height} />
        );
        const canvas = (
            <AvatarEditor
                ref={this.setCanvasRef}
                image={image}
                width={width}
                height={height}
                scale={this.state.scale}
                position={this.state.position}
                onImageChange={this.handleCanvasImageChange}
                onPositionChange={this.handleCanvasPosChange}
                border={0}
                {...avatarEditorProps} />
        );

        return (

                    {shouldShowPlaceholder ? placeholder : canvas}

                {this.renderControl()}

        );
    }
}

export default ImageEditor;
<commit_msg>Move scale range to configurable props<commit_after>import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';

import icBEM from '@ichef/gypcrete/lib/utils/icBEM';
import prefixClass from '@ichef/gypcrete/lib/utils/prefixClass';

import AvatarEditor from 'react-avatar-editor';
import EditorPlaceholder from './EditorPlaceholder';

import getInitScale from './utils/getInitScale';
import getInitPosition from './utils/getInitPosition';

import './styles/index.scss';

const DEFAULT_SCALE = 1;

export const COMPONENT_NAME = prefixClass('image-editor');
const ROOT_BEM = icBEM(COMPONENT_NAME);
export const BEM = {
    root: ROOT_BEM,
    canvas: ROOT_BEM.element('canvas'),
    control: ROOT_BEM.element('control'),
    slider: ROOT_BEM.element('slider'),
    placeholder: ROOT_BEM.element('placeholder'),
};

/**
 * <ImageEditor>
 * =============
 * This component is built upon `mosch/react-avatar-editor`, offering pre-configured
 * scale slider, no-image placeholder and a loading indicator mode. It also supports
 * setting an initial cropping rectangle via `initCropRect` prop.
 *
 * This component passes unknown props to the inner `<AvatarEditor>`.
 * Plase refer to: https://git.io/vxhT8, for a full list of supported props.
 *
 * ### Appearance configs
 * - `control`: toggles the scale slider
 * - `autoMargin`: adds `auto` to both left and right CSS margin.
 * - `readOnly`: prevent the editor from modifing the crop.
 * - `loading`: put the editor into a loading indicator mode.
 *
 * ### Notable <AvatarEditor> props
 * - `onLoadSuccess`: called with `imgInfo` when image finishes loading
 *
 */
class ImageEditor extends PureComponent {
    static propTypes = {
        // cropping configs
        minScale: PropTypes.number,
        maxScale: PropTypes.number,
        initCropRect: PropTypes.shape({
            x: PropTypes.number,
            y: PropTypes.number,
            width: PropTypes.number,
            height: PropTypes.number,
        }),
        onCropChange: PropTypes.func,
        // appearance configs
        control: PropTypes.bool,
        autoMargin: PropTypes.bool,
        readOnly: PropTypes.bool,
        loading: PropTypes.bool,
        // props for <AvatarEditor>
        image: AvatarEditor.propTypes.image,
        width: AvatarEditor.propTypes.width,
        height: AvatarEditor.propTypes.height,
        onImageChange: AvatarEditor.propTypes.onImageChange,
        onPositionChange: AvatarEditor.propTypes.onPositionChange,
    };

    static defaultProps = {
        minScale: 0.5,
        maxScale: 5,
        initCropRect: undefined,
        onCropChange: () => {},
        control: false,
        autoMargin: false,
        readOnly: false,
        loading: false,
        // props for <AvatarEditor>
        image: AvatarEditor.defaultProps.image,
        width: AvatarEditor.defaultProps.width,
        height: AvatarEditor.defaultProps.height,
        onImageChange: AvatarEditor.defaultProps.onImageChange,
        onPositionChange: AvatarEditor.defaultProps.onPositionChange,
    };

    state = {
        scale: getInitScale(this.props.initCropRect) || DEFAULT_SCALE,
        position: getInitPosition(this.props.initCropRect),
    };

    componentWillReceiveProps(nextProps) {
        // Consider current `scale`, `position` and `initCropRect` outdated when image changes
        if (nextProps.image !== this.props.image) {
            this.setState({
                scale: DEFAULT_SCALE,
                position: undefined,
            });
        }
    }

    /**
     * When maintaining ref with inline arrow function, it sometimes receives
     * mystery `null` during canvas drag. This blocks accessing cropping rect
     * via `onImageChange()` callback.
     *
     * Setting ref with instance method doesn't break. It's just MAGIC.
     */
    setCanvasRef = (ref) => {
        this.canvasRef = ref;
    }

    handleSliderChange = (event) => {
        const newScale = Number(event.target.value);

        this.setState({ scale: newScale });
    }

    handleCanvasPosChange = (newPos) => {
        if (!this.props.readOnly) {
            this.setState({ position: newPos });
        }

        // Proxies original `onPositionChange()` prop for `<AvatarEditor>`
        this.props.onPositionChange(newPos);
    }

    handleCanvasImageChange = () => {
        const newCropRect = this.canvasRef.getCroppingRect();
        this.props.onCropChange(newCropRect);

        // Proxies original `onImageChange()` prop for `<AvatarEditor>`
        this.props.onImageChange();
    }

    renderControl() {
        if (!this.props.control) {
            return null;
        }

        const {
            minScale,
            maxScale,
            image,
            readOnly,
            loading,
        } = this.props;
        const shouldDisable = readOnly || !image || loading;

        return (

                <input
                    ref={(ref) => { this.sliderRef = ref; }}
                    type="range"
                    value={this.state.scale}
                    className={BEM.slider.toString()}
                    disabled={shouldDisable}
                    step="0.1"
                    min={minScale}
                    max={maxScale}
                    onChange={this.handleSliderChange} />

        );
    }

    render() {
        const {
            // cropping configs
            minScale,
            maxScale,
            initCropRect,
            onCropChange,
            // appearance configs
            control,
            autoMargin,
            readOnly,
            loading,
            // props for <AvatarEditor>
            image,
            width,
            height,
            onImageChange,
            onPositionChange,
            // react props
            className,
            style,
            ...avatarEditorProps,
        } = this.props;

        const wraperBEM = BEM.root
            .modifier('auto-margin', autoMargin)
            .modifier('readonly', readOnly)
            .toString();

        const wrapperClass = classNames(className, wraperBEM);
        const wrapperStyle = { ...style, width };

        const shouldShowPlaceholder = (!image || loading);

        const placeholder = (
            <EditorPlaceholder
                loading={loading}
                className={BEM.placeholder.toString()}
                canvasHeight={height} />
        );
        const canvas = (
            <AvatarEditor
                ref={this.setCanvasRef}
                image={image}
                width={width}
                height={height}
                scale={this.state.scale}
                position={this.state.position}
                onImageChange={this.handleCanvasImageChange}
                onPositionChange={this.handleCanvasPosChange}
                border={0}
                {...avatarEditorProps} />
        );

        return (

                    {shouldShowPlaceholder ? placeholder : canvas}

                {this.renderControl()}

        );
    }
}

export default ImageEditor;
<|endoftext|>


<commit_before>import { isArray } from '../polyfills';

function serialize(element) {
  var result = {};
  var keys = Object.keys(element);

  var recursiveKeys;
  for (var i = 0; i < keys.length; i++) {
    if (typeof element[keys[i]] === 'object' && !isArray(element[keys[i]])) {
      // Handle hash of arrays of children.
      if (Object.keys(element[keys[i]]).length) {
        result[keys[i]] = serialize(element[keys[i]]);
      }
    } else {
      // Handle arrays of children.
      for (var j = 0; j < element[keys[i]].length; j++) {
        if (!result[keys[i]]) {
          result[keys[i]] = new Array(element[keys[i]].length);
        }
        result[keys[i]][j] = element[keys[i]][j].id;
      }
    }
  }

  return result;
}

class SegmentTrieNode {
  constructor(router, value) {
    this.router = router;
    this.id = this.router.nodes.push(this);

    this.parent = undefined;
    this.haystack = undefined;
    this.children = {
      staticSegments: {},
      epsilonSegments: [],
      dynamicSegments: [],
      globNodes: []
    };

    this.name = undefined;
    this.type = undefined;
    this.handler = undefined;
    this.value = value;
  }

  get regex() {
    return '';
  }

  get score() {
    return '0';
  }

  output() {
    return '';
  }

  append(node) {
    return node.appendTo(this);
  }

  appendTo() {
    throw new Error('appendTo may only be called on a subclass of SegmentTrieNode.');
  }

  _equivalent(node) {
    return (
      this.type === node.type &&
      this.value === node.value &&
      this.handler === node.handler
    );
  }

  _checkExisting() {
    for (let i = 0; i < this.haystack.length; i++) {
      if (this._equivalent(this.haystack[i])) {
        return this.haystack[i];
      }
    }
    return false;
  }

  _existingOrSelf() {
    let existingNode = this._checkExisting();
    if (existingNode) {
      // This node is equivalent to an existing node.
      return existingNode;
    } else {
      // This node isn't equivalent to any existing node.
      this.haystack.push(this);
    }

    return this;
  }

  toJSON() {
    // Set up baseline own properties.
    var result = {
      id: this.id,
      type: this.type
    };

    // Only include fields when necessary for size reasons.
    if (this.value) {
      result.value = this.value;
    }

    if (this.handler) {
      result.handler = this.handler;
    }

    // Set up parent reference.
    if (this.parent) {
      result.parent = this.parent.id;
    }

    var children = serialize(this.children);
    if (Object.keys(children).length) {
      result.children = children;
    }

    return result;
  }

}

export default SegmentTrieNode;
<commit_msg>Don't need to serialize child references. Parent IDs cover that.<commit_after>class SegmentTrieNode {
  constructor(router, value) {
    this.router = router;
    this.id = this.router.nodes.push(this);

    this.parent = undefined;
    this.haystack = undefined;
    this.children = {
      staticSegments: {},
      epsilonSegments: [],
      dynamicSegments: [],
      globNodes: []
    };

    this.name = undefined;
    this.type = undefined;
    this.handler = undefined;
    this.value = value;
  }

  get regex() {
    return '';
  }

  get score() {
    return '0';
  }

  output() {
    return '';
  }

  append(node) {
    return node.appendTo(this);
  }

  appendTo() {
    throw new Error('appendTo may only be called on a subclass of SegmentTrieNode.');
  }

  _equivalent(node) {
    return (
      this.type === node.type &&
      this.value === node.value &&
      this.handler === node.handler
    );
  }

  _checkExisting() {
    for (let i = 0; i < this.haystack.length; i++) {
      if (this._equivalent(this.haystack[i])) {
        return this.haystack[i];
      }
    }
    return false;
  }

  _existingOrSelf() {
    let existingNode = this._checkExisting();
    if (existingNode) {
      // This node is equivalent to an existing node.
      return existingNode;
    } else {
      // This node isn't equivalent to any existing node.
      this.haystack.push(this);
    }

    return this;
  }

  toJSON() {
    // Set up baseline own properties.
    var result = {
      id: this.id,
      type: this.type
    };

    // Only include fields when necessary for size reasons.
    if (this.value) {
      result.value = this.value;
    }

    if (this.handler) {
      result.handler = this.handler;
    }

    // Set up parent reference.
    if (this.parent) {
      result.parent = this.parent.id;
    }

    return result;
  }

}

export default SegmentTrieNode;
<|endoftext|>


<commit_before>
/**
 * Module dependencies
 */

var radclient = require('..');
var colors = require('colors');
var path = require('path');

function random(begin, end) {
  return Math.floor(Math.random() * (end - begin + 1 ) + begin);
}

// Sample Access-Request packet

var packet = {
  code: 'Access-Request',
  secret: 'd3ath$t@r_Rd',
  identifier: random(0, 255),
  attributes: [
    ['NAS-IP-Address', '192.168.10.39'],
    ['User-Name', 'utente'],
    ['User-Password', 'uccellone231']
  ]
};

// Options

var options = {
  host: '192.168.100.102',
  dictionaries: path.join(__dirname, '../dictionaries')
};

// Go!

radclient(packet, options, function(err, response) {
  console.log('Error'.bold.white);
  console.log(err);

  if (response) {
    console.log('\nResponse'.bold.cyan);
    console.log(response);

    console.log('\nAttributes'.bold.green);
    console.log(response.attributes);
  }

});
<commit_msg>Updated example<commit_after>
/**
 * Module dependencies
 */

var radclient = require('..');
var colors = require('colors');
var path = require('path');

function random(begin, end) {
  return Math.floor(Math.random() * (end - begin + 1) + begin);
}

// Sample Access-Request packet

var packet = {
  code: 'Access-Request',
  secret: 'd3ath$t@r_Rd',
  identifier: random(0, 255),
  attributes: [
    ['NAS-IP-Address', '192.168.1.10'],
    ['User-Name', 'john'],
    ['User-Password', 'doe']
  ]
};

// Options

var options = {
  host: '192.168.1.2',
  dictionaries: path.join(__dirname, '../dictionaries')
};

// Go!

radclient(packet, options, function(err, response) {
  console.log('Error'.bold.white);
  console.log(err);

  if (response) {
    console.log('\nResponse'.bold.cyan);
    console.log(response);

    console.log('\nAttributes'.bold.green);
    console.log(response.attributes);
  }

});
<|endoftext|>


<commit_before>var cities = new L.LayerGroup();

L.marker([39.61, -105.02]).bindPopup('This is Littleton, CO.').addTo(cities),
L.marker([39.74, -104.99]).bindPopup('This is Denver, CO.').addTo(cities),
L.marker([39.73, -104.8]).bindPopup('This is Aurora, CO.').addTo(cities),
L.marker([39.77, -105.23]).bindPopup('This is Golden, CO.').addTo(cities);

var streets = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
	attribution: '© OpenStreetMap contributors'
});

var map = L.map('map', {
	center: [39.73, -104.99],
	zoom: 10,
	layers: [streets, cities]
});

var baseLayers = {
	"Streets": streets
};

var overlays = {
	"Cities": cities
};

L.control.layers(baseLayers, overlays).addTo(map);
<commit_msg>Moved markers<commit_after>var urbanParks = new L.LayerGroup();
var urbanBuildings = new L.LayerGroup();
var riversideParks = new L.LayerGroup();
var riversideBuildings = new L.LayerGroup();

L.marker([51.503984, -0.118253]).addTo(riversideParks);
L.marker([51.497466, -0.124905]).addTo(riversideParks);
L.marker([51.506061, -0.116966]).addTo(riversideBuildings);
L.marker([51.499102, -0.124648]).addTo(riversideBuildings);
L.marker([51.503797, -0.143649]).addTo(urbanParks);
L.marker([51.530535, -0.153362]).addTo(urbanParks);
L.marker([51.500784, -0.143052]).addTo(urbanBuildings);
L.marker([51.497770, -0.101477]).addTo(urbanBuildings);

var streets = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
	attribution: '© OpenStreetMap contributors'
});

var map = L.map('map', {
	center: [51.515, -0.13],
	zoom: 13,
	layers: [streets, urbanParks, urbanBuildings, riversideParks, riversideBuildings]
});

var baseLayers = {
	"Streets": streets
};

var overlays = {
	"urbanParks": urbanParks,
	"urbanBuildings": urbanBuildings,
	"riversideParks": riversideParks,
	"riversideBuildings": riversideBuildings
};

L.control.layers(baseLayers, overlays).addTo(map);
<|endoftext|>


<commit_before>/* eslint no-console:0 */

require('rc-input-number/assets/index.less');
const InputNumber = require('rc-input-number');
const React = require('react');
const ReactDOM = require('react-dom');

const Component = React.createClass({
  getInitialState() {
    return {
      disabled: false,
      readOnly: false,
      value: 1,
    };
  },
  onChange(v) {
    console.log('onChange:', v);
    this.setState({
      value: v,
    });
  },
  toggleDisabled() {
    this.setState({
      disabled: !this.state.disabled,
    });
  },
  toggleReadOnly() {
    this.setState({
      readOnly: !this.state.readOnly,
    });
  },
  render() {
    return (

        <InputNumber
          min={-8}
          max={100}
          value={this.state.value}
          style={{width: 100}}
          readOnly={this.state.readOnly}
          onChange={this.onChange}
          disabled={this.state.disabled} />

          <button onClick={this.toggleDisabled}>toggle Disabled</button>
          <button onClick={this.toggleReadOnly}>toggle readOnly</button>

    );
  },
});

ReactDOM.render(<Component/>, document.getElementById('__react-content'));
<commit_msg>make example get maximum easily.<commit_after>/* eslint no-console:0 */

require('rc-input-number/assets/index.less');
const InputNumber = require('rc-input-number');
const React = require('react');
const ReactDOM = require('react-dom');

const Component = React.createClass({
  getInitialState() {
    return {
      disabled: false,
      readOnly: false,
      value: 5,
    };
  },
  onChange(v) {
    console.log('onChange:', v);
    this.setState({
      value: v,
    });
  },
  toggleDisabled() {
    this.setState({
      disabled: !this.state.disabled,
    });
  },
  toggleReadOnly() {
    this.setState({
      readOnly: !this.state.readOnly,
    });
  },
  render() {
    return (

        <InputNumber
          min={-8}
          max={10}
          value={this.state.value}
          style={{width: 100}}
          readOnly={this.state.readOnly}
          onChange={this.onChange}
          disabled={this.state.disabled} />

          <button onClick={this.toggleDisabled}>toggle Disabled</button>
          <button onClick={this.toggleReadOnly}>toggle readOnly</button>

    );
  },
});

ReactDOM.render(<Component/>, document.getElementById('__react-content'));
<|endoftext|>


<commit_before>import external from '../externalModules.js';
import BaseTool from './base/BaseTool.js';
import { getToolState, removeToolState } from '../stateManagement/toolState.js';
import { state } from '../store/index.js';

/**
 * @public
 * @class EraserTool
 * @memberof Tools
 *
 * @classdesc Tool for deleting the data of other Annotation Tools.
 * @extends Tools.Base.BaseTool
 */
export default class EraserTool extends BaseTool {
  constructor(configuration = {}) {
    const defaultConfig = {
      name: 'Eraser',
      supportedInteractionTypes: ['Mouse', 'Touch'],
    };
    const initialConfiguration = Object.assign(defaultConfig, configuration);

    super(initialConfiguration);

    this.initialConfiguration = initialConfiguration;

    this.preMouseDownCallback = this._deleteAllNearbyTools.bind(this);
    this.preTouchStartCallback = this._deleteAllNearbyTools.bind(this);
  }

  _deleteAllNearbyTools(evt) {
    const coords = evt.detail.currentPoints.canvas;
    const element = evt.detail.element;

    state.tools.forEach(function(tool) {
      const toolState = getToolState(element, tool.name);

      if (toolState) {
        // Modifying in a foreach? Probably not ideal
        toolState.data.forEach(function(data) {
          if (
            typeof tool.pointNearTool === 'function' &&
            tool.pointNearTool(element, data, coords)
          ) {
            removeToolState(element, tool.name, data);
            external.cornerstone.updateImage(element);
          }
        });
      }
    });

    const consumeEvent = true;

    return consumeEvent;
  }
}
<commit_msg>add Eraser Cursor.<commit_after>import external from '../externalModules.js';
import BaseTool from './base/BaseTool.js';
import MouseCursor from '../util/MouseCursor.js';
import { getToolState, removeToolState } from '../stateManagement/toolState.js';
import { state } from '../store/index.js';

/**
 * @public
 * @class EraserTool
 * @memberof Tools
 *
 * @classdesc Tool for deleting the data of other Annotation Tools.
 * @extends Tools.Base.BaseTool
 */
export default class EraserTool extends BaseTool {
  constructor(configuration = {}) {
    const defaultConfig = {
      name: 'Eraser',
      supportedInteractionTypes: ['Mouse', 'Touch'],
    };
    const initialConfiguration = Object.assign(defaultConfig, configuration);

    super(initialConfiguration);

    this.initialConfiguration = initialConfiguration;

    this.configuration.svgCursor = this.configuration.svgCursor || eraserCursor;

    this.preMouseDownCallback = this._deleteAllNearbyTools.bind(this);
    this.preTouchStartCallback = this._deleteAllNearbyTools.bind(this);
  }

  _deleteAllNearbyTools(evt) {
    const coords = evt.detail.currentPoints.canvas;
    const element = evt.detail.element;

    state.tools.forEach(function(tool) {
      const toolState = getToolState(element, tool.name);

      if (toolState) {
        // Modifying in a foreach? Probably not ideal
        toolState.data.forEach(function(data) {
          if (
            typeof tool.pointNearTool === 'function' &&
            tool.pointNearTool(element, data, coords)
          ) {
            removeToolState(element, tool.name, data);
            external.cornerstone.updateImage(element);
          }
        });
      }
    });

    const consumeEvent = true;

    return consumeEvent;
  }
}

const eraserCursor = new MouseCursor(
  `<svg
    data-icon="eraser" role="img" xmlns="http://www.w3.org/2000/svg"
    width="32" height="28" viewBox="0 0 2048 1792"
  >
    <path transform="translate(0,1792) scale(1,-1)" fill="#ffffff" d="M960 1408l336-384h-768l-336 384h768zm1013-1077q15
      34 9.5 71.5t-30.5 65.5l-896 1024q-38 44-96 44h-768q-38
      0-69.5-20.5t-47.5-54.5q-15-34-9.5-71.5t30.5-65.5l896-1024q38-44 96-44h768q38
      0 69.5 20.5t47.5 54.5z"
    />
  </svg>`,
  'topLeft'
);
<|endoftext|>


<commit_before>'use strict';

var util = require('util');

module.exports = {
  maxDepthFactory: maxDepthFactory,
  serialize: serialize,
  toJSON: toJSON,
  toStringFactory: toStringFactory,
};

function createSerializer() {
  var seen = createWeakSet();

  return function (key, value) {
    if (typeof value === 'object' && value !== null) {
      if (seen.has(value)) {
        return undefined;
      }

      seen.add(value);
    }

    return serialize(key, value);
  };
}

/**
 * @return {WeakSet<object>}
 */
function createWeakSet() {
  if (typeof WeakSet !== 'undefined') {
    return new WeakSet();
  }

  var cache = [];
  this.add = function (value) { cache.push(value) };
  this.has = function (value) { return cache.indexOf(value) !== -1 };

  return this;
}

function maxDepth(data, depth) {
  if (!data) {
    return data;
  }

  if (depth < 1) {
    if (isArray(data)) return '[array]';
    if (typeof data === 'object' && data) return '[object]';

    return data;
  }

  if (isArray(data)) {
    return data.map(function (child) {
      return maxDepth(child, depth - 1);
    });
  }

  if (typeof data !== 'object') {
    return data;
  }

  if (data && typeof data.toISOString === 'function') {
    return data;
  }

  // noinspection PointlessBooleanExpressionJS
  if (data === null) {
    return null;
  }

  if (data instanceof Error) {
    return data;
  }

  var newJson = {};
  for (var i in data) {
    if (!Object.prototype.hasOwnProperty.call(data, i)) continue;
    newJson[i] = maxDepth(data[i], depth - 1);
  }

  return newJson;
}

function maxDepthFactory(depth) {
  depth = depth || 6;

  return function maxDepthFunction(data) {
    return maxDepth(data, depth);
  };
}

function serialize(key, value) {
  if (value instanceof Error) {
    return value.stack;
  }

  if (!value) {
    return value;
  }

  if (typeof value.toJSON === 'function') {
    return value.toJSON();
  }

  if (typeof value === 'function') {
    return '[function] ' + value.toString();
  }

  return value;
}

function toJSON(data) {
  return JSON.parse(JSON.stringify(data, createSerializer()));
}

function toStringFactory(depth) {
  depth = depth || 5;

  return function toStringFunction(data) {
    var simplifiedData = data.map(function (item) {
      if (item === undefined) {
        return undefined;
      }

      var str = JSON.stringify(item, createSerializer(), '  ');
      if (str === undefined) {
        return undefined;
      }

      return JSON.parse(str);
    });

    if (util.formatWithOptions) {
      simplifiedData.unshift({ depth: depth });
      return util.formatWithOptions.apply(util, simplifiedData);
    }

    return util.format.apply(util, simplifiedData);
  };
}

function isArray(value) {
  return Object.prototype.toString.call(value) === '[object Array]';
}
<commit_msg>fix(transform): Wrong scope in WeekSet polyfill<commit_after>'use strict';

var util = require('util');

module.exports = {
  maxDepthFactory: maxDepthFactory,
  serialize: serialize,
  toJSON: toJSON,
  toStringFactory: toStringFactory,
};

function createSerializer() {
  var seen = createWeakSet();

  return function (key, value) {
    if (typeof value === 'object' && value !== null) {
      if (seen.has(value)) {
        return undefined;
      }

      seen.add(value);
    }

    return serialize(key, value);
  };
}

/**
 * @return {WeakSet<object>}
 */
function createWeakSet() {
  if (typeof WeakSet !== 'undefined') {
    return new WeakSet();
  }

  var cache = [];
  return {
    add: function (value) { cache.push(value) },
    has: function (value) { return cache.indexOf(value) !== -1 },
  };
}

function maxDepth(data, depth) {
  if (!data) {
    return data;
  }

  if (depth < 1) {
    if (isArray(data)) return '[array]';
    if (typeof data === 'object' && data) return '[object]';

    return data;
  }

  if (isArray(data)) {
    return data.map(function (child) {
      return maxDepth(child, depth - 1);
    });
  }

  if (typeof data !== 'object') {
    return data;
  }

  if (data && typeof data.toISOString === 'function') {
    return data;
  }

  // noinspection PointlessBooleanExpressionJS
  if (data === null) {
    return null;
  }

  if (data instanceof Error) {
    return data;
  }

  var newJson = {};
  for (var i in data) {
    if (!Object.prototype.hasOwnProperty.call(data, i)) continue;
    newJson[i] = maxDepth(data[i], depth - 1);
  }

  return newJson;
}

function maxDepthFactory(depth) {
  depth = depth || 6;

  return function maxDepthFunction(data) {
    return maxDepth(data, depth);
  };
}

function serialize(key, value) {
  if (value instanceof Error) {
    return value.stack;
  }

  if (!value) {
    return value;
  }

  if (typeof value.toJSON === 'function') {
    return value.toJSON();
  }

  if (typeof value === 'function') {
    return '[function] ' + value.toString();
  }

  return value;
}

function toJSON(data) {
  return JSON.parse(JSON.stringify(data, createSerializer()));
}

function toStringFactory(depth) {
  depth = depth || 5;

  return function toStringFunction(data) {
    var simplifiedData = data.map(function (item) {
      if (item === undefined) {
        return undefined;
      }

      var str = JSON.stringify(item, createSerializer(), '  ');
      if (str === undefined) {
        return undefined;
      }

      return JSON.parse(str);
    });

    if (util.formatWithOptions) {
      simplifiedData.unshift({ depth: depth });
      return util.formatWithOptions.apply(util, simplifiedData);
    }

    return util.format.apply(util, simplifiedData);
  };
}

function isArray(value) {
  return Object.prototype.toString.call(value) === '[object Array]';
}
<|endoftext|>


<commit_before>import PropTypes from 'proptypes'

// primitive types are types that never needs type annotations, e.g their values maps directly to a
// native javascript/json-serializable type
export default {
  object: {
    options: {
      title: PropTypes.string,
      fields: PropTypes.object.isRequired
    },
    parse(options, typeBuilders, schema) {
      if (!options.fields) {
        throw new Error('Object types must have fields')
      }
      const fieldNames = Object.keys(options.fields)

      const fields = {}

      fieldNames.forEach(fieldName => {

        if (fieldName === '$type') {
          throw new Error('`$type` is reserved and cannot be used as field name.')
        }

        const field = options.fields[fieldName]

        if (!(field || {}).type) {
          throw new Error(`Missing .type property for field "${fieldName}".`)
        }

        const typeBuilder = typeBuilders[field.type]
        if (!typeBuilder) {
          throw new Error(`Invalid type "${field.type}" for field "${fieldName}".`)
        }
        fields[fieldName] = typeBuilder(field, typeBuilders, schema)
      })
      return {fields}
    }
  },
  boolean: {
    options: {
      title: PropTypes.string
    }
  },
  array: {
    options: {
      title: PropTypes.string,
      of: PropTypes.array.isRequired
    },
    parse(options, typeBuilders, schema) {
      const containsTypes = options.of.map(typeDef => {
        const typeBuilder = typeBuilders[typeDef.type]
        if (!typeBuilder) {
          throw new Error(`Invalid type: ${typeDef.type}.`)
        }
        return typeBuilder(typeDef, typeBuilders, schema)
      })
      return {of: containsTypes}
    }
  },
  number: {
    options: {
      title: PropTypes.string
    }
  },
  date: {
    options: {
      title: PropTypes.string,
      precision: PropTypes.oneOf(['second', 'minute', 'hour', 'day', 'month', 'year', 'decade', 'century'])
    },
    defaultOptions: {
      precision: 'minute'
    }
  },
  string: {
    options: {
      title: PropTypes.string,
      format: PropTypes.oneOf(['markdown', 'html', 'plain']),
      maxLength: PropTypes.number
    },
    defaultOptions: {
      format: 'plain'
    }
  }
}
<commit_msg>Improve error message<commit_after>import PropTypes from 'proptypes'

// primitive types are types that never needs type annotations, e.g their values maps directly to a
// native javascript/json-serializable type
export default {
  object: {
    options: {
      title: PropTypes.string,
      fields: PropTypes.object.isRequired
    },
    parse(options, typeBuilders, schema) {
      if (!options.fields) {
        throw new Error('Object types must have fields')
      }
      const fieldNames = Object.keys(options.fields)

      const fields = {}

      fieldNames.forEach(fieldName => {

        if (fieldName === '$type') {
          throw new Error('`$type` is reserved and cannot be used as field name.')
        }

        const field = options.fields[fieldName]

        if (!(field || {}).type) {
          throw new Error(`Missing .type property for field "${fieldName}".`)
        }

        const typeBuilder = typeBuilders[field.type]
        if (!typeBuilder) {
          throw new Error(
            `Invalid type "${field.type}" for field "${fieldName}". Did you forget to declare the type ${field.type} in the schema?`
          )
        }
        fields[fieldName] = typeBuilder(field, typeBuilders, schema)
      })
      return {fields}
    }
  },
  boolean: {
    options: {
      title: PropTypes.string
    }
  },
  array: {
    options: {
      title: PropTypes.string,
      of: PropTypes.array.isRequired
    },
    parse(options, typeBuilders, schema) {
      const containsTypes = options.of.map(typeDef => {
        const typeBuilder = typeBuilders[typeDef.type]
        if (!typeBuilder) {
          throw new Error(`Invalid type: ${typeDef.type}.`)
        }
        return typeBuilder(typeDef, typeBuilders, schema)
      })
      return {of: containsTypes}
    }
  },
  number: {
    options: {
      title: PropTypes.string
    }
  },
  date: {
    options: {
      title: PropTypes.string,
      precision: PropTypes.oneOf(['second', 'minute', 'hour', 'day', 'month', 'year', 'decade', 'century'])
    },
    defaultOptions: {
      precision: 'minute'
    }
  },
  string: {
    options: {
      title: PropTypes.string,
      format: PropTypes.oneOf(['markdown', 'html', 'plain']),
      maxLength: PropTypes.number
    },
    defaultOptions: {
      format: 'plain'
    }
  }
}
<|endoftext|>


<commit_before>/*
Class: CollapsingNav

Monitors the padding of nav elements inside a flexible horizontal nav container, putting items into a submenu when the padding gets too small (ie items get scrunched together).  Kinda limited in scope, in that it won't work for items with fixed padding, but that could be added as a different calculation method.

Example Usage:
	$sectionNavs = jQuery('.sectionNav');
	if($sectionNavs.length){
		$sectionNavs.each(function(){
			var $this = jQuery(this);
			var _collapsingNav = new __CollapsingNav({
				$: $this
				,doHandleResize: function(){
					return this.$.is('.current');
				}
			});
			var _dropDownMenu = new __.classes.DropDownMenu({
				elmWrapper: $this
				,itemSelector: '> .topItem'
			});
		});
	}

*/
/* global clearTimeout, define, setTimeout, window */
define(['tmclasses/tmclasses', 'jquery', './DropDown'], function(__tmclasses, jQuery, __DropDown){
	var __hasTooManyItemsMethods = {
		itemPadding: function(){
			var _this = this;
			var $navItems = this.mainList.find(this.navItemSelector);
			var _hasEnoughHeightDifference = false;
			var _hasTooLittlePadding = false;

			$navItems.each(function(){
				var $this = jQuery(this);
				var $topLevel = $this.find(_this.topLevelSelector);
				var _itemPadding = $this.outerWidth() - $topLevel.outerWidth();
				if(_itemPadding < _this.minimumPadding){
					_hasTooLittlePadding = true;
					return false;
				}
				//--check height to see if item wraps
				//-# must do this for each item, since individual items may have different font-size, etc
				var _html = $topLevel.html();
				$topLevel.html('x');
				var _singleLineHeight = $topLevel.outerHeight();
				$topLevel.html(_html);
				var _outerHeight = $topLevel.outerHeight();
				if(
					_singleLineHeight
					&& Math.abs(_outerHeight - _singleLineHeight) > 0.3 * _singleLineHeight
				){
					_hasEnoughHeightDifference = true;
					return false;
				}
			});
			return _hasEnoughHeightDifference || _hasTooLittlePadding;
		}
		,rightPos: function(){
			var _this = this;
			var $container = _this.getContainer();

			var containerRight = $container.offset().left + $container.outerWidth();
			var mainListRight = _this.mainList.offset().left + _this.mainList.outerWidth();

			return mainListRight > containerRight;
		}
	};

	var __CollapsingNav = __tmclasses.create({
		init: function(){
			this.__parent(arguments);
			var _this = this;

			if(!_this.moreItem){
				_this.moreItem = jQuery(_this.moreItemHTML);
			}
			_this.moreItem.data('isAttached', false);

			if(!_this.moreList){
				_this.moreList = _this.moreItem.find(_this.moreListSelector);
			}

			if(!_this.mainList){
				_this.mainList = _this.$.find(_this.mainListSelector);
			}

			if(_this.dropDown === undefined){
				_this.dropDown = new __DropDown(_this.getDropDownOpts());
			}

			if(_this.isActive){
				_this.activate();
			}
		}
		,properties: {
			$: null
			,$window: jQuery(window)
			,activate: function(){
				//--attach resize listener
				this.$window.on('resize', jQuery.proxy(this.handleResizeInInterval, this));

				this.isActive = true;

				this.handleResize();
			}
			,container: function(){
				this.container = jQuery('body');
				return this.container;
			}
			,dropDown: undefined
			,getContainer: function(){
				if(typeof this.container === 'function'){
					return this.container();
				}else{
					return this.container;
				}
			}
			,getDropDownOpts: function(_opts){
				return jQuery.extend({
					$: this.moreItem
					,itemSelector: 'this'
				}, _opts);
			}
			,deactivate: function(){
				clearTimeout(this.resizeTimeout);

				//--detach resize listener
				this.$window.off('resize', jQuery.proxy(this.handleResizeInInterval, this));

				if(this.dropDown){
					this.dropDown.deactivate();
				}

				this.isActive = false;

				this.popAllFromMoreList();
			}
			,doHandleResize: true
			,fillFrom: 'top'
			,getNextItemInMoreList: function(){
				var $items = this.moreList.find(this.navItemSelector);
				if($items.length){
					if(this.fillFrom === 'top'){
						return $items.first();
					}else{
						return $items.last();
					}
				}else{
					return null;
				}
			}
			,handleResize: function(){
				var doHandleResize = true;
				switch(typeof this.doHandleResize){
					case 'function':
						doHandleResize = this.doHandleResize.apply(this, arguments);
					break;
					default:
						doHandleResize = (this.doHandleResize);
					break;
				}
				if(doHandleResize){
					if(this.hasTooManyItems()){
						if(!this.moreItem.data('isAttached')){
							//--attach moreItem
							this.mainList.append(this.moreItem);
							this.moreItem.data('isAttached', true);
						}
						//--add items one by one to menu until not _isSectionNavTooNarrow
						do{
							this.pushItemToMoreList();
						}while(this.hasTooManyItems());
					}else{
						//--remove items one by one until not _isSectionNavTooNarrow
						do{
							this.popItemFromMoreList();
						}while(this.moreList.find(this.navItemSelector).length && !this.hasTooManyItems());

						//--reinsert one if too many are added
						if(this.hasTooManyItems()){
							this.pushItemToMoreList();
						}

						//--if item count reaches 0, detach moreItem
						if(this.moreItem.data('isAttached') && !this.moreList.find(this.navItemSelector).length){
							this.moreItem.detach();
							this.moreItem.data('isAttached', false);
						}
					}
					if(this.dropDown){
						this.dropDown.activate();
					}
				}
			}
			,handleResizeInInterval: function(){
				var _this = this;
				clearTimeout(_this.resizeTimeout);
				_this.resizeTimeout = setTimeout(function(){
					_this.handleResize();
				}, _this.resizeInterval);
			}
			,isActive: true
			,hasTooManyItems: function(){
				//--get actual method from private map based on 'hasTooManyItemsMethod' setting
				return __hasTooManyItemsMethods[this.hasTooManyItemsMethod].apply(this, arguments);
			}
			,hasTooManyItemsMethod: 'rightPos'
			,mainListSelector: '.navList.l-1'
			,minimumPadding: 20
			,moreItem: null
			,moreItemHTML: '
'
				+	'More'
				+	'
'
				+		'

'
				+	'
'
				+ '
'
			,moreList: null
			,moreListSelector: '.navList'
			,mainList: null
			,navItemSelector: '> .topItem'
			,popAllFromMoreList: function(){
				var $item;
				while(($item = this.getNextItemInMoreList())){
					this.popItemFromMoreList($item);
				}
				return this;
			}
			,popItemFromMoreList: function($item){
				if(!$item){
					$item = this.getNextItemInMoreList();
				}
				if($item){
					$item.detach();
					this.mainList.find(this.navItemSelector).last().before($item);
					if(this.dropDown && this.dropDown.doSizeAndCenter){
						this.dropDown.sizeAndCenter();
					}
				}
				return this;
			}
			,pushItemToMoreList: function(){
				var $item = (this.moreItem.data('isAttached'))
					? this.moreItem.prev()
					: this.mainList.find(this.navItemSelector).last();
				$item.detach();
				if(this.fillFrom === 'bottom'){
					this.moreList.append($item);
				}else{
					this.moreList.prepend($item);
				}
				if(this.dropDown && this.dropDown.doSizeAndCenter){
					this.dropDown.sizeAndCenter();
				}
				return this;
			}
			,resizeTimeout: null
			,resizeInterval: 200
			,topLevelSelector: '> .topLevel'
		}
	});
	return __CollapsingNav;
});
<commit_msg>ui/collapsingnav: 'topLevelSelector' now more generic ('.navItem')<commit_after>/*
Class: CollapsingNav

Monitors the padding of nav elements inside a flexible horizontal nav container, putting items into a submenu when the padding gets too small (ie items get scrunched together).  Kinda limited in scope, in that it won't work for items with fixed padding, but that could be added as a different calculation method.

Example Usage:
	$sectionNavs = jQuery('.sectionNav');
	if($sectionNavs.length){
		$sectionNavs.each(function(){
			var $this = jQuery(this);
			var _collapsingNav = new __CollapsingNav({
				$: $this
				,doHandleResize: function(){
					return this.$.is('.current');
				}
			});
			var _dropDownMenu = new __.classes.DropDownMenu({
				elmWrapper: $this
				,itemSelector: '> .topItem'
			});
		});
	}

*/
/* global clearTimeout, define, setTimeout, window */
define(['tmclasses/tmclasses', 'jquery', './DropDown'], function(__tmclasses, jQuery, __DropDown){
	var __hasTooManyItemsMethods = {
		itemPadding: function(){
			var _this = this;
			var $navItems = this.mainList.find(this.navItemSelector);
			var _hasEnoughHeightDifference = false;
			var _hasTooLittlePadding = false;

			$navItems.each(function(){
				var $this = jQuery(this);
				var $topLevel = $this.find(_this.topLevelSelector);
				var _itemPadding = $this.outerWidth() - $topLevel.outerWidth();
				if(_itemPadding < _this.minimumPadding){
					_hasTooLittlePadding = true;
					return false;
				}
				//--check height to see if item wraps
				//-# must do this for each item, since individual items may have different font-size, etc
				var _html = $topLevel.html();
				$topLevel.html('x');
				var _singleLineHeight = $topLevel.outerHeight();
				$topLevel.html(_html);
				var _outerHeight = $topLevel.outerHeight();
				if(
					_singleLineHeight
					&& Math.abs(_outerHeight - _singleLineHeight) > 0.3 * _singleLineHeight
				){
					_hasEnoughHeightDifference = true;
					return false;
				}
			});
			return _hasEnoughHeightDifference || _hasTooLittlePadding;
		}
		,rightPos: function(){
			var _this = this;
			var $container = _this.getContainer();

			var containerRight = $container.offset().left + $container.outerWidth();
			var mainListRight = _this.mainList.offset().left + _this.mainList.outerWidth();

			return mainListRight > containerRight;
		}
	};

	var __CollapsingNav = __tmclasses.create({
		init: function(){
			this.__parent(arguments);
			var _this = this;

			if(!_this.moreItem){
				_this.moreItem = jQuery(_this.moreItemHTML);
			}
			_this.moreItem.data('isAttached', false);

			if(!_this.moreList){
				_this.moreList = _this.moreItem.find(_this.moreListSelector);
			}

			if(!_this.mainList){
				_this.mainList = _this.$.find(_this.mainListSelector);
			}

			if(_this.dropDown === undefined){
				_this.dropDown = new __DropDown(_this.getDropDownOpts());
			}

			if(_this.isActive){
				_this.activate();
			}
		}
		,properties: {
			$: null
			,$window: jQuery(window)
			,activate: function(){
				//--attach resize listener
				this.$window.on('resize', jQuery.proxy(this.handleResizeInInterval, this));

				this.isActive = true;

				this.handleResize();
			}
			,container: function(){
				this.container = jQuery('body');
				return this.container;
			}
			,dropDown: undefined
			,getContainer: function(){
				if(typeof this.container === 'function'){
					return this.container();
				}else{
					return this.container;
				}
			}
			,getDropDownOpts: function(_opts){
				return jQuery.extend({
					$: this.moreItem
					,itemSelector: 'this'
				}, _opts);
			}
			,deactivate: function(){
				clearTimeout(this.resizeTimeout);

				//--detach resize listener
				this.$window.off('resize', jQuery.proxy(this.handleResizeInInterval, this));

				if(this.dropDown){
					this.dropDown.deactivate();
				}

				this.isActive = false;

				this.popAllFromMoreList();
			}
			,doHandleResize: true
			,fillFrom: 'top'
			,getNextItemInMoreList: function(){
				var $items = this.moreList.find(this.navItemSelector);
				if($items.length){
					if(this.fillFrom === 'top'){
						return $items.first();
					}else{
						return $items.last();
					}
				}else{
					return null;
				}
			}
			,handleResize: function(){
				var doHandleResize = true;
				switch(typeof this.doHandleResize){
					case 'function':
						doHandleResize = this.doHandleResize.apply(this, arguments);
					break;
					default:
						doHandleResize = (this.doHandleResize);
					break;
				}
				if(doHandleResize){
					if(this.hasTooManyItems()){
						if(!this.moreItem.data('isAttached')){
							//--attach moreItem
							this.mainList.append(this.moreItem);
							this.moreItem.data('isAttached', true);
						}
						//--add items one by one to menu until not _isSectionNavTooNarrow
						do{
							this.pushItemToMoreList();
						}while(this.hasTooManyItems());
					}else{
						//--remove items one by one until not _isSectionNavTooNarrow
						do{
							this.popItemFromMoreList();
						}while(this.moreList.find(this.navItemSelector).length && !this.hasTooManyItems());

						//--reinsert one if too many are added
						if(this.hasTooManyItems()){
							this.pushItemToMoreList();
						}

						//--if item count reaches 0, detach moreItem
						if(this.moreItem.data('isAttached') && !this.moreList.find(this.navItemSelector).length){
							this.moreItem.detach();
							this.moreItem.data('isAttached', false);
						}
					}
					if(this.dropDown){
						this.dropDown.activate();
					}
				}
			}
			,handleResizeInInterval: function(){
				var _this = this;
				clearTimeout(_this.resizeTimeout);
				_this.resizeTimeout = setTimeout(function(){
					_this.handleResize();
				}, _this.resizeInterval);
			}
			,isActive: true
			,hasTooManyItems: function(){
				//--get actual method from private map based on 'hasTooManyItemsMethod' setting
				return __hasTooManyItemsMethods[this.hasTooManyItemsMethod].apply(this, arguments);
			}
			,hasTooManyItemsMethod: 'rightPos'
			,mainListSelector: '.navList.l-1'
			,minimumPadding: 20
			,moreItem: null
			,moreItemHTML: '
'
				+	'More'
				+	'
'
				+		'

'
				+	'
'
				+ '
'
			,moreList: null
			,moreListSelector: '.navList'
			,mainList: null
			,navItemSelector: '> .topItem'
			,popAllFromMoreList: function(){
				var $item;
				while(($item = this.getNextItemInMoreList())){
					this.popItemFromMoreList($item);
				}
				return this;
			}
			,popItemFromMoreList: function($item){
				if(!$item){
					$item = this.getNextItemInMoreList();
				}
				if($item){
					$item.detach();
					this.mainList.find(this.navItemSelector).last().before($item);
					if(this.dropDown && this.dropDown.doSizeAndCenter){
						this.dropDown.sizeAndCenter();
					}
				}
				return this;
			}
			,pushItemToMoreList: function(){
				var $item = (this.moreItem.data('isAttached'))
					? this.moreItem.prev()
					: this.mainList.find(this.navItemSelector).last();
				$item.detach();
				if(this.fillFrom === 'bottom'){
					this.moreList.append($item);
				}else{
					this.moreList.prepend($item);
				}
				if(this.dropDown && this.dropDown.doSizeAndCenter){
					this.dropDown.sizeAndCenter();
				}
				return this;
			}
			,resizeTimeout: null
			,resizeInterval: 200
			,topLevelSelector: '> .navItem'
		}
	});
	return __CollapsingNav;
});
<|endoftext|>


<commit_before>import Vue from 'vue';
import { addClass, removeClass, getStyle } from 'element-ui/src/utils/dom';
let Mask = Vue.extend(require('./loading.vue'));

exports.install = Vue => {
  if (Vue.prototype.$isServer) return;
  let toggleLoading = (el, binding) => {
    if (binding.value) {
      Vue.nextTick(() => {
        if (binding.modifiers.fullscreen) {
          el.originalPosition = getStyle(document.body, 'position');
          el.originalOverflow = getStyle(document.body, 'overflow');

          addClass(el.mask, 'is-fullscreen');
          insertDom(document.body, el, binding);
        } else {
          removeClass(el.mask, 'is-fullscreen');

          if (binding.modifiers.body) {
            el.originalPosition = getStyle(document.body, 'position');

            ['top', 'left'].forEach(property => {
              let scroll = property === 'top' ? 'scrollTop' : 'scrollLeft';
              el.maskStyle[property] = el.getBoundingClientRect()[property] + document.body[scroll] + document.documentElement[scroll] + 'px';
            });
            ['height', 'width'].forEach(property => {
              el.maskStyle[property] = el.getBoundingClientRect()[property] + 'px';
            });

            insertDom(document.body, el, binding);
          } else {
            el.originalPosition = getStyle(el, 'position');
            insertDom(el, el, binding);
          }
        }
      });
    } else {
      if (el.domVisible) {
        el.instance.$on('after-leave', _ => {
          el.domVisible = false;
          if (binding.modifiers.fullscreen && el.originalOverflow !== 'hidden') {
            document.body.style.overflow = el.originalOverflow;
          }
          if (binding.modifiers.fullscreen || binding.modifiers.body) {
            document.body.style.position = el.originalPosition;
          } else {
            el.style.position = el.originalPosition;
          }
        });
        el.instance.visible = false;
      }
    }
  };
  let insertDom = (parent, el, binding) => {
    if (!el.domVisible && getStyle(el, 'display') !== 'none' && getStyle(el, 'visibility') !== 'hidden') {
      Object.keys(el.maskStyle).forEach(property => {
        el.mask.style[property] = el.maskStyle[property];
      });

      if (el.originalPosition !== 'absolute' && el.originalPosition !== 'fixed') {
        parent.style.position = 'relative';
      }
      if (binding.modifiers.fullscreen && binding.modifiers.lock) {
        parent.style.overflow = 'hidden';
      }
      el.domVisible = true;

      parent.appendChild(el.mask);
      Vue.nextTick(() => {
        el.instance.visible = true;
      });
      el.domInserted = true;
    }
  };

  Vue.directive('loading', {
    bind: function(el, binding) {
      let mask = new Mask({
        el: document.createElement('div'),
        data: {
          text: el.getAttribute('element-loading-text'),
          fullscreen: !!binding.modifiers.fullscreen
        }
      });
      el.instance = mask;
      el.mask = mask.$el;
      el.maskStyle = {};

      toggleLoading(el, binding);
    },

    update: function(el, binding) {
      el.instance.setText(el.getAttribute('element-loading-text'));
      if (binding.oldValue !== binding.value) {
        toggleLoading(el, binding);
      }
    },

    unbind: function(el, binding) {
      if (el.domInserted) {
        if (binding.modifiers.fullscreen || binding.modifiers.body) {
          document.body.removeChild(el.mask);
        } else {
          el.mask &&
          el.mask.parentNode &&
          el.mask.parentNode.removeChild(el.mask);
        }
      }
    }
  });
};
<commit_msg>Loading: update code style (#7152)<commit_after>import Vue from 'vue';
import { addClass, removeClass, getStyle } from 'element-ui/src/utils/dom';
const Mask = Vue.extend(require('./loading.vue'));

exports.install = Vue => {
  if (Vue.prototype.$isServer) return;
  const toggleLoading = (el, binding) => {
    if (binding.value) {
      Vue.nextTick(() => {
        if (binding.modifiers.fullscreen) {
          el.originalPosition = getStyle(document.body, 'position');
          el.originalOverflow = getStyle(document.body, 'overflow');

          addClass(el.mask, 'is-fullscreen');
          insertDom(document.body, el, binding);
        } else {
          removeClass(el.mask, 'is-fullscreen');

          if (binding.modifiers.body) {
            el.originalPosition = getStyle(document.body, 'position');

            ['top', 'left'].forEach(property => {
              const scroll = property === 'top' ? 'scrollTop' : 'scrollLeft';
              el.maskStyle[property] = el.getBoundingClientRect()[property] + document.body[scroll] + document.documentElement[scroll] + 'px';
            });
            ['height', 'width'].forEach(property => {
              el.maskStyle[property] = el.getBoundingClientRect()[property] + 'px';
            });

            insertDom(document.body, el, binding);
          } else {
            el.originalPosition = getStyle(el, 'position');
            insertDom(el, el, binding);
          }
        }
      });
    } else {
      if (el.domVisible) {
        el.instance.$on('after-leave', _ => {
          el.domVisible = false;
          if (binding.modifiers.fullscreen && el.originalOverflow !== 'hidden') {
            document.body.style.overflow = el.originalOverflow;
          }
          if (binding.modifiers.fullscreen || binding.modifiers.body) {
            document.body.style.position = el.originalPosition;
          } else {
            el.style.position = el.originalPosition;
          }
        });
        el.instance.visible = false;
      }
    }
  };
  const insertDom = (parent, el, binding) => {
    if (!el.domVisible && getStyle(el, 'display') !== 'none' && getStyle(el, 'visibility') !== 'hidden') {
      Object.keys(el.maskStyle).forEach(property => {
        el.mask.style[property] = el.maskStyle[property];
      });

      if (el.originalPosition !== 'absolute' && el.originalPosition !== 'fixed') {
        parent.style.position = 'relative';
      }
      if (binding.modifiers.fullscreen && binding.modifiers.lock) {
        parent.style.overflow = 'hidden';
      }
      el.domVisible = true;

      parent.appendChild(el.mask);
      Vue.nextTick(() => {
        el.instance.visible = true;
      });
      el.domInserted = true;
    }
  };

  Vue.directive('loading', {
    bind: function(el, binding) {
      const mask = new Mask({
        el: document.createElement('div'),
        data: {
          text: el.getAttribute('element-loading-text'),
          fullscreen: !!binding.modifiers.fullscreen
        }
      });
      el.instance = mask;
      el.mask = mask.$el;
      el.maskStyle = {};

      toggleLoading(el, binding);
    },

    update: function(el, binding) {
      el.instance.setText(el.getAttribute('element-loading-text'));
      if (binding.oldValue !== binding.value) {
        toggleLoading(el, binding);
      }
    },

    unbind: function(el, binding) {
      if (el.domInserted) {
        if (binding.modifiers.fullscreen || binding.modifiers.body) {
          document.body.removeChild(el.mask);
        } else {
          el.mask &&
          el.mask.parentNode &&
          el.mask.parentNode.removeChild(el.mask);
        }
      }
    }
  });
};
<|endoftext|>