<commit_before>import { setupTest } from 'ember-qunit';
import { module, test } from 'qunit';
import 'ember-qunit';

module('Unit | Component | programyear list', function(hooks) {
  setupTest(hooks);

  test('properties have default values', function(assert) {
    assert.expect(1);

    const expected = {
      program:      null,
      programYears: [],
      editorOn:     false,
      selection:    null
    };

    const Factory = this.owner.factoryFor('component:programyear-list');
    const component = Factory.create();

    const actual = {
      program:      component.get('program'),
      programYears: component.get('programYears'),
      editorOn:     component.get('editorOn'),
      selection:    component.get('selection'),
    };

    assert.deepEqual(actual.program, expected.program, 'default values are correct');
  });

  test('`availableAcademicYears` computed property works properly', function(assert) {
    assert.expect(1);

    const currentYear = new Date().getFullYear();
    const nextYear = currentYear + 1;
    const twoYearsFromNow = nextYear + 1;
    const threeYearsFromNow = twoYearsFromNow + 1;

    const programYears = [{
      academicYears: `${nextYear} - ${twoYearsFromNow}`, startYear: `${nextYear}`
    }, {
      academicYears: `${twoYearsFromNow} - ${threeYearsFromNow}`, startYear: `${twoYearsFromNow}`
    }];

    for (let i = 0; i < 10; i++) {
      if (i !== 5) {
        const start = (currentYear - 5 + i).toString();
        const end = (currentYear - 4 + i).toString();

        programYears.pushObject({ academicYears: `${start} - ${end}`, startYear: start });
      }
    }

    const startYear = currentYear.toString();
    const endYear = (currentYear + 1).toString();

    const expected = [{ value: currentYear, label: `${startYear} - ${endYear}` }];

    const Factory = this.owner.factoryFor('component:programyear-list');
    const component = Factory.create({
      programYears
    });

    const actual = component.get('availableAcademicYears');

    assert.deepEqual(actual, expected, 'computed property works');
  });
});
<commit_msg>rm obsolete unit test for component.<commit_after><|endoftext|>


<commit_before>'use strict';

angular.module('app').directive('giveFocus', [
  '$timeout',
  '$parse', ($timeout, $parse) => {
    return {
      link: (scope, element, attrs) => {
        var model = $parse(attrs.giveFocus);
        scope.$watch(model, (value) => {
          if (value === true) {
            $timeout(() => {
              element[0].focus();
            });
          }
        });
        element.bind('blur', () => {
          scope.$apply(model.assign(scope, false));
        });
      }
    };
  }
]);
<commit_msg>don’t change scope value on blur<commit_after>'use strict';

angular.module('app').directive('giveFocus', [
  '$timeout',
  '$parse', ($timeout, $parse) => {
    return {
      link: (scope, element, attrs) => {
        var model = $parse(attrs.giveFocus);
        scope.$watch(model, (value) => {
          if (value === true) {
            $timeout(() => {
              element[0].focus();
            });
          }
        });
      }
    };
  }
]);
<|endoftext|>


<commit_before>/**
* Editable Text Field
*
* @author voloko
* @name uki.view.TextField
* @class
* @extends uki.view.Base
* @implements uki.view.Focusable
*/
uki.view.declare('uki.view.TextField', uki.view.Base, uki.view.Focusable, function(Base, Focusable) {
    var emptyInputHeight = {};

    function getEmptyInputHeight (fontSize) {
        if (!emptyInputHeight[fontSize]) {
            var node = uki.createElement('input', Base.defaultCss + "border:none;padding:0;border:0;overflow:hidden;font-size:"+fontSize+";left:-999em;top:0");
            uki.dom.probe(
                node,
                function(probe) {
                    emptyInputHeight[fontSize] = probe.offsetHeight;
                }
            );
        }
        return emptyInputHeight[fontSize];
    }

    function nativePlaceholder (node) {
        return typeof node.placeholder == 'string';
    }

    this._setup = function() {
        Base._setup.apply(this, arguments);
        uki.extend(this, {
            _value: '',
            _multiline: false,
            _placeholder: '',
            _backgroundPrefix: '',
            _tagName: 'input',
            _type: 'text'
        });
        this.defaultCss += "margin:0;border:none;outline:none;padding:0;left:2px;top:0;z-index:100;resize:none;background: url(" + uki.theme.imageSrc('x') + ");" + uki.theme.style('input');
    };

    this._updateBg = function() {
        this._input.style.color = this._disabled ? '#999' : '#000';
    };

    /**
    * @function
    * @name uki.view.TextField#name
    */
    uki.delegateProp(this, 'name', '_input');

    /**
    * @function
    * @name uki.view.TextField#value
    */
    this.value = function(value) {
        if (value === undefined) return this._input.value;

        this._input.value = value;
        this._updatePlaceholderVis();
        return this;
    };

    /**
    * Cross browser placeholder implementation
    * @function
    * @name uki.view.TextField#placeholder
    */
    this.placeholder = uki.newProp('_placeholder', function(v) {
        this._placeholder = v;
        if (!this._multiline && nativePlaceholder(this._input)) {
            this._input.placeholder = v;
        } else {
            if (!this._placeholderDom) {
                this._placeholderDom = uki.createElement('div', this.defaultCss + 'z-input:103;color:#999;cursor:text;-moz-user-select:none;', v);
                if (!this._multiline) this._placeholderDom.style.whiteSpace = 'nowrap';
                this._dom.appendChild(this._placeholderDom);
                this._updatePlaceholderVis();
                uki.each(['fontSize', 'fontFamily', 'fontWeight'], function(i, name) {
                    this._placeholderDom.style[name] = this.style(name);
                }, this);

                uki.dom.bind(this._placeholderDom, 'mousedown', uki.proxy(function(e) {
                    this.focus();
                    e.preventDefault();
                }, this));
            } else {
                this._placeholderDom.innerHTML = v;
            }
        }
    });

    this._style = function(name, value) {
        if (value === undefined) return this._input.style[name];
        this._input.style[name] = value;
        if (this._placeholderDom) this._placeholderDom.style[name] = value;
        return this;
    };

    /**
    * @function
    * @name uki.view.TextField#backgroundPrefix
    */
    uki.addProps(this, ['backgroundPrefix']);

    /**
    * @function
    * @name uki.view.TextField#defaultBackground
    */
    this.defaultBackground = function() {
        return uki.theme.background(this._backgroundPrefix + 'input');
    };

    this._createDom = function() {
        this._dom = uki.createElement('div', Base.defaultCss + ';cursor:text;overflow:visible');
        this._input = uki.createElement(this._tagName, this.defaultCss + (this._multiline ? '' : ';overflow:hidden;'));

        this._input.value = this._value;
        if (this._type) this._input.type = this._type;
        this._dom.appendChild(this._input);

        this._input.value = this.value();

        this._initFocusable(this._input);
        this.bind('mousedown', function(e) {
            if (e.target == this._input) return;
            this.focus();
        });
    };

    this._layoutDom = function(rect) {
        Base._layoutDom.apply(this, arguments);
        uki.dom.layout(this._input.style, {
            width: this._rect.width - 4
        });
        var margin;
        if (this._multiline) {
            this._input.style.height = this._rect.height - 4 + PX;
            this._input.style.top = 2 + PX;
            margin = '2px 0';
        } else {
            var o = (this._rect.height - getEmptyInputHeight(this.style('fontSize'))) / 2;
            margin = CEIL(o) + 'px 0 ' + FLOOR(o) + 'px 0';
            this._input.style.margin = margin;
        }
        if (this._placeholderDom) this._placeholderDom.style.margin = margin;
    };

    this._updatePlaceholderVis = function() {
        if (this._placeholderDom) this._placeholderDom.style.display = this.value() ? 'none' : 'block';
    };

    this._focus = function(e) {
        this._focusBackground = this._focusBackground || uki.theme.background(this._backgroundPrefix + 'input-focus');
        this._focusBackground.attachTo(this);
        if (this._placeholderDom) this._placeholderDom.style.display = 'none';
        Focusable._focus.call(this, e);
    };

    this._blur = function(e) {
        this._focusBackground.detach();
        this._updatePlaceholderVis();
        Focusable._blur.call(this, e);
    };

    this._bindToDom = function(name) {
        return Focusable._bindToDom.call(this, name) || Base._bindToDom.call(this, name);
    };
});

/**
* Multiline Editable Text Field (textarea)
*
* @author voloko
* @name uki.view.MultilineTextField
* @class
* @extends uki.view.TextField
*/
uki.view.declare('uki.view.MultilineTextField', uki.view.TextField, function(Base) {
    this._setup = function() {
        Base._setup.call(this);
        this._tagName = 'textarea';
        this._type = '';
        this._multiline = true;
    };
});

/**
* Password Field
*
* @author voloko
* @name uki.view.PasswordTextField
* @class
* @extends uki.view.TextField
*/
uki.view.declare('uki.view.PasswordTextField', uki.view.TextField, function(Base) {
    this._setup = function() {
        Base._setup.call(this);
        this._type = 'password';
    };
});

