<commit_before>/**
 * @copyright 2015, Prometheus Research, LLC
 */

import memoize                    from 'memoize-decorator';
import selectValue                from 'lodash/object/get';
import emptyFunction              from 'empty/function';
import update                     from 'immupdate';
import makeKeyPath                from './keyPath';
import {Schema,
        select as selectSchema}   from './Schema';

export class Value {

  select(key) {
    let keyPath = this.keyPath.concat(makeKeyPath(key));
    return new ValueLeaf(this._root, keyPath);
  }

  set(value, quiet) {
    console.warn(// eslint-disable-line no-console
      'Value.prototype.set(value) is deprecated, ' +
      'use Value.prototype.update(value) instead'
    );
    return this.update(value, quiet);
  }

  update(value, quiet) {
    let rootValue;
    if (this.keyPath.length === 0) {
      rootValue = value;
    } else {
      rootValue = update(this._root.value, this.keyPath.join('.'), value);
    }
    let nextRoot = createValue(
      this._root.schema,
      rootValue,
      this._root.onChange,
      this._root.params);
    if (!quiet) {
      this._root.onChange(nextRoot);
    }
    return nextRoot;
  }
}

class ValueRoot extends Value {

  keyPath = [];
  parent = null;

  constructor(schema, value, onChange, params, errorList) {
    super();
    this._root = this;
    this.keyPath = [];
    this.schema = schema;
    this.value = value;
    this.onChange = onChange;
    this.params = params;
    this.errorList = errorList.filter(error => error.field === 'data');
    this.completeErrorList = errorList;
  }
}

class ValueLeaf extends Value {

  constructor(root, keyPath) {
    super();
    this._root = root;
    this.keyPath = keyPath;
    this.schema = selectSchema(root.schema, keyPath);
    this.value = selectValue(root.value, keyPath);
  }

  get params() {
    return this._root.params;
  }

  @memoize
  get errorList() {
    let errorKeyPath = `data.${this.keyPath.join('.')}`;
    return this._root.completeErrorList.filter(error => error.field === errorKeyPath);
  }

  @memoize
  get completeErrorList() {
    let errorKeyPath = `data.${this.keyPath.join('.')}`;
    let length = errorKeyPath.length;
    return this._root.completeErrorList
      .filter(error => error.field.slice(0, length) === errorKeyPath);
  }

  get parent() {
    if (this.keyPath.length === 1) {
      return this._root;
    } else {
      let keyPath = this.keyPath.slice();
      keyPath.pop();
      return new ValueLeaf(
        this._root,
        keyPath
      );
    }
  }

}

const NON_ENUMERABLE_PROP = {
  enumerable: false,
  writable: true,
  configurable: true
};

function cache(obj, key, value) {
  Object.defineProperty(obj, key, {...NON_ENUMERABLE_PROP, value});
}

function validate(schema, value) {
  if (!schema) {
    return [];
  }
  if (value.__schema === schema && value.__errorList) {
    return value.__errorList;
  } else {
    if (schema.__validator === undefined) {
      cache(schema, '__validator', Schema(schema, {formats: schema.formats}));
    }
    let errorList = schema.__validator(value);
    cache(value, '__schema', schema);
    cache(value, '__errorList', errorList);
    return errorList;
  }
}

/**
 * Check if value is a form value.
 */
export function isValue(maybeValue) {
  return maybeValue instanceof Value;
}

/**
 * Create a new root value.
 */
export default function createValue(
    schema,
    value = {},
    onChange = emptyFunction,
    params = {},
    errorList = null) {
  if (errorList === null) {
    errorList = validate(schema, value);
  }
  return new ValueRoot(schema, value, onChange, params, errorList);
}
<commit_msg>feat(Value): add keyPath to onChange args<commit_after>/**
 * @copyright 2015, Prometheus Research, LLC
 */

import memoize                    from 'memoize-decorator';
import selectValue                from 'lodash/object/get';
import emptyFunction              from 'empty/function';
import update                     from 'immupdate';
import makeKeyPath                from './keyPath';
import {Schema,
        select as selectSchema}   from './Schema';

export class Value {

  select(key) {
    let keyPath = this.keyPath.concat(makeKeyPath(key));
    return new ValueLeaf(this._root, keyPath);
  }

  set(value, quiet) {
    console.warn(// eslint-disable-line no-console
      'Value.prototype.set(value) is deprecated, ' +
      'use Value.prototype.update(value) instead'
    );
    return this.update(value, quiet);
  }

  update(value, quiet) {
    let rootValue;
    if (this.keyPath.length === 0) {
      rootValue = value;
    } else {
      rootValue = update(this._root.value, this.keyPath.join('.'), value);
    }
    let nextRoot = createValue(
      this._root.schema,
      rootValue,
      this._root.onChange,
      this._root.params);
    if (!quiet) {
      this._root.onChange(nextRoot, this.keyPath);
    }
    return nextRoot;
  }
}

class ValueRoot extends Value {

  keyPath = [];
  parent = null;

  constructor(schema, value, onChange, params, errorList) {
    super();
    this._root = this;
    this.keyPath = [];
    this.schema = schema;
    this.value = value;
    this.onChange = onChange;
    this.params = params;
    this.errorList = errorList.filter(error => error.field === 'data');
    this.completeErrorList = errorList;
  }
}

class ValueLeaf extends Value {

  constructor(root, keyPath) {
    super();
    this._root = root;
    this.keyPath = keyPath;
    this.schema = selectSchema(root.schema, keyPath);
    this.value = selectValue(root.value, keyPath);
  }

  get params() {
    return this._root.params;
  }

  @memoize
  get errorList() {
    let errorKeyPath = `data.${this.keyPath.join('.')}`;
    return this._root.completeErrorList.filter(error => error.field === errorKeyPath);
  }

  @memoize
  get completeErrorList() {
    let errorKeyPath = `data.${this.keyPath.join('.')}`;
    let length = errorKeyPath.length;
    return this._root.completeErrorList
      .filter(error => error.field.slice(0, length) === errorKeyPath);
  }

  get parent() {
    if (this.keyPath.length === 1) {
      return this._root;
    } else {
      let keyPath = this.keyPath.slice();
      keyPath.pop();
      return new ValueLeaf(
        this._root,
        keyPath
      );
    }
  }

}

const NON_ENUMERABLE_PROP = {
  enumerable: false,
  writable: true,
  configurable: true
};

function cache(obj, key, value) {
  Object.defineProperty(obj, key, {...NON_ENUMERABLE_PROP, value});
}

function validate(schema, value) {
  if (!schema) {
    return [];
  }
  if (value.__schema === schema && value.__errorList) {
    return value.__errorList;
  } else {
    if (schema.__validator === undefined) {
      cache(schema, '__validator', Schema(schema, {formats: schema.formats}));
    }
    let errorList = schema.__validator(value);
    cache(value, '__schema', schema);
    cache(value, '__errorList', errorList);
    return errorList;
  }
}

/**
 * Check if value is a form value.
 */
export function isValue(maybeValue) {
  return maybeValue instanceof Value;
}

/**
 * Create a new root value.
 */
export default function createValue(
    schema,
    value = {},
    onChange = emptyFunction,
    params = {},
    errorList = null) {
  if (errorList === null) {
    errorList = validate(schema, value);
  }
  return new ValueRoot(schema, value, onChange, params, errorList);
}
<|endoftext|>


<commit_before>var sd = require('skin-deep'),
    expect = require('chai').expect,
    React = require('react'),
    Suite = require('../../../ui/components/suite.jsx'),
    fixture = require('../../fixtures/components/suite.js');

describe('Suite', function() {
  var tree;

  beforeEach(function() {
    tree = sd.shallowRender(<Suite suite={fixture}/>);
  });

  it('should render the component with class "suite"', function() {
    expect(tree.findNode('.suite')).to.not.be.false;
  });

  it('should indent the suite properly', function() {
    var expected = {
      marginLeft: 20 * (fixture.indent - 1) + 'px'
    };

    expect(tree.findNode('.suite').props.style).to.be.deep.equal(expected);
  });

  it('should render the suite title', function() {
    expect(tree.textIn('.suite-title')).to.be.equal(fixture.title);
  });

  it('should set the suite title fontSize correctly', function() {
    var expected = {
      fontSize: 100 / fixture.indent + '%'
    };

    expect(tree.findNode('.suite-title').props.style).to.deep.equal(expected);
  });

  it('should render the tests array', function() {
    var tests = tree.findNode('.suite').props.children[1];

    for (var i = 0; i < tests.length; i++) {
      expect(tests[i].props.test).to.be.equal(fixture.tests[i]);
    }
  });
});
<commit_msg>Remove class test #13<commit_after>var sd = require('skin-deep'),
    expect = require('chai').expect,
    React = require('react'),
    Suite = require('../../../ui/components/suite.jsx'),
    fixture = require('../../fixtures/components/suite.js');

describe('Suite', function() {
  var tree;

  beforeEach(function() {
    tree = sd.shallowRender(<Suite suite={fixture}/>);
  });

  it('should indent the suite properly', function() {
    var expected = {
      marginLeft: 20 * (fixture.indent - 1) + 'px'
    };

    expect(tree.findNode('.suite').props.style).to.be.deep.equal(expected);
  });

  it('should render the suite title', function() {
    expect(tree.textIn('.suite-title')).to.be.equal(fixture.title);
  });

  it('should set the suite title fontSize correctly', function() {
    var expected = {
      fontSize: 100 / fixture.indent + '%'
    };

    expect(tree.findNode('.suite-title').props.style).to.deep.equal(expected);
  });

  it('should render the tests array', function() {
    var tests = tree.findNode('.suite').props.children[1];

    for (var i = 0; i < tests.length; i++) {
      expect(tests[i].props.test).to.be.equal(fixture.tests[i]);
    }
  });
});
<|endoftext|>


<commit_before>/*
 * mobile core unit tests
 */

