<commit_before>var DEBUG = function() {
	console.log(arguments);
};

mini.Module(
	"engine/rendering/debugdraw/debugdraw"
)
.requires(
	"engine/rendering/renderer"
)
.defines(function(Renderer) {
	/*
	 * Init
	 */
	var DebugDraw = Renderer.subclass({
		initialize: function() {
			Renderer.prototype.initialize.apply(this, arguments);

			this.setOptions();
		},

		/*
		 * Drawing
		 */
		draw: function(objectToDraw) {
			// clear canvas
			this.context.clearRect(
				0,
				0,
				this.canvas.width,
				this.canvas.height
			);

			// Update canvas aabb for filtering "out of screen" objects.
			var min = env.camera.screenToWorldCoordinates(new Jello.Vector2(0, env.canvas.canvasHeight));
			var max = env.camera.screenToWorldCoordinates(new Jello.Vector2(env.canvas.canvasWidth, 0));
			this.canvasWorldAABB = new Jello.AABB(min, max);

			// Draw given object.
			objectToDraw.debugDraw(this);
		},

		/*
		 * Graphical primitives
		 */
		drawRectangle: function(vec, size) {
			size = size || 2;
			this.context.fillRect(
				env.camera.scaleX(vec.x) - size / 2,
				env.camera.scaleY(vec.y) - size / 2,
				size,
				size
			);
		},

		drawDot: function(vec, size) {
			size = size || 2;
			this.context.arc(
				env.camera.scaleX(vec.x),
				env.camera.scaleY(vec.y),
				size, // radius
				0,
				2 * Math.PI,
				false
			);
			this.context.fill();
		},

		drawPolyline: function(vList) {
			// draw a polyline
			this.context.beginPath();

			this.context.moveTo(
				env.camera.scaleX(vList[0].x),
				env.camera.scaleY(vList[0].y)
			);
			for(var i = 1; i < vList.length; i++)
				this.context.lineTo(
					env.camera.scaleX(vList[i].x),
					env.camera.scaleY(vList[i].y)
				);
			this.context.lineTo(
				env.camera.scaleX(vList[0].x),
				env.camera.scaleY(vList[0].y)
			);
			this.context.stroke();

			this.context.closePath();
		},

		drawPlus: function(point, size) {
			size = size || 3;

			this.context.beginPath();

			// draw a polyline
			this.context.moveTo(
				env.camera.scaleX(point.x) - size,
				env.camera.scaleY(point.y)
			);
			this.context.lineTo(
				env.camera.scaleX(point.x) + size,
				env.camera.scaleY(point.y)
			);
			this.context.moveTo(
				env.camera.scaleX(point.x),
				env.camera.scaleY(point.y) - size
			);
			this.context.lineTo(
				env.camera.scaleX(point.x),
				env.camera.scaleY(point.y) + size
			);

			this.context.stroke();
			this.context.closePath();
		},

		drawText: function(text, screenPoint) {
			this.context.fillText(
					text,
					screenPoint.x,
					screenPoint.y
				);
		},

		drawTextWorld: function(text, worldPoint) {
			this.context.fillText(
					text,
					env.camera.scaleX(worldPoint.x),
					env.camera.scaleY(worldPoint.y)
				);
		},

		/*
		 * Configure Drawing
		 */
		setOptions: function(options) {
			// set properties
			options = options || {};
			this.color = options.color || "white";
			this.opacity = options.opacity || 1.0;
			this.lineWidth = options.lineWidth || 1.0;

			// apply to context
			this.context.fillStyle = this.color;
			this.context.strokeStyle = this.color;
			this.context.globalAlpha = this.opacity;

			this.context.lineWidth = this.lineWidth;
		},

		// Check for visibility
		isVisible: function(aabb) {
			/*
			this.drawText("test", new Vector2(0, env.canvas.canvasHeight/2));
			this.drawText("test", new Vector2(env.canvas.canvasWidth/2, env.canvas.canvasHeight/2));
			this.drawText("test", new Vector2(env.canvas.canvasWidth/2, 0));
			this.drawText("test", new Vector2(0, 0));
			*/
			return aabb.intersects(this.canvasWorldAABB);
		}

	});

	return DebugDraw;
});

<commit_msg>removed test aabb<commit_after>var DEBUG = function() {
	console.log(arguments);
};

mini.Module(
	"engine/rendering/debugdraw/debugdraw"
)
.requires(
	"engine/rendering/renderer"
)
.defines(function(Renderer) {
	/*
	 * Init
	 */
	var DebugDraw = Renderer.subclass({
		initialize: function() {
			Renderer.prototype.initialize.apply(this, arguments);

			this.setOptions();
		},

		/*
		 * Drawing
		 */
		draw: function(objectToDraw) {
			// clear canvas
			this.context.clearRect(
				0,
				0,
				this.canvas.width,
				this.canvas.height
			);

			// Update canvas aabb for filtering "out of screen" objects.
			var min = env.camera.screenToWorldCoordinates(new Jello.Vector2(0, env.canvas.canvasHeight));
			var max = env.camera.screenToWorldCoordinates(new Jello.Vector2(env.canvas.canvasWidth, 0));
			this.canvasWorldAABB = new Jello.AABB(min, max);

			// Draw given object.
			objectToDraw.debugDraw(this);
		},

		/*
		 * Graphical primitives
		 */
		drawRectangle: function(vec, size) {
			size = size || 2;
			this.context.fillRect(
				env.camera.scaleX(vec.x) - size / 2,
				env.camera.scaleY(vec.y) - size / 2,
				size,
				size
			);
		},

		drawDot: function(vec, size) {
			size = size || 2;
			this.context.arc(
				env.camera.scaleX(vec.x),
				env.camera.scaleY(vec.y),
				size, // radius
				0,
				2 * Math.PI,
				false
			);
			this.context.fill();
		},

		drawPolyline: function(vList) {
			// draw a polyline
			this.context.beginPath();

			this.context.moveTo(
				env.camera.scaleX(vList[0].x),
				env.camera.scaleY(vList[0].y)
			);
			for(var i = 1; i < vList.length; i++)
				this.context.lineTo(
					env.camera.scaleX(vList[i].x),
					env.camera.scaleY(vList[i].y)
				);
			this.context.lineTo(
				env.camera.scaleX(vList[0].x),
				env.camera.scaleY(vList[0].y)
			);
			this.context.stroke();

			this.context.closePath();
		},

		drawPlus: function(point, size) {
			size = size || 3;

			this.context.beginPath();

			// draw a polyline
			this.context.moveTo(
				env.camera.scaleX(point.x) - size,
				env.camera.scaleY(point.y)
			);
			this.context.lineTo(
				env.camera.scaleX(point.x) + size,
				env.camera.scaleY(point.y)
			);
			this.context.moveTo(
				env.camera.scaleX(point.x),
				env.camera.scaleY(point.y) - size
			);
			this.context.lineTo(
				env.camera.scaleX(point.x),
				env.camera.scaleY(point.y) + size
			);

			this.context.stroke();
			this.context.closePath();
		},

		drawText: function(text, screenPoint) {
			this.context.fillText(
					text,
					screenPoint.x,
					screenPoint.y
				);
		},

		drawTextWorld: function(text, worldPoint) {
			this.context.fillText(
					text,
					env.camera.scaleX(worldPoint.x),
					env.camera.scaleY(worldPoint.y)
				);
		},

		/*
		 * Configure Drawing
		 */
		setOptions: function(options) {
			// set properties
			options = options || {};
			this.color = options.color || "white";
			this.opacity = options.opacity || 1.0;
			this.lineWidth = options.lineWidth || 1.0;

			// apply to context
			this.context.fillStyle = this.color;
			this.context.strokeStyle = this.color;
			this.context.globalAlpha = this.opacity;

			this.context.lineWidth = this.lineWidth;
		},

		// Check for visibility
		isVisible: function(aabb) {
			return aabb.intersects(this.canvasWorldAABB);
		}

	});

	return DebugDraw;
});

<|endoftext|>


<commit_before>export const API_ROOT_URL = '';
// export const API_ROOT_URL = 'http://localhost:9000';

export const COFFEE_SYMBOL = '\u2615';

const INFINITY_SYMBOL= '\u221e';

export const LEGAL_ESTIMATES = [0, 0.5, 1, 2, 3, 5, 8, 13, 20, 50, 100, INFINITY_SYMBOL, '?'].map(x => x.toString());
<commit_msg>Formatting<commit_after>export const API_ROOT_URL = '';
// export const API_ROOT_URL = 'http://localhost:9000';

export const COFFEE_SYMBOL = '\u2615';

const INFINITY_SYMBOL = '\u221e';

export const LEGAL_ESTIMATES = [0, 0.5, 1, 2, 3, 5, 8, 13, 20, 50, 100, INFINITY_SYMBOL, '?'].map(x => x.toString());
<|endoftext|>


<commit_before>var { URL } = window;
var defaultScope = {
    hasInstance: false,
    btn: button
};
function setValue(src) {
    if (this.value === src) return;
    this.value = src;
    cast(this, src);
    return src;
}
function getValue() {
    return this.value;
}

var choose = function () {
    var elem = this;
    var { uploadto } = this;
    chooseFile('image/*').then(function ([file]) {

        if (URL) {
            var url = URL.createObjectURL(file);
            elem.setValue(url);
            dispatch(elem, 'change');
            if (uploadto) {
                uploadto = uploadto.replace(/\/+$/, '') + "/";
                var serverUrl = uploadto + url.replace(/^[\s\S]*?([\w\-]+)$/, "$1");
                cross("put", serverUrl).send(file).done(function (resposne) {
                    elem.setValue(serverUrl);
                    dispatch(elem, 'change');
                });
            }
        }
        elem.hasInstance = true;
    });
};

var build = function () {
    var elem = this;
    var { $scope = {} } = elem;
    elem.choose = choose;
    extendIfNeeded($scope, defaultScope);
    elem.setValue = setValue;
    elem.getValue = getValue;
    render(elem, $scope);
};

function main(elem = div()) {
    var { uploadto } = elem;
    elem.innerHTML = image;
    if (!uploadto) {
        uploadto = elem.getAttribute("uploadto");
    }
    care(elem, function (src) {
        css(elem, {
            backgroundImage: `url('${src}')`
        });
        this.$scope.hasInstance = !!src;
        render.refresh();
    }, false);
    build.call(elem);
    return elem;
}<commit_msg>修复hasInstance<commit_after>var { URL } = window;
var defaultScope = {
    hasInstance: false,
    btn: button
};
function setValue(src) {
    if (this.value === src) return;
    this.value = src;
    cast(this, src);
    return src;
}
function getValue() {
    return this.value;
}

var choose = function () {
    var elem = this;
    var { uploadto } = this;
    chooseFile('image/*').then(function ([file]) {

        if (URL) {
            var url = URL.createObjectURL(file);
            elem.setValue(url);
            dispatch(elem, 'change');
            if (uploadto) {
                uploadto = uploadto.replace(/\/+$/, '') + "/";
                var serverUrl = uploadto + url.replace(/^[\s\S]*?([\w\-]+)$/, "$1");
                cross("put", serverUrl).send(file).done(function (resposne) {
                    elem.setValue(serverUrl);
                    dispatch(elem, 'change');
                });
            }
        }
    });
};

var build = function () {
    var elem = this;
    var { $scope = {} } = elem;
    elem.choose = choose;
    extendIfNeeded($scope, defaultScope);
    elem.setValue = setValue;
    elem.getValue = getValue;
    render(elem, $scope);
};