<commit_msg>placeholder colleciton attr<commit_after>/**
* Editable Text Field
*
* @author voloko
* @name uki.view.TextField
* @class
* @extends uki.view.Base
* @implements uki.view.Focusable
*/
uki.view.declare('uki.view.TextField', uki.view.Base, uki.view.Focusable, function(Base, Focusable) {
    var emptyInputHeight = {};

    function getEmptyInputHeight (fontSize) {
        if (!emptyInputHeight[fontSize]) {
            var node = uki.createElement('input', Base.defaultCss + "border:none;padding:0;border:0;overflow:hidden;font-size:"+fontSize+";left:-999em;top:0");
            uki.dom.probe(
                node,
                function(probe) {
                    emptyInputHeight[fontSize] = probe.offsetHeight;
                }
            );
        }
        return emptyInputHeight[fontSize];
    }

    function nativePlaceholder (node) {
        return typeof node.placeholder == 'string';
    }

    this._setup = function() {
        Base._setup.apply(this, arguments);
        uki.extend(this, {
            _value: '',
            _multiline: false,
            _placeholder: '',
            _backgroundPrefix: '',
            _tagName: 'input',
            _type: 'text'
        });
        this.defaultCss += "margin:0;border:none;outline:none;padding:0;left:2px;top:0;z-index:100;resize:none;background: url(" + uki.theme.imageSrc('x') + ");" + uki.theme.style('input');
    };

    this._updateBg = function() {
        this._input.style.color = this._disabled ? '#999' : '#000';
    };

    /**
    * @function
    * @name uki.view.TextField#name
    */
    uki.delegateProp(this, 'name', '_input');

    /**
    * @function
    * @name uki.view.TextField#value
    */
    this.value = function(value) {
        if (value === undefined) return this._input.value;

        this._input.value = value;
        this._updatePlaceholderVis();
        return this;
    };

    /**
    * Cross browser placeholder implementation
    * @function
    * @name uki.view.TextField#placeholder
    */
    this.placeholder = uki.newProp('_placeholder', function(v) {
        this._placeholder = v;
        if (!this._multiline && nativePlaceholder(this._input)) {
            this._input.placeholder = v;
        } else {
            if (!this._placeholderDom) {
                this._placeholderDom = uki.createElement('div', this.defaultCss + 'z-input:103;color:#999;cursor:text;-moz-user-select:none;', v);
                if (!this._multiline) this._placeholderDom.style.whiteSpace = 'nowrap';
                this._dom.appendChild(this._placeholderDom);
                this._updatePlaceholderVis();
                uki.each(['fontSize', 'fontFamily', 'fontWeight'], function(i, name) {
                    this._placeholderDom.style[name] = this.style(name);
                }, this);

                uki.dom.bind(this._placeholderDom, 'mousedown', uki.proxy(function(e) {
                    this.focus();
                    e.preventDefault();
                }, this));
            } else {
                this._placeholderDom.innerHTML = v;
            }
        }
    });

    this._style = function(name, value) {
        if (value === undefined) return this._input.style[name];
        this._input.style[name] = value;
        if (this._placeholderDom) this._placeholderDom.style[name] = value;
        return this;
    };

    /**
    * @function
    * @name uki.view.TextField#backgroundPrefix
    */
    uki.addProps(this, ['backgroundPrefix', 'placeholder']);

    /**
    * @function
    * @name uki.view.TextField#defaultBackground
    */
    this.defaultBackground = function() {
        return uki.theme.background(this._backgroundPrefix + 'input');
    };

    this._createDom = function() {
        this._dom = uki.createElement('div', Base.defaultCss + ';cursor:text;overflow:visible');
        this._input = uki.createElement(this._tagName, this.defaultCss + (this._multiline ? '' : ';overflow:hidden;'));

        this._input.value = this._value;
        if (this._type) this._input.type = this._type;
        this._dom.appendChild(this._input);

        this._input.value = this.value();

        this._initFocusable(this._input);
        this.bind('mousedown', function(e) {
            if (e.target == this._input) return;
            this.focus();
        });
    };

    this._layoutDom = function(rect) {
        Base._layoutDom.apply(this, arguments);
        uki.dom.layout(this._input.style, {
            width: this._rect.width - 4
        });
        var margin;
        if (this._multiline) {
            this._input.style.height = this._rect.height - 4 + PX;
            this._input.style.top = 2 + PX;
            margin = '2px 0';
        } else {
            var o = (this._rect.height - getEmptyInputHeight(this.style('fontSize'))) / 2;
            margin = CEIL(o) + 'px 0 ' + FLOOR(o) + 'px 0';
            this._input.style.margin = margin;
        }
        if (this._placeholderDom) this._placeholderDom.style.margin = margin;
    };

    this._updatePlaceholderVis = function() {
        if (this._placeholderDom) this._placeholderDom.style.display = this.value() ? 'none' : 'block';
    };

    this._focus = function(e) {
        this._focusBackground = this._focusBackground || uki.theme.background(this._backgroundPrefix + 'input-focus');
        this._focusBackground.attachTo(this);
        if (this._placeholderDom) this._placeholderDom.style.display = 'none';
        Focusable._focus.call(this, e);
    };

    this._blur = function(e) {
        this._focusBackground.detach();
        this._updatePlaceholderVis();
        Focusable._blur.call(this, e);
    };

    this._bindToDom = function(name) {
        return Focusable._bindToDom.call(this, name) || Base._bindToDom.call(this, name);
    };
});

/**
* Multiline Editable Text Field (textarea)
*
* @author voloko
* @name uki.view.MultilineTextField
* @class
* @extends uki.view.TextField
*/
uki.view.declare('uki.view.MultilineTextField', uki.view.TextField, function(Base) {
    this._setup = function() {
        Base._setup.call(this);
        this._tagName = 'textarea';
        this._type = '';
        this._multiline = true;
    };
});

/**
* Password Field
*
* @author voloko
* @name uki.view.PasswordTextField
* @class
* @extends uki.view.TextField
*/
uki.view.declare('uki.view.PasswordTextField', uki.view.TextField, function(Base) {
    this._setup = function() {
        Base._setup.call(this);
        this._type = 'password';
    };
});

<|endoftext|>


<commit_before>import { module, test } from 'qunit';
import CartLineItemModel from 'shopify-buy/models/cart-line-item-model';
import BaseModel from 'shopify-buy/models/base-model';

let model;

const lineItemFixture = {
  id: 3,
  image: 'http://google.com/image.png',
  variant_id: 12345,
  product_id: 45678,
  title: 'Some Product',
  quantity: 1,
  properties: {},
  variant_title: 'Red / Small',
  price: '12.00',
  compare_at_price: '',
  line_price: '12.00',
  grams: 4
};

module('Unit | CartLineItemModel', {
  setup() {
    model = new CartLineItemModel(lineItemFixture);
  },

  teardown() {
    model = null;
  }
});

test('it extends from BaseModel', function (assert) {
  assert.expect(1);

  assert.ok(BaseModel.prototype.isPrototypeOf(model));
});

test('it updates line_price based on changing quantity', function (assert) {
  assert.expect(/* Add a value here */);
});

<commit_msg>complete test for line_price value based on quantity change<commit_after>import { module, test } from 'qunit';
import CartLineItemModel from 'shopify-buy/models/cart-line-item-model';
import BaseModel from 'shopify-buy/models/base-model';

let model;

const lineItemFixture = {
  id: 3,
  image: 'http://google.com/image.png',
  variant_id: 12345,
  product_id: 45678,
  title: 'Some Product',
  quantity: 1,
  properties: {},
  variant_title: 'Red / Small',
  price: '12.00',
  compare_at_price: '',
  line_price: '12.00',
  grams: 4
};

module('Unit | CartLineItemModel', {
  setup() {
    model = new CartLineItemModel(lineItemFixture);
  },

  teardown() {
    model = null;
  }
});

test('it extends from BaseModel', function (assert) {
  assert.expect(1);

  assert.ok(BaseModel.prototype.isPrototypeOf(model));
});

test('it updates line_price based on changing quantity', function (assert) {
  assert.expect(6);

  assert.equal(model.quantity, 1);
  assert.equal(model.price, '12.00');
  assert.equal(model.line_price, '12.00');

  model.quantity = 2;
  assert.equal(model.quantity, 2);
  assert.equal(model.price, '12.00');
  assert.equal(model.line_price, '24.00');
});
<|endoftext|>


<commit_before>"use strict";
/**
 * Copyright (c) 2013 Bruno Jouhier <bruno.jouhier@sage.com>
 * MIT License
 */
var util = require('../util');
var glob = util.getGlobals('generators');

var counters = {
	slowAwait: 0,
	fastAwait: 0,
};

function makeArgs(i) {
	if (i <= 0) return "";
	return i > 1 ? makeArgs(i - 1) + ', a' + i : "a1";
}

if (typeof glob.yielded === "undefined") glob.yielded = true;
glob.PENDING = glob.PENDING || {};

function isGenerator(val) {
	return val && (
	Object.prototype.toString.call(val) === "[object Generator]" || val.toString() === "[object Generator]");
}

function Frame(g) {
	this.g = g;
	this.prev = glob.frame;
	g.frame = this;
	this.name = glob.calling || "unknown";
	this.file = "unknown";
	this.line = 0;
	this.recurse = 0;
	this.yielded = 0;
}

Object.defineProperty(Frame.prototype, "info", {
	get: function() {
		return this;
	}
});

function pushFrame(g) {
	glob.frame = g.frame || new Frame(g);
	if (glob.emitter) glob.emitter.emit('enter', g.frame);
}

function popFrame(g) {
	if (!glob.frame) return;
	if (glob.emitter) glob.emitter.emit('exit', g.frame);
	glob.frame = glob.frame.prev;
}

function run(g, cb, options) {
	var rsm = glob.resume;
	var emit = function(ev, g) {
			g.frame = g.frame || new Frame(g);
			if (glob.emitter) glob.emitter.emit(ev, g.frame);
		}

	try {
		glob.resume = function(err, val) {
			if (glob.yielded) {
				emit("resume", g);
				glob.yielded = false;
			}
			while (g) {
				if (options && options.interrupt && options.interrupt()) return;
				try {
					// ES6 is deprecating send in favor of next. Following line makes us compatible with both.
					var send = g.send || g.next;
					var v = err ? g.
					throw (err) : send.call(g, val);
					val = v.value;
					err = null;
					// if we get PENDING, the current call completed with a pending I/O
					// resume will be called again when the I/O completes. So just save the context and return here.
					if (val === glob.PENDING) {
						if (!glob.yielded) {
							emit("yield", g);
							glob.yielded = true;
						}
						return;
					}
					// if we get [PENDING, e, r], the current call invoked its callback synchronously
					// we just loop to send/throw what the callback gave us.
					if (val && val[0] === glob.PENDING) {
						err = val[1];
						val = val[2];
						if (err) err = wrapError(err, g, glob.resume);
					}
					// else, if g is done we unwind it we send val to the parent generator (or through cb if we are at the top)
					else if (v.done) {
						//g.close();
						popFrame(g);
						g = g.prev;
					}
					// else if val is not a generator we have an error. Yield was not applied to a generators
					else {
						if (!isGenerator(val)) {
							throw new Error("invalid value was yielded. Expected a generator, got " + val);
						}
						// we got a new generator which means that g called another generator function
						// the new generator become current and we loop with g.send(undefined) (equiv to g.next())
						val.prev = g;
						g = val;
						pushFrame(g);
						val = undefined;
					}
				} catch (ex) {
					// the send/throw call failed.
					// we unwind the current generator and we rethrow into the parent generator (or through cb if at the top)
					//g.close();
					err = wrapError(ex, g, glob.resume);
					popFrame(g);
					g = g.prev;
					val = undefined;
				}
			}
			// we have exhausted the stack of generators.
			// return the result or error through the callback.
			cb(err, val);
		}

		// start the resume loop
		glob.resume();
	} finally {
		// restore resume global
		glob.resume = rsm;
	}
}