(function($){
	var libName = "jquery.mobile.core.js",
			scrollTimeout = 20, // TODO expose timing as an attribute
			scrollStartEnabledTimeout = 150;

	module(libName, {
		setup: function(){
			$("

").appendTo("body");
		},

		teardown: function(){
			$("#scroll-testing").remove();
		}
	});

	var scrollUp = function( pos ){
		$(window).scrollTop(1000);
		ok($(window).scrollTop() > 0);

		if(pos) {
			$.mobile.silentScroll(pos);
		} else {
			$.mobile.silentScroll();
		}
	};

	test( "silent scroll scrolls the page to the top by default", function(){
		scrollUp();

		stop();
		setTimeout(function(){
			same($(window).scrollTop(), 0);
			start();
		}, scrollTimeout);
	});

	test( "silent scroll scrolls the page to the passed y position", function(){
		var pos = 10;
		scrollUp(pos);

		stop();
		setTimeout(function(){
			same($(window).scrollTop(), pos);
			start();
		}, scrollTimeout);
	});

	// NOTE may be brittle depending on timing
	test( "silent scroll takes at least 20 ms to scroll to the top", function(){
		scrollUp();

		stop();
		setTimeout(function(){
			ok($(window).scrollTop() != 0);
			start();
		}, scrollTimeout - 1);
	});

	test( "scrolling marks scrollstart as disabled for 150 ms", function(){
		$.event.special.scrollstart.enabled = true;
		scrollUp();
		ok(!$.event.special.scrollstart.enabled);

		stop();
		setTimeout(function(){
			ok($.event.special.scrollstart.enabled);
			start();
		}, scrollStartEnabledTimeout);
	});

	//TODO test that silentScroll is called on window load
})(jQuery);
<commit_msg>small simplification of core scrolling tests<commit_after>/*
 * mobile core unit tests
 */

(function($){
	var libName = "jquery.mobile.core.js",
			scrollTimeout = 20, // TODO expose timing as an attribute
			scrollStartEnabledTimeout = 150;

	module(libName, {
		setup: function(){
			$("

").appendTo("body");
		},

		teardown: function(){
			$("#scroll-testing").remove();
			window.fizz = '';
		}
	});

	var scrollUp = function( pos ){
		$(window).scrollTop(1000);
		ok($(window).scrollTop() > 0, $(window).scrollTop());
		$.mobile.silentScroll(pos);
	};

	asyncTest( "silent scroll scrolls the page to the top by default", function(){
		scrollUp();

		setTimeout(function(){
			same($(window).scrollTop(), 0);
			start();
		}, scrollTimeout);
	});

	asyncTest( "silent scroll scrolls the page to the passed y position", function(){
		var pos = 10;
		scrollUp(pos);

		setTimeout(function(){
			same($(window).scrollTop(), pos);
			start();
		}, scrollTimeout);
	});

	// NOTE may be brittle depending on timing
	asyncTest( "silent scroll takes at least 20 ms to scroll to the top", function(){
		scrollUp();

		setTimeout(function(){
			ok($(window).scrollTop() != 0, "scrolltop position should not be zero");
			start();
		}, scrollTimeout - 2);
	});

	asyncTest( "scrolling marks scrollstart as disabled for 150 ms", function(){
		$.event.special.scrollstart.enabled = true;
		scrollUp();
		ok(!$.event.special.scrollstart.enabled);

		setTimeout(function(){
			ok($.event.special.scrollstart.enabled);
			start();
		}, scrollStartEnabledTimeout);
	});

	//TODO test that silentScroll is called on window load
})(jQuery);
<|endoftext|>


<commit_before>import { module, test } from 'qunit';
import { typeIn, setupContext, teardownContext } from '@ember/test-helpers';
import { buildInstrumentedElement } from '../../helpers/events';
import { isIE11 } from '../../helpers/browser-detect';
import { debounce } from '@ember/runloop';
import { Promise } from 'rsvp';
import hasEmberVersion from '@ember/test-helpers/has-ember-version';

/*
 * Event order based on https://jsbin.com/zitazuxabe/edit?html,js,console,output
 */

let expectedEvents = [
  'focus',
  'focusin',
  'keydown',
  'keypress',
  'input',
  'keyup',
  'keydown',
  'keypress',
  'input',
  'keyup',
  'keydown',
  'keypress',
  'input',
  'keyup',
  'change',
];

if (isIE11) {
  expectedEvents = [
    'focusin',
    'keydown',
    'keypress',
    'keyup',
    'keydown',
    'keypress',
    'keyup',
    'keydown',
    'keypress',
    'keyup',
    'input',
    'change',
    'focus',
  ];
}

module('DOM Helper: typeIn', function (hooks) {
  if (!hasEmberVersion(2, 4)) {
    return;
  }

  let context, element;

  hooks.beforeEach(function () {
    context = {};
  });

  hooks.afterEach(async function () {
    element.setAttribute('data-skip-steps', true);

    if (element) {
      element.parentNode.removeChild(element);
    }
    if (context.owner) {
      await teardownContext(context);
    }

    document.getElementById('ember-testing').innerHTML = '';
  });

  test('typing in an input', async function (assert) {
    element = buildInstrumentedElement('input');
    await typeIn(element, 'foo');

    assert.verifySteps(expectedEvents);
    assert.strictEqual(document.activeElement, element, 'activeElement updated');
    assert.equal(element.value, 'foo');
  });

  test('it triggers key events with correct arguments', async function (assert) {
    element = buildInstrumentedElement('input', ['key', 'shiftKey']);
    await typeIn(element, 'F o');

    let chars = ['F', ' ', 'o'];
    let shiftKeys = [true, false, false];
    let expectedEventsWithArguments = expectedEvents.map(eventName => {
      // Only key events get the key arguments
      if (!['keydown', 'keypress', 'keyup'].includes(eventName)) {
        return `${eventName} undefined undefined`;
      }
      // After each keyup, the next character comes up
      let char = eventName === 'keyup' ? chars.shift() : chars[0];
      let shiftKey = eventName === 'keyup' ? shiftKeys.shift() : shiftKeys[0];

      return `${eventName} ${char.toUpperCase()} ${shiftKey}`;
    });

    assert.verifySteps(expectedEventsWithArguments);
  });

  test('typing in an input with a delay', async function (assert) {
    element = buildInstrumentedElement('input');
    await typeIn(element, 'foo', { delay: 150 });

    assert.verifySteps(expectedEvents);
    assert.strictEqual(document.activeElement, element, 'activeElement updated');
    assert.equal(element.value, 'foo');
  });

  test('typing in a textarea', async function (assert) {
    element = buildInstrumentedElement('textarea');
    await typeIn(element, 'foo');

    assert.verifySteps(expectedEvents);
    assert.strictEqual(document.activeElement, element, 'activeElement updated');
    assert.equal(element.value, 'foo');
  });

  test('typing in not a form control', async function (assert) {
    element = buildInstrumentedElement('div');

    await setupContext(context);
    assert.rejects(typeIn(`#${element.id}`, 'foo'), /`typeIn` is only usable on form controls/);
  });

  test('typing in a disabled element', async function (assert) {
    element = buildInstrumentedElement('input');
    element.dataset.testDisabled = '';
    element.setAttribute('disabled', '');

    await setupContext(context);
    assert.rejects(
      typeIn(`[data-test-disabled]`, 'foo'),
      new Error("Can not `typeIn` disabled '[data-test-disabled]'.")
    );

    assert.rejects(
      typeIn(element, 'foo'),
      new Error("Can not `typeIn` disabled '[object HTMLInputElement]'.")
    );
  });

  test('typing in a readonly element', async function (assert) {
    element = buildInstrumentedElement('input');
    element.dataset.testDisabled = '';
    element.setAttribute('readonly', '');

    await setupContext(context);
    assert.rejects(
      typeIn(`[data-test-disabled]`, 'foo'),
      new Error("Can not `typeIn` readonly '[data-test-disabled]'.")
    );

    assert.rejects(
      typeIn(element, 'foo'),
      new Error("Can not `typeIn` readonly '[object HTMLInputElement]'.")
    );
  });

  test('rejects if selector is not found', async function (assert) {
    element = buildInstrumentedElement('div');

    await setupContext(context);

    assert.rejects(
      typeIn(`#foo-bar-baz-not-here-ever-bye-bye`, 'foo'),
      /Element not found when calling `typeIn\('#foo-bar-baz-not-here-ever-bye-bye'\)`/
    );
  });

  test('rejects if text to fill in is not provided', async function (assert) {
    element = buildInstrumentedElement('input');

    assert.rejects(typeIn(element), /Must provide `text` when calling `typeIn`/);
  });

  test('does not run sync', async function (assert) {
    element = buildInstrumentedElement('input');

    let promise = typeIn(element, 'foo');

    assert.verifySteps([]);

    await promise;

    assert.verifySteps(expectedEvents);
    assert.strictEqual(document.activeElement, element, 'activeElement updated');
    assert.equal(element.value, 'foo');
  });

  test('does not wait for other promises to settle', async function (assert) {
    element = buildInstrumentedElement('input');

    let runcount = 0;
    let onInput = function () {
      return Promise.resolve().then(() => runcount++);
    };

    element.oninput = function () {
      // debounce 2 seconds for easy visualization in test
      debounce(onInput, 2000);
    };

    await typeIn(element, 'foo');

    assert.verifySteps(expectedEvents);
    assert.equal(runcount, 1, 'debounced function only called once');
  });

  test('typing in an input with a maxlength with suitable value', async function (assert) {
    element = buildInstrumentedElement('input');
    const maxLengthString = 'foo';
    element.setAttribute('maxlength', maxLengthString.length);

    await setupContext(context);

    await typeIn(element, maxLengthString);

    assert.verifySteps(expectedEvents);
    assert.equal(
      element.value,
      maxLengthString,
      `typeIn respects input attribute [maxlength=${maxLengthString.length}]`
    );
  });

  test('typing in an input with a maxlength with too long value', async function (assert) {
    element = buildInstrumentedElement('input');
    const maxLengthString = 'f';
    const tooLongString = maxLengthString.concat('o');
    element.setAttribute('maxlength', maxLengthString.length);

    await setupContext(context);

    await assert.rejects(
      typeIn(element, tooLongString).finally(() => {
        // should throw before the second input event
        assert.verifySteps(expectedEvents.slice(0, 8));
      }),
      new Error("Can not `typeIn` with text: 'fo' that exceeds maxlength: '1'.")
    );
  });
});
<commit_msg>should fix IE test<commit_after>import { module, test } from 'qunit';
import { typeIn, setupContext, teardownContext } from '@ember/test-helpers';
import { buildInstrumentedElement } from '../../helpers/events';
import { isIE11 } from '../../helpers/browser-detect';
import { debounce } from '@ember/runloop';
import { Promise } from 'rsvp';
import hasEmberVersion from '@ember/test-helpers/has-ember-version';

/*
 * Event order based on https://jsbin.com/zitazuxabe/edit?html,js,console,output
 */

let expectedEvents = [
  'focus',
  'focusin',
  'keydown',
  'keypress',
  'input',
  'keyup',
  'keydown',
  'keypress',
  'input',
  'keyup',
  'keydown',
  'keypress',
  'input',
  'keyup',
  'change',
];

if (isIE11) {
  expectedEvents = [
    'focusin',
    'keydown',
    'keypress',
    'keyup',
    'keydown',
    'keypress',
    'keyup',
    'keydown',
    'keypress',
    'keyup',
    'input',
    'change',
    'focus',
  ];
}

module('DOM Helper: typeIn', function (hooks) {
  if (!hasEmberVersion(2, 4)) {
    return;
  }

  let context, element;

  hooks.beforeEach(function () {
    context = {};
  });

  hooks.afterEach(async function () {
    element.setAttribute('data-skip-steps', true);

    if (element) {
      element.parentNode.removeChild(element);
    }
    if (context.owner) {
      await teardownContext(context);
    }

    document.getElementById('ember-testing').innerHTML = '';
  });

  test('typing in an input', async function (assert) {
    element = buildInstrumentedElement('input');
    await typeIn(element, 'foo');

    assert.verifySteps(expectedEvents);
    assert.strictEqual(document.activeElement, element, 'activeElement updated');
    assert.equal(element.value, 'foo');
  });

  test('it triggers key events with correct arguments', async function (assert) {
    element = buildInstrumentedElement('input', ['key', 'shiftKey']);
    await typeIn(element, 'F o');

    let chars = ['F', ' ', 'o'];
    let shiftKeys = [true, false, false];
    let expectedEventsWithArguments = expectedEvents.map(eventName => {
      // Only key events get the key arguments
      if (!['keydown', 'keypress', 'keyup'].includes(eventName)) {
        return `${eventName} undefined undefined`;
      }
      // After each keyup, the next character comes up
      let char = eventName === 'keyup' ? chars.shift() : chars[0];
      let shiftKey = eventName === 'keyup' ? shiftKeys.shift() : shiftKeys[0];

      return `${eventName} ${char.toUpperCase()} ${shiftKey}`;
    });

    assert.verifySteps(expectedEventsWithArguments);
  });

  test('typing in an input with a delay', async function (assert) {
    element = buildInstrumentedElement('input');
    await typeIn(element, 'foo', { delay: 150 });

    assert.verifySteps(expectedEvents);
    assert.strictEqual(document.activeElement, element, 'activeElement updated');
    assert.equal(element.value, 'foo');
  });

  test('typing in a textarea', async function (assert) {
    element = buildInstrumentedElement('textarea');
    await typeIn(element, 'foo');

    assert.verifySteps(expectedEvents);
    assert.strictEqual(document.activeElement, element, 'activeElement updated');
    assert.equal(element.value, 'foo');
  });

  test('typing in not a form control', async function (assert) {
    element = buildInstrumentedElement('div');

    await setupContext(context);
    assert.rejects(typeIn(`#${element.id}`, 'foo'), /`typeIn` is only usable on form controls/);
  });

  test('typing in a disabled element', async function (assert) {
    element = buildInstrumentedElement('input');
    element.dataset.testDisabled = '';
    element.setAttribute('disabled', '');

    await setupContext(context);
    assert.rejects(
      typeIn(`[data-test-disabled]`, 'foo'),
      new Error("Can not `typeIn` disabled '[data-test-disabled]'.")
    );

    assert.rejects(
      typeIn(element, 'foo'),
      new Error("Can not `typeIn` disabled '[object HTMLInputElement]'.")
    );
  });

  test('typing in a readonly element', async function (assert) {
    element = buildInstrumentedElement('input');
    element.dataset.testDisabled = '';
    element.setAttribute('readonly', '');

    await setupContext(context);
    assert.rejects(
      typeIn(`[data-test-disabled]`, 'foo'),
      new Error("Can not `typeIn` readonly '[data-test-disabled]'.")
    );

    assert.rejects(
      typeIn(element, 'foo'),
      new Error("Can not `typeIn` readonly '[object HTMLInputElement]'.")
    );
  });

  test('rejects if selector is not found', async function (assert) {
    element = buildInstrumentedElement('div');

    await setupContext(context);

    assert.rejects(
      typeIn(`#foo-bar-baz-not-here-ever-bye-bye`, 'foo'),
      /Element not found when calling `typeIn\('#foo-bar-baz-not-here-ever-bye-bye'\)`/
    );
  });

  test('rejects if text to fill in is not provided', async function (assert) {
    element = buildInstrumentedElement('input');

    assert.rejects(typeIn(element), /Must provide `text` when calling `typeIn`/);
  });

  test('does not run sync', async function (assert) {
    element = buildInstrumentedElement('input');

    let promise = typeIn(element, 'foo');

    assert.verifySteps([]);

    await promise;

    assert.verifySteps(expectedEvents);
    assert.strictEqual(document.activeElement, element, 'activeElement updated');
    assert.equal(element.value, 'foo');
  });

  test('does not wait for other promises to settle', async function (assert) {
    element = buildInstrumentedElement('input');

    let runcount = 0;
    let onInput = function () {
      return Promise.resolve().then(() => runcount++);
    };

    element.oninput = function () {
      // debounce 2 seconds for easy visualization in test
      debounce(onInput, 2000);
    };

    await typeIn(element, 'foo');

    assert.verifySteps(expectedEvents);
    assert.equal(runcount, 1, 'debounced function only called once');
  });

  test('typing in an input with a maxlength with suitable value', async function (assert) {
    element = buildInstrumentedElement('input');
    const maxLengthString = 'foo';
    element.setAttribute('maxlength', maxLengthString.length);

    await setupContext(context);

    await typeIn(element, maxLengthString);

    assert.verifySteps(expectedEvents);
    assert.equal(
      element.value,
      maxLengthString,
      `typeIn respects input attribute [maxlength=${maxLengthString.length}]`
    );
  });

  test('typing in an input with a maxlength with too long value', async function (assert) {
    element = buildInstrumentedElement('input');
    const maxLengthString = 'f';
    const tooLongString = maxLengthString.concat('o');
    element.setAttribute('maxlength', maxLengthString.length);

    await setupContext(context);

    await assert.rejects(
      typeIn(element, tooLongString).finally(() => {
        // should throw before the second input event (or second keyup for IE)
        const expectedNumberOfSteps = isIE11 ? 6 : 8;
        assert.verifySteps(expectedEvents.slice(0, expectedNumberOfSteps));
      }),
      new Error("Can not `typeIn` with text: 'fo' that exceeds maxlength: '1'.")
    );
  });
});
<|endoftext|>


<commit_before>var bartApi = {
  apiKey: 'BART_API_KEY',
  url: {
    stations: function() {
       return 'http://api.bart.gov/api/stn.aspx?cmd=stns&key=' + bartApi.apiKey;
    },
    time: function(station, direction) {
      return ['http://api.bart.gov/api/etd.aspx?cmd=etd&orig=',station,'&dir=',direction,'&key=',bartApi.apiKey].join('');
    }
  }
}
<commit_msg>added station XML processor code<commit_after>var bartApi = {
  apiKey: 'BART_API_KEY',
  get: {
    root: 'http://api.bart.gov/api/',
    stations: {
      link: function() { return bartApi.get.root + 'stn.aspx?'; },
      data: function() { return { cmd: 'stns', key: bartApi.apiKey }; }
    },
    times: {
      link: function() { return bartApi.get.root + 'etd.aspx?'; },
      data: function(station,dir) { return { cmd: 'etd', orig: station, dir: dir, key: bartApi.apiKey }; }
    }
  }
}

var getStationList = function(cb) {
  var endpoint = bartApi.get.stations;
  $.get(endpoint.link(),endpoint.data()).done(cb);
};

var processStationList = function(rawXml) {
  var $xml = $(rawXml);
  var stations = $xml.find('station');
  var properties = ['name','abbr'];
  stations = stations.map(function(i,elem) {
    var obj = {};
    properties.forEach(function(prop) {
      obj[prop] = $(elem).find(prop).text();
    });
    return obj;
  }).get();
  return stations;
};

<|endoftext|>


<commit_before>var sax = require("sax");
var fs = require("fs");
var path = require("path");
var Promise = require("bluebird");
var log = require("../logger");
var strict = true;
var parser = sax.parser(strict);

function FileExtractingError(message, fileName) {
    this.message = message;
    this.fileName = fileName;
    this.name = "FileExtractingError";
    //Error.captureStackTrace(this, FileExtractingError);
}
FileExtractingError.prototype = Object.create(Error.prototype);
FileExtractingError.prototype.constructor = FileExtractingError;

module.exports = function (xmlFileNames, targetDir, callback) {
    log.info("Extracting node tags and attributes for %d files to %s",
        xmlFileNames.length, targetDir);
    Promise.map(xmlFileNames, function (xmlFile) {
        var outFile = path.resolve(targetDir, path.basename(xmlFile, '.xml') +
            '-ui-tag.txt');
        var readStream = fs.createReadStream(xmlFile, {encoding: "utf8"});
        var writeStream = fs.createWriteStream(outFile, {encoding: "utf8"});
        return extract(xmlFile, readStream, writeStream)
            .then(function (res) {
                log.info(res);
            });

    }, {concurrency: 1}).then(function () {
        callback(null);
    }).catch(FileExtractingError, function (e) {
        log.error("Failed to extract tag names for %s. %s", e.fileName, e.message);
        callback(e);
    });

}

function extract(fileName, readStream, writeStream) {

    function entity(str) {
        return str.replace('"', '"');
    }

    return new Promise(function (resolve, reject) {
        var saxStream = sax.createStream(strict, {
            lowercasetags: true,
            trim: true
        })
            .on("error", function (e) {
                console.error("SAX Parser Error. Reason: ", e);
                // clear the error
                this._parser.error = null;
                this._parser.resume();
            }).on("opentag", function (node) {
                write(node.name + "\n")
                for (var i in node.attributes) {
                    write(node.name + "(" + i + "=\"" +
                        entity(node.attributes[i]) + "\")\n");
                }
            }).on('end', function () {
                writeStream.end();
            });

        function write(string) {
            if (!writeStream.write(string)) {
                readStream.pause();
            }
        }

        writeStream.on("drain", function () {
            readStream.resume();
        });

        writeStream.on("finish", function () {
            resolve("Node tags and attributes have been extracted from " +
                fileName);
        });

        writeStream.on("error", function (error) {
            console.error("An error has occurred while writing to file."
                + " Reason: " + error.message);
            reject(new FileExtractingError("Failed to write output file for " +
                fileName));
        });

        readStream.on("error", function (error) {
            log.error("An error has occurred while reading from file."
                + " Reason: " + error.message);
            reject(error);
        });

        readStream.pipe(saxStream);
    });
}<commit_msg>change file name<commit_after>var sax = require("sax");
var fs = require("fs");
var path = require("path");
var Promise = require("bluebird");
var log = require("../logger");
var strict = true;
var parser = sax.parser(strict);

function FileExtractingError(message, fileName) {
    this.message = message;
    this.fileName = fileName;
    this.name = "FileExtractingError";
    //Error.captureStackTrace(this, FileExtractingError);
}
FileExtractingError.prototype = Object.create(Error.prototype);
FileExtractingError.prototype.constructor = FileExtractingError;

module.exports = function (xmlFileNames, targetDir, postfix, callback) {
    log.info("Extracting node tags and attributes for %d files to %s",
        xmlFileNames.length, targetDir);
    Promise.map(xmlFileNames, function (xmlFile) {
        var outFile = path.resolve(targetDir, path.basename(xmlFile, '.xml') +
            postfix + '.txt');
        var readStream = fs.createReadStream(xmlFile, {encoding: "utf8"});
        var writeStream = fs.createWriteStream(outFile, {encoding: "utf8"});
        return extract(xmlFile, readStream, writeStream)
            .then(function (res) {
                log.info(res);
            });

    }, {concurrency: 1}).then(function () {
        callback(null);
    }).catch(FileExtractingError, function (e) {
        log.error("Failed to extract tag names for %s. %s", e.fileName, e.message);
        callback(e);
    });

}

function extract(fileName, readStream, writeStream) {

    function entity(str) {
        return str.replace('"', '"');
    }

    return new Promise(function (resolve, reject) {
        var saxStream = sax.createStream(strict, {
            lowercasetags: true,
            trim: true
        })
            .on("error", function (e) {
                console.error("SAX Parser Error. Reason: ", e);
                // clear the error
                this._parser.error = null;
                this._parser.resume();
            }).on("opentag", function (node) {
                write(node.name + "\n")
                for (var i in node.attributes) {
                    write(node.name + "(" + i + "=\"" +
                        entity(node.attributes[i]) + "\")\n");
                }
            }).on('end', function () {
                writeStream.end();
            });

        function write(string) {
            if (!writeStream.write(string)) {
                readStream.pause();
            }
        }

        writeStream.on("drain", function () {
            readStream.resume();
        });

        writeStream.on("finish", function () {
            resolve("Node tags and attributes have been extracted from " +
                fileName);
        });

        writeStream.on("error", function (error) {
            console.error("An error has occurred while writing to file."
                + " Reason: " + error.message);
            reject(new FileExtractingError("Failed to write output file for " +
                fileName));
        });

        readStream.on("error", function (error) {
            log.error("An error has occurred while reading from file."
                + " Reason: " + error.message);
            reject(error);
        });

        readStream.pipe(saxStream);
    });
}<|endoftext|>


<commit_before>var sax = require("sax");
var fs = require("fs");
var path = require("path");
var Promise = require("bluebird");
var log = require("../logger");
var strict = true;
var parser = sax.parser(strict);

function FileExtractingError(message, fileName) {
    this.message = message;
    this.fileName = fileName;
    this.name = "FileExtractingError";
    //Error.captureStackTrace(this, FileExtractingError);
}
FileExtractingError.prototype = Object.create(Error.prototype);
FileExtractingError.prototype.constructor = FileExtractingError;

module.exports = function (xmlFileNames, targetDir, postfix, callback) {
    log.info("Extracting node tags and attributes for %d files to %s",
        xmlFileNames.length, targetDir);
    Promise.map(xmlFileNames, function (xmlFile) {
        var outFile = path.resolve(targetDir, path.basename(xmlFile, '.xml') +
            postfix + '.txt');
        var readStream = fs.createReadStream(xmlFile, {encoding: "utf8"});
        var writeStream = fs.createWriteStream(outFile, {encoding: "utf8"});
        return extract(xmlFile, readStream, writeStream)
            .then(function (res) {
                log.info(res);
            });

    }, {concurrency: 1}).then(function () {
        callback(null);
    }).catch(FileExtractingError, function (e) {
        log.error("Failed to extract tag names for %s. %s", e.fileName, e.message);
        callback(e);
    });

}

function extract(fileName, readStream, writeStream) {

    function entity(str) {
        return str.replace('"', '"');
    }

    return new Promise(function (resolve, reject) {
        var saxStream = sax.createStream(strict, {
            lowercasetags: true,
            trim: true
        })
            .on("error", function (e) {
                console.error("SAX Parser Error. Reason: ", e);
                // clear the error
                this._parser.error = null;
                this._parser.resume();
            }).on("opentag", function (node) {
                write(node.name + "\n")
                for (var i in node.attributes) {
                    write(node.name + "(" + i + "=\"" +
                        entity(node.attributes[i]) + "\")\n");
                }
            }).on('end', function () {
                writeStream.end();
            });

        function write(string) {
            if (!writeStream.write(string)) {
                readStream.pause();
            }
        }

        writeStream.on("drain", function () {
            readStream.resume();
        });

        writeStream.on("finish", function () {
            resolve("Node tags and attributes have been extracted from " +
                fileName);
        });

        writeStream.on("error", function (error) {
            console.error("An error has occurred while writing to file."
                + " Reason: " + error.message);
            reject(new FileExtractingError("Failed to write output file for " +
                fileName));
        });

        readStream.on("error", function (error) {
            log.error("An error has occurred while reading from file."
                + " Reason: " + error.message);
            reject(error);
        });

        readStream.pipe(saxStream);
    });
}<commit_msg>fix out of memory error<commit_after>var sax = require("sax");
var fs = require("fs");
var path = require("path");
var Promise = require("bluebird");
var log = require("../logger");
sax.MAX_BUFFER_LENGTH = 128 * 1024
var strict = true;
var parser = sax.parser(strict);

function FileExtractingError(message, fileName) {
    this.message = message;
    this.fileName = fileName;
    this.name = "FileExtractingError";
}
FileExtractingError.prototype = Object.create(Error.prototype);
FileExtractingError.prototype.constructor = FileExtractingError;

module.exports = function (xmlFileNames, targetDir, postfix, callback) {
    log.info("Extracting node tags and attributes for %d files to %s",
        xmlFileNames.length, targetDir);
    Promise.map(xmlFileNames, function (xmlFile) {
        var outFile = path.resolve(targetDir, path.basename(xmlFile, '.xml') +
            postfix + '.txt');
        var readStream = fs.createReadStream(xmlFile, {encoding: "utf8"});
        var writeStream = fs.createWriteStream(outFile, {encoding: "utf8"});
        return extract(xmlFile, readStream, writeStream)
            .then(function (res) {
                log.info(res);
            })
            .catch(FileExtractingError, function (e) {
                log.error("FileExtractingError in " + e.fileName + " , " + e.message);
            })
            .catch(function (e) {
                log.error(e);
            });

    }, {concurrency: 1}).then(function () {
        callback(null);
    }).catch(FileExtractingError, function (e) {
        log.error("Failed to extract tag names for %s. %s", e.fileName, e.message);
        callback(e);
    });

}

function extract(fileName, readStream, writeStream) {

    function entity(str) {
        return str.replace('"', '"');
    }

    return new Promise(function (resolve, reject) {
        var saxStream = sax.createStream(strict, {
            lowercasetags: true,
            trim: true
        })
            .on("error", function (e) {
                reject(new FileExtractingError("SAX Parser Error. Reason: " +
                    e.message, fileName));
            }).on("opentag", function (node) {
                readStream.pause();
                write(node.name + "\n")
                for (var i in node.attributes) {
                    write(node.name + "(" + i + "=\"" +
                        entity(node.attributes[i]) + "\")\n");
                }
                readStream.resume();
            }).on('end', function () {
                writeStream.end();
            }).on('end', function () {
            });

        function write(string) {
            if (!writeStream.write(string)) {
                readStream.pause();
            }
        }

        writeStream.on("drain", function () {
            readStream.resume();
        });

        writeStream.on("finish", function () {
            resolve("Node tags and attributes have been extracted from " +
                fileName);
        });

        writeStream.on("error", function (error) {
            reject(new FileExtractingError("Failed to write output file. " +
                " Reason: " + error.message, fileName));
        });

        readStream.on("error", function (error) {
            log.error("An error has occurred while reading from file."
                + " Reason: " + error.message);
            reject(error);
        });

        readStream.pipe(saxStream);
    });
}<|endoftext|>


<commit_before>const path = require('path');

const folders = {
  dist: 'static',
  storage: '',
  marmelad: 'marmelad',
  _blocks: '_blocks',
  _pages: '_pages',
  iconizer: {
    src: 'iconizer',
    icons: 'icons',
  },
  js: {
    src: 'js',
    vendors: 'vendors',
    plugins: 'plugins',
  },
  styles: 'styles',
  static: 'static',
};

const paths = {
  dist: path.join(folders.dist),
  storage: path.join(folders.dist, folders.storage),
  marmelad: path.join(folders.marmelad),
  _blocks: path.join(folders.marmelad, folders._blocks),
  _pages: path.join(folders.marmelad, folders._pages),
  js: {
    src: path.join(folders.marmelad, folders.js.src),
    vendors: path.join(folders.marmelad, folders.js.src, folders.js.vendors),
    plugins: path.join(folders.marmelad, folders.js.src, folders.js.plugins),
  },
  styles: path.join(folders.marmelad, folders.styles),
  static: path.join(folders.marmelad, folders.static),
};

const iconizer = {
  cssClass: 'main-svg-sprite',
  mode: 'inline', // external отдельный подключаемый файл спрайта (default:inline)
  dest: path.join(paths.dist, 'img'), // путь для собираемых спрайтов
  url: 'img', // путь до подключаемого спрайта iconizer.dest без paths.dist
  srcIcons: path.join(folders.marmelad, folders.iconizer.src, 'icons'),
  srcColored: path.join(folders.marmelad, folders.iconizer.src, 'colored'),
  icon(name, opts) {
    opts = Object.assign({
      tag: 'div',
      type: 'icons',
      class: '',
      mode: this.ctx.app.settings.iconizer.mode,
      url: this.ctx.app.settings.iconizer.url,
    }, opts);

    let external = '';
    let typeClass = '';

    if (opts.mode === 'external') {
      external = `${opts.url}/sprite.${opts.type}.svg`;
    }

    if (opts.type !== 'icons') {
      typeClass = ` svg-icon--${opts.type}`;
    }

    opts.class = opts.class ? ` ${opts.class}` : '';

    return `
      <${opts.tag} class="svg-icon svg-icon--${name}${typeClass}${opts.class}" aria-hidden="true">
        <svg class="svg-icon__link">
          <use xlink:href="${external}#${name}"></use>
        </svg>
      </${opts.tag}>
    `;
  },
  plugin: {
    mode: {
      symbol: { // symbol mode to build the SVG
        example: false, // Build sample page
      },
    },
    svg: {
      xmlDeclaration: false, // strip out the XML attribute
      doctypeDeclaration: false, // don't include the !DOCTYPE declaration
    },
  },
};

const autoprefixer = {
  overrideBrowserslist: [
    '>= 1%',
    'last 2 major version',
    'not dead',
    'Chrome >= 45',
    'Firefox >= 38',
    'Edge >= 12',
    'Explorer >= 10',
    'iOS >= 9',
    'Safari >= 9',
    'Android >= 4.4',
    'Opera >= 30',
  ],
};

const app = {
  css: '<%- css %>',
  watchOpts: {
    ignoreInitial: true,
    ignored: [
      `${folders.marmelad}/**/*.db`,
      `${folders.marmelad}/**/*tmp*`,
    ],
    usePolling: false,
    cwd: process.cwd(),
  },
  cssnano: {
    zIndex: false,
  },
  beml: {
    elemPrefix: '__',
    modPrefix: '--',
    modDlmtr: '-',
  },
  autoprefixer,
  postcss: {
    easingGradients: {},
    inlineSvg: {},
  },
  bsSP: {
    server: {
      baseDir: paths.dist,
    },
    port: 8967,
    open: false,
    directory: true,
    ghostMode: false,
    notify: true,
    logLevel: 'info',
    logPrefix: 'MARMELAD STATIC',
    logFileChanges: false,
    ui: false,
    latencyRoutes: [
      {
        route: '/api',
        latency: 3000,
        active: true,
      },
    ],
  },
  bts: {
    use: '<%- btsUse %>',
    donor: '<%- btsDonor %>',
    4: {
      code: '4.3.1',
      src: {
        css: path.join(paths.marmelad, 'bootstrap', '4.3.1'),
        js: path.join(paths.marmelad, 'bootstrap', '4.3.1'),
      },
      dest: {
        css: path.join(paths.storage, 'bootstrap', 'css'),
        js: path.join(paths.storage, 'bootstrap'),
      },
      sass: {
        precision: 6,
        outputStyle: 'expanded',
      },
      autoprefixer,
    },
  },
};

const proxy = {
  sources: {
    copy: [
      // path.join(folders.static, 'css'),
      // path.join(folders.static, 'fonts'),
      // path.join(folders.static, 'js'),
    ], // ресурсы для копирования
    ignored: [
      `${folders.static}/**/*.db`,
      `${folders.static}/**/*tmp*`,
    ],
    to: 'marmelad-no-proxy-folder-targer', // путь до директории копирования (wp-content/themes/marmelad)
  },
  server: {
    proxy: 'http://marmelad.loc',
    logFileChanges: false,
    ui: false,
    latencyRoutes: [
      {
        route: '/wp-admin/admin-ajax.php',
        latency: 3000,
        active: true,
      },
    ],
  },
};

module.exports = {
  folders,
  app,
  paths,
  iconizer,
  proxy,
};
<commit_msg>Отключение авто открытие браузера для proxy-mod<commit_after>const path = require('path');

const folders = {
  dist: 'static',
  storage: '',
  marmelad: 'marmelad',
  _blocks: '_blocks',
  _pages: '_pages',
  iconizer: {
    src: 'iconizer',
    icons: 'icons',
  },
  js: {
    src: 'js',
    vendors: 'vendors',
    plugins: 'plugins',
  },
  styles: 'styles',
  static: 'static',
};

const paths = {
  dist: path.join(folders.dist),
  storage: path.join(folders.dist, folders.storage),
  marmelad: path.join(folders.marmelad),
  _blocks: path.join(folders.marmelad, folders._blocks),
  _pages: path.join(folders.marmelad, folders._pages),
  js: {
    src: path.join(folders.marmelad, folders.js.src),
    vendors: path.join(folders.marmelad, folders.js.src, folders.js.vendors),
    plugins: path.join(folders.marmelad, folders.js.src, folders.js.plugins),
  },
  styles: path.join(folders.marmelad, folders.styles),
  static: path.join(folders.marmelad, folders.static),
};

const iconizer = {
  cssClass: 'main-svg-sprite',
  mode: 'inline', // external отдельный подключаемый файл спрайта (default:inline)
  dest: path.join(paths.dist, 'img'), // путь для собираемых спрайтов
  url: 'img', // путь до подключаемого спрайта iconizer.dest без paths.dist
  srcIcons: path.join(folders.marmelad, folders.iconizer.src, 'icons'),
  srcColored: path.join(folders.marmelad, folders.iconizer.src, 'colored'),
  icon(name, opts) {
    opts = Object.assign({
      tag: 'div',
      type: 'icons',
      class: '',
      mode: this.ctx.app.settings.iconizer.mode,
      url: this.ctx.app.settings.iconizer.url,
    }, opts);

    let external = '';
    let typeClass = '';

    if (opts.mode === 'external') {
      external = `${opts.url}/sprite.${opts.type}.svg`;
    }

    if (opts.type !== 'icons') {
      typeClass = ` svg-icon--${opts.type}`;
    }

    opts.class = opts.class ? ` ${opts.class}` : '';

    return `
      <${opts.tag} class="svg-icon svg-icon--${name}${typeClass}${opts.class}" aria-hidden="true">
        <svg class="svg-icon__link">
          <use xlink:href="${external}#${name}"></use>
        </svg>
      </${opts.tag}>
    `;
  },
  plugin: {
    mode: {
      symbol: { // symbol mode to build the SVG
        example: false, // Build sample page
      },
    },
    svg: {
      xmlDeclaration: false, // strip out the XML attribute
      doctypeDeclaration: false, // don't include the !DOCTYPE declaration
    },
  },
};

const autoprefixer = {
  overrideBrowserslist: [
    '>= 1%',
    'last 2 major version',
    'not dead',
    'Chrome >= 45',
    'Firefox >= 38',
    'Edge >= 12',
    'Explorer >= 10',
    'iOS >= 9',
    'Safari >= 9',
    'Android >= 4.4',
    'Opera >= 30',
  ],
};

const app = {
  css: '<%- css %>',
  watchOpts: {
    ignoreInitial: true,
    ignored: [
      `${folders.marmelad}/**/*.db`,
      `${folders.marmelad}/**/*tmp*`,
    ],
    usePolling: false,
    cwd: process.cwd(),
  },
  cssnano: {
    zIndex: false,
  },
  beml: {
    elemPrefix: '__',
    modPrefix: '--',
    modDlmtr: '-',
  },
  autoprefixer,
  postcss: {
    easingGradients: {},
    inlineSvg: {},
  },
  bsSP: {
    server: {
      baseDir: paths.dist,
    },
    port: 8967,
    open: false,
    directory: true,
    ghostMode: false,
    notify: true,
    logLevel: 'info',
    logPrefix: 'MARMELAD STATIC',
    logFileChanges: false,
    ui: false,
    latencyRoutes: [
      {
        route: '/api',
        latency: 3000,
        active: true,
      },
    ],
  },
  bts: {
    use: '<%- btsUse %>',
    donor: '<%- btsDonor %>',
    4: {
      code: '4.3.1',
      src: {
        css: path.join(paths.marmelad, 'bootstrap', '4.3.1'),
        js: path.join(paths.marmelad, 'bootstrap', '4.3.1'),
      },
      dest: {
        css: path.join(paths.storage, 'bootstrap', 'css'),
        js: path.join(paths.storage, 'bootstrap'),
      },
      sass: {
        precision: 6,
        outputStyle: 'expanded',
      },
      autoprefixer,
    },
  },
};

const proxy = {
  sources: {
    copy: [
      // path.join(folders.static, 'css'),
      // path.join(folders.static, 'fonts'),
      // path.join(folders.static, 'js'),
    ], // ресурсы для копирования
    ignored: [
      `${folders.static}/**/*.db`,
      `${folders.static}/**/*tmp*`,
    ],
    to: 'marmelad-no-proxy-folder-targer', // путь до директории копирования (wp-content/themes/marmelad)
  },
  server: {
    proxy: 'http://marmelad.loc',
    logFileChanges: false,
    ui: false,
    open: false,
    latencyRoutes: [
      {
        route: '/wp-admin/admin-ajax.php',
        latency: 3000,
        active: true,
      },
    ],
  },
};

module.exports = {
  folders,
  app,
  paths,
  iconizer,
  proxy,
};
<|endoftext|>


<commit_before>const benchmark = require('benchmark');
const suite = new benchmark.Suite();
const DataTask = require('data.task');
const RamdaFuture = require('ramda-fantasy').Future;
const Fluture = require('..');

const noop = () => {};
const fluture = Fluture((rej, res) => res(1));
const task = new DataTask((rej, res) => res(1));
const future = RamdaFuture((rej, res) => res(1));
const flutureF = Fluture((rej, res) => res(x => x + 1));
const taskF = new DataTask((rej, res) => res(x => x + 1));
const futureF = RamdaFuture((rej, res) => res(x => x + 1));

suite.add('Fluture', () => {
  flutureF.ap(fluture).fork(noop, noop);
});

suite.add('data.task', () => {
  taskF.ap(task).fork(noop, noop);
});

suite.add('Ramda Fantasy', () => {
  futureF.ap(future).fork(noop, noop);
});

suite.on('complete', require('./_print'))
suite.run()
<commit_msg>Fix the `ap` benchmark<commit_after>const benchmark = require('benchmark');
const suite = new benchmark.Suite();
const DataTask = require('data.task');
const RamdaFuture = require('ramda-fantasy').Future;
const Fluture = require('..');

const noop = () => {};
const fluture = Fluture((rej, res) => res(1));
const task = new DataTask((rej, res) => res(1));
const future = RamdaFuture((rej, res) => res(1));
const flutureF = Fluture((rej, res) => res(x => x + 1));
const taskF = new DataTask((rej, res) => res(x => x + 1));
const futureF = RamdaFuture((rej, res) => res(x => x + 1));

suite.add('Fluture', () => {
  fluture.ap(flutureF).fork(noop, noop);
});

suite.add('data.task', () => {
  taskF.ap(task).fork(noop, noop);
});

suite.add('Ramda Fantasy', () => {
  futureF.ap(future).fork(noop, noop);
});

suite.on('complete', require('./_print'))
suite.run()
<|endoftext|>


<commit_before>import AJV from 'ajv';
const ajv = AJV();

function safeEscapeQuotes(str) {
  return str.replace(/\\([\s\S])|(')/g,"\\$1$2").replace(/\\([\s\S])|(")/g,"\\$1$2"); // escape only if not escaped already
}

ajv.addKeyword('deprecated', { inline: function (it, keyword, schema){
  var op = schema ? `console && console.warn && console.warn('Property "${it.schemaPath.replace(/^\.properties\./, '')}" was deprecated on: ${schema.deprecatedOn}. Recommended alternative is: "${safeEscapeQuotes(schema.description)}".')` : '';
  return `${op} || 1`;
}});

export default ajv;<commit_msg>Fixing tests and imports after merge from master<commit_after><|endoftext|>


<commit_before>/**
  * Riassence Core -- http://rsence.org/
  *
  * Copyright (C) 2008 Juha-Jarmo Heinonen <jjh@riassence.com>
  * Copyright (C) 2006 Helmi Technologies Inc.
  *
  * This file is part of Riassence Core.
  *
  * Riassence Core is free software: you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
  * the Free Software Foundation, either version 3 of the License, or
  * (at your option) any later version.
  *
  * Riassence Core is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Public License for more details.
  *
  * You should have received a copy of the GNU General Public License
  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  *
  **/

/*** class: HSlider
  **
  ** HSlider is a control unit that enables the user to choose a value in a range of values.
  ** Sliders support both dragging the handle and clicking the mouse anywhere on the slider
  ** to move the handle towards the mouse, as well as keyboard support
  ** after the handle is in active mode. There are two types of sliders: vertical and horizontal.
  ** Naturally, sliders are commonly used as colour mixers, volume controls,
  ** graphical equalizers and seekers in media applications.
  ** A typical slider is a drag-able thumb along vertical or horizontal line.
  ** Slider view or theme can be changed; the helmiTheme is used by default.
  **
  ** vars: Instance variables
  **  type - '[HSlider]'
  **  value - Numeric value currently set to this object.
  **  minValue - The minimum value that can be set to this object.
  **  maxValue - The maximum value that can be set to this object.
  **
  ** Extends:
  **  <HControl>
  **
  ** See also:
  **  <HControl> <HVSlider>
  ***/
HSlider = HControl.extend({

  componentName: "slider",

/** constructor: constructor
  *
  * Parameters:
  *   _rect - An <HRect> object that sets the position and dimensions of this control.
  *   _parent - The parent view that this control is to be inserted in.
  *   _options - (optional) All other parameters. See <HComponentDefaults>.
  **/
  constructor: function(_rect,_parent,_options) {

    // Makes sure there is at least an empty options block
    if (!_options) {
      _options = {};
    }

    // Makes sure the default events for HStepper are enabled
    if (!_options.events) {
      _options.events = {
        mouseDown: false,
        mouseUp:   false,
        draggable: true,
        keyDown: true,
        keyUp: true,
        mouseWheel: true
      };
    }

    // Makes sure some other optional options are at some sane defaults
    _options = HClass.extend({

      // The smallest allowed value
      minValue: 0,

      // The biggest allowed value
      maxValue: 1,

      // Interval in milliseconds for repeat
      repeatDelay: 300,

      // Interval in milliseconds for repeat
      repeatInterval: 50,

      // Inverse Scrollwheel axis:
      // As there is only one scrollwheel event, sideways
      // scrolling doesn't work logically for horizonal
      // scrollbars by default, so set this to true to
      // have horizonal sliders work logically
      // with sideways scrolling, where supported.
      inverseAxis: false

    }).extend(

      // Include user-specified overrides to options
      _options

    ).nu(); // new instance of the HClass as _options

    if(this.isinherited){
      this.base(_rect,_parent,_options);
    }
    else {
      this.isinherited = true;
      this.base(_rect,_parent,_options);
      this.isinherited = false;
    }

    this.refreshOnValueChange = false;

    // This is overridden in vertical slider.
    this._isVertical = false;

    if(!this.isinherited){
      this.draw();
    }
  },

/** method: setValue
  *
  * Sets the current value of the object and moves the slider thumb to the correct position.
  *
  * Parameters:
  *   _value - A numeric value to be set to the object.
  *
  * See also:
  *  <HControl.setValue>
  **/
  setValue: function(_value) {
    if (_value < this.minValue) {
      var _value = this.minValue;
    }
    if (_value > this.maxValue) {
      var _value = this.maxValue;
    }
    this.base(_value);
    if(this._thumbElemId){
      this.drawThumbPos();
    }
  },

/** method: draw
  *
  * Draws the rectangle and the markup of this object on the screen.
  *
  * See also:
  *  <HView.draw>
  **/
  draw: function() {
    if(!this.drawn) {
      this.drawRect();
      this.drawMarkup();
      this._initThumb();
    }
    this.refresh();
  },

/** event: startDrag
  *
  * This gets called automatically when the user starts to drag the slider thumb.
  * Extend this method if you want something special to happen when the dragging starts.
  *
  * Parameters:
  *   _x - The X coordinate of the point where the drag started.
  *   _y - The Y coordinate of the point where the drag started.
  *
  * See also:
  *  <HControl.startDrag>
  **/
  startDrag: function(_x,_y){
    var _originalPosition = ELEM.getVisiblePosition(this.elemId, true);
    this._originX = _originalPosition[0];
    this._originY = _originalPosition[1];

    this.doDrag(_x,_y);
  },

/** event: endDrag
  *
  * This gets called automatically when the user stops dragging the slider thumb.
  * Extend this method if you want something special to happen when the dragging ends.
  *
  * Parameters:
  *   _x - The X coordinate of the point where the drag ended.
  *   _y - The Y coordinate of the point where the drag ended.
  *
  * See also:
  *  <HControl.endDrag>
  **/
  endDrag: function(_x,_y){
    this.doDrag(_x,_y);
  },

/** event: doDrag
  *
  * This gets called periodically while the user drags the slider thumb.
  * Extend this method if you want something special to happen while dragging.
  *
  * Parameters:
  *   _x - The X coordinate of the point where the user is currently dragging.
  *   _y - The Y coordinate of the point where the user is currently dragging.
  *
  * See also:
  *  <HControl.doDrag>
  **/
  doDrag: function(_x,_y){
    _x -= this._originX;
    _y -= this._originY;

    var _rawVal = this._isVertical?_y:_x;
    var _value = this._pos2value(_rawVal);
    this.setValue(_value);
  },

/** event: keyDown
  *
  * This gets called when the user presses a key down while this control is
  * active. The default behaviour is to move the thumb with arrow keys, page up,
  * page down, home and end.
  *
  * Parameters:
  *   _keycode - The keycode of the key that was pressed down.
  *
  * See also:
  *  <HControl.keyDown>
  **/
  keyDown: function(_keycode) {
    // Arrow keys move the thumb 5% at a time.
    if ( (_keycode === Event.KEY_LEFT && !this._isVertical) ||
      (_keycode === Event.KEY_DOWN && this._isVertical) ) {
      this._moving = true;
      this._moveThumb(-0.05);
    }
    else if ( (_keycode === Event.KEY_RIGHT && !this._isVertical) ||
      (_keycode === Event.KEY_UP && this._isVertical) ) {
      this._moving = true;
      this._moveThumb(0.05);
    }
    // Home key moves the thumb to the beginning and end key to the end.
    else if (_keycode === Event.KEY_HOME) {
      this.setValue(this.minValue);
    }
    else if (_keycode === Event.KEY_END) {
      this.setValue(this.maxValue);
    }
    // Page up and page down keys move the thumb 25% at a time.
    else if (_keycode === Event.KEY_PAGEDOWN) {
      this._moving = true;
      this._moveThumb(-0.25);
    }
    else if (_keycode === Event.KEY_PAGEUP) {
      this._moving = true;
      this._moveThumb(0.25);
    }

  },

/** event: keyUp
  *
  * This gets called when the user releases a key while this control is active.
  *
  * Parameters:
  *   _keycode - The keycode of the key that was released.
  *
  * See also:
  *  <HControl.keyUp>
  **/
  keyUp: function(_keycode) {
    this._moving = false;
  },

/** event: mouseWheel
  *
  * This gets called when the mouse wheel is used and the component instance has
  * focus.
  *
  * Parameters:
  *  _delta - Scrolling delta, the wheel angle change. If delta is positive,
  *   wheel was scrolled up. Otherwise, it was scrolled down.
  *
  * See also:
  *  <HControl.mouseWheel>
  **/
  mouseWheel: function(_delta) {
    var _valueChange;
    if (_delta > 0) {
      _valueChange = 0.05;
    }
    else {
      _valueChange = -0.05;
    }
    if ( this.options.inverseAxis ) {
      _valueChange = 0 - _valueChange;
    }

    var _value = (this.maxValue - this.minValue) * _valueChange;
    this.setValue( this.value + _value);
  },

  // private method
  _moveThumb: function(_valueChange, _rate) {

    if (!_rate) {
      // If the key is held down, wait for a while before starting repeat.
      _rate = this.options.repeatDelay;
    }
    else if (_rate === this.options.repeatDelay) {
      _rate = this.options.repeatInterval;
    }

    if (this._moving && this.active) {

      var _value = (this.maxValue - this.minValue) * _valueChange;

      this.setValue( this.value + _value);

      var _that = this;
      if (this._thumbMoveTimeout) {
        window.clearTimeout(this._thumbMoveTimeout);
        this._thumbMoveTimeout = null;
      }
      this._thumbMoveTimeout = window.setTimeout(function(){
        _that._moveThumb(_valueChange, _rate);
      }, _rate);
    }

  },

  thumbSize: 21,
  // private method
  _initThumb: function() {
    this._thumbElemId = this.markupElemIds.control;
    this.drawThumbPos();
  },

  // private method
  _value2px: function() {
    if(this._isVertical){
      var _pxrange  = this.rect.height - this.thumbSize;
    } else {
      var _pxrange  = this.rect.width - this.thumbSize;
    }
    var _intvalue = _pxrange * (
      (this.value-this.minValue) / (this.maxValue - this.minValue)
    );
    if ( this._isVertical ) {
      _intvalue = _pxrange - _intvalue;
    }
    var _pxvalue = parseInt(_intvalue, 10)+'px';
    return _pxvalue;
  },

  // private method
  _pos2value: function(_mousePos) {
    if(this._isVertical){
      var _pxrange  = this.rect.height - this.thumbSize;
    } else {
      var _pxrange  = this.rect.width - this.thumbSize;
    }
    _mousePos -= (this.thumbSize/2);
    if(_mousePos < 0){
      _mousePos = 0;
    }
    if(_mousePos > _pxrange){
      _mousePos = _pxrange;
    }
    if(this._isVertical){
      return this.maxValue - ((_mousePos / _pxrange) * (this.maxValue - this.minValue));
    } else {
      return this.minValue + ((_mousePos / _pxrange) * (this.maxValue - this.minValue));
    }
  },

  // private method
  drawThumbPos: function() {
    var _whichprop = this._isVertical?'top':'left',
        _propval   = this._value2px();
    ELEM.setStyle(this._thumbElemId,_whichprop,_propval);
    this.setOrientation(this.options['orientation']||this.prevOrientation);
  },

  prevOrientation: 'c',

  cssClassPrefix: 'h',

  setOrientation: function(_orientation) {
    if(!_orientation){
      _orientation = 'c';
    }
    _orientation = _orientation.toLowerCase();
    if(_orientation === this.prevOrientation){
      return false;
    }
    if(this['markupElemIds']===undefined){
      return false;
    }
    if(this.markupElemIds['control']===undefined){
      return false;
    }
    var _toggleCSS = this.toggleCSSClass,
        _ctrlId    = this.markupElemIds.control,
        _orientations = ['n','s','w','e','c'],
        _iOrientation = '',
        _cssClassName = '',
        _cssClassPrefix = this.cssClassPrefix,
        _cssClassVert = this._isVertical?'v':'',
        _activeOrientation = false,
        i = 0;
    for(;i<5;i++){
      _iOrientation = _orientations[i];
      _activeOrientation = (_orientation===_iOrientation);
      _cssClassName = (_orientation==='c')?_cssClassPrefix+_cssClassVert+'slider_thumb':_cssClassPrefix+'slider_thumb_'+_iOrientation;
      _toggleCSS( _ctrlId, _cssClassName, _activeOrientation );
    }

    this.prevOrientation = _orientation;
  }
});

<commit_msg>Fixed various minor syntax issues<commit_after>/**
  * Riassence Core -- http://rsence.org/
  *
  * Copyright (C) 2008 Juha-Jarmo Heinonen <jjh@riassence.com>
  * Copyright (C) 2006 Helmi Technologies Inc.
  *
  * This file is part of Riassence Core.
  *
  * Riassence Core is free software: you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
  * the Free Software Foundation, either version 3 of the License, or
  * (at your option) any later version.
  *
  * Riassence Core is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Public License for more details.
  *
  * You should have received a copy of the GNU General Public License
  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  *
  **/

/*** class: HSlider
  **
  ** HSlider is a control unit that enables the user to choose a value in a range of values.
  ** Sliders support both dragging the handle and clicking the mouse anywhere on the slider
  ** to move the handle towards the mouse, as well as keyboard support
  ** after the handle is in active mode. There are two types of sliders: vertical and horizontal.
  ** Naturally, sliders are commonly used as colour mixers, volume controls,
  ** graphical equalizers and seekers in media applications.
  ** A typical slider is a drag-able thumb along vertical or horizontal line.
  ** Slider view or theme can be changed; the helmiTheme is used by default.
  **
  ** vars: Instance variables
  **  type - '[HSlider]'
  **  value - Numeric value currently set to this object.
  **  minValue - The minimum value that can be set to this object.
  **  maxValue - The maximum value that can be set to this object.
  **
  ** Extends:
  **  <HControl>
  **
  ** See also:
  **  <HControl> <HVSlider>
  ***/
HSlider = HControl.extend({

  componentName: "slider",

/** constructor: constructor
  *
  * Parameters:
  *   _rect - An <HRect> object that sets the position and dimensions of this control.
  *   _parent - The parent view that this control is to be inserted in.
  *   _options - (optional) All other parameters. See <HComponentDefaults>.
  **/
  constructor: function(_rect,_parent,_options) {

    // Makes sure there is at least an empty options block
    if (!_options) {
      _options = {};
    }

    // Makes sure the default events for HStepper are enabled
    if (!_options.events) {
      _options.events = {
        mouseDown: false,
        mouseUp:   false,
        draggable: true,
        keyDown: true,
        keyUp: true,
        mouseWheel: true
      };
    }

    // Makes sure some other optional options are at some sane defaults
    _options = HClass.extend({

      // The smallest allowed value
      minValue: 0,

      // The biggest allowed value
      maxValue: 1,

      // Interval in milliseconds for repeat
      repeatDelay: 300,

      // Interval in milliseconds for repeat
      repeatInterval: 50,

      // Inverse Scrollwheel axis:
      // As there is only one scrollwheel event, sideways
      // scrolling doesn't work logically for horizonal
      // scrollbars by default, so set this to true to
      // have horizonal sliders work logically
      // with sideways scrolling, where supported.
      inverseAxis: false

    }).extend(

      // Include user-specified overrides to options
      _options

    ).nu(); // new instance of the HClass as _options

    if(this.isinherited){
      this.base(_rect,_parent,_options);
    }
    else {
      this.isinherited = true;
      this.base(_rect,_parent,_options);
      this.isinherited = false;
    }

    this.refreshOnValueChange = false;

    // This is overridden in vertical slider.
    this._isVertical = false;

    if(!this.isinherited){
      this.draw();
    }
  },

/** method: setValue
  *
  * Sets the current value of the object and moves the slider thumb to the correct position.
  *
  * Parameters:
  *   _value - A numeric value to be set to the object.
  *
  * See also:
  *  <HControl.setValue>
  **/
  setValue: function(_value) {
    if (_value < this.minValue) {
      _value = this.minValue;
    }
    if (_value > this.maxValue) {
      _value = this.maxValue;
    }
    this.base(_value);
    if(this._thumbElemId){
      this.drawThumbPos();
    }
    return this;
  },

/** method: draw
  *
  * Draws the rectangle and the markup of this object on the screen.
  *
  * See also:
  *  <HView.draw>
  **/
  draw: function() {
    if(!this.drawn) {
      this.drawRect();
      this.drawMarkup();
      this._initThumb();
    }
    this.refresh();
  },

/** event: startDrag
  *
  * This gets called automatically when the user starts to drag the slider thumb.
  * Extend this method if you want something special to happen when the dragging starts.
  *
  * Parameters:
  *   _x - The X coordinate of the point where the drag started.
  *   _y - The Y coordinate of the point where the drag started.
  *
  * See also:
  *  <HControl.startDrag>
  **/
  startDrag: function(_x,_y){
    var _originalPosition = ELEM.getVisiblePosition(this.elemId, true);
    this._originX = _originalPosition[0];
    this._originY = _originalPosition[1];

    this.doDrag(_x,_y);
  },

/** event: endDrag
  *
  * This gets called automatically when the user stops dragging the slider thumb.
  * Extend this method if you want something special to happen when the dragging ends.
  *
  * Parameters:
  *   _x - The X coordinate of the point where the drag ended.
  *   _y - The Y coordinate of the point where the drag ended.
  *
  * See also:
  *  <HControl.endDrag>
  **/
  endDrag: function(_x,_y){
    this.doDrag(_x,_y);
  },

/** event: doDrag
  *
  * This gets called periodically while the user drags the slider thumb.
  * Extend this method if you want something special to happen while dragging.
  *
  * Parameters:
  *   _x - The X coordinate of the point where the user is currently dragging.
  *   _y - The Y coordinate of the point where the user is currently dragging.
  *
  * See also:
  *  <HControl.doDrag>
  **/
  doDrag: function(_x,_y){
    _x -= this._originX;
    _y -= this._originY;

    var _rawVal = this._isVertical?_y:_x;
    var _value = this._pos2value(_rawVal);
    this.setValue(_value);
  },

/** event: keyDown
  *
  * This gets called when the user presses a key down while this control is
  * active. The default behaviour is to move the thumb with arrow keys, page up,
  * page down, home and end.
  *
  * Parameters:
  *   _keycode - The keycode of the key that was pressed down.
  *
  * See also:
  *  <HControl.keyDown>
  **/
  keyDown: function(_keycode) {
    // Arrow keys move the thumb 5% at a time.
    if ( (_keycode === Event.KEY_LEFT && !this._isVertical) ||
      (_keycode === Event.KEY_DOWN && this._isVertical) ) {
      this._moving = true;
      this._moveThumb(-0.05);
    }
    else if ( (_keycode === Event.KEY_RIGHT && !this._isVertical) ||
      (_keycode === Event.KEY_UP && this._isVertical) ) {
      this._moving = true;
      this._moveThumb(0.05);
    }
    // Home key moves the thumb to the beginning and end key to the end.
    else if (_keycode === Event.KEY_HOME) {
      this.setValue(this.minValue);
    }
    else if (_keycode === Event.KEY_END) {
      this.setValue(this.maxValue);
    }
    // Page up and page down keys move the thumb 25% at a time.
    else if (_keycode === Event.KEY_PAGEDOWN) {
      this._moving = true;
      this._moveThumb(-0.25);
    }
    else if (_keycode === Event.KEY_PAGEUP) {
      this._moving = true;
      this._moveThumb(0.25);
    }

  },

/** event: keyUp
  *
  * This gets called when the user releases a key while this control is active.
  *
  * Parameters:
  *   _keycode - The keycode of the key that was released.
  *
  * See also:
  *  <HControl.keyUp>
  **/
  keyUp: function(_keycode) {
    this._moving = false;
  },

/** event: mouseWheel
  *
  * This gets called when the mouse wheel is used and the component instance has
  * focus.
  *
  * Parameters:
  *  _delta - Scrolling delta, the wheel angle change. If delta is positive,
  *   wheel was scrolled up. Otherwise, it was scrolled down.
  *
  * See also:
  *  <HControl.mouseWheel>
  **/
  mouseWheel: function(_delta) {
    var _valueChange;
    if (_delta > 0) {
      _valueChange = 0.05;
    }
    else {
      _valueChange = -0.05;
    }
    if ( this.options.inverseAxis ) {
      _valueChange = 0 - _valueChange;
    }

    var _value = (this.maxValue - this.minValue) * _valueChange;
    this.setValue( this.value + _value);
  },

  // private method
  _moveThumb: function(_valueChange, _rate) {

    if (!_rate) {
      // If the key is held down, wait for a while before starting repeat.
      _rate = this.options.repeatDelay;
    }
    else if (_rate === this.options.repeatDelay) {
      _rate = this.options.repeatInterval;
    }

    if (this._moving && this.active) {

      var _value = (this.maxValue - this.minValue) * _valueChange;

      this.setValue( this.value + _value);

      var _that = this;
      if (this._thumbMoveTimeout) {
        window.clearTimeout(this._thumbMoveTimeout);
        this._thumbMoveTimeout = null;
      }
      this._thumbMoveTimeout = window.setTimeout(function(){
        _that._moveThumb(_valueChange, _rate);
      }, _rate);
    }

  },

  thumbSize: 21,
  // private method
  _initThumb: function() {
    this._thumbElemId = this.markupElemIds.control;
    this.drawThumbPos();
  },

  // private method
  _value2px: function() {
    var _pxrange;
    if(this._isVertical){
      _pxrange  = this.rect.height - this.thumbSize;
    } else {
      _pxrange  = this.rect.width - this.thumbSize;
    }
    var _intvalue = _pxrange * (
      (this.value-this.minValue) / (this.maxValue - this.minValue)
    );
    if ( this._isVertical ) {
      _intvalue = _pxrange - _intvalue;
    }
    _pxvalue = parseInt(_intvalue, 10)+'px';
    return _pxvalue;
  },

  // private method
  _pos2value: function(_mousePos) {
    var _pxrange;
    if(this._isVertical){
      _pxrange  = this.rect.height - this.thumbSize;
    } else {
      _pxrange  = this.rect.width - this.thumbSize;
    }
    _mousePos -= (this.thumbSize/2);
    if(_mousePos < 0){
      _mousePos = 0;
    }
    if(_mousePos > _pxrange){
      _mousePos = _pxrange;
    }
    if(this._isVertical){
      return this.maxValue - ((_mousePos / _pxrange) * (this.maxValue - this.minValue));
    } else {
      return this.minValue + ((_mousePos / _pxrange) * (this.maxValue - this.minValue));
    }
  },

  // private method
  drawThumbPos: function() {
    var _whichprop = this._isVertical?'top':'left',
        _propval   = this._value2px();
    ELEM.setStyle(this._thumbElemId,_whichprop,_propval);
    this.setOrientation(this.options['orientation']||this.prevOrientation);
  },

  prevOrientation: 'c',

  cssClassPrefix: 'h',

  setOrientation: function(_orientation) {
    if(!_orientation){
      _orientation = 'c';
    }
    _orientation = _orientation.toLowerCase();
    if(_orientation === this.prevOrientation){
      return;
    }
    if(this['markupElemIds']===undefined){
      return;
    }
    if(this.markupElemIds['control']===undefined){
      return;
    }
    var _toggleCSS = this.toggleCSSClass,
        _ctrlId    = this.markupElemIds.control,
        _orientations = ['n','s','w','e','c'],
        _iOrientation = '',
        _cssClassName = '',
        _cssClassPrefix = this.cssClassPrefix,
        _cssClassVert = this._isVertical?'v':'',
        _activeOrientation = false,
        i = 0;
    for(;i<5;i++){
      _iOrientation = _orientations[i];
      _activeOrientation = (_orientation===_iOrientation);
      _cssClassName = (_orientation==='c')?_cssClassPrefix+_cssClassVert+'slider_thumb':_cssClassPrefix+'slider_thumb_'+_iOrientation;
      _toggleCSS( _ctrlId, _cssClassName, _activeOrientation );
    }

    this.prevOrientation = _orientation;
  }
});

<|endoftext|>


<commit_before>'use strict';

import Logger from '../../services/logger';
import Platform from '../../services/platform';
import ComponentLoader from '../../services/componentLoader';

class SelectionController {

  constructor($scope, $state, $timeout, installerDataSvc, electron) {
    this.router = $state;
    this.sc = $scope;
    this.timeout = $timeout;
    this.installerDataSvc = installerDataSvc;
    this.electron = electron;
    this.loader = new ComponentLoader(installerDataSvc);
    this.loader.loadComponents();
    this.installedSearchNote = '';
    this.isDisabled = false;
    this.numberOfExistingInstallations = 0;
    this.step = 1;
    this.installables = {};
    $scope.checkboxModel = {};
    $scope.platform = Platform.OS;
    $scope.detectionStyle = false;
    $scope.virtualization = true;
    this.channelList = require('../../../channels');
    this.channel_tab = 'all';
    $scope.componentsInChannel = this.componentsInChannel.bind(this);

    for (let [key, value] of this.installerDataSvc.allInstallables().entries()) {
      $scope.checkboxModel[key] = value;
      $scope.$watch(`checkboxModel.${key}.selectedOption`, function watchInstallSelectionChange() {
        $scope.checkboxModel[key].validateVersion();
      });
    }

    $scope.$on('$destroy', ()=>{
      restoreMenu();
    });

    $scope.isConfigurationValid = this.isConfigurationValid;
    $scope.$watch('$viewContentLoaded', this.initPage.bind(this));

    this.electron.remote.getCurrentWindow().addListener('focus', this.activatePage.bind(this));
    this.componentDetails = Object.values(this.sc.checkboxModel);
  }

  componentsInChannel() {
    return this.componentDetails.filter(value=> {
      return this.channel_tab === 'all' || value.channel && value.channel[this.channel_tab];
    });
  }

  toggleSelection(type) {
    let deselectedComponents = [];
    this.componentsInChannel(this.channel_tab).forEach((node)=>{
      if(type==='all') {
        if (node.isInstallable && node.isNotDetected()) {
          node.selectedOption = 'install';
        }
      } else if(type==='none') {
        node.selectedOption = 'detected';
        deselectedComponents.push(node);
      }
    });
    for (const node of deselectedComponents) {
      if (node.references > 0) {
        node.selectedOption = 'install';
      }
    }
  }

  channelBadge(tab) {
    if(tab === 'all') {
      return this.componentDetails.length;
    } else {
      var channels = this.componentDetails.filter(value=> {
        return value.channel && value.channel[tab];
      });
      return channels.length;
    }
  }

  componentsSelected() {
    let downloadedComponents = [];
    this.componentsInChannel(this.channel_tab).forEach((value)=> {
      if(value.selectedOption == 'install' && !value.isSkipped()) {
        downloadedComponents.push(value);
      }
      this.downloadComp = downloadedComponents;
    });
    return this.downloadComp.length;
  }

  initPage() {
    return this.detectInstalledComponents().then(()=> {
      this.graph = ComponentLoader.loadGraph(this.installerDataSvc);
      this.installWatchers();
    }).then(
      ()=> this.setIsDisabled()
    ).catch((error)=> {
      console.error(error);
      this.setIsDisabled();
    });
  }

  activatePage() {
    return this.detectInstalledComponents().then(
      ()=> this.setIsDisabled()
    ).catch((error)=> {
      Logger.error(error);
      this.setIsDisabled();
    });
  }

  installWatchers() {
    let graph = this.graph;
    let nodes = graph.overallOrder() ;
    let checkboxModel = this.sc.checkboxModel;
    for (let node of nodes) {
      checkboxModel[node].dependenciesOf = [];
      for(let dependant of this.graph.dependantsOf(node)) {
        checkboxModel[node].dependenciesOf.push(checkboxModel[dependant]);
      }
      checkboxModel[node].references=0;
    }
    for (let node of nodes) {
      this.sc.$watch(`checkboxModel.${node}.selectedOption`, this.watchComponent.bind(this, node));
    }
  }

  watchComponent(node, newv, oldv) {
    let graph = this.graph;
    let checkboxModel = this.sc.checkboxModel;
    let installer = checkboxModel[node];
    if(installer.isSelected()) {
      for(let dep of graph.dependenciesOf(node)) {
        let depInstaller = checkboxModel[dep];
        if(depInstaller.isInstallable
          && !depInstaller.isDisabled()
          && depInstaller.references === 0
          && (depInstaller.isNotDetected() || depInstaller.isInvalidVersionDetected())) {
          depInstaller.selectedOption = 'install';
        }
        depInstaller.references++;
      }
    } else if(!installer.isSelected() && oldv === 'install') {
      for(let dep of graph.dependenciesOf(node)) {
        let depInstaller = checkboxModel[dep];
        depInstaller.references--;
        if(depInstaller.references === 0) {
          depInstaller.selectedOption = 'detected';
        }
      }
    }
  }

  detectInstalledComponents() {
    if(!this.isDisabled) {
      this.isDisabled = true;
      this.timeout(()=>{});
      this.installedSearchNote = ' The system is checking if you have any installed components.';
      let detectors = [];
      for (let installer of this.installerDataSvc.allInstallables().values()) {
        detectors.push(installer.detectExistingInstall());
      }
      this.detection = Promise.all(detectors);
    }
    return this.detection;
  }

  // Prep the install location path for each product, then go to the next page.
  next() {
    this.loader.orderInstallation(this.graph);
    this.electron.remote.getCurrentWindow().removeAllListeners('focus');
    this.router.go('confirm');
  }

  setIsDisabled() {
    // Uncomment the timeout to see the initial disabled view.
    this.timeout(() => {
      // Switch this boolean flag when the app is done looking for existing installations.
      this.isDisabled = false;
      this.numberOfExistingInstallations = 0;
      // Count the number of existing installations.
      for (var [, value] of this.installerDataSvc.allInstallables()) {
        if (value.hasOption('detected')) {
          ++this.numberOfExistingInstallations;
        }
      }

      if (this.numberOfExistingInstallations == 1) {
        this.installedSearchNote = `  We found ${this.numberOfExistingInstallations} installed component.`;
      } else if (this.numberOfExistingInstallations > 1) {
        this.installedSearchNote = `  We found ${this.numberOfExistingInstallations} installed components.`;
      } else {
        this.installedSearchNote = '';
      }

      if (this.numberOfExistingInstallations == 0) {
        this.installInstructions = 'Select components to install.';
      } else if (this.numberOfExistingInstallations > 0) {
        this.installInstructions = 'Select any additional components to install.';
      }
    }, true);
  }

  isConfigurationValid() {
    let result = true;
    for (let [, value] of this.installerDataSvc.allInstallables().entries()) {
      if(! (result = value.isConfigurationValid())) {
        break;
      }
    }
    return result && this.isAtLeastOneSelected();
  }

  isAtLeastOneSelected() {
    let selected = false;
    for (var [, value] of this.installerDataSvc.allInstallables()) {
      selected = !value.isSkipped();
      if(selected) {
        break;
      }
    }
    return selected;
  }

  exit() {
    Logger.info('Closing the installer window');
    this.electron.remote.getCurrentWindow().close();
  }

  back() {
    Logger.info('Going back a page');
    this.electron.remote.getCurrentWindow().removeAllListeners('focus');
    this.router.go('location');
  }
}

SelectionController.$inject = ['$scope', '$state', '$timeout', 'installerDataSvc', 'electron'];

export default SelectionController;
<commit_msg>Ignore not selected items when using clear all<commit_after>'use strict';

import Logger from '../../services/logger';
import Platform from '../../services/platform';
import ComponentLoader from '../../services/componentLoader';

class SelectionController {

  constructor($scope, $state, $timeout, installerDataSvc, electron) {
    this.router = $state;
    this.sc = $scope;
    this.timeout = $timeout;
    this.installerDataSvc = installerDataSvc;
    this.electron = electron;
    this.loader = new ComponentLoader(installerDataSvc);
    this.loader.loadComponents();
    this.installedSearchNote = '';
    this.isDisabled = false;
    this.numberOfExistingInstallations = 0;
    this.step = 1;
    this.installables = {};
    $scope.checkboxModel = {};
    $scope.platform = Platform.OS;
    $scope.detectionStyle = false;
    $scope.virtualization = true;
    this.channelList = require('../../../channels');
    this.channel_tab = 'all';
    $scope.componentsInChannel = this.componentsInChannel.bind(this);

    for (let [key, value] of this.installerDataSvc.allInstallables().entries()) {
      $scope.checkboxModel[key] = value;
      $scope.$watch(`checkboxModel.${key}.selectedOption`, function watchInstallSelectionChange() {
        $scope.checkboxModel[key].validateVersion();
      });
    }

    $scope.$on('$destroy', ()=>{
      restoreMenu();
    });

    $scope.isConfigurationValid = this.isConfigurationValid;
    $scope.$watch('$viewContentLoaded', this.initPage.bind(this));

    this.electron.remote.getCurrentWindow().addListener('focus', this.activatePage.bind(this));
    this.componentDetails = Object.values(this.sc.checkboxModel);
  }

  componentsInChannel() {
    return this.componentDetails.filter(value=> {
      return this.channel_tab === 'all' || value.channel && value.channel[this.channel_tab];
    });
  }

  toggleSelection(type) {
    let deselectedComponents = [];
    this.componentsInChannel(this.channel_tab).forEach((node)=>{
      if(type==='all') {
        if (node.isInstallable && node.isNotDetected()) {
          node.selectedOption = 'install';
        }
      } else if(type ==='none' && node.selectedOption === 'install') {
        node.selectedOption = 'detected';
        deselectedComponents.push(node);
      }
    });
    for (const node of deselectedComponents) {
      if (node.references > 0) {
        node.selectedOption = 'install';
      }
    }
  }

  channelBadge(tab) {
    if(tab === 'all') {
      return this.componentDetails.length;
    } else {
      var channels = this.componentDetails.filter(value=> {
        return value.channel && value.channel[tab];
      });
      return channels.length;
    }
  }

  componentsSelected() {
    let downloadedComponents = [];
    this.componentsInChannel(this.channel_tab).forEach((value)=> {
      if(value.selectedOption == 'install' && !value.isSkipped()) {
        downloadedComponents.push(value);
      }
      this.downloadComp = downloadedComponents;
    });
    return this.downloadComp.length;
  }

  initPage() {
    return this.detectInstalledComponents().then(()=> {
      this.graph = ComponentLoader.loadGraph(this.installerDataSvc);
      this.installWatchers();
    }).then(
      ()=> this.setIsDisabled()
    ).catch((error)=> {
      console.error(error);
      this.setIsDisabled();
    });
  }

  activatePage() {
    return this.detectInstalledComponents().then(
      ()=> this.setIsDisabled()
    ).catch((error)=> {
      Logger.error(error);
      this.setIsDisabled();
    });
  }

  installWatchers() {
    let graph = this.graph;
    let nodes = graph.overallOrder() ;
    let checkboxModel = this.sc.checkboxModel;
    for (let node of nodes) {
      checkboxModel[node].dependenciesOf = [];
      for(let dependant of this.graph.dependantsOf(node)) {
        checkboxModel[node].dependenciesOf.push(checkboxModel[dependant]);
      }
      checkboxModel[node].references=0;
    }
    for (let node of nodes) {
      this.sc.$watch(`checkboxModel.${node}.selectedOption`, this.watchComponent.bind(this, node));
    }
  }

  watchComponent(node, newv, oldv) {
    let graph = this.graph;
    let checkboxModel = this.sc.checkboxModel;
    let installer = checkboxModel[node];
    if(installer.isSelected()) {
      for(let dep of graph.dependenciesOf(node)) {
        let depInstaller = checkboxModel[dep];
        if(depInstaller.isInstallable
          && !depInstaller.isDisabled()
          && depInstaller.references === 0
          && (depInstaller.isNotDetected() || depInstaller.isInvalidVersionDetected())) {
          depInstaller.selectedOption = 'install';
        }
        depInstaller.references++;
      }
    } else if(!installer.isSelected() && oldv === 'install') {
      for(let dep of graph.dependenciesOf(node)) {
        let depInstaller = checkboxModel[dep];
        depInstaller.references--;
        if(depInstaller.references === 0) {
          depInstaller.selectedOption = 'detected';
        }
      }
    }
  }

  detectInstalledComponents() {
    if(!this.isDisabled) {
      this.isDisabled = true;
      this.timeout(()=>{});
      this.installedSearchNote = ' The system is checking if you have any installed components.';
      let detectors = [];
      for (let installer of this.installerDataSvc.allInstallables().values()) {
        detectors.push(installer.detectExistingInstall());
      }
      this.detection = Promise.all(detectors);
    }
    return this.detection;
  }

  // Prep the install location path for each product, then go to the next page.
  next() {
    this.loader.orderInstallation(this.graph);
    this.electron.remote.getCurrentWindow().removeAllListeners('focus');
    this.router.go('confirm');
  }

  setIsDisabled() {
    // Uncomment the timeout to see the initial disabled view.
    this.timeout(() => {
      // Switch this boolean flag when the app is done looking for existing installations.
      this.isDisabled = false;
      this.numberOfExistingInstallations = 0;
      // Count the number of existing installations.
      for (var [, value] of this.installerDataSvc.allInstallables()) {
        if (value.hasOption('detected')) {
          ++this.numberOfExistingInstallations;
        }
      }

      if (this.numberOfExistingInstallations == 1) {
        this.installedSearchNote = `  We found ${this.numberOfExistingInstallations} installed component.`;
      } else if (this.numberOfExistingInstallations > 1) {
        this.installedSearchNote = `  We found ${this.numberOfExistingInstallations} installed components.`;
      } else {
        this.installedSearchNote = '';
      }

      if (this.numberOfExistingInstallations == 0) {
        this.installInstructions = 'Select components to install.';
      } else if (this.numberOfExistingInstallations > 0) {
        this.installInstructions = 'Select any additional components to install.';
      }
    }, true);
  }

  isConfigurationValid() {
    let result = true;
    for (let [, value] of this.installerDataSvc.allInstallables().entries()) {
      if(! (result = value.isConfigurationValid())) {
        break;
      }
    }
    return result && this.isAtLeastOneSelected();
  }

  isAtLeastOneSelected() {
    let selected = false;
    for (var [, value] of this.installerDataSvc.allInstallables()) {
      selected = !value.isSkipped();
      if(selected) {
        break;
      }
    }
    return selected;
  }

  exit() {
    Logger.info('Closing the installer window');
    this.electron.remote.getCurrentWindow().close();
  }

  back() {
    Logger.info('Going back a page');
    this.electron.remote.getCurrentWindow().removeAllListeners('focus');
    this.router.go('location');
  }
}

SelectionController.$inject = ['$scope', '$state', '$timeout', 'installerDataSvc', 'electron'];

export default SelectionController;
<|endoftext|>