function main(elem = div()) {
    var { uploadto } = elem;
    elem.innerHTML = image;
    if (!uploadto) {
        uploadto = elem.getAttribute("uploadto");
    }
    care(elem, function (src) {
        css(elem, {
            backgroundImage: `url('${src}')`
        });
        this.hasInstance = this.$scope.hasInstance = !!src;
        render.refresh();
    }, false);
    build.call(elem);
    return elem;
}<|endoftext|>


<commit_before>/**
 * 弹出层
 */
onkeydown(document, function (e) {
    if (e.which === 27 && popups.length) {
        history.back();
    }
});
var popups = [];
var addMask = function () {
    escMask.call(this);
    popups.push(this);
};
var escMask = function () {
    for (var cx = popups.length - 1; cx >= 0; cx--) {
        if (popups[cx] === this) {
            popups.splice(cx, 1);
        }
    }
};
put("/popup/window", function () {
    var window = createElement(div);
    css(window, `height:100px;width:100px;position:absolute;background-color:#fff;left:${popups.length << 4}px;top:${popups.length << 4}px;`);
    return window;
});
/**
 * 弹出子窗口的函数
 * @param {string} path 窗口路径的唯一索引
 * @param {any} parameters 给窗口的作域预先赋值
 * @param {object} style 自定义样式，主要是width,height等位置参数
 * @returns {Element} 给调用弹窗的命令暴露的可选方法
 */
var popup = function (path) {
    if (isString(path)) {
        return popup_path.apply(null, arguments);
    }
    if (isNode(path)) {
        return popup_extra.apply(null, arguments);
    }
};
var popup_extra = function (element, target) {
    var position = getScreenPosition(target);
    var maxHeight = Math.max(position.top, window.innerHeight - position.top - position.height);
    var maxWidth = Math.max(position.left + position.width, window.innerWidth - position.left);
    if (!element.origin) {
        element.origin = {
            height: element.style.height,
            width: element.style.width
        };
    } else {
        extend(element.style, element.origin);
    }
    css(element, `position:absolute;left:${position.left}px;min-width:${position.width}px;`);
    zimoli.global(element, true);
    var height = element.offsetHeight;
    if (height > maxHeight) {
        css(element, `height:${maxHeight}px`);
    }
    var width = element.offsetWidth;
    if (width > maxWidth) {
        css(element, `width:${maxWidth}px`);
    }
    if (position.top + element.offsetHeight + position.height > window.innerHeight) {
        css(element, `bottom:${window.innerHeight - position.top}px;top:auto;`);
    } else {
        css(element, `top:${position.top + position.height}px;bottom:auto;`);
    }
    if (position.left + element.offsetWidth > window.innerWidth) {
        css(element, `right:${window.innerWidth - position.left - position.width}px;left:auto;`);
    } else {
        css(element, `left:${position.left}px;right:auto;`);
    }
};
var popup_path = function (path = "", parameters, style) {
    var viewsPath = "views";
    if (path.indexOf(".") >= 0) {
        path = path.replace(/\./g, '');
        viewsPath = "builtin";
    }

    var mask = createElement(div);
    css(mask, `position:absolute;position:fixed;z-index${zIndex()};left:0;right:0;bottom:0;top:0;width:auto;height:auto;background-color:rgba(0,0,0,0.2)`);
    mask.className = "popup-factory mask";
    var saved_position;
    // setTimeout(go, 0, "/popup/window",{}, mask);
    onappend(mask, addMask);
    onremove(mask, escMask);
    zimoli.global(mask, true);
    return mask;
};
window["popup"] = popup;<commit_msg>弹出元素时增加键盘操作<commit_after>/**
 * 弹出层
 */
onkeydown(document, function (e) {
    if (e.which === 27 && popups.length) {
        history.back();
    }
});
var popups = [];
var addMask = function () {
    escMask.call(this);
    popups.push(this);
};
var escMask = function () {
    for (var cx = popups.length - 1; cx >= 0; cx--) {
        if (popups[cx] === this) {
            popups.splice(cx, 1);
        }
    }
};
put("/popup/window", function () {
    var window = createElement(div);
    css(window, `height:100px;width:100px;position:absolute;background-color:#fff;left:${popups.length << 4}px;top:${popups.length << 4}px;`);
    return window;
});
/**
 * 弹出子窗口的函数
 * @param {string} path 窗口路径的唯一索引
 * @param {any} parameters 给窗口的作域预先赋值
 * @param {object} style 自定义样式，主要是width,height等位置参数
 * @returns {Element} 给调用弹窗的命令暴露的可选方法
 */
var popup = function (path) {
    if (isString(path)) {
        return popup_path.apply(null, arguments);
    }
    if (isNode(path)) {
        return popup_extra.apply(null, arguments);
    }
};
var popup_view = function (element) {

};
var popup_extra = function (element, target) {
    var position = getScreenPosition(target);
    var maxHeight = Math.max(position.top, window.innerHeight - position.top - position.height);
    var maxWidth = Math.max(position.left + position.width, window.innerWidth - position.left);
    if (!element.origin) {
        element.origin = {
            height: element.style.height,
            width: element.style.width
        };
    } else {
        extend(element.style, element.origin);
    }
    css(element, `position:absolute;left:${position.left}px;min-width:${position.width}px;`);
    onappend(element, addMask);
    onremove(element, escMask);
    onremove(target, function () {
        remove(element);
    });
    zimoli.global(element, true);
    var height = element.offsetHeight;
    if (height > maxHeight) {
        css(element, `height:${maxHeight}px`);
    }
    var width = element.offsetWidth;
    if (width > maxWidth) {
        css(element, `width:${maxWidth}px`);
    }
    if (position.top + element.offsetHeight + position.height > window.innerHeight) {
        css(element, `bottom:${window.innerHeight - position.top}px;top:auto;`);
    } else {
        css(element, `top:${position.top + position.height}px;bottom:auto;`);
    }
    if (position.left + element.offsetWidth > window.innerWidth) {
        css(element, `right:${window.innerWidth - position.left - position.width}px;left:auto;`);
    } else {
        css(element, `left:${position.left}px;right:auto;`);
    }
};
var popup_path = function (path = "", parameters, style) {
    var viewsPath = "views";
    if (path.indexOf(".") >= 0) {
        path = path.replace(/\./g, '');
        viewsPath = "builtin";
    }

    var mask = createElement(div);
    css(mask, `position:absolute;position:fixed;z-index${zIndex()};left:0;right:0;bottom:0;top:0;width:auto;height:auto;background-color:rgba(0,0,0,0.2)`);
    mask.className = "popup-factory mask";
    var saved_position;
    // setTimeout(go, 0, "/popup/window",{}, mask);
    onappend(mask, addMask);
    onremove(mask, escMask);
    zimoli.global(mask, true);
    return mask;
};
window["popup"] = popup;<|endoftext|>


<commit_before>/**
 * 弹出层
 */
onkeydown(document, function (e) {
    if (e.which === 27 && rootElements.length) {
        var r = rootElements.pop();
        r.blur();
        remove(r);
    }
});
var animationStyle = "opacity:0;transform:scale(1.2);transition:.1s opacity ease-out,.2s transform ease-out;";
var setInitialStyle = function (element) {
    if (!element.initialStyle) element.initialStyle = animationStyle;
};
var windowFactory = function (window) {
    css(window, `min-height:10px;min-width:10px;position:absolute;`);
    return window;
};
var loadingFactory = function (element) {
    css(element, `position:absolute;`);
    return element;
}
/**
 * 弹出子窗口的函数
 * @param {string} path 窗口路径的唯一索引
 * @param {any} parameters 给窗口的作域预先赋值
 * @param {object} style 自定义样式，主要是width,height等位置参数
 * @returns {Element} 给调用弹窗的命令暴露的可选方法
 */