function mapResults(options, args) {
	if (options && typeof options === "object") {
		if (options.returnArray) return args;
		if (options.returnObject) return options.returnObject.reduce(function(res, key, i) {
			res[key] = args[i];
			return res;
		}, {});
	}
	return args[0];
}

function invoke(that, fn, args, index, index2, returnArray) {
	if (fn['__unstarred__' + index]) throw new Error("cannot invoke starred function: " + fn['__unstarred__' + index]);
	// Set things up so that call returns:
	// * PENDING if it completes with a pending I/O (and cb will be called later)
	// * [PENDING, e, r] if the callback is called synchronously.
	var result = glob.PENDING,
		sync = true;
	var rsm = glob.resume;

	// convert args to array so that args.length gets correctly set if index is args.length
	args = Array.prototype.slice.call(args, 0);
	var cx = glob.context;
	var callback = function(e, r) {
			var oldContext = glob.context;
			var oldResume = glob.resume;
			try {
				if (returnArray) r = Array.prototype.slice.call(arguments, 1);
				glob.context = cx;
				glob.resume = rsm;
				if (sync) {
					result = [glob.PENDING, e, r];
				} else {
					glob.resume(e, r);
				}
			} finally {
				glob.context = oldContext;
				glob.resume = oldResume;
			}
		}
	if (index2 != null) {
		args[index] = function(r) {
			callback(null, r);
		}
		args[index2] = function(e) {
			callback(e);
		}
	} else {
		args[index] = callback;
	}
	fn.apply(that, args);
	sync = false;
	return result;
}

var star = function(file, line, fn, index, index2, returnArray) {
	if (file) {
		var frame = glob.frame;
		if (frame) {
			frame.file = file;
			frame.line = line;
		}
		// we pass the name of the function via a global - would be great if JS had an API to get generator function from generator
		glob.calling = fn.__name__ || fn.name;
	}
	return function *() {
		return (yield invoke(this, fn, arguments, index, index2, returnArray));
	};
}

var unstarTemplate = function(fn, options) {
		var index = (options && typeof options === 'object') ? options.callbackIndex : options;
		if (index == null) index = fn.length;

		var F = function F() {
			var cb = arguments[index];
			if (typeof cb !== "function") {
				if (glob.allowBooleanPlaceholders && typeof cb === 'boolean') {
					if (cb) cb = util.defaultCallback;
					else return exports.future("", 0, null, wrapper.bind(this), index)(arguments);
				}
				else throw util.argError(fn.name, index, "function", typeof cb);
			}
			var g = fn.apply(this, arguments);
			run.call(this, g, cb);
		};
		// track the original name for stack frames
		F.__name__ = fn.name;
		return F;
	}

var unstarBody = unstarTemplate.toString();
unstarBody = unstarBody.substring(unstarBody.indexOf('{'));
var unstarrors = [];

function makeUnstarror(i) {
	return eval("(function(fn, options)" + unstarBody.replace(/function\s*F\(\)/, "function F(" + makeArgs(i) + ")") + ")");
}

function unstar(fn, index, arity) {
	var i = arity != null ? arity : (index == null ? fn.length + 1 : fn.length);
	var unstarror = unstarrors[i] || (unstarrors[i] = makeUnstarror(i));
	return unstarror(fn, index);
}

function wrapError(err, g, resume) {
	if (!(err instanceof Error)) return err; // handle throw "some string";
	if (err.__frame__) return err;
	err = Object.create(err);
	err.__frame__ = glob.frame;
	Object.defineProperty(err, 'stack', {
		get: function() {
			return stackTrace(this);
		}
	});
	return err;
}

function stackTrace(err) {
	var extra;
	var starredStack = "";
	var frame;
	while (frame = err.__frame__) {
		for (frame = frame.prev; frame; frame = frame.prev) {
			var m = /\$\$(.*)\$\$/.exec(frame.name);
			var fname = (m && m[1]) || "unknown";
			starredStack += '    at ' + fname + ' (' + frame.file + ':' + frame.line + ')\n';
		}
		err = Object.getPrototypeOf(err);
	}
	var rawStack = Object.getOwnPropertyDescriptor(new Error(), 'stack').get.call(err);
	var cut = rawStack.indexOf('    at GeneratorFunctionPrototype');
	if (cut < 0) cut = rawStack.indexOf('\n') + 1;
	var result = rawStack.substring(0, cut).replace(/\n.*regenerator.runtime.*/g, '') + //
	'    <<< yield stack >>>\n' + starredStack + //
	'    <<< raw stack >>>\n' + rawStack.substring(cut);
	return result;
}

exports.await = function(file, line, object, property, index1, index2, returnArray) {
	var bound = typeof property !== "function";
	var fn = bound ? object[property] : property;
	var key = '';
	if (index2 == null && !returnArray) {
		key = 'awaitWrapper-' + index1;
		var wrapper = fn[key];
		if (wrapper) {
			counters.fastAwait++;
			return bound ? wrapper.bind(object) : wrapper;
		}
	}
	counters.slowAwait++;
	if (typeof fn !== "function") throw util.typeError("cannot call", "function", fn);
	wrapper = star(file, line, fn, index1, index2, returnArray);
	if (!bound && key) {
		fn[key] = wrapper;
	}
	return bound ? wrapper.bind(object) : wrapper;
};

exports.async = function(fn, index, arity) {
	if (typeof fn !== "function") throw util.typeError("cannot wrap function", "function", fn);
	var unstarred = unstar(fn, index, arity);
	unstarred["awaitWrapper-" + index] = fn;
	return unstarred;
}

exports.new = function(file, line, constructor, index) {
	if (typeof constructor !== "function") throw util.typeError("cannot instantiate", "function", constructor);
	var starred = star(file, line, constructor, index);
	return function *() {
		var that = Object.create(constructor.prototype);
		yield starred.apply(that, arguments);
		return that;
	};
};

exports.future = require('../future');
require('./builtins');<commit_msg>progress on stack traces in generators mode<commit_after>"use strict";
/**
 * Copyright (c) 2013 Bruno Jouhier <bruno.jouhier@sage.com>
 * MIT License
 */
var util = require('../util');
var glob = util.getGlobals('generators');

var counters = {
	slowAwait: 0,
	fastAwait: 0,
};

function makeArgs(i) {
	if (i <= 0) return "";
	return i > 1 ? makeArgs(i - 1) + ', a' + i : "a1";
}

if (typeof glob.yielded === "undefined") glob.yielded = true;
glob.PENDING = glob.PENDING || {};

function isGenerator(val) {
	return val && (
	Object.prototype.toString.call(val) === "[object Generator]" || val.toString() === "[object Generator]");
}

function Frame(file, line, fn) {
	this.fn = fn;
	this.file = file || "unknown";
	this.line = line || 0;
}

Object.defineProperty(Frame.prototype, "name", {
	get: function() {
		var fn = this.fn;
		return (fn && (fn.__name__ || fn.name)) || "unknown";
	}
});

Object.defineProperty(Frame.prototype, "info", {
	get: function() {
		return this;
	}
});

function pushFrame(g) {
	if (glob.emitter) glob.emitter.emit('enter', g.frame);
	g.frame = g.frame || glob.frame;
	glob.frame = null;
}

function popFrame(g) {
	if (glob.emitter) glob.emitter.emit('exit', g.frame);
}

function run(fn, g, cb, options) {
	var rsm = glob.resume;
	var emit = function(ev, g) {
			if (glob.emitter) glob.emitter.emit(ev, g.frame);
		}

	try {
		if (glob.frame) {
			g.frame = glob.frame;
			g.frame.g = g;
			glob.frame = null;
		} else {
			g.frame = new Frame("", 0, fn);
		}

		glob.resume = function(err, val) {
			if (glob.yielded) {
				emit("resume", g);
				glob.yielded = false;
			}
			while (g) {
				if (options && options.interrupt && options.interrupt()) return;
				try {
					// ES6 is deprecating send in favor of next. Following line makes us compatible with both.
					var send = g.send || g.next;
					var v = err ? g.
					throw (err) : send.call(g, val);
					val = v.value;
					err = null;
					// if we get PENDING, the current call completed with a pending I/O
					// resume will be called again when the I/O completes. So just save the context and return here.
					if (val === glob.PENDING) {
						if (!glob.yielded) {
							emit("yield", g);
							glob.yielded = true;
						}
						return;
					}
					// if we get [PENDING, e, r], the current call invoked its callback synchronously
					// we just loop to send/throw what the callback gave us.
					if (val && val[0] === glob.PENDING) {
						err = val[1];
						val = val[2];
						if (err) err = wrapError(err, g);
					}
					// else, if g is done we unwind it we send val to the parent generator (or through cb if we are at the top)
					else if (v.done) {
						//g.close();
						popFrame(g);
						g = g.prev;
					}
					// else if val is not a generator we have an error. Yield was not applied to a generators
					else {
						if (!isGenerator(val)) {
							throw new Error("invalid value was yielded. Expected a generator, got " + val);
						}
						// we got a new generator which means that g called another generator function
						// the new generator become current and we loop with g.send(undefined) (equiv to g.next())
						val.prev = g;
						g = val;
						pushFrame(g);
						val = undefined;
					}
				} catch (ex) {
					// the send/throw call failed.
					// we unwind the current generator and we rethrow into the parent generator (or through cb if at the top)
					//g.close();
					err = wrapError(ex, g);
					popFrame(g);
					g = g.prev;
					val = undefined;
				}
			}
			// we have exhausted the stack of generators.
			// return the result or error through the callback.
			cb(err, val);
		}

		// start the resume loop
		glob.resume();
	} finally {
		// restore resume global
		glob.resume = rsm;
	}
}

function mapResults(options, args) {
	if (options && typeof options === "object") {
		if (options.returnArray) return args;
		if (options.returnObject) return options.returnObject.reduce(function(res, key, i) {
			res[key] = args[i];
			return res;
		}, {});
	}
	return args[0];
}

function invoke(that, fn, args, index, index2, returnArray) {
	// Set things up so that call returns:
	// * PENDING if it completes with a pending I/O (and cb will be called later)
	// * [PENDING, e, r] if the callback is called synchronously.
	var result = glob.PENDING,
		sync = true;
	var rsm = glob.resume;

	// convert args to array so that args.length gets correctly set if index is args.length
	args = Array.prototype.slice.call(args, 0);
	var cx = glob.context;
	var callback = function(e, r) {
			var oldContext = glob.context;
			var oldResume = glob.resume;
			try {
				if (returnArray) r = Array.prototype.slice.call(arguments, 1);
				glob.context = cx;
				glob.resume = rsm;
				if (sync) {
					result = [glob.PENDING, e, r];
				} else {
					glob.resume(e, r);
				}
			} finally {
				glob.context = oldContext;
				glob.resume = oldResume;
			}
		}
	if (index2 != null) {
		args[index] = function(r) {
			callback(null, r);
		}
		args[index2] = function(e) {
			callback(e);
		}
	} else {
		args[index] = callback;
	}
	fn.apply(that, args);
	sync = false;
	return result;
}

var star = function(fn, index, index2, returnArray) {
	return function *() {
		return (yield invoke(this, fn, arguments, index, index2, returnArray));
	};
}

var unstarTemplate = function(fn, options) {
		var index = (options && typeof options === 'object') ? options.callbackIndex : options;
		if (index == null) index = fn.length;

		var F = function F() {
			var cb = arguments[index];
			if (typeof cb !== "function") {
				if (glob.allowBooleanPlaceholders && typeof cb === 'boolean') {
					if (cb) cb = util.defaultCallback;
					else return exports.future("", 0, null, wrapper.bind(this), index)(arguments);
				}
				else throw util.argError(fn.name, index, "function", typeof cb);
			}
			var g = fn.apply(this, arguments);
			run.call(this, fn, g, cb);
		};
		// track the original name for stack frames
		F.__name__ = fn.name;
		return F;
	}

var unstarBody = unstarTemplate.toString();
unstarBody = unstarBody.substring(unstarBody.indexOf('{'));
var unstarrors = [];

function makeUnstarror(i) {
	return eval("(function(fn, options)" + unstarBody.replace(/function\s*F\(\)/, "function F(" + makeArgs(i) + ")") + ")");
}

function unstar(fn, index, arity) {
	var i = arity != null ? arity : (index == null ? fn.length + 1 : fn.length);
	var unstarror = unstarrors[i] || (unstarrors[i] = makeUnstarror(i));
	return unstarror(fn, index);
}

function wrapError(err, g) {
	if (!(err instanceof Error)) return err; // handle throw "some string";
	if (err.g) return err;
	err = Object.create(err);
	err.g = g;
	Object.defineProperty(err, 'stack', {
		get: function() {
			return stackTrace(this);
		}
	});
	return err;
}

function stackTrace(err) {
	var extra;
	var starredStack = "";
	var g;
	while (g = err.g) {
		for (g = g.prev; g; g = g.prev) {
			if (!g.frame) continue;
			var fname = (g.prev && g.prev.frame && g.prev.frame.name) || "";
			var m = /\$\$(.*)\$\$/.exec(fname);
			if (m) fname = m[1];
			starredStack += '    at ' + fname + ' (' + g.frame.file + ':' + g.frame.line + ')\n';
		}
		err = Object.getPrototypeOf(err);
	}
	var rawStack = Object.getOwnPropertyDescriptor(new Error(), 'stack').get.call(err);
	var cut = rawStack.indexOf('    at GeneratorFunctionPrototype');
	if (cut < 0) cut = rawStack.indexOf('\n') + 1;
	var result = rawStack.substring(0, cut).replace(/\n.*regenerator.runtime.*/g, '') + //
	'    <<< yield stack >>>\n' + starredStack + //
	'    <<< raw stack >>>\n' + rawStack.substring(cut);
	return result;
}

exports.await = function(file, line, object, property, index1, index2, returnArray) {
	var bound = typeof property !== "function";
	var fn = bound ? object[property] : property;
	glob.frame = new Frame(file, line, fn);
	var key = '';
	if (index2 == null && !returnArray) {
		key = 'awaitWrapper-' + index1;
		var wrapper = fn[key];
		if (wrapper) {
			counters.fastAwait++;
			return bound ? wrapper.bind(object) : wrapper;
		}
	}
	counters.slowAwait++;
	if (typeof fn !== "function") throw util.typeError("cannot call", "function", fn);
	wrapper = star(fn, index1, index2, returnArray);
	if (!bound && key) {
		fn[key] = wrapper;
	}
	return bound ? wrapper.bind(object) : wrapper;
};

exports.async = function(fn, index, arity) {
	if (typeof fn !== "function") throw util.typeError("cannot wrap function", "function", fn);
	var unstarred = unstar(fn, index, arity);
	unstarred["awaitWrapper-" + index] = fn;
	return unstarred;
}

exports.new = function(file, line, constructor, index) {
	if (typeof constructor !== "function") throw util.typeError("cannot instantiate", "function", constructor);
	glob.frame = new Frame(file, line, constructor);
	var starred = star(constructor, index);
	return function *() {
		var that = Object.create(constructor.prototype);
		yield starred.apply(that, arguments);
		return that;
	};
};

exports.future = require('../future');
require('./builtins');<|endoftext|>


<commit_before>module.exports = function(config) {
  // find modules to exclude from compilation
  var reappIncludeModules = [
      'reapp-ui',
      'reapp-routes',
      'reapp-component',
      'reapp-platform',
      'react-router'
    ].concat(config.parseModules || []);

  var userModules = Object.keys(require(config.dir + '/package.json').dependencies);
  var excludeModules = userModules.filter(function(dep) {
    return reappIncludeModules.indexOf(dep) === -1;
  }).map(function(name) {
    return escapeRegExp('node_modules/' + name + '/');
  });

  excludeModules = excludeModules.concat(
    config.excludeModules || [],
    'socket\\.io'
  );

  if (config.debug)
    console.log('Not running babel on modules...', excludeModules.join(', '), "\n");

  return new RegExp(excludeModules.join('|'))
}

function escapeRegExp(str) {
  return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}<commit_msg>add reapp-reducer and router to parse modules<commit_after>module.exports = function(config) {
  // find modules to exclude from compilation
  var reappIncludeModules = [
      'reapp-ui',
      'reapp-routes',
      'reapp-component',
      'reapp-platform',
      'react-router',
      'reapp-reducer'
    ].concat(config.parseModules || []);

  var userModules = Object.keys(require(config.dir + '/package.json').dependencies);
  var excludeModules = userModules.filter(function(dep) {
    return reappIncludeModules.indexOf(dep) === -1;
  }).map(function(name) {
    return escapeRegExp('node_modules/' + name + '/');
  });

  excludeModules = excludeModules.concat(
    config.excludeModules || [],
    'socket\\.io'
  );

  if (config.debug)
    console.log('Not running babel on modules...', excludeModules.join(', '), "\n");

  return new RegExp(excludeModules.join('|'))
}

function escapeRegExp(str) {
  return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}<|endoftext|>


<commit_before>/**
 * Copyright 2004-present Facebook. All Rights Reserved.
 *
 * @flow strict
 * @typechecks
 * @format
 */

/**
 * Retrieve an object's own values as an array. If you want the values in the
 * protoype chain, too, use getObjectValuesIncludingPrototype.
 *
 * If you are looking for a function that creates an Array instance based
 * on an "Array-like" object, use createArrayFrom instead.
 *
 * @param {object} obj An object.
 * @return {array}     The object's values.
 */
function getOwnObjectValues<TValue>(obj: {
  +[key: string]: TValue,
  ...,
}): Array<TValue> {
  return Object.keys(obj).map(key => obj[key]);
}

module.exports = getOwnObjectValues;
<commit_msg>Format JavaScript files with Prettier: scripts/draft-js/__github__/src/util<commit_after>/**
 * Copyright 2004-present Facebook. All Rights Reserved.
 *
 * @flow strict
 * @typechecks
 * @format
 */

/**
 * Retrieve an object's own values as an array. If you want the values in the
 * protoype chain, too, use getObjectValuesIncludingPrototype.
 *
 * If you are looking for a function that creates an Array instance based
 * on an "Array-like" object, use createArrayFrom instead.
 *
 * @param {object} obj An object.
 * @return {array}     The object's values.
 */
function getOwnObjectValues<TValue>(obj: {
  +[key: string]: TValue,
  ...
}): Array<TValue> {
  return Object.keys(obj).map(key => obj[key]);
}

module.exports = getOwnObjectValues;
<|endoftext|>


<commit_before>
/*
 * This is a temporary fix for when shouldComponentUpdate()
 * makes the context stale.
 * For reference check out react routers issue https://github.com/facebook/react/issues/2517
 */

let observerId = 0;
const observers = {};

export function forceContext(Component) {
  const {
    componentDidMount, componentWillUnmount
  } = Component.prototype;

  Component.prototype.componentDidMount = function() {
    this.observerId = observerId++;

    observers[this.observerId] = function (newBreak) {
      const breakpoint = this.props.isRoot ?
        this.props.breakpoint : this.context.cellblockBreakpoint;

      if (breakpoint !== newBreak) {
        console.log('somethings up!');
      }

      this.forceUpdate();

    }.bind(this);

    if (componentDidMount) componentDidMount.apply(this, arguments);
  }

  Component.prototype.componentWillUnmount = function() {
    delete observers[this.observerId];

    // console.log('removed observer');

    if (componentWillUnmount) componentWillUnmount.apply(this, arguments);
  }

  return Component;
}