var popup = function (path) {
    if (isString(path)) {
        return popup_path.apply(null, arguments);
    }
    if (isNode(path)) {
        return popup_view.apply(null, arguments);
    }
    throw new Error(`path isn't valid:${path}`);
};
var popup_path = function (path = "", parameters, target) {
    if (!popup.go || !popup.prepare) throw new Error("当前环境无法使用");
    // 3 has mask has view control
    var element;
    if (/^#/.test(path)) {
        // mask
        path = path.replace(/^#/, "");
        var load = function () {
            windowFactory(element);
            setInitialStyle(element);
            popup_with_mask(element, target);
            if (element.dragHandle) drag.on(element);
        };
    }
    // 2 has view control has no mask
    else if (/^@/.test(path)) {
        path = path.replace(/^@/, "");
        var load = function () {
            windowFactory(element);
            setInitialStyle(element);
            popup_as_single(element);
            if (element.dragHandle) drag.on(element);
        };
    }
    // 1 has mask has no control
    else if (/^!/.test(path)) {
        path = path.replace(/^!/, "");
        var load = function () {
            loadingFactory(element);
            setInitialStyle(element);
            popup_with_mask(element);
        };
    }
    // 0 has no mask no control
    else {
        var load = function () {
            loadingFactory(element);
            if (isNode(target)) {
                popup_as_extra(element, target);
            }
            else if (target instanceof Event) {
                popup_to_event(element, target);
            } else if (target instanceof Array) {
                popup_to_point(element, target);
            } else if (target) {
                popup_with_mask(element);
            } else {
                if (parameters !== false && target !== false) setInitialStyle(element);
                popup_as_single(element);
            }
        };
    }
    var fullfill = function () {
        remove(element);
        remove(element && element.mask);
        element = popup.create(path, parameters);
        if (!element) return;
        load();
        element.$reload = fullfill;
        if (!target && target !== false && parameters !== false) {
            element.style.opacity = 0;
            if (element.parentNode) move.bindPosition(element, [.5, .5]), element.style.opacity = 1;
            else once('append')(element, function () {
                move.bindPosition(element, [.5, .5]);
                element.style.opacity = 1;
            });
        }
    };
    popup.prepare(path, fullfill);
    return element;
};

var popup_view = function (element, target, style) {
    if (isNode(target)) {
        if (target.isMask) {
            popup_with_mask(element, target);
            return element;
        }
        return popup_as_extra(element, target, style);
    }
    if (target instanceof Event) {
        popup_to_event(element, target);
    } else if (target instanceof Array) {
        popup_to_point(element, target);
    } else if (target) {
        popup_with_mask(element);
    } else {
        popup_as_single(element);
    }
    return element;
};

css(".mask", `position:absolute;position:fixed;left:0;right:0;bottom:0;top:0;width:auto;height:auto;background:#000;opacity:0.2;transform:scale(1);display:block`);
var createMask = function (element) {
    var masks = element.with;
    if (masks) for (var cx = 0, dx = masks.length; cx < dx; cx++) {
        var m = masks[cx];
        if (m.isMask) return m;
    }
    var mask = document.createElement("mask");
    mask.initialStyle = animationStyle;
    css(mask, `z-index:${zIndex()};`);
    mask.className = "mask";
    mask.isMask = true;
    return mask;
};
var popup_with_mask = function (element, mask = createMask(element)) {
    if (!mask.clean) {
        mask.clean = new Cleanup(element.with);
    }
    onremove(element, mask.clean);
    css(element, `z-index:${zIndex()};`);
    if (mask.parentNode) {
        global(element, false);
    }
    if (!element.with) {
        element.with = [mask];
    } else if (element.with instanceof Array) {
        if (!~element.with.indexOf(element)) element.with.push(mask);
    } else {
        if (element.with !== element) element.with = [element.with, mask];
    }
    if (!element.parentNode) global(element, false);
    return element;
};
var isypop = function (target) {
    var { offsetParent, nextSibling, previousSibling } = target;
    if (
        nextSibling
        && (
            nextSibling.offsetLeft - target.offsetLeft >= target.offsetWidth / 2
            || target.offsetLeft - nextSibling.offsetLeft >= nextSibling.offsetWidth / 2
        )
        || previousSibling
        && (
            previousSibling.offsetLeft - target.offsetLeft >= target.offsetWidth / 2
            || target.offsetLeft - previousSibling.offsetLeft >= previousSibling.offsetWidth / 2
        )
    ) return true;
    if (offsetParent && target.offsetTop / target.offsetHeight < .2 && offsetParent.offsetWidth / target.offsetWidth > 1.5) return true;

};
var isxpop = arriswise(isypop, arguments);
var popup_as_extra = function (element, target, style) {
    if (style) {
        if (/^[vy]/i.test(style)) {
            popup_as_yextra(element, target, style);
            return;
        }
        if (/^[hx]/i.test(style)) {
            popup_as_xextra(element, target, style);
            return;
        }

    }
    if (isypop(target)) {
        popup_as_yextra(element, target, style);
    } else if (isxpop(target)) {
        popup_as_xextra(element, target, style);
    } else if (isypop(target.parentNode)) {
        popup_as_yextra(element, target, style);
    } else if (isxpop(target.parentNode)) {
        popup_as_xextra(element, target, style);
    } else {
        if (/inline|cell/i.test(getComputedStyle(target).display)) {
            popup_as_yextra(element, target, style);
        } else {
            popup_as_xextra(element, target, style);
        }
    }

};
var _as_yextra = function (global, innerWidth, innerHeight, element, target, pointer) {
    var withRhomb = pointer && /rhomb|rhombus|diamond|lozenge|triangle|[drlt]$/i.test(pointer);
    if (withRhomb) {
        var _rhomb = rhomb();
    }
    if (!element.origin) {
        element.origin = {
            height: element.style.height,
            width: element.style.width,
            minWidth: element.style.minWidth,
            display: element.style.display
        };
    }
    var zindex = zIndex();
    css(element, `position:absolute;z-index:${zindex}`);
    css(_rhomb, { zIndex: zindex });
    var release1 = onremove(target, function () {
        remove(element);
    });
    var release2 = onremove(element, function () {
        release1();
        release2();
        remove(_rhomb);
        if (document.removeEventListener) {
            document.removeEventListener("scroll", reshape, true);
            window.removeEventListener("resize", reshape);
        }
    });
    global(element, false);
    var reshape = function () {
        extend(element.style, element.origin);
        var position = getScreenPosition(target);
        var viewrect = getScreenPosition(element.offsetParent);
        var documentbody = document.body;
        if (element.offsetParent === documentbody && !/^(absolute|relative|fixed)$/i.test(getComputedStyle(documentbody).position)) {
            viewrect.left = 0;
            viewrect.top = 0;
            viewrect.right += innerWidth - viewrect.right;
            viewrect.bottom += innerHeight - viewrect.bottom;
            viewrect.width = viewrect.right - viewrect.left;
            viewrect.height = viewrect.bottom - viewrect.top;
        } else {
            viewrect.top += documentbody.clientTop;
            viewrect.left += documentbody.clientLeft;
            viewrect.height = documentbody.clientHeight;
            viewrect.width = documentbody.clientWidth;
            viewrect.right = viewrect.left + viewrect.width;
            viewrect.bottom = viewrect.top + viewrect.height;
        }
        var maxHeight = Math.max(position.top, innerHeight - position.top - position.height);
        var maxWidth = Math.max(position.left + position.width, innerWidth - position.left);
        var height = element.offsetHeight;
        //如果高度超出可视区，调整高度
        if (height > maxHeight) {
            css(element, { height: fromOffset(maxHeight) });
        }

        css(element, `min-width:auto;`);
        var aimedWidth = element.offsetWidth;
        //如果宽度不足其附着元素的宽度
        if (aimedWidth < target.offsetWidth) {
            aimedWidth = target.offsetWidth;
        }

        //如果宽度超出可视区，调整宽度
        if (aimedWidth > maxWidth) {
            aimedWidth = maxWidth;
        }
        var side;
        if (aimedWidth !== element.offsetWidth) {
            css(element, { width: fromOffset(aimedWidth) });
        }
        if (position.top + element.offsetHeight + position.height > innerHeight) {
            side = 'bottom';
            var temp = `bottom:${fromOffset(viewrect.height - position.top + viewrect.top)};top:auto;`;
        } else {
            side = 'top';
            var temp = `top:${fromOffset(position.top - viewrect.top + position.height)};bottom:auto;`
        }
        css(element, temp);
        if (_rhomb) {
            css(_rhomb, temp);
            _rhomb.setSide(side);
        }
        if (_rhomb) {
            var targetX = position.left + (position.width - element.offsetWidth) / 2;
            if (targetX < 0) {
                css(element, `left:0;right:auto`);
                css(_rhomb, `left:${fromOffset(position.left + position.width / 2)};right:auto`);
            }
            else if (targetX + element.offsetWidth > innerWidth) {
                css(element, `right:0;left:auto`);
                css(_rhomb, `right:${fromOffset(innerWidth - position.left - position.width / 2)};left:auto`);
            }
            else {
                css(element, `left:${fromOffset(targetX)};right:auto`);
                css(_rhomb, `left:${fromOffset(position.left + position.width / 2)};right:auto`);

            }
        } else {
            if (position.left + element.offsetWidth > innerWidth) {
                css(element, `right:${fromOffset(viewrect.width + viewrect.left - position.left - position.width)};left:auto;`);
            }
            else {
                css(element, `left:${fromOffset(position.left - viewrect.left)};right:auto;`);
            }
        }

        var offsetParent = target.offsetParent;
        if (offsetParent) {
            if (overlap(target, offsetParent) > 0) {
                element.style.display = element.origin.display;
                if (_rhomb && !_rhomb.parentNode) {
                    appendChild.before(element, _rhomb)
                }
            } else {
                element.style.display = "none";
                remove(_rhomb);
            };
        } else if (_rhomb && !_rhomb.parentNode) {
            appendChild.before(element, _rhomb)
        }
    }
    if (document.addEventListener) {
        document.addEventListener("scroll", reshape, true);
        window.addEventListener("resize", reshape);
    }
    reshape();
    lazy(reshape)();
};
var _as_xextra = arriswise(_as_yextra, arguments);
var popup_as_single = function (element) {
    css(element, `z-index:${zIndex()};`);
    global(element, false);
};
var popup_to_point = function (element, [x, y]) {
    if (x <= 1 && y <= 1 && x >= 0 && y >= 0) {
        popup_as_single(element);
        move.bindPosition(element, [x, y]);
    } else {
        x = calcPixel(x), y = calcPixel(y);
        popup_fixup(element, x, y);
    }
};
var popup_fixup = function (element, x, y) {
    css(element, {
        position: 'absolute',
    });
    popup_as_single(element);
    var left = "left", top = 'top';
    if (y + element.offsetHeight > window.innerHeight && y << 1 > window.innerHeight) {
        top = "bottom";
        y = window.innerHeight - y;
    }
    if (x + element.offsetWidth > window.innerWidth && x << 1 > window.innerWidth) {
        left = "right";
        x = window.innerWidth - x;
    }
    css(element, {
        [left]: fromOffset(x),
        [top]: fromOffset(y)
    });

};
var popup_to_event = function (element, { clientX, clientY }) {
    popup_fixup(element, clientX, clientY);
};
var global = function (element, issingle) {
    once("remove")(element, cleanup);
    rootElements.push(element);
    popup.global &&
        issingle !== false ? popup.global(element, true) : appendChild(document.body, element);
};
var popup_as_yextra = _as_yextra.bind(null, global, innerWidth, innerHeight);
var popup_as_xextra = _as_xextra.bind(null, global, innerHeight, innerWidth);
var cleanup = new Cleanup(rootElements);<commit_msg>添加#路径的替代方案<commit_after>/**
 * 弹出层
 */
onkeydown(document, function (e) {
    if (e.which === 27 && rootElements.length) {
        var r = rootElements.pop();
        r.blur();
        remove(r);
    }
});
var animationStyle = "opacity:0;transform:scale(1.2);transition:.1s opacity ease-out,.2s transform ease-out;";
var setInitialStyle = function (element) {
    if (!element.initialStyle) element.initialStyle = animationStyle;
};
var windowFactory = function (window) {
    css(window, `min-height:10px;min-width:10px;position:absolute;`);
    return window;
};
var loadingFactory = function (element) {
    css(element, `position:absolute;`);
    return element;
}
/**
 * 弹出子窗口的函数
 * @param {string} path 窗口路径的唯一索引
 * @param {any} parameters 给窗口的作域预先赋值
 * @param {object} style 自定义样式，主要是width,height等位置参数
 * @returns {Element} 给调用弹窗的命令暴露的可选方法
 */
var popup = function (path) {
    if (isString(path)) {
        return popup_path.apply(null, arguments);
    }
    if (isNode(path)) {
        return popup_view.apply(null, arguments);
    }
    throw new Error(`path isn't valid:${path}`);
};
var popup_path = function (path = "", parameters, target) {
    if (!popup.go || !popup.prepare) throw new Error("当前环境无法使用");
    // 3 has mask has view control
    var element;
    if (/^[#\+]/.test(path)) {
        // mask
        path = path.replace(/^[#\+]/, "");
        var load = function () {
            windowFactory(element);
            setInitialStyle(element);
            popup_with_mask(element, target);
            if (element.dragHandle) drag.on(element);
        };
    }
    // 2 has view control has no mask
    else if (/^@/.test(path)) {
        path = path.replace(/^@/, "");
        var load = function () {
            windowFactory(element);
            setInitialStyle(element);
            popup_as_single(element);
            if (element.dragHandle) drag.on(element);
        };
    }
    // 1 has mask has no control
    else if (/^!/.test(path)) {
        path = path.replace(/^!/, "");
        var load = function () {
            loadingFactory(element);
            setInitialStyle(element);
            popup_with_mask(element);
        };
    }
    // 0 has no mask no control
    else {
        var load = function () {
            loadingFactory(element);
            if (isNode(target)) {
                popup_as_extra(element, target);
            }
            else if (target instanceof Event) {
                popup_to_event(element, target);
            } else if (target instanceof Array) {
                popup_to_point(element, target);
            } else if (target) {
                popup_with_mask(element);
            } else {
                if (parameters !== false && target !== false) setInitialStyle(element);
                popup_as_single(element);
            }
        };
    }
    var fullfill = function () {
        remove(element);
        remove(element && element.mask);
        element = popup.create(path, parameters);
        if (!element) return;
        load();
        element.$reload = fullfill;
        if (!target && target !== false && parameters !== false) {
            element.style.opacity = 0;
            if (element.parentNode) move.bindPosition(element, [.5, .5]), element.style.opacity = 1;
            else once('append')(element, function () {
                move.bindPosition(element, [.5, .5]);
                element.style.opacity = 1;
            });
        }
    };
    popup.prepare(path, fullfill);
    return element;
};

var popup_view = function (element, target, style) {
    if (isNode(target)) {
        if (target.isMask) {
            popup_with_mask(element, target);
            return element;
        }
        return popup_as_extra(element, target, style);
    }
    if (target instanceof Event) {
        popup_to_event(element, target);
    } else if (target instanceof Array) {
        popup_to_point(element, target);
    } else if (target) {
        popup_with_mask(element);
    } else {
        popup_as_single(element);
    }
    return element;
};

css(".mask", `position:absolute;position:fixed;left:0;right:0;bottom:0;top:0;width:auto;height:auto;background:#000;opacity:0.2;transform:scale(1);display:block`);
var createMask = function (element) {
    var masks = element.with;
    if (masks) for (var cx = 0, dx = masks.length; cx < dx; cx++) {
        var m = masks[cx];
        if (m.isMask) return m;
    }
    var mask = document.createElement("mask");
    mask.initialStyle = animationStyle;
    css(mask, `z-index:${zIndex()};`);
    mask.className = "mask";
    mask.isMask = true;
    return mask;
};
var popup_with_mask = function (element, mask = createMask(element)) {
    if (!mask.clean) {
        mask.clean = new Cleanup(element.with);
    }
    onremove(element, mask.clean);
    css(element, `z-index:${zIndex()};`);
    if (mask.parentNode) {
        global(element, false);
    }
    if (!element.with) {
        element.with = [mask];
    } else if (element.with instanceof Array) {
        if (!~element.with.indexOf(element)) element.with.push(mask);
    } else {
        if (element.with !== element) element.with = [element.with, mask];
    }
    if (!element.parentNode) global(element, false);
    return element;
};
var isypop = function (target) {
    var { offsetParent, nextSibling, previousSibling } = target;
    if (
        nextSibling
        && (
            nextSibling.offsetLeft - target.offsetLeft >= target.offsetWidth / 2
            || target.offsetLeft - nextSibling.offsetLeft >= nextSibling.offsetWidth / 2
        )
        || previousSibling
        && (
            previousSibling.offsetLeft - target.offsetLeft >= target.offsetWidth / 2
            || target.offsetLeft - previousSibling.offsetLeft >= previousSibling.offsetWidth / 2
        )
    ) return true;
    if (offsetParent && target.offsetTop / target.offsetHeight < .2 && offsetParent.offsetWidth / target.offsetWidth > 1.5) return true;

};
var isxpop = arriswise(isypop, arguments);
var popup_as_extra = function (element, target, style) {
    if (style) {
        if (/^[vy]/i.test(style)) {
            popup_as_yextra(element, target, style);
            return;
        }
        if (/^[hx]/i.test(style)) {
            popup_as_xextra(element, target, style);
            return;
        }

    }
    if (isypop(target)) {
        popup_as_yextra(element, target, style);
    } else if (isxpop(target)) {
        popup_as_xextra(element, target, style);
    } else if (isypop(target.parentNode)) {
        popup_as_yextra(element, target, style);
    } else if (isxpop(target.parentNode)) {
        popup_as_xextra(element, target, style);
    } else {
        if (/inline|cell/i.test(getComputedStyle(target).display)) {
            popup_as_yextra(element, target, style);
        } else {
            popup_as_xextra(element, target, style);
        }
    }

};
var _as_yextra = function (global, innerWidth, innerHeight, element, target, pointer) {
    var withRhomb = pointer && /rhomb|rhombus|diamond|lozenge|triangle|[drlt]$/i.test(pointer);
    if (withRhomb) {
        var _rhomb = rhomb();
    }
    if (!element.origin) {
        element.origin = {
            height: element.style.height,
            width: element.style.width,
            minWidth: element.style.minWidth,
            display: element.style.display
        };
    }
    var zindex = zIndex();
    css(element, `position:absolute;z-index:${zindex}`);
    css(_rhomb, { zIndex: zindex });
    var release1 = onremove(target, function () {
        remove(element);
    });
    var release2 = onremove(element, function () {
        release1();
        release2();
        remove(_rhomb);
        if (document.removeEventListener) {
            document.removeEventListener("scroll", reshape, true);
            window.removeEventListener("resize", reshape);
        }
    });
    global(element, false);
    var reshape = function () {
        extend(element.style, element.origin);
        var position = getScreenPosition(target);
        var viewrect = getScreenPosition(element.offsetParent);
        var documentbody = document.body;
        if (element.offsetParent === documentbody && !/^(absolute|relative|fixed)$/i.test(getComputedStyle(documentbody).position)) {
            viewrect.left = 0;
            viewrect.top = 0;
            viewrect.right += innerWidth - viewrect.right;
            viewrect.bottom += innerHeight - viewrect.bottom;
            viewrect.width = viewrect.right - viewrect.left;
            viewrect.height = viewrect.bottom - viewrect.top;
        } else {
            viewrect.top += documentbody.clientTop;
            viewrect.left += documentbody.clientLeft;
            viewrect.height = documentbody.clientHeight;
            viewrect.width = documentbody.clientWidth;
            viewrect.right = viewrect.left + viewrect.width;
            viewrect.bottom = viewrect.top + viewrect.height;
        }
        var maxHeight = Math.max(position.top, innerHeight - position.top - position.height);
        var maxWidth = Math.max(position.left + position.width, innerWidth - position.left);
        var height = element.offsetHeight;
        //如果高度超出可视区，调整高度
        if (height > maxHeight) {
            css(element, { height: fromOffset(maxHeight) });
        }

        css(element, `min-width:auto;`);
        var aimedWidth = element.offsetWidth;
        //如果宽度不足其附着元素的宽度
        if (aimedWidth < target.offsetWidth) {
            aimedWidth = target.offsetWidth;
        }

        //如果宽度超出可视区，调整宽度
        if (aimedWidth > maxWidth) {
            aimedWidth = maxWidth;
        }
        var side;
        if (aimedWidth !== element.offsetWidth) {
            css(element, { width: fromOffset(aimedWidth) });
        }
        if (position.top + element.offsetHeight + position.height > innerHeight) {
            side = 'bottom';
            var temp = `bottom:${fromOffset(viewrect.height - position.top + viewrect.top)};top:auto;`;
        } else {
            side = 'top';
            var temp = `top:${fromOffset(position.top - viewrect.top + position.height)};bottom:auto;`
        }
        css(element, temp);
        if (_rhomb) {
            css(_rhomb, temp);
            _rhomb.setSide(side);
        }
        if (_rhomb) {
            var targetX = position.left + (position.width - element.offsetWidth) / 2;
            if (targetX < 0) {
                css(element, `left:0;right:auto`);
                css(_rhomb, `left:${fromOffset(position.left + position.width / 2)};right:auto`);
            }
            else if (targetX + element.offsetWidth > innerWidth) {
                css(element, `right:0;left:auto`);
                css(_rhomb, `right:${fromOffset(innerWidth - position.left - position.width / 2)};left:auto`);
            }
            else {
                css(element, `left:${fromOffset(targetX)};right:auto`);
                css(_rhomb, `left:${fromOffset(position.left + position.width / 2)};right:auto`);

            }
        } else {
            if (position.left + element.offsetWidth > innerWidth) {
                css(element, `right:${fromOffset(viewrect.width + viewrect.left - position.left - position.width)};left:auto;`);
            }
            else {
                css(element, `left:${fromOffset(position.left - viewrect.left)};right:auto;`);
            }
        }

        var offsetParent = target.offsetParent;
        if (offsetParent) {
            if (overlap(target, offsetParent) > 0) {
                element.style.display = element.origin.display;
                if (_rhomb && !_rhomb.parentNode) {
                    appendChild.before(element, _rhomb)
                }
            } else {
                element.style.display = "none";
                remove(_rhomb);
            };
        } else if (_rhomb && !_rhomb.parentNode) {
            appendChild.before(element, _rhomb)
        }
    }
    if (document.addEventListener) {
        document.addEventListener("scroll", reshape, true);
        window.addEventListener("resize", reshape);
    }
    reshape();
    lazy(reshape)();
};
var _as_xextra = arriswise(_as_yextra, arguments);
var popup_as_single = function (element) {
    css(element, `z-index:${zIndex()};`);
    global(element, false);
};
var popup_to_point = function (element, [x, y]) {
    if (x <= 1 && y <= 1 && x >= 0 && y >= 0) {
        popup_as_single(element);
        move.bindPosition(element, [x, y]);
    } else {
        x = calcPixel(x), y = calcPixel(y);
        popup_fixup(element, x, y);
    }
};
var popup_fixup = function (element, x, y) {
    css(element, {
        position: 'absolute',
    });
    popup_as_single(element);
    var left = "left", top = 'top';
    if (y + element.offsetHeight > window.innerHeight && y << 1 > window.innerHeight) {
        top = "bottom";
        y = window.innerHeight - y;
    }
    if (x + element.offsetWidth > window.innerWidth && x << 1 > window.innerWidth) {
        left = "right";
        x = window.innerWidth - x;
    }
    css(element, {
        [left]: fromOffset(x),
        [top]: fromOffset(y)
    });

};
var popup_to_event = function (element, { clientX, clientY }) {
    popup_fixup(element, clientX, clientY);
};
var global = function (element, issingle) {
    once("remove")(element, cleanup);
    rootElements.push(element);
    popup.global &&
        issingle !== false ? popup.global(element, true) : appendChild(document.body, element);
};
var popup_as_yextra = _as_yextra.bind(null, global, innerWidth, innerHeight);
var popup_as_xextra = _as_xextra.bind(null, global, innerHeight, innerWidth);
var cleanup = new Cleanup(rootElements);<|endoftext|>


<commit_before>foam.CLASS({
  package: 'foam.nanos.controller',
  name: 'ApplicationLoader',
  extends: 'foam.u2.Element',
  implements: [
    'foam.nanos.controller.ApplicationConfig',
    'foam.box.Context',
    'foam.mlang.Expressions',
  ],
  requires: [
    'foam.nanos.controller.ApplicationController',
    'foam.box.HTTPBox',
    'foam.box.RetryBox',
    'foam.dao.RequestResponseClientDAO',
    'foam.nanos.boot.NSpec',
    'foam.dao.EasyDAO',
  ],
  properties: [
    {
      name: 'view',
      value: 'Loading...',
    },
    {
      name: 'nSpecDAO',
      factory: function() {
        // The client completely fails if nSpecDAO fails to load, so infinitely retry
        // requests to nSpecDAO.
        return this.RequestResponseClientDAO.create({
          of: this.NSpec,
          delegate: this.RetryBox.create({
            maxAttempts: -1,
            delegate: this.HTTPBox.create({
              method: 'POST',
              url: 'service/nSpecDAO'
            })
          })
        });
      }
    },
    {
      name: 'promise',
      factory: function() {
        var self = this;
        return new Promise(function(resolve) {

          var client = {
            refines: 'foam.nanos.controller.ApplicationController',
            requires: [
              'foam.dao.EasyDAO',
            ],
            exports: [],
            properties: [],
            methods: [
              function createDAO(config) {
                config.daoType = 'MDAO'; // 'IDB';
                config.cache   = true;

                return this.EasyDAO.create(config);
              }
            ]
          };

          var references = [];

          // Force hard reload when app version updates
          self.nSpecDAO.find("appConfig").then(function(spec) {
            var appConfig = spec.service;
            var version   = appConfig.version;

            if ( "CLIENT_VERSION" in localStorage ) {
              var oldVersion = localStorage.CLIENT_VERSION;
              if ( version != oldVersion ) {
                localStorage.CLIENT_VERSION = version;
                location.reload(true);
              }
            } else {
              localStorage.CLIENT_VERSION = version;
            }
          });

          self.nSpecDAO.where(self.EQ(self.NSpec.SERVE, true)).select({
            put: function(spec) {
              if ( spec.client ) {
                client.exports.push(spec.name);

                var json = JSON.parse(spec.client);

                references = references.concat(foam.json.references(self.__context__, json));

                client.properties.push({
                  name: spec.name,
                  factory: function() {
                    if ( ! json.serviceName ) json.serviceName = 'service/' + spec.name;
                    if ( ! json.class       ) json.class       = 'foam.dao.EasyDAO'
                    if ( ! json.daoType     ) json.daoType     = 'CLIENT';
                    return foam.json.parse(json, null, this);
                    //return foam.json.parseString(spec.client, this.__context__);
                  }
                });
              }
            },
            eof: function() {
              Promise.all(references).then(function() {
                foam.core.Model.create(client).buildClass();

                var args = {};
                foam.nanos.controller.ApplicationConfig.getAxiomsByClass(foam.core.Property).forEach(function(p) {
                  args[p.name] = self[p.name]
                })
                resolve(self.ApplicationController.create(args));
              });
            }
          });
        })
      },
    },
  ],
  methods: [
    function initE() {
      var self = this;
      self.add(self.view$);
      self.promise.then(function(v) { self.view = v });
    },
  ],
});
<commit_msg>Make ApplicationLoader take an optional controller to load.<commit_after>foam.CLASS({
  package: 'foam.nanos.controller',
  name: 'ApplicationLoader',
  extends: 'foam.u2.Element',
  implements: [
    'foam.nanos.controller.ApplicationConfig',
    'foam.box.Context',
    'foam.mlang.Expressions',
  ],
  requires: [
    'foam.box.HTTPBox',
    'foam.box.RetryBox',
    'foam.dao.RequestResponseClientDAO',
    'foam.nanos.boot.NSpec',
    'foam.dao.EasyDAO',
    'foam.nanos.controller.ApplicationConfig',
  ],
  imports: [
    'classloader',
  ],
  properties: [
    {
      name: 'view',
      value: 'Loading...',
    },
    {
      name: 'controller',
      value: 'foam.nanos.controller.ApplicationController',
    },
    {
      name: 'nSpecDAO',
      factory: function() {
        // The client completely fails if nSpecDAO fails to load, so infinitely retry
        // requests to nSpecDAO.
        return this.RequestResponseClientDAO.create({
          of: this.NSpec,
          delegate: this.RetryBox.create({
            maxAttempts: -1,
            delegate: this.HTTPBox.create({
              method: 'POST',
              url: 'service/nSpecDAO'
            })
          })
        });
      }
    },
    {
      name: 'promise',
      factory: function() {
        var self = this;
        return self.classloader.load(self.controller).then(function(cls) {
          return new Promise(function(resolve) {

            var client = {
              refines: cls.model_.id,
              requires: [
                'foam.dao.EasyDAO',
              ],
              exports: [],
              properties: [],
              methods: [
                function createDAO(config) {
                  config.daoType = 'MDAO'; // 'IDB';
                  config.cache   = true;

                  return this.EasyDAO.create(config);
                }
              ]
            };

            var references = [];

            // Force hard reload when app version updates
            self.nSpecDAO.find("appConfig").then(function(spec) {
              var appConfig = spec.service;
              var version   = appConfig.version;

              if ( "CLIENT_VERSION" in localStorage ) {
                var oldVersion = localStorage.CLIENT_VERSION;
                if ( version != oldVersion ) {
                  localStorage.CLIENT_VERSION = version;
                  location.reload(true);
                }
              } else {
                localStorage.CLIENT_VERSION = version;
              }
            });

            self.nSpecDAO.where(self.EQ(self.NSpec.SERVE, true)).select({
              put: function(spec) {
                if ( spec.client ) {
                  client.exports.push(spec.name);

                  var json = JSON.parse(spec.client);

                  references = references.concat(foam.json.references(self.__context__, json));

                  client.properties.push({
                    name: spec.name,
                    factory: function() {
                      if ( ! json.serviceName ) json.serviceName = 'service/' + spec.name;
                      if ( ! json.class       ) json.class       = 'foam.dao.EasyDAO'
                      if ( ! json.daoType     ) json.daoType     = 'CLIENT';
                      return foam.json.parse(json, null, this);
                      //return foam.json.parseString(spec.client, this.__context__);
                    }
                  });
                }
              },
              eof: function() {
                Promise.all(references).then(function() {
                  foam.core.Model.create(client).buildClass();

                  var args = {};
                  self.ApplicationConfig.getAxiomsByClass(foam.core.Property).forEach(function(p) {
                    args[p.name] = self[p.name]
                  })
                  resolve(cls.create(args));
                });
              }
            });
          })
        });
      },
    },
  ],
  methods: [
    function initE() {
      var self = this;
      self.add(self.view$);
      self.promise.then(function(v) { self.view = v });
    },
  ],
});
<|endoftext|>


<commit_before>(function(){
  var root = this,
      self, statusSocket;

  var Gush = {

    initialize: function(){
      self = this;
      console.log("Hello from gush");
      this.registerSockets();
    },

    registerSockets: function(){
      this.registerStatusSocket();
    },

    registerStatusSocket: function(){
      statusSocket = new EventSource("/subscribe/workers.status");

      statusSocket.onopen    = this.onOpen;
      statusSocket.onerror   = this.onError;
      statusSocket.onmessage = this.onStatus;
      statusSocket.onclose   = this.onClose;
    },

    onOpen: function(){
      console.log("Socket has been opened!");
    },

    onError: function(error){
      console.log(error);
    },

    onClose: function(){
      console.log("Connection closed");
    },

    onStatus: function(message){
      message = JSON.parse(message.data);

      switch(message.status){
        case "started":
          self.onJobStart(message);
        case "finished":
          self.onJobSuccess(message);
        case "heartbeat":
          self.onJobHeartbeat(message);
        case "failed":
          self.onJobFail(message);
      }
    },

    onJobStart: function(message){
      console.log("Job started:", message.job);
    },

    onJobSuccess: function(message){
      console.log("Job success:");
      console.log(message);
    },

    onJobHeartbeat: function(message){
    },

    onJobFail: function(message){
      console.log("Job failed:");
      console.log(message);
    }
  };

  root.Gush = Gush;
})();

Gush.initialize();
<commit_msg>Added breaks; added default handler<commit_after>(function(){
  var root = this,
      self, statusSocket;

  var Gush = {

    initialize: function(){
      self = this;
      console.log("Hello from gush");
      this.registerSockets();
    },

    registerSockets: function(){
      this.registerStatusSocket();
    },

    registerStatusSocket: function(){
      statusSocket = new EventSource("/subscribe/workers.status");

      statusSocket.onopen    = this.onOpen;
      statusSocket.onerror   = this.onError;
      statusSocket.onmessage = this.onStatus;
      statusSocket.onclose   = this.onClose;
    },

    onOpen: function(){
      console.log("Socket has been opened!");
    },

    onError: function(error){
      console.log(error);
    },

    onClose: function(){
      console.log("Connection closed");
    },

    onStatus: function(message){
      message = JSON.parse(message.data);

      switch(message.status){
        case "started":
          self.onJobStart(message);
          break;
        case "finished":
          self.onJobSuccess(message);
          break;
        case "heartbeat":
          self.onJobHeartbeat(message);
          break;
        case "failed":
          self.onJobFail(message);
          break;
        default:
          console.error("Unkown job status:", message.status, "data: ", message);
      }
    },

    onJobStart: function(message){
      console.log("Job started:", message.job);
    },

    onJobSuccess: function(message){
      console.log("Job success:");
      console.log(message);
    },

    onJobHeartbeat: function(message){
    },

    onJobFail: function(message){
      console.log("Job failed:");
      console.log(message);
    }
  };

  root.Gush = Gush;
})();

Gush.initialize();
<|endoftext|>


<commit_before>/**
 *
 */
class RomanNumerals {

    numerals = [
        {value: 4, numeral: 'IV'},
        {value: 1, numeral: 'I'}
    ];

    /**
     *
     */
    fromNumber(n) {
        let result = '';

        this.numerals.forEach(item => {
            while (n >= item.value) {
                result += item.numeral;
                n -= item.value;
            }
        });

        return result;
    }

}

export default new RomanNumerals();<commit_msg>slight refactor of the while loop, converted to for, looks cleaner<commit_after>/**
 *
 */
class RomanNumerals {

    numerals = [
        {value: 4, numeral: 'IV'},
        {value: 1, numeral: 'I'}
    ];

    /**
     *
     */
    fromNumber(n) {
        let result = '';

        this.numerals.forEach(item => {
            for (; n >= item.value; n -= item.value) {
                result += item.numeral;
            }
        });

        return result;
    }

}

export default new RomanNumerals();<|endoftext|>


<commit_before>/**
 * @license AngularJS v1.2.25
 * (c) 2010-2014 Google, Inc. http://angularjs.org
 * License: MIT
 */
(function(window, angular, undefined) {'use strict';

var $resourceMinErr = angular.$$minErr('$resource');

// Helper functions and regex to lookup a dotted path on an object
// stopping at undefined/null.  The path must be composed of ASCII
// identifiers (just like $parse)
var MEMBER_NAME_REGEX = /^(\.[a-zA-Z_$][0-9a-zA-Z_$]*)+$/;

function isValidDottedPath(path) {
  return (path != null && path !== '' && path !== 'hasOwnProperty' &&
      MEMBER_NAME_REGEX.test('.' + path));
}

function lookupDottedPath(obj, path) {
  if (!isValidDottedPath(path)) {
    throw $resourceMinErr('badmember', 'Dotted member path "@{0}" is invalid.', path);
  }
  var keys = path.split('.');
  for (var i = 0, ii = keys.length; i < ii && obj !== undefined; i++) {
    var key = keys[i];
    obj = (obj !== null) ? obj[key] : undefined;
  }
  return obj;
}

/**
 * Create a shallow copy of an object and clear other fields from the destination
 */
function shallowClearAndCopy(src, dst) {
  dst = dst || {};

  angular.forEach(dst, function(value, key){
    delete dst[key];
  });

  for (var key in src) {
    if (src.hasOwnProperty(key) && !(key.charAt(0) === '$' && key.charAt(1) === '$')) {
      dst[key] = src[key];
    }
  }

  return dst;
}

/**
 * @ngdoc module
 * @name ngResource
 * @description
 *
 * # ngResource
 *
 * The `ngResource` module provides interaction support with RESTful services
 * via the $resource service.
 *
 *
 *

 *
 * See {@link ngResource.$resource `$resource`} for usage.
 */

/**
 * @ngdoc service
 * @name $resource
 * @requires $http
 *
 * @description
 * A factory which creates a resource object that lets you interact with
 * [RESTful](http://en.wikipedia.org/wiki/Representational_State_Transfer) server-side data sources.
 *
 * The returned resource object has action methods which provide high-level behaviors without
 * the need to interact with the low level {@link ng.$http $http} service.
 *
 * Requires the {@link ngResource `ngResource`} module to be installed.
 *
 * @param {string} url A parametrized URL template with parameters prefixed by `:` as in
 *   `/user/:username`. If you are using a URL with a port number (e.g.
 *   `http://example.com:8080/api`), it will be respected.
 *
 *   If you are using a url with a suffix, just add the suffix, like this:
 *   `$resource('http://example.com/resource.json')` or `$resource('http://example.com/:id.json')`
 *   or even `$resource('http://example.com/resource/:resource_id.:format')`
 *   If the parameter before the suffix is empty, :resource_id in this case, then the `/.` will be
 *   collapsed down to a single `.`.  If you need this sequence to appear and not collapse then you
 *   can escape it with `/\.`.
 *
 * @param {Object=} paramDefaults Default values for `url` parameters. These can be overridden in
 *   `actions` methods. If any of the parameter value is a function, it will be executed every time
 *   when a param value needs to be obtained for a request (unless the param was overridden).
 *
 *   Each key value in the parameter object is first bound to url template if present and then any
 *   excess keys are appended to the url search query after the `?`.
 *
 *   Given a template `/path/:verb` and parameter `{verb:'greet', salutation:'Hello'}` results in
 *   URL `/path/greet?salutation=Hello`.
 *
 *   If the parameter value is prefixed with `@` then the value for that parameter will be extracted
 *   from the corresponding property on the `data` object (provided when calling an action method).  For
 *   example, if the `defaultParam` object is `{someParam: '@someProp'}` then the value of `someParam`
 *   will be `data.someProp`.
 *
 * @param {Object.<Object>=} actions Hash with declaration of custom action that should extend
 *   the default set of resource actions. The declaration should be created in the format of {@link
 *   ng.$http#usage_parameters $http.config}:
 *
 *       {action1: {method:?, params:?, isArray:?, headers:?, ...},
 *        action2: {method:?, params:?, isArray:?, headers:?, ...},
 *        ...}
 *
 *   Where:
 *
 *   - **`action`** – {string} – The name of action. This name becomes the name of the method on
 *     your resource object.
 *   - **`method`** – {string} – Case insensitive HTTP method (e.g. `GET`, `POST`, `PUT`,
 *     `DELETE`, `JSONP`, etc).
 *   - **`params`** – {Object=} – Optional set of pre-bound parameters for this action. If any of
 *     the parameter value is a function, it will be executed every time when a param value needs to
 *     be obtained for a request (unless the param was overridden).
 *   - **`url`** – {string} – action specific `url` override. The url templating is supported just
 *     like for the resource-level urls.
 *   - **`isArray`** – {boolean=} – If true then the returned object for this action is an array,
 *     see `returns` section.
 *   - **`transformRequest`** –
 *     `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
 *     transform function or an array of such functions. The transform function takes the http
 *     request body and headers and returns its transformed (typically serialized) version.
 *     By default, transformRequest will contain one function that checks if the request data is
 *     an object and serializes to using `angular.toJson`. To prevent this behavior, set
 *     `transformRequest` to an empty array: `transformRequest: []`
 *   - **`transformResponse`** –
 *     `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
 *     transform function or an array of such functions. The transform function takes the http
 *     response body and headers and returns its transformed (typically deserialized) version.
 *     By default, transformResponse will contain one function that checks if the response looks like
 *     a JSON string and deserializes it using `angular.fromJson`. To prevent this behavior, set
 *     `transformResponse` to an empty array: `transformResponse: []`
 *   - **`cache`** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the
 *     GET request, otherwise if a cache instance built with
 *     {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
 *     caching.
 *   - **`timeout`** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise} that
 *     should abort the request when resolved.
 *   - **`withCredentials`** - `{boolean}` - whether to set the `withCredentials` flag on the
 *     XHR object. See
 *     [requests with credentials](https://developer.mozilla.org/en/http_access_control#section_5)
 *     for more information.
 *   - **`responseType`** - `{string}` - see
 *     [requestType](https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType).
 *   - **`interceptor`** - `{Object=}` - The interceptor object has two optional methods -
 *     `response` and `responseError`. Both `response` and `responseError` interceptors get called
 *     with `http response` object. See {@link ng.$http $http interceptors}.
 *
 * @returns {Object} A resource "class" object with methods for the default set of resource actions
 *   optionally extended with custom `actions`. The default set contains these actions:
 *   ```js
 *   { 'get':    {method:'GET'},
 *     'save':   {method:'POST'},
 *     'query':  {method:'GET', isArray:true},
 *     'remove': {method:'DELETE'},
 *     'delete': {method:'DELETE'} };
 *   ```
 *
 *   Calling these methods invoke an {@link ng.$http} with the specified http method,
 *   destination and parameters. When the data is returned from the server then the object is an
 *   instance of the resource class. The actions `save`, `remove` and `delete` are available on it
 *   as  methods with the `$` prefix. This allows you to easily perform CRUD operations (create,
 *   read, update, delete) on server-side data like this:
 *   ```js
 *   var User = $resource('/user/:userId', {userId:'@id'});
 *   var user = User.get({userId:123}, function() {
 *     user.abc = true;
 *     user.$save();
 *   });
 *   ```
 *
 *   It is important to realize that invoking a $resource object method immediately returns an
 *   empty reference (object or array depending on `isArray`). Once the data is returned from the
 *   server the existing reference is populated with the actual data. This is a useful trick since
 *   usually the resource is assigned to a model which is then rendered by the view. Having an empty
 *   object results in no rendering, once the data arrives from the server then the object is
 *   populated with the data and the view automatically re-renders itself showing the new data. This
 *   means that in most cases one never has to write a callback function for the action methods.
 *
 *   The action methods on the class object or instance object can be invoked with the following
 *   parameters:
 *
 *   - HTTP GET "class" actions: `Resource.action([parameters], [success], [error])`
 *   - non-GET "class" actions: `Resource.action([parameters], postData, [success], [error])`
 *   - non-GET instance actions:  `instance.$action([parameters], [success], [error])`
 *
 *   Success callback is called with (value, responseHeaders) arguments. Error callback is called
 *   with (httpResponse) argument.
 *
 *   Class actions return empty instance (with additional properties below).
 *   Instance actions return promise of the action.
 *
 *   The Resource instances and collection have these additional properties:
 *
 *   - `$promise`: the {@link ng.$q promise} of the original server interaction that created this
 *     instance or collection.
 *
 *     On success, the promise is resolved with the same resource instance or collection object,
 *     updated with data from server. This makes it easy to use in
 *     {@link ngRoute.$routeProvider resolve section of $routeProvider.when()} to defer view
 *     rendering until the resource(s) are loaded.
 *
 *     On failure, the promise is resolved with the {@link ng.$http http response} object, without
 *     the `resource` property.
 *
 *     If an interceptor object was provided, the promise will instead be resolved with the value
 *     returned by the interceptor.
 *
 *   - `$resolved`: `true` after first server interaction is completed (either with success or
 *      rejection), `false` before that. Knowing if the Resource has been resolved is useful in
 *      data-binding.
 *
 * @example
 *
 * # Credit card resource
 *
 * ```js
     // Define CreditCard class
     var CreditCard = $resource('/user/:userId/card/:cardId',
      {userId:123, cardId:'@id'}, {
       charge: {method:'POST', params:{charge:true}}
      });

     // We can retrieve a collection from the server
     var cards = CreditCard.query(function() {
       // GET: /user/123/card
       // server returns: [ {id:456, number:'1234', name:'Smith'} ];

       var card = cards[0];
       // each item is an instance of CreditCard
       expect(card instanceof CreditCard).toEqual(true);
       card.name = "J. Smith";
       // non GET methods are mapped onto the instances
       card.$save();
       // POST: /user/123/card/456 {id:456, number:'1234', name:'J. Smith'}
       // server returns: {id:456, number:'1234', name: 'J. Smith'};

       // our custom method is mapped as well.
       card.$charge({amount:9.99});
       // POST: /user/123/card/456?amount=9.99&charge=true {id:456, number:'1234', name:'J. Smith'}
     });

     // we can create an instance as well
     var newCard = new CreditCard({number:'0123'});
     newCard.name = "Mike Smith";
     newCard.$save();
     // POST: /user/123/card {number:'0123', name:'Mike Smith'}
     // server returns: {id:789, number:'0123', name: 'Mike Smith'};
     expect(newCard.id).toEqual(789);
 * ```
 *
 * The object returned from this function execution is a resource "class" which has "static" method
 * for each action in the definition.
 *
 * Calling these methods invoke `$http` on the `url` template with the given `method`, `params` and
 * `headers`.
 * When the data is returned from the server then the object is an instance of the resource type and
 * all of the non-GET methods are available with `$` prefix. This allows you to easily support CRUD
 * operations (create, read, update, delete) on server-side data.

   ```js
     var User = $resource('/user/:userId', {userId:'@id'});
     User.get({userId:123}, function(user) {
       user.abc = true;
       user.$save();
     });
   ```
 *
 * It's worth noting that the success callback for `get`, `query` and other methods gets passed
 * in the response that came from the server as well as $http header getter function, so one
 * could rewrite the above example and get access to http headers as:
 *
   ```js
     var User = $resource('/user/:userId', {userId:'@id'});
     User.get({userId:123}, function(u, getResponseHeaders){
       u.abc = true;
       u.$save(function(u, putResponseHeaders) {
         //u => saved user object
         //putResponseHeaders => $http header getter
       });
     });
   ```
 *
 * You can also access the raw `$http` promise via the `$promise` property on the object returned
 *
   ```
     var User = $resource('/user/:userId', {userId:'@id'});
     User.get({userId:123})
         .$promise.then(function(user) {
           $scope.user = user;
         });
   ```

 * # Creating a custom 'PUT' request
 * In this example we create a custom method on our resource to make a PUT request
 * ```js
 *    var app = angular.module('app', ['ngResource', 'ngRoute']);
 *
 *    // Some APIs expect a PUT request in the format URL/object/ID
 *    // Here we are creating an 'update' method
 *    app.factory('Notes', ['$resource', function($resource) {
 *    return $resource('/notes/:id', null,
 *        {
 *            'update': { method:'PUT' }
 *        });
 *    }]);
 *
 *    // In our controller we get the ID from the URL using ngRoute and $routeParams
 *    // We pass in $routeParams and our Notes factory along with $scope
 *    app.controller('NotesCtrl', ['$scope', '$routeParams', 'Notes',
                                      function($scope, $routeParams, Notes) {
 *    // First get a note object from the factory
 *    var note = Notes.get({ id:$routeParams.id });
 *    $id = note.id;
 *
 *    // Now call update passing in the ID first then the object you are updating
 *    Notes.update({ id:$id }, note);
 *
 *    // This will PUT /notes/ID with the note object in the request payload
 *    }]);
 * ```
 */
angular.module('ngResource', ['ng']).
  factory('$resource', ['$http', '$q', function($http, $q) {

    var DEFAULT_ACTIONS = {
      'get':    {method:'GET'},
      'save':   {method:'POST'},
      'query':  {method:'GET', isArray:true},
      'remove': {method:'DELETE'},
      'delete': {method:'DELETE'}
    };
    var noop = angular.noop,
        forEach = angular.forEach,
        extend = angular.extend,
        copy = angular.copy,
        isFunction = angular.isFunction;

    /**
     * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
     * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
     * segments:
     *    segment       = *pchar
     *    pchar         = unreserved / pct-encoded / sub-delims / ":" / "@"
     *    pct-encoded   = "%" HEXDIG HEXDIG
     *    unreserved    = ALPHA / DIGIT / "-" / "." / "_" / "~"
     *    sub-delims    = "!" / "$" / "&" / "'" / "(" / ")"
     *                     / "*" / "+" / "," / ";" / "="
     */
    function encodeUriSegment(val) {
      return encodeUriQuery(val, true).
        replace(/%26/gi, '&').
        replace(/%3D/gi, '=').
        replace(/%2B/gi, '+');
    }

    /**
     * This method is intended for encoding *key* or *value* parts of query component. We need a
     * custom method because encodeURIComponent is too aggressive and encodes stuff that doesn't
     * have to be encoded per http://tools.ietf.org/html/rfc3986:
     *    query       = *( pchar / "/" / "?" )
     *    pchar         = unreserved / pct-encoded / sub-delims / ":" / "@"
     *    unreserved    = ALPHA / DIGIT / "-" / "." / "_" / "~"
     *    pct-encoded   = "%" HEXDIG HEXDIG
     *    sub-delims    = "!" / "$" / "&" / "'" / "(" / ")"
     *                     / "*" / "+" / "," / ";" / "="
     */
    function encodeUriQuery(val, pctEncodeSpaces) {
      return encodeURIComponent(val).
        replace(/%40/gi, '@').
        replace(/%3A/gi, ':').
        replace(/%24/g, '$').
        replace(/%2C/gi, ',').
        replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
    }

    function Route(template, defaults) {
      this.template = template;
      this.defaults = defaults || {};
      this.urlParams = {};
    }

    Route.prototype = {
      setUrlParams: function(config, params, actionUrl) {
        var self = this,
            url = actionUrl || self.template,
            val,
            encodedVal;

        var urlParams = self.urlParams = {};
        forEach(url.split(/\W/), function(param){
          if (param === 'hasOwnProperty') {
            throw $resourceMinErr('badname', "hasOwnProperty is not a valid parameter name.");
          }
          if (!(new RegExp("^\\d+$").test(param)) && param &&
               (new RegExp("(^|[^\\\\]):" + param + "(\\W|$)").test(url))) {
            urlParams[param] = true;
          }
        });
        url = url.replace(/\\:/g, ':');

        params = params || {};
        forEach(self.urlParams, function(_, urlParam){
          val = params.hasOwnProperty(urlParam) ? params[urlParam] : self.defaults[urlParam];
          if (angular.isDefined(val) && val !== null) {
            encodedVal = encodeUriSegment(val);
            url = url.replace(new RegExp(":" + urlParam + "(\\W|$)", "g"), function(match, p1) {
              return encodedVal + p1;
            });
          } else {
            url = url.replace(new RegExp("(\/?):" + urlParam + "(\\W|$)", "g"), function(match,
                leadingSlashes, tail) {
              if (tail.charAt(0) == '/') {
                return tail;
              } else {
                return leadingSlashes + tail;
              }
            });
          }
        });

        // strip trailing slashes and set the url
        url = url.replace(/\/+$/, '') || '/';
        // then replace collapse `/.` if found in the last URL path segment before the query
        // E.g. `http://url.com/id./format?q=x` becomes `http://url.com/id.format?q=x`
        url = url.replace(/\/\.(?=\w+($|\?))/, '.');
        // replace escaped `/\.` with `/.`
        config.url = url.replace(/\/\\\./, '/.');

        // set params - delegate param encoding to $http
        forEach(params, function(value, key){
          if (!self.urlParams[key]) {
            config.params = config.params || {};
            config.params[key] = value;
          }
        });
      }
    };

    function resourceFactory(url, paramDefaults, actions) {
      var route = new Route(url);

      actions = extend({}, DEFAULT_ACTIONS, actions);

      function extractParams(data, actionParams){
        var ids = {};
        actionParams = extend({}, paramDefaults, actionParams);
        forEach(actionParams, function(value, key){
          if (isFunction(value)) { value = value(); }
          ids[key] = value && value.charAt && value.charAt(0) == '@' ?
            lookupDottedPath(data, value.substr(1)) : value;
        });
        return ids;
      }

      function defaultResponseInterceptor(response) {
        return response.resource;
      }

      function Resource(value){
        shallowClearAndCopy(value || {}, this);
      }

      forEach(actions, function(action, name) {
        var hasBody = /^(POST|PUT|PATCH)$/i.test(action.method);

        Resource[name] = function(a1, a2, a3, a4) {
          var params = {}, data, success, error;

          /* jshint -W086 */ /* (purposefully fall through case statements) */
          switch(arguments.length) {
          case 4:
            error = a4;
            success = a3;
            //fallthrough
          case 3:
          case 2:
            if (isFunction(a2)) {
              if (isFunction(a1)) {
                success = a1;
                error = a2;
                break;
              }

              success = a2;
              error = a3;
              //fallthrough
            } else {
              params = a1;
              data = a2;
              success = a3;
              break;
            }
          case 1:
            if (isFunction(a1)) success = a1;
            else if (hasBody) data = a1;
            else params = a1;
            break;
          case 0: break;
          default:
            throw $resourceMinErr('badargs',
              "Expected up to 4 arguments [params, data, success, error], got {0} arguments",
              arguments.length);
          }
          /* jshint +W086 */ /* (purposefully fall through case statements) */

          var isInstanceCall = this instanceof Resource;
          var value = isInstanceCall ? data : (action.isArray ? [] : new Resource(data));
          var httpConfig = {};
          var responseInterceptor = action.interceptor && action.interceptor.response ||
                                    defaultResponseInterceptor;
          var responseErrorInterceptor = action.interceptor && action.interceptor.responseError ||
                                    undefined;

          forEach(action, function(value, key) {
            if (key != 'params' && key != 'isArray' && key != 'interceptor') {
              httpConfig[key] = copy(value);
            }
          });

          if (hasBody) httpConfig.data = data;
          route.setUrlParams(httpConfig,
                             extend({}, extractParams(data, action.params || {}), params),
                             action.url);

          var promise = $http(httpConfig).then(function (response) {
            var data = response.data,
              promise = value.$promise;

            if (data) {
              // Need to convert action.isArray to boolean in case it is undefined
              // jshint -W018
              if (angular.isArray(data) !== (!!action.isArray)) {
                throw $resourceMinErr('badcfg',
                    'Error in resource configuration. Expected ' +
                    'response to contain an {0} but got an {1}',
                  action.isArray ? 'array' : 'object',
                  angular.isArray(data) ? 'array' : 'object');
              }
              // jshint +W018
              if (action.isArray) {
                value.length = 0;
                forEach(data, function (item) {
                  if (typeof item === "object") {
                    value.push(new Resource(item));
                  } else {
                    // Valid JSON values may be string literals, and these should not be converted
                    // into objects. These items will not have access to the Resource prototype
                    // methods, but unfortunately there
                    value.push(item);
                  }
                });
              } else {
                shallowClearAndCopy(data, value);
                value.$promise = promise;
              }
            }

            value.$resolved = true;

            response.resource = value;

            return response;
          }, function(response) {
            value.$resolved = true;

            (error||noop)(response);

            return $q.reject(response);
          });

          promise = promise.then(
              function(response) {
                var value = responseInterceptor(response);
                (success||noop)(value, response.headers);
                return value;
              },
              responseErrorInterceptor);

          if (!isInstanceCall) {
            // we are creating instance / collection
            // - set the initial promise
            // - return the instance / collection
            value.$promise = promise;
            value.$resolved = false;

            return value;
          }

          // instance call
          return promise;
        };

        Resource.prototype['$' + name] = function(params, success, error) {
          if (isFunction(params)) {
            error = success; success = params; params = {};
          }
          var result = Resource[name].call(this, params, this, success, error);
          return result.$promise || result;
        };
      });

      Resource.bind = function(additionalParamDefaults){
        return resourceFactory(url, extend({}, paramDefaults, additionalParamDefaults), actions);
      };

      return Resource;
    }

    return resourceFactory;
  }]);

})(window, window.angular);
<commit_msg>Delete angular-resource.js<commit_after><|endoftext|>


<commit_before>/*
 * files.js: Instance methods for working with files from Google Cloud Storage
 *
 * (C) 2012 Nodejitsu Inc.
 *
 */

var pkgcloud = require('../../../../../lib/pkgcloud'),
  through = require('through2'),
  storage = pkgcloud.providers.google.storage,
  _ = require('underscore');

/**
 * Destroy a file in the specified container.
 *
 * @param {string} container - Name of the container to destroy the file in.
 * @param {string} file - Name of the file to destroy.
 * @param {function} callback - Continuation to respond to when complete.
 */
exports.removeFile = function (container, file, callback) {
  var bucket = this._getBucket(container),
    file = this._getFile(bucket, file);

  file.delete(function(err) {
    return err
      ? callback(err)
      : callback(null, true);
  });
};

/**
 * Upload a file to the specified bucket.
 *
 * @param {object} options - Configuration object.
 * @param {object} options.container - Container object for the file.
 * @param {object|string} options.file - The file to upload content to.
 * @return {stream}
 */
exports.upload = function (options) {
  var self = this,
    bucket = this._getBucket(options),
    file = this._getFile(bucket, options);

  // check for deprecated calling with a callback
  if (typeof arguments[arguments.length - 1] === 'function') {
    self.emit('log::warn', 'storage.upload no longer supports calling with a callback');
  }

  var proxyStream = through(),
    writableStream = file.createWriteStream();

  // we need a proxy stream so we can always return a file model
  // via the 'success' event
  writableStream.on('complete', function(file) {
    proxyStream.emit('success', new storage.File(self, file));
  });

  writableStream.on('error', function(err) {
    proxyStream.emit('error', err);
  });

  writableStream.on('data', function(chunk) {
    proxyStream.emit('data', chunk);
  });

  proxyStream.pipe(writableStream);

  return proxyStream;
};

/**
 * Download a file from the specified bucket.
 *
 * @param {object} options - Configuration object.
 * @param {object} options.container - Container object for the file.
 * @param {object|string} options.file - The file to upload content to.
 * @return {stream}
 */
exports.download = function (options) {
  var bucket = this._getBucket(options),
    file = this._getFile(bucket, options);

  return file.createReadStream(options);
};

exports.getFile = function (container, file, callback) {
  var self = this,
    bucket = this._getBucket(container),
    file = this._getFile(bucket, file);

  file.getMetadata(function(err, data) {
    return err
      ? callback(err)
      : callback(null, new storage.File(self, _.extend({ metadata: data }, {
      container: container
    })));
  });
};

/**
 * Get all of the files from a gcloud bucket.
 *
 * @param {object} container - Container object for the file.
 * @param {object=|function} options - Options or callback.
 * @param {string} options.maxResults - Maximum amount of results to fetch.
 * @param {function} callback - Continuation to respond to when complete.
 */
exports.getFiles = function (container, options, callback) {
  var self = this,
    bucket = this._getBucket(container);

  if (typeof options === 'function') {
    callback = options;
    options = {};
  }
  else if (!options) {
    options = {};
  }

  bucket.getFiles(options, function(err, files, nextQuery) {
    return err
      ? callback(err)
      : callback(null, files.map(function (file) {
      file.container = container;
      return new storage.File(self, file);
    }), nextQuery);
  });
};
<commit_msg>storage: google: upload: return metadata in success handler - fixes #400<commit_after>/*
 * files.js: Instance methods for working with files from Google Cloud Storage
 *
 * (C) 2012 Nodejitsu Inc.
 *
 */

var pkgcloud = require('../../../../../lib/pkgcloud'),
  through = require('through2'),
  storage = pkgcloud.providers.google.storage,
  _ = require('underscore');

/**
 * Destroy a file in the specified container.
 *
 * @param {string} container - Name of the container to destroy the file in.
 * @param {string} file - Name of the file to destroy.
 * @param {function} callback - Continuation to respond to when complete.
 */
exports.removeFile = function (container, file, callback) {
  var bucket = this._getBucket(container),
    file = this._getFile(bucket, file);

  file.delete(function(err) {
    return err
      ? callback(err)
      : callback(null, true);
  });
};

/**
 * Upload a file to the specified bucket.
 *
 * @param {object} options - Configuration object.
 * @param {object} options.container - Container object for the file.
 * @param {object|string} options.file - The file to upload content to.
 * @return {stream}
 */
exports.upload = function (options) {
  var self = this,
    bucket = this._getBucket(options),
    file = this._getFile(bucket, options);

  // check for deprecated calling with a callback
  if (typeof arguments[arguments.length - 1] === 'function') {
    self.emit('log::warn', 'storage.upload no longer supports calling with a callback');
  }

  var proxyStream = through(),
    writableStream = file.createWriteStream();

  // we need a proxy stream so we can always return a file model
  // via the 'success' event
  writableStream.on('complete', function() {
    proxyStream.emit('success', new storage.File(self, file));
  });

  writableStream.on('error', function(err) {
    proxyStream.emit('error', err);
  });

  writableStream.on('data', function(chunk) {
    proxyStream.emit('data', chunk);
  });

  proxyStream.pipe(writableStream);

  return proxyStream;
};

/**
 * Download a file from the specified bucket.
 *
 * @param {object} options - Configuration object.
 * @param {object} options.container - Container object for the file.
 * @param {object|string} options.file - The file to upload content to.
 * @return {stream}
 */
exports.download = function (options) {
  var bucket = this._getBucket(options),
    file = this._getFile(bucket, options);

  return file.createReadStream(options);
};

exports.getFile = function (container, file, callback) {
  var self = this,
    bucket = this._getBucket(container),
    file = this._getFile(bucket, file);

  file.getMetadata(function(err, data) {
    return err
      ? callback(err)
      : callback(null, new storage.File(self, _.extend({ metadata: data }, {
      container: container
    })));
  });
};

/**
 * Get all of the files from a gcloud bucket.
 *
 * @param {object} container - Container object for the file.
 * @param {object=|function} options - Options or callback.
 * @param {string} options.maxResults - Maximum amount of results to fetch.
 * @param {function} callback - Continuation to respond to when complete.
 */
exports.getFiles = function (container, options, callback) {
  var self = this,
    bucket = this._getBucket(container);

  if (typeof options === 'function') {
    callback = options;
    options = {};
  }
  else if (!options) {
    options = {};
  }

  bucket.getFiles(options, function(err, files, nextQuery) {
    return err
      ? callback(err)
      : callback(null, files.map(function (file) {
      file.container = container;
      return new storage.File(self, file);
    }), nextQuery);
  });
};
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2017-present, Shopgate, Inc. All rights reserved.
 *
 * This source code is licensed under the Apache 2.0 license found in the
 * LICENSE file in the root directory of this source tree.
 */

import { css } from 'glamor';
import colors from 'Styles/colors';
import variables from 'Styles/variables';

const container = css({
  position: 'relative',
}).toString();

const grid = css({
  alignItems: 'flex-start',
}).toString();

const icon = css({
  position: 'relative',
  top: variables.gap.big,
  width: 72,
  fontSize: '1.5rem',
  padding: `0 ${variables.gap.big * 2}px 0 ${variables.gap.big}px`,
  color: colors.shade11,
}).toString();

const labelBaseStyle = {
  display: 'flex',
  alignItems: 'flex-start',
  padding: `${variables.gap.big + 2}px 0`,
  fontSize: '0.875rem',
  fontWeight: 500,
};

const label = css(labelBaseStyle).toString();

const labelWithIndicator = css({
  ...labelBaseStyle,
  display: 'flex',
  justifyContent: 'space-between',
  paddingRight: 32,
  ':after': {
    background: colors.primary,
    borderRadius: '4.5px',
    content: ' ',
    display: 'inline-block',
    height: '9px',
    width: '9px',
    alignSelf: 'center',
    marginRight: -12,
  },
}).toString();

const count = css({
  backgroundColor: colors.primary,
  color: colors.primaryContrast,
  fontSize: '0.75rem',
  fontWeight: 700,
  height: variables.gap.big * 1.125,
  minWidth: variables.gap.big * 1.125,
  borderRadius: variables.gap.big * 1.125,
  position: 'relative',
  textAlign: 'center',
  padding: `0 ${variables.gap.small * 0.625}px`,
  margin: `${variables.gap.big * 1.1875}px ${variables.gap.big}px`,
}).toString();

const primary = css({
  background: colors.primary,
}).toString();

const primaryIcon = css({
  color: colors.primaryContrast,
}).toString();

export default {
  container,
  grid,
  icon,
  label,
  labelWithIndicator,
  count,
  primary,
  primaryIcon,
};
<commit_msg>CON-2766 - small styling fixes (code style and removed duplicated declaration)<commit_after>/**
 * Copyright (c) 2017-present, Shopgate, Inc. All rights reserved.
 *
 * This source code is licensed under the Apache 2.0 license found in the
 * LICENSE file in the root directory of this source tree.
 */

import { css } from 'glamor';
import colors from 'Styles/colors';
import variables from 'Styles/variables';

const container = css({
  position: 'relative',
}).toString();

const grid = css({
  alignItems: 'flex-start',
}).toString();

const icon = css({
  position: 'relative',
  top: variables.gap.big,
  width: 72,
  fontSize: '1.5rem',
  padding: `0 ${variables.gap.big * 2}px 0 ${variables.gap.big}px`,
  color: colors.shade11,
}).toString();

const labelBaseStyle = {
  display: 'flex',
  alignItems: 'flex-start',
  padding: `${variables.gap.big + 2}px 0`,
  fontSize: '0.875rem',
  fontWeight: 500,
};

const label = css(labelBaseStyle).toString();

const labelWithIndicator = css({
  ...labelBaseStyle,
  justifyContent: 'space-between',
  paddingRight: variables.gap.xbig,
  ':after': {
    background: colors.primary,
    borderRadius: '4.5px',
    content: ' ',
    display: 'inline-block',
    height: '9px',
    width: '9px',
    alignSelf: 'center',
    marginRight: -12,
  },
}).toString();

const count = css({
  backgroundColor: colors.primary,
  color: colors.primaryContrast,
  fontSize: '0.75rem',
  fontWeight: 700,
  height: variables.gap.big * 1.125,
  minWidth: variables.gap.big * 1.125,
  borderRadius: variables.gap.big * 1.125,
  position: 'relative',
  textAlign: 'center',
  padding: `0 ${variables.gap.small * 0.625}px`,
  margin: `${variables.gap.big * 1.1875}px ${variables.gap.big}px`,
}).toString();

const primary = css({
  background: colors.primary,
}).toString();

const primaryIcon = css({
  color: colors.primaryContrast,
}).toString();

export default {
  container,
  grid,
  icon,
  label,
  labelWithIndicator,
  count,
  primary,
  primaryIcon,
};
<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { getWidgetName, getContainerFromCurrentScript, createConfig } from 'widget'
import { configureAjaxHelper } from 'ajax_helper';
import { setPolicy } from 'policy';

let widgetName = getWidgetName(__dirname)
let scriptTagContainer = getContainerFromCurrentScript(widgetName)
let ajaxConfig = createConfig(scriptTagContainer.scriptParams, widgetName).ajaxHelper

configureAjaxHelper(ajaxConfig)

setPolicy()

ReactDOM.render(<App />, scriptTagContainer.reactContainer);
<commit_msg>[lbaas2]: load policy once the document is ready (#667)<commit_after>import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { getWidgetName, getContainerFromCurrentScript, createConfig } from 'widget'
import { configureAjaxHelper } from 'ajax_helper';
import { setPolicy } from 'policy';

const createNewConfig = (widgetName, scriptParams) => {
  // // document is not loaded yet -> create a new Promise and resolve it as soon
  // // as document is loaded.
  return new Promise((resolve, reject) => {
    document.addEventListener('DOMContentLoaded', () => {
      resolve(createConfig(widgetName, scriptTagContainer.scriptParams))
    })
  })
}

let widgetName = getWidgetName(__dirname)
let scriptTagContainer = getContainerFromCurrentScript(widgetName)
createNewConfig(widgetName, scriptTagContainer.scriptParams).then((config) => {
  configureAjaxHelper(config.ajaxHelper)
  setPolicy(config.policy)
  ReactDOM.render(<App />, scriptTagContainer.reactContainer);
})
<|endoftext|>


<commit_before>'use strict';

var propertiesTab = require('./tabs/propertiesTab'),
    is = require('../../utils/modelUtils').is,
    formatTab = require('./tabs/formatTab')
    ;

function PfdnPropertiesProvider(icons, entryFactory, eventBus, modelling) {
  this._icons = icons;
  this._entryFactory = entryFactory;
  this._eventBus = eventBus;
  this._modelling = modelling;
}

PfdnPropertiesProvider.$inject = [
  'icons',
  'entryFactory',
  'eventBus',
  'modelling'
];

module.exports = PfdnPropertiesProvider;

PfdnPropertiesProvider.prototype.updateDrawing = function(definition){
  if (is(definition, 'pfdn:Settings')){
    // trigger to redraw the axes
    this._eventBus.emit('canvas.resized');
  } else if (is(definition, 'pfdn:Label')){
    this._modelling._elements.label._labels.appendElement(definition);
  } else if (is(definition, 'pfdn:Link')){
    this._modelling._elements.link._links.appendElement(definition);
    this._modelling._elements.label._labels.appendElement(definition.label);
  } else if (is(definition, 'pfdn:Node')){
    this._modelling._elements.node._nodes.appendElement(definition);
    this._modelling._elements.label._labels.appendElement(definition.label);
  }
};

PfdnPropertiesProvider.prototype.getTabs = function(element){
  var icons = this._icons,
      entryFactory = this._entryFactory;
  return [
    propertiesTab(element, entryFactory),
    formatTab(element, entryFactory, icons)
  ];
};<commit_msg>new builder arch<commit_after>'use strict';

var propertiesTab = require('./tabs/propertiesTab'),
    is = require('../../utils/modelUtils').is,
    formatTab = require('./tabs/formatTab')
    ;

function PfdnPropertiesProvider(icons, entryFactory, eventBus, modelling) {
  this._icons = icons;
  this._entryFactory = entryFactory;
  this._eventBus = eventBus;
  this._modelling = modelling;
}

PfdnPropertiesProvider.$inject = [
  'icons',
  'entryFactory',
  'eventBus',
  'modelling'
];

module.exports = PfdnPropertiesProvider;

PfdnPropertiesProvider.prototype.updateDrawing = function(definition){
  if (is(definition, 'pfdn:Settings')){
    // trigger to redraw the axes
    this._eventBus.emit('canvas.resized');
  } else if (is(definition, 'pfdn:Label')){
    this._modelling._elements.label._labels._builder(definition.id, definition);
  } else if (is(definition, 'pfdn:Link')){
    this._modelling._elements.link._links.appendElement(definition.id, definition);
    this._modelling._elements.label._labels.appendElement(definition.label.id, definition.label);
  } else if (is(definition, 'pfdn:Node')){
    this._modelling._elements.node._nodes.appendElement(definition.id, definition);
    this._modelling._elements.label._labels.appendElement(definition.label.id, definition.label);
  }
};

PfdnPropertiesProvider.prototype.getTabs = function(element){
  var icons = this._icons,
      entryFactory = this._entryFactory;
  return [
    propertiesTab(element, entryFactory),
    formatTab(element, entryFactory, icons)
  ];
};<|endoftext|>