export function updateObservers(newBreakpoint) {
  console.log(Object.keys(observers).length)
  for (let o in observers) {
    observers[o](newBreakpoint);
  }
}<commit_msg>more questions<commit_after>
/*
 * This is a temporary fix for when shouldComponentUpdate()
 * makes the context stale.
 * For reference check out react routers issue https://github.com/facebook/react/issues/2517
 */

let observerId = 0;
const observers = {};

export function forceContext(Component) {
  const {
    componentDidMount, componentWillUnmount
  } = Component.prototype;

  Component.prototype.componentDidMount = function() {
    this.observerId = observerId++;

    observers[this.observerId] = function (newBreak) {
      // const breakpoint = this.props.isRoot ?
      //   this.props.breakpoint : this.context.cellblockBreakpoint;

      // if (breakpoint !== newBreak) {
      //   console.log('somethings up!'); // WHY DOESNT THIS CHECK WORK?
      // }

      this.forceUpdate();

    }.bind(this);

    if (componentDidMount) componentDidMount.apply(this, arguments);
  }

  Component.prototype.componentWillUnmount = function() {
    delete observers[this.observerId];

    // console.log('removed observer');

    if (componentWillUnmount) componentWillUnmount.apply(this, arguments);
  }

  return Component;
}

export function updateObservers(newBreakpoint) {
  for (let o in observers) {
    observers[o](newBreakpoint);
  }
}<|endoftext|>


<commit_before>
import { appLogger } from './logger';
import { isFunction, isUndefined } from 'lodash';

const _cacheFns = Symbol('cacheFns');

export default function createProxyObject(source, debugName) {
	return new Proxy({}, {
		get(_, name) {
			const proxy = new Proxy({}, {
				get(_, key) {
					const dist = source[name];
					if (isUndefined(dist)) {
						appLogger.error(`${debugName} "${name}" is undefined`);
						return {}; // avoid throw `undefined.sth()` like error
					}
					const result = dist[key];
					if (isFunction(result)) {
						if (!dist[_cacheFns]) {
							dist[_cacheFns] = {};
						}

						if (!dist[_cacheFns][key]) {
							dist[_cacheFns][key] = result.bind(dist);
						}

						return dist[_cacheFns][key];
					}
					else {
						return result;
					}
				},
			});
			return proxy;
		}
	});
}
<commit_msg>fix models bug<commit_after>
import { appLogger } from './logger';
import { isUndefined } from 'lodash';

export default function createProxyObject(source, debugName) {
	return new Proxy({}, {
		get(_, name) {
			const proxy = new Proxy({}, {
				get(_, key) {
					const dist = source[name];
					if (isUndefined(dist)) {
						appLogger.error(`${debugName} "${name}" is undefined`);
						return {}; // avoid throw `undefined.sth()` like error
					}
					return dist[key];
				},
			});
			return proxy;
		}
	});
}
<|endoftext|>


<commit_before>angular.module('BasketCtrl', [
  'getBaskets',
  'newBasketButtonDirective',
  'currentUser',
  'basketsInfoBox'
])

.controller('BasketCtrl', ['$scope', '$http', 'getUsersBaskets', 'getCurrentUser', function(
  $scope,
  $http,
  getUsersBaskets,
  getCurrentUser
) {

  getCurrentUser().then(function(response) {

    $scope.user = response.data;

  })

  // Make call to Rails API to get a list of the users baskets
  getUsersBaskets().then(function(result) {

    $scope.baskets = result.data;

  });

  // move this logic to the basket-button-directive
  $scope.createBasket = function() {

    var promise = $http({
      url: 'http://localhost:3000/folders',
      dataType: 'json',
      method: 'POST',
      params: {
        name: $scope.newBasketName
      },
      headers: {'Content-Type': 'application/json'}
    }).success(function(response) {

      $scope.baskets.push(response);

      $scope.showForm = false;
      $scope.newBasketName = '';
      return $scope.baskets;

    }).error(function(response) {

      return {'status': false};

    })

  }; // createBasket()

}])<commit_msg>changed end point of create basket button<commit_after>angular.module('BasketCtrl', [
  'getBaskets',
  'newBasketButtonDirective',
  'currentUser',
  'basketsInfoBox'
])

.controller('BasketCtrl', ['$scope', '$http', 'getUsersBaskets', 'getCurrentUser', function(
  $scope,
  $http,
  getUsersBaskets,
  getCurrentUser
) {

  getCurrentUser().then(function(response) {

    $scope.user = response.data;

  })

  // Make call to Rails API to get a list of the users baskets
  getUsersBaskets().then(function(result) {

    $scope.baskets = result.data;

  });

  // move this logic to the basket-button-directive
  $scope.createBasket = function() {

    var promise = $http({
      url: '/folders',
      dataType: 'json',
      method: 'POST',
      params: {
        name: $scope.newBasketName
      },
      headers: {'Content-Type': 'application/json'}
    }).success(function(response) {

      $scope.baskets.push(response);

      $scope.showForm = false;
      $scope.newBasketName = '';
      return $scope.baskets;

    }).error(function(response) {

      return {'status': false};

    })

  }; // createBasket()

}])<|endoftext|>


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

/**
 * Internal dependencies
 */
import Data from 'googlesitekit-data';
import {
	MODULES_ANALYTICS,
	SETUP_FLOW_MODE_LEGACY,
	SETUP_FLOW_MODE_UA,
	SETUP_FLOW_MODE_GA4,
	SETUP_FLOW_MODE_GA4_TRANSITIONAL,
} from './constants';
import { MODULES_ANALYTICS_4 } from '../../analytics-4/datastore/constants';

const { createRegistrySelector } = Data;

const baseSelectors = {
	getSetupFlowMode: createRegistrySelector( ( select ) => () => {
		// The Google Analytics 4 datastore hasn't been loaded, so we have
		// to use the legacy implementation.
		if ( ! select( MODULES_ANALYTICS_4 ) ) {
			return SETUP_FLOW_MODE_LEGACY;
		}

		// Check to see if the Admin API is working—if it's `undefined` the request
		// is loading, but if it's `false` we should also use the legacy analytics
		// because the API isn't working properly.
		const isAdminAPIWorking = select( MODULES_ANALYTICS_4 ).isAdminAPIWorking();

		if ( isAdminAPIWorking === undefined ) {
			return undefined;
		}

		if ( isAdminAPIWorking === false ) {
			return SETUP_FLOW_MODE_LEGACY;
		}

		// Ensure the Analytics settings have loaded. If we check
		// `select( MODULES_ANALYTICS ).getAccountID();` directly, it
		// could return `undefined` because the settings are loading OR
		// because accountID is not set. Ensuring the settings are loaded
		// means an `undefined` accountID is legitimate.
		// See: https://github.com/google/site-kit-wp/pull/3260#discussion_r623924928
		if ( select( MODULES_ANALYTICS ).getSettings() === undefined ) {
			return undefined;
		}

		const accountID = select( MODULES_ANALYTICS ).getAccountID();

		if ( ! accountID ) {
			return SETUP_FLOW_MODE_UA;
		}

		const ga4Properties = select( MODULES_ANALYTICS_4 ).getProperties( accountID );

		if ( ga4Properties === undefined ) {
			return undefined;
		}

		// If there are no GA4 properties available for this account, don't use
		// GA4 and use the UA version.
		if ( ga4Properties.length === 0 ) {
			return SETUP_FLOW_MODE_UA;
		}

		const uaProperties = select( MODULES_ANALYTICS ).getProperties( accountID );

		if ( uaProperties === undefined ) {
			return undefined;
		}

		// If no UA properties exist and there are GA4 properties, use GA4-only.
		if ( uaProperties.length === 0 ) {
			return SETUP_FLOW_MODE_GA4;
		}

		// There are UA and GA4 properties, so use the transitional mode.
		return SETUP_FLOW_MODE_GA4_TRANSITIONAL;
	} ),
};

const store = Data.combineStores(
	{
		selectors: baseSelectors,
	}
);

export const initialState = store.initialState;
export const actions = store.actions;
export const controls = store.controls;
export const reducer = store.reducer;
export const resolvers = store.resolvers;
export const selectors = store.selectors;

export default store;
<commit_msg>Clarify accountID comment.<commit_after>/**
 * `modules/analytics` data store: setup-flow.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Internal dependencies
 */
import Data from 'googlesitekit-data';
import {
	MODULES_ANALYTICS,
	SETUP_FLOW_MODE_LEGACY,
	SETUP_FLOW_MODE_UA,
	SETUP_FLOW_MODE_GA4,
	SETUP_FLOW_MODE_GA4_TRANSITIONAL,
} from './constants';
import { MODULES_ANALYTICS_4 } from '../../analytics-4/datastore/constants';

const { createRegistrySelector } = Data;

const baseSelectors = {
	getSetupFlowMode: createRegistrySelector( ( select ) => () => {
		// The Google Analytics 4 datastore hasn't been loaded, so we have
		// to use the legacy implementation.
		if ( ! select( MODULES_ANALYTICS_4 ) ) {
			return SETUP_FLOW_MODE_LEGACY;
		}

		// Check to see if the Admin API is working—if it's `undefined` the request
		// is loading, but if it's `false` we should also use the legacy analytics
		// because the API isn't working properly.
		const isAdminAPIWorking = select( MODULES_ANALYTICS_4 ).isAdminAPIWorking();

		if ( isAdminAPIWorking === undefined ) {
			return undefined;
		}

		if ( isAdminAPIWorking === false ) {
			return SETUP_FLOW_MODE_LEGACY;
		}

		// Ensure the Analytics settings have loaded. If we check
		// `select( MODULES_ANALYTICS ).getAccountID();` directly, it
		// could return `undefined` because the settings are loading OR
		// because accountID is not set. Ensuring the settings are loaded
		// means an `undefined` accountID is legitimate.
		// See: https://github.com/google/site-kit-wp/pull/3260#discussion_r623924928
		if ( select( MODULES_ANALYTICS ).getSettings() === undefined ) {
			return undefined;
		}

		const accountID = select( MODULES_ANALYTICS ).getAccountID();

		// If no accountID exists then no account is selected. This means we should
		// use the UA setup flow.
		if ( ! accountID ) {
			return SETUP_FLOW_MODE_UA;
		}

		const ga4Properties = select( MODULES_ANALYTICS_4 ).getProperties( accountID );

		if ( ga4Properties === undefined ) {
			return undefined;
		}

		// If there are no GA4 properties available for this account, don't use
		// GA4 and use the UA version.
		if ( ga4Properties.length === 0 ) {
			return SETUP_FLOW_MODE_UA;
		}

		const uaProperties = select( MODULES_ANALYTICS ).getProperties( accountID );

		if ( uaProperties === undefined ) {
			return undefined;
		}

		// If no UA properties exist and there are GA4 properties, use GA4-only.
		if ( uaProperties.length === 0 ) {
			return SETUP_FLOW_MODE_GA4;
		}

		// There are UA and GA4 properties, so use the transitional mode.
		return SETUP_FLOW_MODE_GA4_TRANSITIONAL;
	} ),
};

const store = Data.combineStores(
	{
		selectors: baseSelectors,
	}
);

export const initialState = store.initialState;
export const actions = store.actions;
export const controls = store.controls;
export const reducer = store.reducer;
export const resolvers = store.resolvers;
export const selectors = store.selectors;

export default store;
<|endoftext|>


<commit_before>
zound.ui.ModulePropertyEditor = Backbone.View.extend({
  tagName: 'li',
  initialize: function () {
    this.render();
    this.listenTo(this.model, "change:value", this.onValueChange);
  },
  template: _.template('<%= title %>

'),
  render: function() {
    this.$el.attr("id", this.model.get("id"));
    // FIXME We use an input[type=range] for quick impl. - this can be replaced in the future.
    var granularity = this.model.getValueGranularity();
    if (!isFinite(granularity)) granularity = 1000;
    this.$el.html(this.template(this.model.attributes));
    this.$component = this.$el.find(".component");
    var value = Math.round(granularity*this.model.getPercent());
    this.$valueText = $(''+this.model.getText()+'');
    this.$range = $('<input type="range" min="0" max="'+granularity+'" value="'+value+'" />');
    this.$component.append(this.$valueText);
    this.$component.append(this.$range);

    this.$range.on("change", _.bind(function (e) {
      this._dontSetInputValue = true;
      this.model.setPercent(parseInt(this.$range.val())/granularity);
      this._dontSetInputValue = false;
    }, this));

    zound.models.MIDIController.makeAssignable(this.$el, _.bind(function (midiValue) {
      this.model.setPercent(midiValue / 127);
    }, this));
    return this;
  },
  onValueChange: function (model, rawValue) {
    var granularity = model.getValueGranularity();
    var value = Math.round(granularity*model.getPercent());
    if (!this._dontSetInputValue) {
      this.$range.val(value);
    }
    this.$valueText.text(model.getText());
  }
});

zound.ui.ModulePropertiesEditor = Backbone.View.extend({
  tagName: 'div',

  initialize: function () {
    this.init();
    this.listenTo(this.model, "change", this.render);
    this.render();
  },

  init: function () {
    var $title = $('
');
    $title.text(this.model.get("title"));
    var $ul = $('
');
    this.model.properties.each(function (property) {
      var propertyView = new zound.ui.ModulePropertyEditor({
        model: property
      });
      $ul.append(propertyView.el);
    }, this);
    this.$el.append($title);
    this.$el.append($ul);
  },

  render: function () {

  }
});
<commit_msg>Fix module properties id<commit_after>
zound.ui.ModulePropertyEditor = Backbone.View.extend({
  tagName: 'li',
  initialize: function () {
    this.render();
    this.listenTo(this.model, "change:value", this.onValueChange);
  },
  template: _.template('<%= title %>

'),
  render: function() {
    this.$el.attr("id", this.model.cid);
    // FIXME We use an input[type=range] for quick impl. - this can be replaced in the future.
    var granularity = this.model.getValueGranularity();
    if (!isFinite(granularity)) granularity = 1000;
    this.$el.html(this.template(this.model.attributes));
    this.$component = this.$el.find(".component");
    var value = Math.round(granularity*this.model.getPercent());
    this.$valueText = $(''+this.model.getText()+'');
    this.$range = $('<input type="range" min="0" max="'+granularity+'" value="'+value+'" />');
    this.$component.append(this.$valueText);
    this.$component.append(this.$range);

    this.$range.on("change", _.bind(function (e) {
      this._dontSetInputValue = true;
      this.model.setPercent(parseInt(this.$range.val())/granularity);
      this._dontSetInputValue = false;
    }, this));

    zound.models.MIDIController.makeAssignable(this.$el, _.bind(function (midiValue) {
      this.model.setPercent(midiValue / 127);
    }, this));
    return this;
  },
  onValueChange: function (model, rawValue) {
    var granularity = model.getValueGranularity();
    var value = Math.round(granularity*model.getPercent());
    if (!this._dontSetInputValue) {
      this.$range.val(value);
    }
    this.$valueText.text(model.getText());
  }
});

zound.ui.ModulePropertiesEditor = Backbone.View.extend({
  tagName: 'div',

  initialize: function () {
    this.init();
    this.listenTo(this.model, "change", this.render);
    this.render();
  },

  init: function () {
    var $title = $('
');
    $title.text(this.model.get("title"));
    var $ul = $('
');
    this.model.properties.each(function (property) {
      var propertyView = new zound.ui.ModulePropertyEditor({
        model: property
      });
      $ul.append(propertyView.el);
    }, this);
    this.$el.append($title);
    this.$el.append($ul);
  },

  render: function () {

  }
});
<|endoftext|>


<commit_before>/**
 * Watchdog.
 * @constructor
 */

function watchdog(){

    this.request_timeout = 30000;
    this.event_active_id = 0;
    this.reboot_after_ok = false;
    this.running = false;
}

watchdog.prototype.run = function(timeout, timeslot){
    _debug('watchdog.run', timeout, timeslot);

    _debug('watchdog.running', this.running);

    if (this.running){
        return;
    }

    this.request_timeout = timeout*1000 || this.request_timeout;
    timeslot = timeslot*1000;

    _debug('this.request_timeout', this.request_timeout);

    var day_start = new Date();
    day_start.setHours(0);
    day_start.setMinutes(0);
    day_start.setSeconds(0);
    day_start.setMilliseconds(0);
    day_start = day_start.getTime();

    var now = new Date().getTime();

    _debug('now', now);
    _debug('day_start', day_start);

    _debug('Math.floor((now - day_start)/this.request_timeout)', Math.floor((now - day_start)/this.request_timeout));

    var delay = this.request_timeout - ((now - day_start) - Math.floor((now - day_start)/this.request_timeout) * this.request_timeout);

    _debug('delay', delay);

    //delay += timeslot;

    if ((delay + timeslot) > this.request_timeout){
        delay = delay - (this.request_timeout - timeslot);
    }else{
        delay += timeslot;
    }

    _debug('delay', delay);
    _debug('date', new Date(now + delay) + " " + new Date(now + delay).getMilliseconds() + "ms");

    var self = this;

    this.running = true;

    this.send_request(true);

    window.setTimeout(function(){
        window.setInterval(function(){
            self.send_request();
        }, self.request_timeout);
        self.send_request();
    }, delay);
};

watchdog.prototype.send_request = function(init){

    var self = this;
    init = init | false;

    var cur_play_type = 0;

    if (!stb.player.pause.on){
        cur_play_type = stb.get_current_place();
    }

    _debug('cur_play_type', cur_play_type);

    _debug('now', new Date() + " " + new Date().getMilliseconds() + "ms");

    stb.load(
        {
            "type"            : "watchdog",
            "action"          : "get_events",
            "cur_play_type"   : cur_play_type,
            "event_active_id" : this.event_active_id,
            "init"            : init
        },

        function(result){
            try{

                self.parse_result(result.data);

            }catch(e){
                _debug(e);
            }
        }
    );
};

watchdog.prototype.parse_result = function(data){

    _debug('watchdog.parse_result', data);

    try{

        //module.curweather && module.curweather.set && module.curweather.set(data.cur_weather);

        //module.course && module.course.set && data.course && module.course.set(data.course);

        stb.check_additional_services(data.additional_services_on);
    }catch(e){
        _debug(e);
    }

    if (typeof(data.id) != 'undefined'){

        _debug('data.id', data.id);

        switch(data.event){
            case 'reboot':
            {
                stb.Stop();
                stb.ExecAction('reboot');
                break;
            }
            case 'reload_portal':
            {
                stb.Stop();
                window.location = window.location;
                break;
            }
            case 'send_msg':
            {

                if (!stb.msg){
                    return;
                }

                if (this.event_active_id == data.id){
                    return;
                }

                this.event_active_id = data.id;

                var self = this;

                stb.msg.set_callback(
                    function(){
                        self.send_confirm(function(){
                            if (data.reboot_after_ok == 1){
                                stb.ExecAction('reboot');
                            }
                        });
                    });

                stb.msg.push(
                    {
                        msg               : (data.send_time ? '[' + data.send_time + '] ' : '') + data.msg,
                        auto_hide_timeout : data.auto_hide_timeout || 0
                    }
                );

                this.reboot_after_ok = data.reboot_after_ok;

                break;
            }
            case 'update_channels':
            {
                stb.load_channels();
                stb.load_fav_channels();
                stb.load_fav_itv();
                break;
            }
            case 'update_subscription':
            {
                if (stb.cur_off_on){
                    stb.ExecAction('reboot');
                }else{
                    stb.load_channels();
                    stb.load_fav_channels();
                    stb.load_fav_itv();
                }
                break;
            }
            case 'update_epg':
            {
                _debug('stb.user.timeslot_ratio', stb.user.timeslot_ratio);
                _debug('stb.user.epg_update_time_range', stb.user.epg_update_time_range);

                if (stb.user.timeslot_ratio){
                    var delay = stb.user.timeslot_ratio * stb.user.epg_update_time_range;
                }else{
                    delay = 0 ;
                }

                _debug('delay', delay);

                window.clearTimeout(this.update_epg_timeout);

                this.update_epg_timeout = window.setTimeout(function(){
                    stb.epg_loader.epg = null;
                    stb.epg_loader.load();
                }, delay * 1000);
                break;
            }
            case 'cut_off':
            {
                stb.cut_off();
                break;
            }
            case 'cut_on':
            {
                stb.cut_on();
                break;
            }
            case 'update_image':
            {
                keydown_observer.emulate_key(key.MENU);
                stbUpdate.startAutoUpdate(stb.user['update_url'], false);
                break;
            }
            case 'mount_all_storages':
            {
                //stb.mount_home_dir(data.msg);
                stb.set_storages(data.msg);
                break;
            }
            case 'show_menu': // reset paused
            {
                keydown_observer.emulate_key(key.MENU);
                break;
            }
            case 'play_channel':
            {
                keydown_observer.emulate_key(key.MENU);

                stb.user.fav_itv_on = 0;

                var ch_idx = stb.player.channels.getIdxByNumber(parseInt(data.msg));

                stb.player.ch_idx = ch_idx || 0;
                stb.player.cur_media_item = stb.player.channels[stb.player.ch_idx];
                stb.player.cur_tv_item = stb.player.channels[stb.player.ch_idx];
                stb.player.last_not_locked_tv_item = stb.player.channels[stb.player.ch_idx];

                //keydown_observer.emulate_key(key.EXIT);
                main_menu.hide();
                stb.player.play_last();
                break;
            }
            case 'update_modules':
            {
                stb.update_modules();
                break;
            }
        }
    }
};

watchdog.prototype.send_confirm = function(callback){

    stb.load(
    {
        "type"   : "watchdog",
        "action" : "confirm_event",
        "event_active_id" : this.event_active_id
    },

    function(result){
        _debug(result);
        callback && callback();
    });

    this.event_active_id = 0;
};<commit_msg>Fix send_msg event with reboot by OK button (issue #3643)<commit_after>/**
 * Watchdog.
 * @constructor
 */

function watchdog(){

    this.request_timeout = 30000;
    this.event_active_id = 0;
    this.reboot_after_ok = false;
    this.running = false;
}

watchdog.prototype.run = function(timeout, timeslot){
    _debug('watchdog.run', timeout, timeslot);

    _debug('watchdog.running', this.running);

    if (this.running){
        return;
    }

    this.request_timeout = timeout*1000 || this.request_timeout;
    timeslot = timeslot*1000;

    _debug('this.request_timeout', this.request_timeout);

    var day_start = new Date();
    day_start.setHours(0);
    day_start.setMinutes(0);
    day_start.setSeconds(0);
    day_start.setMilliseconds(0);
    day_start = day_start.getTime();

    var now = new Date().getTime();

    _debug('now', now);
    _debug('day_start', day_start);

    _debug('Math.floor((now - day_start)/this.request_timeout)', Math.floor((now - day_start)/this.request_timeout));

    var delay = this.request_timeout - ((now - day_start) - Math.floor((now - day_start)/this.request_timeout) * this.request_timeout);

    _debug('delay', delay);

    //delay += timeslot;

    if ((delay + timeslot) > this.request_timeout){
        delay = delay - (this.request_timeout - timeslot);
    }else{
        delay += timeslot;
    }

    _debug('delay', delay);
    _debug('date', new Date(now + delay) + " " + new Date(now + delay).getMilliseconds() + "ms");

    var self = this;

    this.running = true;

    this.send_request(true);

    window.setTimeout(function(){
        window.setInterval(function(){
            self.send_request();
        }, self.request_timeout);
        self.send_request();
    }, delay);
};

watchdog.prototype.send_request = function(init){

    var self = this;
    init = init | false;

    var cur_play_type = 0;

    if (!stb.player.pause.on){
        cur_play_type = stb.get_current_place();
    }

    _debug('cur_play_type', cur_play_type);

    _debug('now', new Date() + " " + new Date().getMilliseconds() + "ms");

    stb.load(
        {
            "type"            : "watchdog",
            "action"          : "get_events",
            "cur_play_type"   : cur_play_type,
            "event_active_id" : this.event_active_id,
            "init"            : init
        },

        function(result){
            try{

                self.parse_result(result.data);

            }catch(e){
                _debug(e);
            }
        }
    );
};

watchdog.prototype.parse_result = function(data){

    _debug('watchdog.parse_result', data);

    try{

        //module.curweather && module.curweather.set && module.curweather.set(data.cur_weather);

        //module.course && module.course.set && data.course && module.course.set(data.course);

        stb.check_additional_services(data.additional_services_on);
    }catch(e){
        _debug(e);
    }

    if (typeof(data.id) != 'undefined'){

        _debug('data.id', data.id);

        switch(data.event){
            case 'reboot':
            {
                stb.Stop();
                stb.ExecAction('reboot');
                break;
            }
            case 'reload_portal':
            {
                stb.Stop();
                window.location = window.location;
                break;
            }
            case 'send_msg':
            {

                if (!stb.msg){
                    return;
                }

                if (this.event_active_id == data.id){
                    return;
                }

                this.event_active_id = data.id;

                var self = this;

                stb.msg.set_callback(
                    function(){
                        self.send_confirm(function(){
                            if (data.reboot_after_ok == 1){
                                stb.Stop();
                                stb.ExecAction('reboot');
                            }
                        });
                    });

                stb.msg.push(
                    {
                        msg               : (data.send_time ? '[' + data.send_time + '] ' : '') + data.msg,
                        auto_hide_timeout : data.auto_hide_timeout || 0
                    }
                );

                this.reboot_after_ok = data.reboot_after_ok;

                break;
            }
            case 'update_channels':
            {
                stb.load_channels();
                stb.load_fav_channels();
                stb.load_fav_itv();
                break;
            }
            case 'update_subscription':
            {
                if (stb.cur_off_on){
                    stb.Stop();
                    stb.ExecAction('reboot');
                }else{
                    stb.load_channels();
                    stb.load_fav_channels();
                    stb.load_fav_itv();
                }
                break;
            }
            case 'update_epg':
            {
                _debug('stb.user.timeslot_ratio', stb.user.timeslot_ratio);
                _debug('stb.user.epg_update_time_range', stb.user.epg_update_time_range);

                if (stb.user.timeslot_ratio){
                    var delay = stb.user.timeslot_ratio * stb.user.epg_update_time_range;
                }else{
                    delay = 0 ;
                }

                _debug('delay', delay);

                window.clearTimeout(this.update_epg_timeout);

                this.update_epg_timeout = window.setTimeout(function(){
                    stb.epg_loader.epg = null;
                    stb.epg_loader.load();
                }, delay * 1000);
                break;
            }
            case 'cut_off':
            {
                stb.cut_off();
                break;
            }
            case 'cut_on':
            {
                stb.cut_on();
                break;
            }
            case 'update_image':
            {
                keydown_observer.emulate_key(key.MENU);
                stbUpdate.startAutoUpdate(stb.user['update_url'], false);
                break;
            }
            case 'mount_all_storages':
            {
                //stb.mount_home_dir(data.msg);
                stb.set_storages(data.msg);
                break;
            }
            case 'show_menu': // reset paused
            {
                keydown_observer.emulate_key(key.MENU);
                break;
            }
            case 'play_channel':
            {
                keydown_observer.emulate_key(key.MENU);

                stb.user.fav_itv_on = 0;

                var ch_idx = stb.player.channels.getIdxByNumber(parseInt(data.msg));

                stb.player.ch_idx = ch_idx || 0;
                stb.player.cur_media_item = stb.player.channels[stb.player.ch_idx];
                stb.player.cur_tv_item = stb.player.channels[stb.player.ch_idx];
                stb.player.last_not_locked_tv_item = stb.player.channels[stb.player.ch_idx];

                //keydown_observer.emulate_key(key.EXIT);
                main_menu.hide();
                stb.player.play_last();
                break;
            }
            case 'update_modules':
            {
                stb.update_modules();
                break;
            }
        }
    }
};

watchdog.prototype.send_confirm = function(callback){

    stb.load(
    {
        "type"   : "watchdog",
        "action" : "confirm_event",
        "event_active_id" : this.event_active_id
    },

    function(result){
        _debug(result);
        callback && callback();
    });

    this.event_active_id = 0;
};<|endoftext|>


<commit_before>var Handlebars = require("./base");

// BEGIN(BROWSER)
Handlebars.VM = {
  template: function(templateSpec) {
    // Just add water
    var container = {
      escapeExpression: Handlebars.Utils.escapeExpression,
      invokePartial: Handlebars.VM.invokePartial,
      programs: [],
      program: function(i, fn, data) {
        var programWrapper = this.programs[i];
        if(data) {
          return Handlebars.VM.program(fn, data);
        } else if(programWrapper) {
          return programWrapper;
        } else {
          programWrapper = this.programs[i] = Handlebars.VM.program(fn);
          return programWrapper;
        }
      },
      programWithDepth: Handlebars.VM.programWithDepth,
      noop: Handlebars.VM.noop
    };

    return function(context, options) {
      options = options || {};
      return templateSpec.call(container, Handlebars, context, options.helpers, options.partials, options.data);
    };
  },

  programWithDepth: function(fn, data, $depth) {
    var args = Array.prototype.slice.call(arguments, 2);

    return function(context, options) {
      options = options || {};

      return fn.apply(this, [context, options.data || data].concat(args));
    };
  },
  program: function(fn, data) {
    return function(context, options) {
      options = options || {};

      return fn(context, options.data || data);
    };
  },
  noop: function() { return ""; },
  invokePartial: function(partial, name, context, helpers, partials, data) {
    var options = { helpers: helpers, partials: partials, data: data };

    if(partial === undefined) {
      throw new Handlebars.Exception("The partial " + name + " could not be found");
    } else if(partial instanceof Function) {
      return partial(context, options);
    } else if (!Handlebars.compile) {
      throw new Handlebars.Exception("The partial " + name + " could not be compiled when running in runtime-only mode");
    } else {
      partials[name] = Handlebars.compile(partial);
      return partials[name](context, options);
    }
  }
};

Handlebars.template = Handlebars.VM.template;

// END(BROWSER)

<commit_msg>Ensure plain text partials supplied to registerPartials are compiled using data: true if necessary.<commit_after>var Handlebars = require("./base");

// BEGIN(BROWSER)
Handlebars.VM = {
  template: function(templateSpec) {
    // Just add water
    var container = {
      escapeExpression: Handlebars.Utils.escapeExpression,
      invokePartial: Handlebars.VM.invokePartial,
      programs: [],
      program: function(i, fn, data) {
        var programWrapper = this.programs[i];
        if(data) {
          return Handlebars.VM.program(fn, data);
        } else if(programWrapper) {
          return programWrapper;
        } else {
          programWrapper = this.programs[i] = Handlebars.VM.program(fn);
          return programWrapper;
        }
      },
      programWithDepth: Handlebars.VM.programWithDepth,
      noop: Handlebars.VM.noop
    };

    return function(context, options) {
      options = options || {};
      return templateSpec.call(container, Handlebars, context, options.helpers, options.partials, options.data);
    };
  },

  programWithDepth: function(fn, data, $depth) {
    var args = Array.prototype.slice.call(arguments, 2);

    return function(context, options) {
      options = options || {};

      return fn.apply(this, [context, options.data || data].concat(args));
    };
  },
  program: function(fn, data) {
    return function(context, options) {
      options = options || {};

      return fn(context, options.data || data);
    };
  },
  noop: function() { return ""; },
  invokePartial: function(partial, name, context, helpers, partials, data) {
    var options = { helpers: helpers, partials: partials, data: data };

    if(partial === undefined) {
      throw new Handlebars.Exception("The partial " + name + " could not be found");
    } else if(partial instanceof Function) {
      return partial(context, options);
    } else if (!Handlebars.compile) {
      throw new Handlebars.Exception("The partial " + name + " could not be compiled when running in runtime-only mode");
    } else {
      partials[name] = Handlebars.compile(partial, {data: data !== undefined});
      return partials[name](context, options);
    }
  }
};

Handlebars.template = Handlebars.VM.template;

// END(BROWSER)

<|endoftext|>


<commit_before>var calc = function () {
  document.body.appendChild(calc.display)
  document.body.appendChild(calc.keypad)
}

!function () {

var
set = function (a) {
  e.value = a; e.data.textContent = a.toString()
},
reset = function () {
  delete e.value; e.data.textContent = '0'
},
bs = function () {
  var _ = e.data.textContent.slice(0, -1)

  e.data.textContent = _ === '' ? '0' : _
},
fix = function () {
  e.value = e.value || new Adele(parseInt(e.data.textContent))
},
focus = function () {
  e.classList.remove('focus')
  e = this
  e.classList.add('focus')
},
makeCell = function () {
  var
  cell = html.tr(),
  data = html.td()

  cell.appendChild(data)
  data.textContent = '0'
  cell[touch] = cell.focus = focus

  cell.data = data
  data.cell = cell

  return cell
},
push = function () {
  e.parentNode.insertBefore(makeCell(), e.nextSibling)
  e.nextSibling.focus()
},
pop = function () {
  var _ = e.value

  if (e.previousSibling) {
    e.previousSibling.focus()
    e.parentNode.removeChild(e.nextSibling)
  }

  return _
},
numeric = function () {
  var _ = this.textContent, __

  e.value && push()
  __ = e.data
  __.textContent = (__.textContent === '0' ? '' : __.textContent) + _
},
touch = document.createElement('div').hasOwnProperty('ontouchend') ? 'ontouchend' : 'onmouseup',
html = {}, func = {}, e

10 .forEach(function (i) {
  func[i] = numeric
})
func['.'] = function() {
  e.value && push()
  e.data.textContent += '.'
}
func['↑'] = function () {
  var _ = e.value

  _ ? push() : (_ = new Adele(parseInt(e.data.textContent)))
  set(_)
}
func['↓'] = function () {
  e.previousSibling ? pop() : reset()
}
func['←'] = function () {
  e.value ? reset() : bs()
}
func.mod = function () {
  fix(); set(new Adele(e.value.n))
}
func['↕'] = function () {
  fix()
  if (e.previousSibling) {
    e.parentNode.insertBefore(e, e.previousSibling)
    e.nextSibling.focus()
  }
}
func['↺'] = function () {}
func['/'] = function () {
  fix(); set(e.value.inv())
}
func['−'] = function () {
  fix(); set(e.value.neg())
}
func['\\'] = function () {
  fix(); set(e.value.res())
}
func[' '] = function () {
  var _

  if (e.previousSibling) {
    fix(); _ = pop(); set(e.value ? e.value.mul(_) : _)
  }
}
func['+'] = function () {
  var _

  if (e.previousSibling) {
    fix(); _ = pop(); set(e.value ? e.value.add(_) : _)
  }
}
func.unit = function () {
  var _

  fix(); _ = e.value
  set(_.body()); push()
  set(_.unit())
}
func.zero = function () {
  var _

  fix(); _ = e.value
  set(new Adele(_._r, _.s)); push()
  set(new Adele(0, 1, _.n))
}

;['tr', 'td', 'table'].forEach(function (a) {
  html[a] = function () {
    return document.createElement(a)
  }
})

calc.display = html.table()
calc.keypad  = html.table()

;[
  ['↑', '↓', '←', '7', '8', '9'],
  ['mod', '↕', '↺', '4', '5', '6'],
  ['unit', ' ', '/', '1', '2', '3'],
  ['zero', '+', '−', '0', '.', '\\']
].forEach(function (tds) {
  var tr = html.tr()

  tds.forEach(function (td) {
    var _ = html.td()

    _.textContent = td
    _[touch] = func[td]
    tr.appendChild(_)
  })
  calc.keypad.appendChild(tr)
})
calc.keypad.classList.add('keypad')

e = makeCell()

calc.display.appendChild(e)
calc.display.classList.add('display')

}()

onload = calc<commit_msg>modified:   calc/adele.js<commit_after>var calc = function () {
  document.body.appendChild(calc.display)
  document.body.appendChild(calc.keypad)
}

!function () {

var
set = function (a) {
  e.value = a; e.data.textContent = a.toString()
},
reset = function () {
  delete e.value; e.data.textContent = '0'
},
bs = function () {
  var _ = e.data.textContent.slice(0, -1)

  e.data.textContent = _ === '' ? '0' : _
},
fix = function () {
  e.value = e.value || new Adele(parseInt(e.data.textContent))
},
focus = function () {
  e.classList.remove('focus')
  e = this
  e.classList.add('focus')
},
makeCell = function () {
  var
  cell = html.tr(),
  data = html.td()

  cell.appendChild(data)
  data.textContent = '0'
  cell[touch] = cell.focus = focus

  cell.data = data
  data.cell = cell

  return cell
},
push = function () {
  e.parentNode.insertBefore(makeCell(), e.nextSibling)
  e.nextSibling.focus()
},
pop = function () {
  var _ = e.value

  if (e.previousSibling) {
    e.previousSibling.focus()
    e.parentNode.removeChild(e.nextSibling)
  }

  return _
},
numeric = function () {
  var _ = this.textContent, __

  e.value && push()
  __ = e.data
  __.textContent = (__.textContent === '0' ? '' : __.textContent) + _
},
touch = document.createElement('div').hasOwnProperty('ontouchend') ? 'ontouchend' : 'onmouseup',
html = {}, func = {}, e

10 .forEach(function (i) {
  func[i] = numeric
})
func['.'] = function() {
  e.value && push()
  e.data.textContent += '.'
}
func['↑'] = function () {
  var _ = e.value

  _ ? push() : (_ = new Adele(parseInt(e.data.textContent)))
  set(_)
}
func['↓'] = function () {
  e.previousSibling ? pop() : reset()
}
func['←'] = function () {
  e.value ? reset() : bs()
}
func['⎵'] = function () {
  fix(); set(new Adele(e.value.n))
}
func['↕'] = function () {
  fix()
  if (e.previousSibling) {
    e.parentNode.insertBefore(e, e.previousSibling)
    e.nextSibling.focus()
  }
}
func['↺'] = function () {}
func['/'] = function () {
  fix(); set(e.value.inv())
}
func['−'] = function () {
  fix(); set(e.value.neg())
}
func['\\'] = function () {
  fix(); set(e.value.res())
}
func[' '] = function () {
  var _

  if (e.previousSibling) {
    fix(); _ = pop(); set(e.value ? e.value.mul(_) : _)
  }
}
func['+'] = function () {
  var _

  if (e.previousSibling) {
    fix(); _ = pop(); set(e.value ? e.value.add(_) : _)
  }
}
func['✃'] = function () {
  var _

  fix(); _ = e.value
  set(_.body()); push()
  set(_.unit())
}
func['✁'] = function () {
  var _

  fix(); _ = e.value
  set(new Adele(_._r, _.s)); push()
  set(new Adele(0, 1, _.n))
}

;['tr', 'td', 'table'].forEach(function (a) {
  html[a] = function () {
    return document.createElement(a)
  }
})

calc.display = html.table()
calc.keypad  = html.table()

;[
  ['↑', '↓', '←', '7', '8', '9'],
  ['⎵', '↕', '↺', '4', '5', '6'],
  ['✃', ' ', '/', '1', '2', '3'],
  ['✁', '+', '−', '0', '.', '\\']
].forEach(function (tds) {
  var tr = html.tr()

  tds.forEach(function (td) {
    var _ = html.td()

    _.textContent = td
    _[touch] = func[td]
    tr.appendChild(_)
  })
  calc.keypad.appendChild(tr)
})
calc.keypad.classList.add('keypad')

e = makeCell()

calc.display.appendChild(e)
calc.display.classList.add('display')

}()

onload = calc<|endoftext|>