<commit_before>'use strict';

const InputBuffer = require('iobuffer').InputBuffer;
const Inflator = require('pako').Inflate;

const empty = new Uint8Array(0);
const NULL = '\0';
const pngSignature = [137, 80, 78, 71, 13, 10, 26, 10];

class PNGDecoder extends InputBuffer {
    constructor(data) {
        var b = data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);
        super(b);
        this._decoded = false;
        this._inflator = new Inflator();
        this._png = null;
        this._end = false;
        // PNG is always big endian
        // http://www.w3.org/TR/PNG/#7Integers-and-byte-order
        this.setBigEndian();
    }

    decode() {
        if (this._decoded) return this._png;
        this._png = {
            tEXt: {}
        };
        this.decodeSignature();
        while (!this._end) {
            this.decodeChunk();
        }
        this.decodeImage();
        return this._png;
    }

    // http://www.w3.org/TR/PNG/#5PNG-file-signature
    decodeSignature() {
        for (var i = 0; i < 8; i++) {
            if (this.readUint8() !== pngSignature[i]) {
                throw new Error(`Wrong PNG signature. Byte at ${i} should be ${pngSignature[i]}.`);
            }
        }
    }

    // http://www.w3.org/TR/PNG/#5Chunk-layout
    decodeChunk() {
        var length = this.readUint32();
        var type = this.readChars(4);
        var offset = this.offset;
        console.log(type);
        switch (type) {
            case 'IHDR':
                this.decodeIHDR();
                break;
            case 'PLTE':
                throw new Error('Palette image type not supported');
            case 'IDAT':
                this.decodeIDAT(length);
                break;
            case 'tEXt':
                this.decodetEXt(length);
                break;
            case 'IEND':
                this._end = true;
                break;
            default:
                this.skip(length);
                break;
        }
        if (this.offset - offset !== length) {
            throw new Error('Length mismatch while decoding chunk ' + type);
        }
        // TODO compute and validate CRC ?
        // http://www.w3.org/TR/PNG/#5CRC-algorithm
        var crc = this.readUint32();
    }

    // http://www.w3.org/TR/PNG/#11IHDR
    decodeIHDR() {
        var image = this._png;
        image.width = this.readUint32();
        image.height = this.readUint32();
        image.bitDepth = this.readUint8();
        image.colourType = this.readUint8();
        image.compressionMethod = this.readUint8();
        image.filterMethod = this.readUint8();
        image.interlaceMethod = this.readUint8();
        if (this._png.compressionMethod !== 0) {
            throw new Error('Unsupported compression method: ' + image.compressionMethod);
        }
    }

    // http://www.w3.org/TR/PNG/#11IDAT
    decodeIDAT(length) {
        this._inflator.push(this.readBytes(length));
    }

    // http://www.w3.org/TR/PNG/#11tEXt
    decodetEXt(length) {
        var keyword = '';
        var char;
        while ((char = this.readChar()) !== NULL) {
            keyword += char;
        }
        this._png.tEXt[keyword] = this.readChars(length - keyword.length - 1);
    }

    decodeImage() {
        this._inflator.push(empty, true);
        if (this._inflator.err) {
            throw new Error('Error while decompressing the data');
        }
        var data = this._inflator.result;
        this._inflator = null;

        if (this._png.filterMethod !== 0) {
            throw new Error('Filter method ' + this._png.interlaceMethod + ' not supported');
        }

        if (this._png.interlaceMethod === 0) {
            this.decodeInterlaceNull(data);
        } else {
            throw new Error('Interlace method ' + this._png.interlaceMethod + ' not supported');
        }
    }

    decodeInterlaceNull(data) {

        var channels;
        switch (this._png.colourType) {
            case 0: channels = 1; break;
            case 2: channels = 3; break;
            case 3: throw new Error('Indexed-colour images are not supported');
            case 4: channels = 2; break;
            case 6: channels = 4; break;
            default: throw new Error('Unknown colour type: ' + this._png.colourType);
        }

        const height = this._png.height;
        const bytesPerPixel = channels * this._png.bitDepth / 8;
        const bytesPerLine = this._png.width * bytesPerPixel;
        const newData = new Uint8Array(this._png.height * bytesPerLine);

        var prevLine = new Uint8Array(bytesPerLine);
        var offset = 0;
        var currentLine, newLine;

        for (var i = 0; i < height; i++) {
            currentLine = data.subarray(offset + 1, offset + 1 + bytesPerLine);
            newLine = newData.subarray(i * bytesPerLine, offset + 1 + bytesPerLine);
            switch (data[offset]) {
                case 0:
                    unfilterNone(currentLine, newLine, bytesPerLine);
                    break;
                case 1:
                    unfilterSub(currentLine, newLine, bytesPerLine, bytesPerPixel);
                    break;
                case 2:
                    unfilterUp(currentLine, newLine, prevLine, bytesPerLine);
                    break;
                case 3:
                    unfilterAverage(currentLine, newLine, prevLine, bytesPerLine, bytesPerPixel);
                    break;
                case 4:
                    unfilterPaeth(currentLine, newLine, prevLine, bytesPerLine, bytesPerPixel);
                    break;
                default: throw new Error('Unsupported filter: ' + data[offset]);
            }
            prevLine = newLine;
            offset += bytesPerLine + 1;
        }

        this._png.data = newData;
    }

}

module.exports = PNGDecoder;

function unfilterNone(currentLine, newLine, bytesPerLine) {
    for(var i = 0; i < bytesPerLine; i++) {
        newLine[i] = currentLine[i];
    }
}

function unfilterSub(currentLine, newLine, bytesPerLine, bytesPerPixel) {
    for(var i = 0; i < bytesPerLine; i++) {
        newLine[i] = (currentLine[i] + currentLine[i - bytesPerPixel])&0xFF;
    }
}

function unfilterUp(currentLine, newLine, prevLine, bytesPerLine) {
    for(var i = 0; i < bytesPerLine; i++) {
        newLine[i] = (currentLine[i] + prevLine[i])&0xFF;
    }
}

function unfilterAverage(currentLine, newLine, prevLine, bytesPerLine, bytesPerPixel) {
    for(var i = 0; i < bytesPerLine; i++) {
        newLine[i] = (currentLine[i] + Math.floor(currentLine[i - bytesPerPixel] + prevLine[i]))&0xFF;
    }
}

function unfilterPaeth(currentLine, newLine, prevLine, bytesPerLine, bytesPerPixel) {
    for(var i = 0; i < bytesPerLine; i++) {
        newLine[i] = (currentLine[i] + paethPredictor(currentLine[i - bytesPerPixel], prevLine[i], prevLine[i - bytesPerPixel]))&0xFF;
    }
}

function paethPredictor(a, b, c) {
    var p = a + b - c;
    var pa = Math.abs(p - a);
    var pb = Math.abs(p - b);
    var pc = Math.abs(p - c);
    if (pa <= pb && pa <= pc) return a;
    else if (pb <= pc) return b;
    else return c;
}
<commit_msg>fix subarray again<commit_after>'use strict';

const InputBuffer = require('iobuffer').InputBuffer;
const Inflator = require('pako').Inflate;

const empty = new Uint8Array(0);
const NULL = '\0';
const pngSignature = [137, 80, 78, 71, 13, 10, 26, 10];

class PNGDecoder extends InputBuffer {
    constructor(data) {
        var b = data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);
        super(b);
        this._decoded = false;
        this._inflator = new Inflator();
        this._png = null;
        this._end = false;
        // PNG is always big endian
        // http://www.w3.org/TR/PNG/#7Integers-and-byte-order
        this.setBigEndian();
    }

    decode() {
        if (this._decoded) return this._png;
        this._png = {
            tEXt: {}
        };
        this.decodeSignature();
        while (!this._end) {
            this.decodeChunk();
        }
        this.decodeImage();
        return this._png;
    }

    // http://www.w3.org/TR/PNG/#5PNG-file-signature
    decodeSignature() {
        for (var i = 0; i < 8; i++) {
            if (this.readUint8() !== pngSignature[i]) {
                throw new Error(`Wrong PNG signature. Byte at ${i} should be ${pngSignature[i]}.`);
            }
        }
    }

    // http://www.w3.org/TR/PNG/#5Chunk-layout
    decodeChunk() {
        var length = this.readUint32();
        var type = this.readChars(4);
        var offset = this.offset;
        console.log(type);
        switch (type) {
            case 'IHDR':
                this.decodeIHDR();
                break;
            case 'PLTE':
                throw new Error('Palette image type not supported');
            case 'IDAT':
                this.decodeIDAT(length);
                break;
            case 'tEXt':
                this.decodetEXt(length);
                break;
            case 'IEND':
                this._end = true;
                break;
            default:
                this.skip(length);
                break;
        }
        if (this.offset - offset !== length) {
            throw new Error('Length mismatch while decoding chunk ' + type);
        }
        // TODO compute and validate CRC ?
        // http://www.w3.org/TR/PNG/#5CRC-algorithm
        var crc = this.readUint32();
    }

    // http://www.w3.org/TR/PNG/#11IHDR
    decodeIHDR() {
        var image = this._png;
        image.width = this.readUint32();
        image.height = this.readUint32();
        image.bitDepth = this.readUint8();
        image.colourType = this.readUint8();
        image.compressionMethod = this.readUint8();
        image.filterMethod = this.readUint8();
        image.interlaceMethod = this.readUint8();
        if (this._png.compressionMethod !== 0) {
            throw new Error('Unsupported compression method: ' + image.compressionMethod);
        }
    }

    // http://www.w3.org/TR/PNG/#11IDAT
    decodeIDAT(length) {
        this._inflator.push(this.readBytes(length));
    }

    // http://www.w3.org/TR/PNG/#11tEXt
    decodetEXt(length) {
        var keyword = '';
        var char;
        while ((char = this.readChar()) !== NULL) {
            keyword += char;
        }
        this._png.tEXt[keyword] = this.readChars(length - keyword.length - 1);
    }

    decodeImage() {
        this._inflator.push(empty, true);
        if (this._inflator.err) {
            throw new Error('Error while decompressing the data');
        }
        var data = this._inflator.result;
        this._inflator = null;

        if (this._png.filterMethod !== 0) {
            throw new Error('Filter method ' + this._png.interlaceMethod + ' not supported');
        }

        if (this._png.interlaceMethod === 0) {
            this.decodeInterlaceNull(data);
        } else {
            throw new Error('Interlace method ' + this._png.interlaceMethod + ' not supported');
        }
    }

    decodeInterlaceNull(data) {

        var channels;
        switch (this._png.colourType) {
            case 0: channels = 1; break;
            case 2: channels = 3; break;
            case 3: throw new Error('Indexed-colour images are not supported');
            case 4: channels = 2; break;
            case 6: channels = 4; break;
            default: throw new Error('Unknown colour type: ' + this._png.colourType);
        }

        const height = this._png.height;
        const bytesPerPixel = channels * this._png.bitDepth / 8;
        const bytesPerLine = this._png.width * bytesPerPixel;
        const newData = new Uint8Array(this._png.height * bytesPerLine);

        var prevLine = new Uint8Array(bytesPerLine);
        var offset = 0;
        var currentLine, newLine;

        for (var i = 0; i < height; i++) {
            currentLine = data.subarray(offset + 1, offset + 1 + bytesPerLine);
            newLine = newData.subarray(i * bytesPerLine, (i + 1) * bytesPerLine);
            switch (data[offset]) {
                case 0:
                    unfilterNone(currentLine, newLine, bytesPerLine);
                    break;
                case 1:
                    unfilterSub(currentLine, newLine, bytesPerLine, bytesPerPixel);
                    break;
                case 2:
                    unfilterUp(currentLine, newLine, prevLine, bytesPerLine);
                    break;
                case 3:
                    unfilterAverage(currentLine, newLine, prevLine, bytesPerLine, bytesPerPixel);
                    break;
                case 4:
                    unfilterPaeth(currentLine, newLine, prevLine, bytesPerLine, bytesPerPixel);
                    break;
                default: throw new Error('Unsupported filter: ' + data[offset]);
            }
            prevLine = newLine;
            offset += bytesPerLine + 1;
        }

        this._png.data = newData;
    }

}

module.exports = PNGDecoder;

function unfilterNone(currentLine, newLine, bytesPerLine) {
    for(var i = 0; i < bytesPerLine; i++) {
        newLine[i] = currentLine[i];
    }
}

function unfilterSub(currentLine, newLine, bytesPerLine, bytesPerPixel) {
    for(var i = 0; i < bytesPerLine; i++) {
        newLine[i] = (currentLine[i] + currentLine[i - bytesPerPixel])&0xFF;
    }
}

function unfilterUp(currentLine, newLine, prevLine, bytesPerLine) {
    for(var i = 0; i < bytesPerLine; i++) {
        newLine[i] = (currentLine[i] + prevLine[i])&0xFF;
    }
}

function unfilterAverage(currentLine, newLine, prevLine, bytesPerLine, bytesPerPixel) {
    for(var i = 0; i < bytesPerLine; i++) {
        newLine[i] = (currentLine[i] + Math.floor(currentLine[i - bytesPerPixel] + prevLine[i]))&0xFF;
    }
}

function unfilterPaeth(currentLine, newLine, prevLine, bytesPerLine, bytesPerPixel) {
    for(var i = 0; i < bytesPerLine; i++) {
        newLine[i] = (currentLine[i] + paethPredictor(currentLine[i - bytesPerPixel], prevLine[i], prevLine[i - bytesPerPixel]))&0xFF;
    }
}

function paethPredictor(a, b, c) {
    var p = a + b - c;
    var pa = Math.abs(p - a);
    var pb = Math.abs(p - b);
    var pc = Math.abs(p - c);
    if (pa <= pb && pa <= pc) return a;
    else if (pb <= pc) return b;
    else return c;
}
<|endoftext|>


<commit_before>/*!
 * Bootstrap Context Menu
 * Author: @sydcanem
 * https://github.com/sydcanem/bootstrap-contextmenu
 *
 * Inspired by Bootstrap's dropdown plugin.
 * Bootstrap (http://getbootstrap.com).
 *
 * Licensed under MIT
 * ========================================================= */

(function (root, factory) {
	if (typeof define === 'function' && define.amd) {
		define(['jquery'], factory);
	} else if (typeof exports === 'object') {
		module.exports = factory(require('jquery'));
	} else {
		factory(root.jQuery);
	}
}(this, function ($) {
	'use strict';

	/* CONTEXTMENU CLASS DEFINITION
	 * ============================ */
	var toggle = '[data-toggle="context"]';

	var ContextMenu = function (element, options) {
		this.$element = $(element);

		this.before = options.before || this.before;
		this.onItem = options.onItem || this.onItem;
		this.scopes = options.scopes || null;

		if (options.target) {
			this.$element.data('target', options.target);
		}

		this.listen();
	};

	ContextMenu.prototype = {

		constructor: ContextMenu
		,show: function(e) {

			var $menu
				, evt
				, tp
				, items
				, relatedTarget = { relatedTarget: this, target: e.currentTarget };

			if (this.isDisabled()) return;

			this.closemenu();

			if (!this.before.call(this,e,$(e.currentTarget))) return;

			$menu = this.getMenu();
			$menu.trigger(evt = $.Event('show.bs.context', relatedTarget));

			tp = this.getPosition(e, $menu);
			items = 'li:not(.dropdown-divider, dropdown-header)';
			$menu.attr('style', '')
				.css(tp)
				.addClass('open')
				.on('click.context.data-api', items, $.proxy(this.onItem, this, $(e.currentTarget)))
				.trigger('shown.bs.context', relatedTarget);
			$menu.find('.dropdown-menu').addClass('show');
			// Delegating the `closemenu` only on the currently opened menu.
			// This prevents other opened menus from closing.
			$('html')
				.on('click.context.data-api', $menu.selector, $.proxy(this.closemenu, this));

			return false;
		}

		,closemenu: function(e) {
			var $menu
				, evt
				, items
				, relatedTarget;

			$menu = this.getMenu();

			if(!$menu.hasClass('open')) return;

			relatedTarget = { relatedTarget: this };
			$menu.trigger(evt = $.Event('hide.bs.context', relatedTarget));

			items = 'li:not(.dropdown-divider, .dropdown-header)';
			$menu.find('.dropdown-menu').removeClass('show');
			$menu.removeClass('open')
				.off('click.context.data-api', items)
				.trigger('hidden.bs.context', relatedTarget);

			$('html')
				.off('click.context.data-api', $menu.selector);
			// Don't propagate click event so other currently
			// opened menus won't close.
			return false;
		}

		,keydown: function(e) {
			if (e.which == 27) this.closemenu(e);
		}

		,before: function(e) {
			return true;
		}

		,onItem: function(e) {
			return true;
		}

		,listen: function () {
			this.$element.on('contextmenu.context.data-api', this.scopes, $.proxy(this.show, this));
			$('html').on('click.context.data-api', $.proxy(this.closemenu, this));
			$('html').on('keydown.context.data-api', $.proxy(this.keydown, this));
		}

		,destroy: function() {
			this.$element.off('.context.data-api').removeData('context');
			$('html').off('.context.data-api');
		}

		,isDisabled: function() {
			return this.$element.hasClass('disabled') ||
					this.$element.attr('disabled');
		}

		,getMenu: function () {
			var selector = this.$element.data('target')
				, $menu;

			if (!selector) {
				selector = this.$element.attr('href');
				selector = selector && selector.replace(/.*(?=#[^\s]*$)/, ''); //strip for ie7
			}

			$menu = $(selector);

			return $menu && $menu.length ? $menu : this.$element.find(selector);
		}

		,getPosition: function(e, $menu) {
			var mouseX = e.clientX
				, mouseY = e.clientY
				, boundsX = $(window).width()
				, boundsY = $(window).height()
				, menuWidth = $menu.find('.dropdown-menu').outerWidth()
				, menuHeight = $menu.find('.dropdown-menu').outerHeight()
				, tp = {"position":"absolute","z-index":9999}
				, Y, X, parentOffset;

			if (mouseY + menuHeight > boundsY) {
				Y = {"top": mouseY - menuHeight + $(window).scrollTop()};
			} else {
				Y = {"top": mouseY + $(window).scrollTop()};
			}

			if ((mouseX + menuWidth > boundsX) && ((mouseX - menuWidth) > 0)) {
				X = {"left": mouseX - menuWidth + $(window).scrollLeft()};
			} else {
				X = {"left": mouseX + $(window).scrollLeft()};
			}

			// If context-menu's parent is positioned using absolute or relative positioning,
			// the calculated mouse position will be incorrect.
			// Adjust the position of the menu by its offset parent position.
			parentOffset = $menu.offsetParent().offset();
			X.left = X.left - parentOffset.left;
			Y.top = Y.top - parentOffset.top;

			return $.extend(tp, Y, X);
		}

	};

	/* CONTEXT MENU PLUGIN DEFINITION
	 * ========================== */

	$.fn.contextmenu = function (option,e) {
		return this.each(function () {
			var $this = $(this)
				, data = $this.data('context')
				, options = (typeof option == 'object') && option;
			if (!data) $this.data('context', (data = new ContextMenu($this, options)));
			if (typeof option == 'string') data[option].call(data, e);
		});
	};

	$.fn.contextmenu.Constructor = ContextMenu;

	/* APPLY TO STANDARD CONTEXT MENU ELEMENTS
	 * =================================== */

	$(document)
	   .on('contextmenu.context.data-api', function() {
			$(toggle).each(function () {
				var data = $(this).data('context');
				if (!data) return;
				data.closemenu();
			});
		})
		.on('contextmenu.context.data-api', toggle, function(e) {
			$(this).contextmenu('show', e);
			e.preventDefault();
			e.stopPropagation();
		});

}));
<commit_msg>Fixed the double triggering of the 'click' event on the context menu<commit_after>/*!
 * Bootstrap Context Menu
 * Author: @sydcanem
 * https://github.com/sydcanem/bootstrap-contextmenu
 *
 * Inspired by Bootstrap's dropdown plugin.
 * Bootstrap (http://getbootstrap.com).
 *
 * Licensed under MIT
 * ========================================================= */

(function (root, factory) {
	if (typeof define === 'function' && define.amd) {
		define(['jquery'], factory);
	} else if (typeof exports === 'object') {
		module.exports = factory(require('jquery'));
	} else {
		factory(root.jQuery);
	}
}(this, function ($) {
	'use strict';

	/* CONTEXTMENU CLASS DEFINITION
	 * ============================ */
	var toggle = '[data-toggle="context"]';

	var ContextMenu = function (element, options) {
		this.$element = $(element);

		this.before = options.before || this.before;
		this.onItem = options.onItem || this.onItem;
		this.scopes = options.scopes || null;

		if (options.target) {
			this.$element.data('target', options.target);
		}

		this.listen();
	};

	ContextMenu.prototype = {

		constructor: ContextMenu
		,show: function(e) {

			var $menu
				, evt
				, tp
				, items
				, relatedTarget = { relatedTarget: this, target: e.currentTarget };

			if (this.isDisabled()) return;

			this.closemenu();

			if (!this.before.call(this,e,$(e.currentTarget))) return;

			$menu = this.getMenu();
			$menu.trigger(evt = $.Event('show.bs.context', relatedTarget));

			tp = this.getPosition(e, $menu);
			items = 'li:visible a';
			$menu.attr('style', '')
				.css(tp)
				.addClass('open')
				.on('click.context.data-api', items, $.proxy(this.onItem, this, $(e.currentTarget)))
				.trigger('shown.bs.context', relatedTarget);
			$menu.find('.dropdown-menu').addClass('show');
			// Delegating the `closemenu` only on the currently opened menu.
			// This prevents other opened menus from closing.
			$('html')
				.on('click.context.data-api', $menu.selector, $.proxy(this.closemenu, this));

			return false;
		}

		,closemenu: function(e) {
			var $menu
				, evt
				, items
				, relatedTarget;

			$menu = this.getMenu();

			if(!$menu.hasClass('open')) return;

			relatedTarget = { relatedTarget: this };
			$menu.trigger(evt = $.Event('hide.bs.context', relatedTarget));

			items = 'li:visible a';
			$menu.find('.dropdown-menu').removeClass('show');
			$menu.removeClass('open')
				.off('click.context.data-api', items)
				.trigger('hidden.bs.context', relatedTarget);

			$('html')
				.off('click.context.data-api', $menu.selector);
			// Don't propagate click event so other currently
			// opened menus won't close.
			return false;
		}

		,keydown: function(e) {
			if (e.which == 27) this.closemenu(e);
		}

		,before: function(e) {
			return true;
		}

		,onItem: function(e) {
			return true;
		}

		,listen: function () {
			this.$element.on('contextmenu.context.data-api', this.scopes, $.proxy(this.show, this));
			$('html').on('click.context.data-api', $.proxy(this.closemenu, this));
			$('html').on('keydown.context.data-api', $.proxy(this.keydown, this));
		}

		,destroy: function() {
			this.$element.off('.context.data-api').removeData('context');
			$('html').off('.context.data-api');
		}

		,isDisabled: function() {
			return this.$element.hasClass('disabled') ||
					this.$element.attr('disabled');
		}

		,getMenu: function () {
			var selector = this.$element.data('target')
				, $menu;

			if (!selector) {
				selector = this.$element.attr('href');
				selector = selector && selector.replace(/.*(?=#[^\s]*$)/, ''); //strip for ie7
			}

			$menu = $(selector);

			return $menu && $menu.length ? $menu : this.$element.find(selector);
		}

		,getPosition: function(e, $menu) {
			var mouseX = e.clientX
				, mouseY = e.clientY
				, boundsX = $(window).width()
				, boundsY = $(window).height()
				, menuWidth = $menu.find('.dropdown-menu').outerWidth()
				, menuHeight = $menu.find('.dropdown-menu').outerHeight()
				, tp = {"position":"absolute","z-index":9999}
				, Y, X, parentOffset;

			if (mouseY + menuHeight > boundsY) {
				Y = {"top": mouseY - menuHeight + $(window).scrollTop()};
			} else {
				Y = {"top": mouseY + $(window).scrollTop()};
			}

			if ((mouseX + menuWidth > boundsX) && ((mouseX - menuWidth) > 0)) {
				X = {"left": mouseX - menuWidth + $(window).scrollLeft()};
			} else {
				X = {"left": mouseX + $(window).scrollLeft()};
			}

			// If context-menu's parent is positioned using absolute or relative positioning,
			// the calculated mouse position will be incorrect.
			// Adjust the position of the menu by its offset parent position.
			parentOffset = $menu.offsetParent().offset();
			X.left = X.left - parentOffset.left;
			Y.top = Y.top - parentOffset.top;

			return $.extend(tp, Y, X);
		}

	};

	/* CONTEXT MENU PLUGIN DEFINITION
	 * ========================== */

	$.fn.contextmenu = function (option,e) {
		return this.each(function () {
			var $this = $(this)
				, data = $this.data('context')
				, options = (typeof option == 'object') && option;
			if (!data) $this.data('context', (data = new ContextMenu($this, options)));
			if (typeof option == 'string') data[option].call(data, e);
		});
	};

	$.fn.contextmenu.Constructor = ContextMenu;

	/* APPLY TO STANDARD CONTEXT MENU ELEMENTS
	 * =================================== */

	$(document)
	   .on('contextmenu.context.data-api', function() {
			$(toggle).each(function () {
				var data = $(this).data('context');
				if (!data) return;
				data.closemenu();
			});
		})
		.on('contextmenu.context.data-api', toggle, function(e) {
			$(this).contextmenu('show', e);
			e.preventDefault();
			e.stopPropagation();
		});

}));
<|endoftext|>


<commit_before>module.exports = {
  "extend": {
    "sizing": {
      "width": {
        "128": "32rem",
      }
    },
    "spacing": {
      "padding": {
        "12": "3rem",
        "16": "4rem"
      },
      "margin": {
        "12": "3rem",
        "16": "4rem"
      },
      "negativeMargin": {
        "12": "3rem",
        "16": "4rem"
      },
    }
  }
}
<commit_msg>Update to latest default config as base<commit_after>var colors = {
  'black': '#000000',
  'white': '#ffffff',
  'transparent': 'transparent',

  'slate-darker': '#212b35',
  'slate-dark': '#404e5c',
  'slate': '#647382',
  'slate-light': '#919eab',
  'slate-lighter': '#c5ced6',

  'smoke-darker': '#919eab',
  'smoke-dark': '#c5ced6',
  'smoke': '#dfe3e8',
  'smoke-light': '#f0f2f5',
  'smoke-lighter': '#f7f9fa',

  'red-darker': '#960f0d',
  'red-dark': '#d43633',
  'red': '#f25451',
  'red-light': '#fa8785',
  'red-lighter': '#fff1f0',

  'orange-darker': '#875200',
  'orange-dark': '#f29500',
  'orange': '#ffb82b',
  'orange-light': '#ffd685',
  'orange-lighter': '#fff8eb',

  'yellow-darker': '#966100',
  'yellow-dark': '#ffc400',
  'yellow': '#ffe14a',
  'yellow-light': '#ffea83',
  'yellow-lighter': '#fffbe5',

  'green-darker': '#056619',
  'green-dark': '#34ae4c',
  'green': '#57d06f',
  'green-light': '#b1f3be',
  'green-lighter': '#eefff1',

  'teal-darker': '#025654',
  'teal-dark': '#249e9a',
  'teal': '#4dc0b5',
  'teal-light': '#9eebe4',
  'teal-lighter': '#e8fdfa',

  'blue-darker': '#154267',
  'blue-dark': '#3687c8',
  'blue': '#4aa2ea',
  'blue-light': '#acdaff',
  'blue-lighter': '#f1f9ff',

  'indigo-darker': '#242b54',
  'indigo-dark': '#4957a5',
  'indigo': '#6574cd',
  'indigo-light': '#bcc5fb',
  'indigo-lighter': '#f4f5ff',

  'purple-darker': '#331f56',
  'purple-dark': '#714cb4',
  'purple': '#976ae6',
  'purple-light': '#ceb3ff',
  'purple-lighter': '#f7f3ff',

  'pink-darker': '#6b2052',
  'pink-dark': '#d84f7d',
  'pink': '#f66d9b',
  'pink-light': '#ffa5c3',
  'pink-lighter': '#fdf2f5',
}

module.exports = {
  colors: colors,
  screens: {
    sm: '576px',
    md: '768px',
    lg: '992px',
    xl: '1200px',
  },
  text: {
    fonts: {
      'sans': '-apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen, Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue',
      'serif': 'Constantia, "Lucida Bright", Lucidabright, "Lucida Serif", Lucida, "DejaVu Serif", "Bitstream Vera Serif", "Liberation Serif", Georgia, serif',
      'mono': 'Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace',
    },
    sizes: {
      'base': '1rem', // 16px
      'xs': '.75rem', // 12px
      'sm': '.875rem', // 14px
      'md': '1rem', // 16px
      'lg': '1.125rem', // 18px
      'xl': '1.25rem', // 20px
      '2xl': '1.75rem', // 28px
      '3xl': '2.375rem', // 38px
      '4xl': '2.875rem', // 46px
    },
    weights: {
      'hairline': 100,
      'thin': 200,
      'light': 300,
      'normal': 400,
      'medium': 500,
      'semibold': 600,
      'bold': 700,
      'extrabold': 800,
      'black': 900,
    },
    leading: {
      'none': 1,
      'tight': 1.25,
      'normal': 1.5,
      'loose': 2,
    },
    tracking: {
      'tight': '-0.05em',
      'normal': '0',
      'wide': '0.1em',
    },
    colors: {
      ...colors
    },
  },
  backgrounds: {
    colors: {
      ...colors
    },
  },
  borders: {
    widths: {
      default: '1px',
      '0': '0',
      '2': '2px',
      '4': '4px',
      '8': '8px',
    },
    colors: {
      default: colors['slate-lighter'],
      ...colors
    },
  },
  radiuses: {
    default: '.25rem',
    sm: '.125rem',
    lg: '.5rem',
    pill: '9999px',
  },
  sizing: {
    width: {
      'auto': 'auto',
      'px': '1px',
      '1': '0.25rem',
      '2': '0.5rem',
      '3': '0.75rem',
      '4': '1rem',
      '6': '1.5rem',
      '8': '2rem',
      '10': '2.5rem',
      '12': '3rem',
      '16': '4rem',
      '24': '6rem',
      '32': '8rem',
      '48': '12rem',
      '64': '16rem',
      '128': '32rem',
      '1/2': '50%',
      '1/3': '33.33333%',
      '2/3': '66.66667%',
      '1/4': '25%',
      '3/4': '75%',
      '1/5': '20%',
      '2/5': '40%',
      '3/5': '60%',
      '4/5': '80%',
      '1/6': '16.66667%',
      '5/6': '83.33333%',
      'full': '100%',
      'screen': '100vw'
    },
    height: {
      'auto': 'auto',
      'px': '1px',
      '1': '0.25rem',
      '2': '0.5rem',
      '3': '0.75rem',
      '4': '1rem',
      '6': '1.5rem',
      '8': '2rem',
      '10': '2.5rem',
      '12': '3rem',
      '16': '4rem',
      '24': '6rem',
      '32': '8rem',
      '48': '12rem',
      '64': '16rem',
      'full': '100%',
      'screen': '100vh'
    },
    minHeight: {
      '0': '0',
      'full': '100%',
      'screen': '100vh'
    },
    maxHeight: {
      'full': '100%',
      'screen': '100vh'
    },
    minWidth: {
      '0': '0',
      'full': '100%',
    },
    maxWidth: {
      'xs': '20rem',
      'sm': '30rem',
      'md': '40rem',
      'lg': '50rem',
      'xl': '60rem',
      '2xl': '70rem',
      '3xl': '80rem',
      '4xl': '90rem',
      '5xl': '100rem',
      'full': '100%',
    },
  },
  spacing: {
    padding: {
      'px': '1px',
      '0': '0',
      '1': '0.25rem',
      '2': '0.5rem',
      '3': '0.75rem',
      '4': '1rem',
      '6': '1.5rem',
      '8': '2rem',
      '12': '3rem',
      '16': '4rem'
    },
    margin: {
      'px': '1px',
      '0': '0',
      '1': '0.25rem',
      '2': '0.5rem',
      '3': '0.75rem',
      '4': '1rem',
      '6': '1.5rem',
      '8': '2rem',
      '12': '3rem',
      '16': '4rem'
    },
    negativeMargin: {
      'px': '1px',
      '0': '0',
      '1': '0.25rem',
      '2': '0.5rem',
      '3': '0.75rem',
      '4': '1rem',
      '6': '1.5rem',
      '8': '2rem',
      '12': '3rem',
      '16': '4rem'
    },
  },
  shadows: {
    default: '0 1px 3px rgba(0,0,0,.08), 0 1px 2px rgba(0,0,0,.15)',
    md: '0 3px 6px rgba(0,0,0,.12), 0 3px 6px rgba(0,0,0,.13)',
    lg: '0 10px 20px rgba(0,0,0,.13), 0 6px 6px rgba(0,0,0,.13)',
    inner: 'inset 0 1px 2px rgba(0, 0, 0, 0.05)',
    none: 'none',
  },
  zIndex: {
    '0': 0,
    '10': 10,
    '20': 20,
    '30': 30,
    '40': 40,
    '50': 50,
    'auto': 'auto',
  },
  opacity: {
    '0': '0',
    '25': '.25',
    '50': '.5',
    '75': '.75',
    '100': '1',
  },
}
<|endoftext|>


<commit_before>/* Substitute.js -- Scans and resolves placeholders in annotations
 *
 * Copyright (C) 2016 Michael Seibt
 *
 * With contributions from: -
 *
 * This software may be modified and distributed under the terms
 * of the MIT license. See the LICENSE file for details.
 */

'use strict';

var _ = require('lodash');
var Verbose = require('./Verbose');

var Substitute = {
  map: {},
  methods: {},
  staticLipsum: false
};

Substitute.injectConfig = function ( config ) {
  this.staticLipsum = config.staticLipsum;
  return this;
};

Substitute.process = function ( styles ) {

  var style, s, markup;

  // First, collect a map of all selector styles with markup annotation
  for(s in styles) {
    style = styles[s];
    var selector = _.get(style, 'element.selector');
    markup = _.get(style, 'annotations.markup');
    if(selector && markup && (selector.indexOf(':') === -1)){
      this.map[selector] = markup;
    }
  }

  // Loop through all styles again and apply substitutions
  for(s in styles) {
    style = styles[s];
    markup = _.get(style, 'annotations.markup');
    if(markup) {
      _.set(style, 'annotations.markup', this.substitute(markup));
    }
  }

  return styles;
};

Substitute.substitute = function ( markup ) {
  if(_.isEmpty(markup)) {
    return markup;
  }

  var match;
  while (( match = markup.match(/@{([^}]+)}/) )) {
    var interpolation = this.resolve(match[1]);
    markup = markup.replace(match[0], interpolation);
  }

  return markup;
};

Substitute.resolve = function (shortcode) {
  var segments = shortcode.split(':');
  var method = segments.shift();
  if(this.methods[method]) {
    return this.methods[method].apply(this, segments);
  }

  Verbose.warn('invalid_substitution', [shortcode] );
};

Substitute.methods.lipsum = function (quantity, type) {
  quantity = Math.max(quantity, 1);
  if(['paragraphs', 'words', 'sentences'].indexOf(type) === -1) {
    type = 'paragraphs';
  }

  var rnd = 0.01;
  return require('lorem-ipsum')({
    count: quantity,
    units: type,
    random: this.staticLipsum ? function() {
      rnd += 0.01;
      return rnd;
    } : Math.rand
  });
};

Substitute.methods.include = function ( selector ) {
  var markup = _.get(this.map, selector);
  if(markup) {
    return markup;
  }
};

Substitute.methods.image = function (width, height) {
  return 'https://unsplash.it/'+width+'/'+height+(this.staticLipsum ? '' : '?random=' + Math.random()) ;
};

module.exports = Substitute;
<commit_msg>Reset un-random iterator (Fixes: #17)<commit_after>/* Substitute.js -- Scans and resolves placeholders in annotations
 *
 * Copyright (C) 2016 Michael Seibt
 *
 * With contributions from: -
 *
 * This software may be modified and distributed under the terms
 * of the MIT license. See the LICENSE file for details.
 */

'use strict';

var _ = require('lodash');
var Verbose = require('./Verbose');

var Substitute = {
  map: {},
  methods: {},
  staticLipsum: false
};

Substitute.injectConfig = function ( config ) {
  this.staticLipsum = config.staticLipsum;
  return this;
};

Substitute.process = function ( styles ) {

  var style, s, markup;

  // First, collect a map of all selector styles with markup annotation
  for(s in styles) {
    style = styles[s];
    var selector = _.get(style, 'element.selector');
    markup = _.get(style, 'annotations.markup');
    if(selector && markup && (selector.indexOf(':') === -1)){
      this.map[selector] = markup;
    }
  }

  // Loop through all styles again and apply substitutions
  for(s in styles) {
    style = styles[s];
    markup = _.get(style, 'annotations.markup');
    if(markup) {
      _.set(style, 'annotations.markup', this.substitute(markup));
    }
  }

  return styles;
};

Substitute.substitute = function ( markup ) {
  if(_.isEmpty(markup)) {
    return markup;
  }

  var match;
  while (( match = markup.match(/@{([^}]+)}/) )) {
    var interpolation = this.resolve(match[1]);
    markup = markup.replace(match[0], interpolation);
  }

  return markup;
};

Substitute.resolve = function (shortcode) {
  var segments = shortcode.split(':');
  var method = segments.shift();
  if(this.methods[method]) {
    return this.methods[method].apply(this, segments);
  }

  Verbose.warn('invalid_substitution', [shortcode] );
};

Substitute.methods.lipsum = function (quantity, type) {
  quantity = Math.max(quantity, 1);
  if(['paragraphs', 'words', 'sentences'].indexOf(type) === -1) {
    type = 'paragraphs';
  }

  var rnd = 0.01;
  return require('lorem-ipsum')({
    count: quantity,
    units: type,
    random: this.staticLipsum ? function() {
      if(rnd>=1) rnd = 0.01;
      rnd += 0.01;
      return rnd;
    } : Math.rand
  });
};

Substitute.methods.include = function ( selector ) {
  var markup = _.get(this.map, selector);
  if(markup) {
    return markup;
  }
};

Substitute.methods.image = function (width, height) {
  return 'https://unsplash.it/'+width+'/'+height+(this.staticLipsum ? '' : '?random=' + Math.random()) ;
};

module.exports = Substitute;
<|endoftext|>


<commit_before>import React from "react";
import Projection from "./mercator";

// Length of a map tile's side in pixels
const TileSize = 256;

export const TilesLayer = ({ area, zoom, offset, baseUrl }) => {
  const x1 = Projection.getX(area.leftTop.longitude, zoom);
  const x2 = Projection.getX(area.rightBottom.longitude, zoom);
  const y1 = Projection.getY(area.leftTop.latitude, zoom);
  const y2 = Projection.getY(area.rightBottom.latitude, zoom);

  // The entire projection surface is a square with a side size of
  // (TileSize * 2**zoom) pixels. Assuming integer zoom value, there are tiles
  // with indices i,j changing from 0 to 2**zoom. A tile with index i covers x
  // range from (i*TileSize) to ((i+1)*TileSize), and same for the index j.

  // If zoom value is not integer, then we have to use scaled tiles from the
  // nearest zoom level. If we have zoom level Zr but want to use tiles from
  // zoom level Zi, then we have to cover (TileSize*2**Zr) pixels with (2**Zi)
  // tiles, which means each tile from Zi has to be stretched or shrunk to be
  // the size of (TileSize*2**Zr)/(2**Zi) = TileSize * 2**(Zr-Zi) pixels.
  const izoom = Math.round(zoom);
  const size = TileSize * Math.pow(2, zoom - izoom);

  // The tile indices are then simply calculated from proportions.
  const i1 = Math.floor(x1 / size);
  const i2 = Math.floor(x2 / size);
  const j1 = Math.floor(y1 / size);
  const j2 = Math.floor(y2 / size);

  // The parent component puts the rendered result in a coordinate system
  // shifted to keep the relative coordinates of the tiles low. The offset is
  // given as a property here.

  const tiles = [];
  for (let i = i1; i <= i2; i++) {
    for (let j = j1; j <= j2; j++) {
      const key = `${izoom}/${i}/${j}`;
      const url = `${baseUrl}/${key}.png`;
      const style = {
        position: "absolute",
        left: i * size - offset.x + "px",
        top: j * size - offset.y + "px",
        width: size + "px",
        height: size + "px",
        backgroundColor: "#e6ec88",
      };
      tiles.push(

      );
    }
  }
  const style = { position: "relative" };
  return (

      {tiles}

  );
};
<commit_msg>Add memos to tile layer<commit_after>import React, { useMemo, memo } from "react";
import Projection from "./mercator";

// Length of a map tile's side in pixels
const TileSize = 256;

export const TilesLayer = memo(({ area, zoom, offset, baseUrl }) => {
  const x1 = Projection.getX(area.leftTop.longitude, zoom);
  const x2 = Projection.getX(area.rightBottom.longitude, zoom);
  const y1 = Projection.getY(area.leftTop.latitude, zoom);
  const y2 = Projection.getY(area.rightBottom.latitude, zoom);

  // The entire projection surface is a square with a side size of
  // (TileSize * 2**zoom) pixels. Assuming integer zoom value, there are tiles
  // with indices i,j changing from 0 to 2**zoom. A tile with index i covers x
  // range from (i*TileSize) to ((i+1)*TileSize), and same for the index j.

  // If zoom value is not integer, then we have to use scaled tiles from the
  // nearest zoom level. If we have zoom level Zr but want to use tiles from
  // zoom level Zi, then we have to cover (TileSize*2**Zr) pixels with (2**Zi)
  // tiles, which means each tile from Zi has to be stretched or shrunk to be
  // the size of (TileSize*2**Zr)/(2**Zi) = TileSize * 2**(Zr-Zi) pixels.
  const izoom = Math.round(zoom);
  const size = TileSize * Math.pow(2, zoom - izoom);

  // The tile indices are then simply calculated from proportions.
  const i1 = Math.floor(x1 / size);
  const i2 = Math.floor(x2 / size);
  const j1 = Math.floor(y1 / size);
  const j2 = Math.floor(y2 / size);

  const $tiles = useMemo(() => {
    const tiles = [];
    for (let i = i1; i <= i2; i++) {
      for (let j = j1; j <= j2; j++) {
        const key = `${izoom}/${i}/${j}`;
        tiles.push(
          <div
            key={key}
            style={{
              position: "absolute",
              // The parent component puts the rendered result in a coordinate system
              // shifted to keep the relative coordinates of the tiles low. That offset is
              // given as a prop here.
              left: i * size - offset.x + "px",
              top: j * size - offset.y + "px",
              width: size + "px",
              height: size + "px",
              backgroundColor: "#e6ec88",
            }}
          >
            <img
              src={`${baseUrl}/${key}.png`}
              style={{ width: "100%" }}
              alt=""
            />

        );
      }
    }
    return tiles;
  }, [i1, i2, j1, j2, izoom, baseUrl, size]);

  const style = { position: "relative" };
  return (

      {$tiles}

  );
});
<|endoftext|>


<commit_before>'use strict';

angular.module('angularDc', [])

.directive('dcChart', function() {

    var defaultOptions = {
        width: 200,
        height: 200
    };

    function setupChart(scope, iElement, iAttrs) {

        var chartElement = iElement[0],
            chartTypeName = iAttrs.dcChart || iAttrs.chartType,
            chartGroupName = iAttrs.chartGroup || undefined;

        var chartFactory = dc[chartTypeName];

        var chart = chartFactory(chartElement, chartGroupName);

        // all chart options are exposed via a function
        var validOptions = _(chart).functions().value();

        var objOptions = getOptionsFromObject(scope, validOptions);
        var attrOptions = getOptionsFromAttrs(scope, iAttrs, validOptions);
        var scopeOptions = getOptionsFromScope(scope, validOptions);

        var options = _({})
            .extend(defaultOptions,
                objOptions,
                attrOptions,
                scopeOptions)
            .value();

        // TODO: Refactor this, events should be able
        // to be passed in via scope or options obj
        var eventHandlers = _({
            'preRender': scope.onPreRender(),
            'postRender': scope.onPostRender(),
            'preRedraw': scope.onPreRedraw(),
            'postRedraw': scope.onPostRedraw(),
            'filtered': scope.onFiltered(),
            'zoomed': scope.onZoomed(),
        }).omit(_.isUndefined)

        eventHandlers.each(function(handler, evt) {
            chart.on(evt, handler);
        }).value();

        chart.options(options);

        return chart;

    }

    function getOptionsFromObject(scope, validOptions) {
        var config = scope.config();
        if (!_.isObject(config)) {
            config = {};
        }
        return config;
    }

    function getOptionsFromAttrs(scope, iAttrs, validOptions) {
        return _(iAttrs.$attr)
            .keys()
            .intersection(validOptions)
            .map(function(key) {
                var value;
                try {
                    value = scope.$parent.$eval(iAttrs[key]);
                } catch (e) {
                    value = iAttrs[key];
                }
                return [key, value];
            })
            .zipObject()
            .value();
    }

    function getOptionsFromScope(scope, validOptions) {
        return _(scope).keys()
            .intersection(validOptions)
            .map(function(key) {
                return [key, _.result(scope, key)]
            })
            .zipObject()
            .value();
    }

    return {
        restrict: 'EAC',
        scope: {
            group: '&',
            dimension: '&',
            width: '=',
            height: '=',
            config: '&',
            onPreRender: '&',
            onPostRender: '&',
            onPreRedraw: '&',
            onPostRedraw: '&',
            onFiltered: '&',
            onZoomed: '&',
        },
        template: '<svg></svg>',
        link: function(scope, iElement, iAttrs) {

            var chart = setupChart(scope, iElement, iAttrs);

            scope.$watch('options', function(oldValue, newValue) {
                if (oldValue === newValue) {
                    return;
                }
                chart.options(newValue);
            });

            chart.render();

        }
    };

});
<commit_msg>misc tweaks, spacing<commit_after>'use strict';

angular.module('angularDc', [])

.directive('dcChart', function() {

    var defaultOptions = {
        width: 200,
        height: 200
    };

    function setupChart(scope, iElement, iAttrs) {

        var chartElement = iElement[0],
            chartTypeName = iAttrs.dcChart || iAttrs.chartType,
            chartGroupName = iAttrs.chartGroup || undefined;

        var chartFactory = dc[chartTypeName];

        var chart = chartFactory(chartElement, chartGroupName);

        // all chart options are exposed via a function
        var validOptions = _(chart).functions().value();

        var objOptions = getOptionsFromObject(scope, validOptions);
        var attrOptions = getOptionsFromAttrs(scope, iAttrs, validOptions);
        var scopeOptions = getOptionsFromScope(scope, validOptions);

        var options = _({})
            .extend(defaultOptions,
                objOptions,
                attrOptions,
                scopeOptions)
            .value();

        // TODO: Refactor this, events should be able
        // to be passed in via scope or options obj
        var eventHandlers = _({
            'preRender': scope.onPreRender(),
            'postRender': scope.onPostRender(),
            'preRedraw': scope.onPreRedraw(),
            'postRedraw': scope.onPostRedraw(),
            'filtered': scope.onFiltered(),
            'zoomed': scope.onZoomed(),
        }).omit(_.isUndefined)

        eventHandlers.each(function(handler, evt) {
            chart.on(evt, handler);
        }).value();

        chart.options(options);

        return chart;

    }

    function getOptionsFromObject(scope, validOptions) {
        var config = scope.config();
        if (!_.isObject(config)) {
            config = {};
        }
        return config;
    }

    function getOptionsFromAttrs(scope, iAttrs, validOptions) {
        return _(iAttrs.$attr)
            .keys()
            .intersection(validOptions)
            .map(function(key) {
                var value;
                try {
                    value = scope.$parent.$eval(iAttrs[key]);
                } catch (e) {
                    value = iAttrs[key];
                }
                return [key, value];
            })
            .zipObject()
            .value();
    }

    function getOptionsFromScope(scope, validOptions) {
        return _(scope).keys()
            .intersection(validOptions)
            .map(function(key) {
                return [key, _.result(scope, key)]
            })
            .zipObject()
            .value();
    }

    return {
        restrict: 'EAC',
        scope: {
            group: '&',
            dimension: '&',
            width: '=',
            height: '=',
            config: '&',
            onPreRender: '&',
            onPostRender: '&',
            onPreRedraw: '&',
            onPostRedraw: '&',
            onFiltered: '&',
            onZoomed: '&',
        },
        template: '<svg></svg>',
        link: function(scope, iElement, iAttrs) {

            var chart = setupChart(scope, iElement, iAttrs);

            scope.$watch('options', function(oldValue, newValue) {
                if (oldValue === newValue) {
                    return;
                }
                chart.options(newValue);
            });

            chart.render();
        }
    };

});
<|endoftext|>


<commit_before>/**
 * @ngdoc object
 * @name anol.layer.Layer
 *
 * @param {Object} options AnOl Layer options
 * @param {string} options.title Layer title
 * @param {string} options.displayInLayerswitcher Show in layerswitcher
 * @param {boolean} options.isBackgorund Define layer as background layer
 * @param {Object} options.featureinfo Stores informations for feature info
 * @param {string} options.featureinfo.target Target of *GetFeatureInfo* request for {@link api/anol.featureinfo anol.featureinfo}. Supported values are:
 * - *_popup* - Results displayed in a popup
 * - *_blank* - Results displayed in a new window/tab
 * - *[id]* - Id of html element to display results in
 * @param {Array<string>} options.featureinfo.properties List of feature properties to show in {@link api/anol.featurepopup anol.featurepopup}.
 * @param {Object} options.legend Stores informations for legend
 * @param {string} options.legend.type Type of legend entry. Supported values are:
 * - *point* - Extracts point style of vector layer for legend
 * - *line* - Extracts line style of vector layer for legend
 * - *polygon* - Extracts polygon style of vector layer for legend
 * - *GetLegendGraphic* - Use options.legend.url for legend
 * @param {string} options.legend.url Url to image for display in legend
 * @param {string} otpions.legend.target Id of html element to display legend image in. (Only for options.legend.type == 'GetLegendGraphic').
 *                                       If empty, legend image is shown in legend control
 * @param {Object} options.olLayer OpenLayers layer object
 *
 * @description
 * Object for wrapping ol3 layers and add properties to them
 * You can create a normal ol3 layer and give it to a anol.layer.Layer
 *
 * @example
 * ```js
 *   // create ol layer
 *   var olLayer = new ol.layer.Vector({
 *     source: new ol.source.Vector()
 *   });
 *   var anolLayer = new anol.layer.Layer({
 *     title: "Awesome layer",
 *     olLayer: olLayer
 *   });
 * ```
 */
anol.layer.Layer = function(options) {
    if(options === false) {
        return;
    }

    this.name = options.name;
    this.title = options.title;
    this.displayInLayerswitcher = options.displayInLayerswitcher === undefined ? true : options.displayInLayerswitcher;
    this.isBackground = options.isBackground || false;
    this.featureinfo = options.featureinfo || false;
    this.legend = options.legend || false;
    this.attribution = options.attribution || undefined;
    this.isVector = false;

    this.olLayer = options.olLayer;
    if(!(this.olLayer instanceof ol.layer.Base)) {
        throw 'Cannot create object without ol layer';
    }
    this.olLayer.set('anolLayer', this);
};

anol.layer.Layer.prototype = {
    CLASS_NAME: 'anol.layer.Layer',
    DEFAULT_OPTIONS: {
        olLayer: {
            source: undefined
        }
    },
    getVisible: function() {
        var self = this;
        return self.olLayer.getVisible();
    },
    setVisible: function(visible)  {
        var self = this;
        self.olLayer.setVisible(visible);
    },
    onVisibleChange: function(func) {
        var self = this;
        return self.olLayer.on('change:visible', func);
    },
    offVisibleChange: function(key) {
        var self = this;
        self.olLayer.off(key);
    },
    _createSourceOptions: function(srcOptions) {
        srcOptions = srcOptions || {};
        if(srcOptions.tilePixelRatio !== undefined) {
            srcOptions.tilePixelRatio = ol.has.DEVICE_PIXEL_RATIO > 1 ? srcOptions.tilePixelRatio : 1;
        }
        return srcOptions;
    }
};

<commit_msg>Store given options in layer<commit_after>/**
 * @ngdoc object
 * @name anol.layer.Layer
 *
 * @param {Object} options AnOl Layer options
 * @param {string} options.title Layer title
 * @param {string} options.displayInLayerswitcher Show in layerswitcher
 * @param {boolean} options.isBackgorund Define layer as background layer
 * @param {Object} options.featureinfo Stores informations for feature info
 * @param {string} options.featureinfo.target Target of *GetFeatureInfo* request for {@link api/anol.featureinfo anol.featureinfo}. Supported values are:
 * - *_popup* - Results displayed in a popup
 * - *_blank* - Results displayed in a new window/tab
 * - *[id]* - Id of html element to display results in
 * @param {Array<string>} options.featureinfo.properties List of feature properties to show in {@link api/anol.featurepopup anol.featurepopup}.
 * @param {Object} options.legend Stores informations for legend
 * @param {string} options.legend.type Type of legend entry. Supported values are:
 * - *point* - Extracts point style of vector layer for legend
 * - *line* - Extracts line style of vector layer for legend
 * - *polygon* - Extracts polygon style of vector layer for legend
 * - *GetLegendGraphic* - Use options.legend.url for legend
 * @param {string} options.legend.url Url to image for display in legend
 * @param {string} otpions.legend.target Id of html element to display legend image in. (Only for options.legend.type == 'GetLegendGraphic').
 *                                       If empty, legend image is shown in legend control
 * @param {Object} options.olLayer OpenLayers layer object
 *
 * @description
 * Object for wrapping ol3 layers and add properties to them
 * You can create a normal ol3 layer and give it to a anol.layer.Layer
 *
 * @example
 * ```js
 *   // create ol layer
 *   var olLayer = new ol.layer.Vector({
 *     source: new ol.source.Vector()
 *   });
 *   var anolLayer = new anol.layer.Layer({
 *     title: "Awesome layer",
 *     olLayer: olLayer
 *   });
 * ```
 */
anol.layer.Layer = function(options) {
    if(options === false) {
        return;
    }

    this.name = options.name;
    this.title = options.title;
    this.displayInLayerswitcher = options.displayInLayerswitcher === undefined ? true : options.displayInLayerswitcher;
    this.isBackground = options.isBackground || false;
    this.featureinfo = options.featureinfo || false;
    this.legend = options.legend || false;
    this.attribution = options.attribution || undefined;
    this.isVector = false;
    this.options = options;

    this.olLayer = options.olLayer;
    if(!(this.olLayer instanceof ol.layer.Base)) {
        throw 'Cannot create object without ol layer';
    }
    this.olLayer.set('anolLayer', this);
};

anol.layer.Layer.prototype = {
    CLASS_NAME: 'anol.layer.Layer',
    DEFAULT_OPTIONS: {
        olLayer: {
            source: undefined
        }
    },
    getVisible: function() {
        var self = this;
        return self.olLayer.getVisible();
    },
    setVisible: function(visible)  {
        var self = this;
        self.olLayer.setVisible(visible);
    },
    onVisibleChange: function(func) {
        var self = this;
        return self.olLayer.on('change:visible', func);
    },
    offVisibleChange: function(key) {
        var self = this;
        self.olLayer.off(key);
    },
    _createSourceOptions: function(srcOptions) {
        srcOptions = srcOptions || {};
        if(srcOptions.tilePixelRatio !== undefined) {
            srcOptions.tilePixelRatio = ol.has.DEVICE_PIXEL_RATIO > 1 ? srcOptions.tilePixelRatio : 1;
        }
        return srcOptions;
    }
};

<|endoftext|>


<commit_before>class Helper {

    putToLocalStorage(key, value) {
        localStorage.setItem(key, JSON.stringify(value));
    }

    getFromLocalStorage(key) {
        const item = localStorage.getItem(key);
        if (item) return JSON.parse(item);
    }

    getCookie(name) {
        var matches = document.cookie.match(new RegExp(
            "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
        ));
        return matches ? decodeURIComponent(matches[1]) : '';
    }

    setCookie(cname, cvalue, exdays) {
        var expires;
        if (exdays > 0) {
            var d = new Date();
            d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
            expires = "expires=" + d.toUTCString();
        } else {
            expires = 0;
        }
        // does not work on localhost
        let newCookie = `${cname}=${cvalue}; ${expires}; path=/; domain=.${generalOptions.hostname}`;
        document.cookie = newCookie;

    };
}
export let helper = new Helper();
<commit_msg>test commit<commit_after>class Helper {

    putToLocalStorage(key, value) {
        localStorage.setItem(key, JSON.stringify(value));
    }

    getFromLocalStorage(key) {
        const item = localStorage.getItem(key);
        if (item) return JSON.parse(item);
    }

    getCookie(name) {
        var matches = document.cookie.match(new RegExp(
            "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
        ));
        return matches ? decodeURIComponent(matches[1]) : '';
    }

    // setCookie(cname, cvalue, exdays) {
    //     var expires;
    //     if (exdays > 0) {
    //         var d = new Date();
    //         d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
    //         expires = "expires=" + d.toUTCString();
    //     } else {
    //         expires = 0;
    //     }
    //     // does not work on localhost
    //     let newCookie = `${cname}=${cvalue}; ${expires}; path=/; domain=.${generalOptions.hostname}`;
    //     document.cookie = newCookie;
    //
    // };
}
export let helper = new Helper();
<|endoftext|>


<commit_before>import React, {Component} from 'react';
import {Router, Route, IndexRoute, browserHistory} from 'react-router';

import App from './index';
import Documentos from './containers/Documentos/documentosView';
import Forum from './containers/Forum';
import Indicacoes from './containers/Indicacoes';
import NotFound from 'views/NotFound';

const nodeEnv = process.env.NODE_ENV || 'development';
const isProduction = nodeEnv === 'production';
const publicPath = '/';
const appSubRoute = isProduction ? `${publicPath}` : publicPath;
// const appSubRoute = isProduction ? `${publicPath}diario/` : publicPath;

export const routeCodes = {
    DOCUMENTOS: `${ appSubRoute }documentos`,
    FORUM: `${ appSubRoute }forum`,
    INDICACOES: `${ appSubRoute }indicacoes`,
    ABOUT: `${ appSubRoute }about`,
};

export default class Routes extends Component {
    render() {
        return (
            <Router history={ browserHistory }>
                <Route path={ publicPath } component={ App }>

                    <IndexRoute component={ Documentos }/>

                    <Route path={ routeCodes.DOCUMENTOS } component={ Documentos }/>
                    <Route path={ routeCodes.FORUM } component={ Forum }/>
                    <Route path={ routeCodes.INDICACOES } component={ Indicacoes }/>

                    <Route path='*' component={ NotFound }/>
                </Route>
            </Router>
        );
    }
}
<commit_msg>Correção rotas<commit_after>import React, {Component} from 'react';
import {Router, Route, IndexRoute, browserHistory} from 'react-router';

import App from './index';
import Documentos from './containers/Documentos/documentosView';
import Forum from './containers/Forum';
import Indicacoes from './containers/Indicacoes';
import NotFound from './containers/NotFound';

const nodeEnv = process.env.NODE_ENV || 'development';
const isProduction = nodeEnv === 'production';
const publicPath = '/';
const appSubRoute = isProduction ? `${publicPath}` : publicPath;
// const appSubRoute = isProduction ? `${publicPath}diario/` : publicPath;

export const routeCodes = {
    DOCUMENTOS: `${ appSubRoute }documentos`,
    FORUM: `${ appSubRoute }forum`,
    INDICACOES: `${ appSubRoute }indicacoes`,
};

export default class Routes extends Component {
    render() {
        return (
            <Router history={ browserHistory }>
                <Route path={ publicPath } component={ App }>

                    <IndexRoute component={ Documentos }/>

                    <Route path={ routeCodes.DOCUMENTOS } component={ Documentos }/>
                    <Route path={ routeCodes.FORUM } component={ Forum }/>
                    <Route path={ routeCodes.INDICACOES } component={ Indicacoes }/>

                    <Route path='*' component={ NotFound }/>
                </Route>
            </Router>
        );
    }
}
<|endoftext|>


<commit_before>var http = require('http');
var database = require('./db');
var util = require('util');
var sessionFile = require('./session');
var SessionStore = require('./session').SessionStore;
var io = require('socket.io');
var extend = require('extend');
var debug = require('debug')('server');
var async = require('async');
var serverRoot = require('server-root');
var validation = require('json-validation');
var _ = require('underscore');

var logger = require('./logger.js')(this);

function Server(app, options) {
    var server = process.server = this;
    http.Server.call(this);

    var optsHost = options.host;
    if (options.host)
        delete options.host;

    this.options = {
        host: 'localhost',
        port: 2403,
        db: {
            port: 27017,
            host: '127.0.0.1',
            name: 'deployd'
        }
    };

    extend(true, this.options, options);

    debug('started with options %j', options);

    sessionFile.appPath = __dirname;

    var authMngr = null;

    var started = false;

    var logAction = function (db, user, collection, action, objectId, objectData, callback) {

        if (server.app.config.collections[collection]) {
            if (server.app.config.collections[collection].logging) {

                db.actions.post({
                    timestamp: new Date().getTime(),
                    user: user ? user.id : undefined,
                    collection: collection,
                    action: action,
                    objectId: objectId,
                    objectData: objectData || {}
                }, function (results, err) {
                    if (err) {
                        callback(err);
                    }
                    else {
                        callback();
                    }
                });
            }
            else {
                callback();
            }
        }
        else {
            callback();
        }

    };

    this.stores = {};

    this.db = database.create(options.db);

    this.cache = require('./cache.js')();

    if (options.cache)
        this.cache = options.cache;

    this.setCache = function (cache) {
        sSelf.cache = cache;
    };

    this.sockets = io.listen(this, {
        'log level': 0
    }).sockets;

    this.events = {
        db: {
            onPreRead: function (scriptContext, collection, callback) {
                if (!scriptContext.internal && !authMngr.isAuthorized(scriptContext.me, collection, 'R')) {
                    var accessDenied = new Error('access denied');
                    accessDenied.statusCode = 401;
                    callback(accessDenied);
                }
                else {
                    callback();
                }
            },
            onPostRead: function (scriptContext, collection, object, callback) {
                callback();
            },
            onPreCreate: function (scriptContext, collection, callback) {
                if (!scriptContext.internal && !authMngr.isAuthorized(scriptContext.me, collection, 'C')) {
                    var accessDenied = new Error('access denied');
                    accessDenied.statusCode = 401;
                    callback(accessDenied);
                }
                else {
                    callback();
                }
            },
            onPostCreate: function (scriptContext, collection, object, callback) {
                logAction(scriptContext.db, scriptContext.me, collection, 'create', object.id, object, function (err, res) {
                    if (err) {
                        callback(err);
                    }
                    else {
                        if (!scriptContext.internal)
                            scriptContext.emit(collection + 'Created', object);

                        callback();
                    }
                });
            },
            onPreUpdate: function (scriptContext, collection, object, callback) {
                if (!scriptContext.internal && !authMngr.isAuthorized(scriptContext.me, collection, 'U')) {
                    var accessDenied = new Error('access denied');
                    accessDenied.statusCode = 401;
                    callback(accessDenied);
                }
                else {
                    callback();
                }
            },
            onPostUpdate: function (scriptContext, collection, object, callback) {
                logAction(scriptContext.db, scriptContext.me, collection, 'update', object.id, object, function (err, res) {
                    if (err) {
                        callback(err);
                    }
                    else {
                        if (!scriptContext.internal)
                            scriptContext.emit(collection + 'Updated', object);

                        callback();
                    }
                });
            },
            onPreDelete: function (scriptContext, collection, object, callback) {
                if (!scriptContext.internal && !authMngr.isAuthorized(scriptContext.me, collection, 'D')) {
                    var accessDenied = new Error('access denied');
                    accessDenied.statusCode = 401;
                    callback(accessDenied);
                }
                else {
                    callback();
                }
            },
            onPostDelete: function (scriptContext, collection, object, callback) {
                logAction(scriptContext.db, scriptContext.me, collection, 'delete', object.id, object, function (err, res) {
                    if (err) {
                        callback(err);
                    }
                    else {
                        if (!scriptContext.internal)
                            scriptContext.emit(collection + 'Deleted', object);

                        callback();
                    }
                });
            },
            onValidate: function (scriptContext, collection, object, callback) {
                if (server.app.config.collections[collection]) {
                    if (server.app.config.collections[collection].schema) {
                        var validator = new validation.JSONValidation();
                        var validationResult = validator.validate(object, server.app.config.collections[collection].schema);
                        if (!validationResult.ok) {
                            var validationErrors = validationResult.path + ': ' + validationResult.errors.join(' - ');
                            callback(new Error(validationErrors));
                        }
                        else {
                            callback();
                        }
                    }
                    else {
                        callback();
                    }
                }
                else {
                    callback();
                }
            }
        }
    };

    this.sessions = new SessionStore('sessions', this.db, this.sockets);

    if (options.events)
        for (var item in options.events)
            this.on(item, options.events[item]);

    this.on('listening', function () {
        server.host = optsHost;
        server.port = server.options.port;

        authMngr = require('./cms/authMngr.js')(server);

        logger.info('jsnbt server is listening on:' + server.options.port);

        started = true;

        if (server.next)
            server.next();
    });

    this.on('request', function (req, res) {
        if (started) {
            server.route(req, res);
        }
        else {
            req._routed = true;
            res.write('503 - Service is starting');
            res.end();
        }
    });

    this.on("request:error", function (err, req, res) {
        logger.error(req.method, req.url, err.stack || err);
        process.exit(1);
    });

    server.getPath = serverRoot.getPath;

    server.messager = require('./messager.js')(server);

    server.app = app;
}
util.inherits(Server, http.Server);

var getResources = function (server, cb) {

    var resources = [];
    var asyncFns = [];

    Object.keys(server.app.config.collections).forEach(function (collectionName) {

        var collectionConfig = server.app.config.collections[collectionName];

        asyncFns.push(function (fn) {
            //var config = {
            //    type: (collection.users === true ? 'User' : '') + 'Collection',
            //    properties: {},
            //    events: collection.events || {}
            //};

            //var propertyKeys = _.keys(collection.schema.properties);

            //_.each(propertyKeys, function (propertyKey, propertyIndex) {

            //    var collectionProperty = collection.schema.properties[propertyKey];

            //    var propertyRequired = collectionProperty.type === 'boolean' ? false : (collectionProperty.required || false);

            //    var property = {
            //        name: propertyKey,
            //        type: collectionProperty.type,
            //        typeLabel: propertyKey,
            //        required: propertyRequired,
            //        id: propertyKey,
            //        order: propertyIndex
            //    };

            //    config.properties[propertyKey] = property;
            //});

            //var o = {
            //    config: config,
            //    db: server.db
            //}

            var rType = collectionConfig.users ? require('./resources/user-collection.js') : require('./resources/collection.js');
            //var resource = new rType(collectionName, o);
            var resource = new rType(server, collectionConfig);
            resources.push(resource);

            if (resource.load) {
                resource.load(function () {
                    fn();
                });
            } else {
                fn();
            }
        });

    });

    async.series(asyncFns, function (err, results) {
        cb(err, resources);
    });
};

Server.prototype.start = function (next) {
    var server = this;

    getResources(server, function (err, resources) {
        if (err) {
            console.error();
            console.error("Error loading resources: ");
            console.error(err.stack || err);
            process.exit(1);
        } else {
            server.resources = resources;
            http.Server.prototype.listen.call(server, server.options.port, server.options.host);

            if (typeof (next) === 'function') {
                server.next = next;
            }
            else {
                server.next = undefined;
            }
        }

    });
};

Server.prototype.route = function route(req, res) {
    var server = this;

    if (req.url.indexOf('/socket.io/') === 0) return;

    var router = new require('./router.js')(server, req, res);
    router.process();
};

Server.prototype.createStore = function (namespace) {
    return (this.stores[namespace] = this.db.createStore(namespace));
};

module.exports = function (app, options) {
    return new Server(app, options);
};<commit_msg>reading correct config<commit_after>var http = require('http');
var database = require('./db');
var util = require('util');
var sessionFile = require('./session');
var SessionStore = require('./session').SessionStore;
var io = require('socket.io');
var extend = require('extend');
var debug = require('debug')('server');
var async = require('async');
var serverRoot = require('server-root');
var validation = require('json-validation');
var _ = require('underscore');

var logger = require('./logger.js')(this);

function Server(app, options) {
    var server = process.server = this;
    http.Server.call(this);

    var optsHost = options.host;
    if (options.host)
        delete options.host;

    this.options = {
        host: 'localhost',
        port: 2403,
        db: {
            port: 27017,
            host: '127.0.0.1',
            name: 'deployd'
        }
    };

    extend(true, this.options, options);

    debug('started with options %j', options);

    sessionFile.appPath = __dirname;

    var authMngr = null;

    var started = false;

    var logAction = function (db, user, collection, action, objectId, objectData, callback) {

        if (server.app.config.collections[collection]) {
            if (server.app.config.collections[collection].logging) {

                db.actions.post({
                    timestamp: new Date().getTime(),
                    user: user ? user.id : undefined,
                    collection: collection,
                    action: action,
                    objectId: objectId,
                    objectData: objectData || {}
                }, function (results, err) {
                    if (err) {
                        callback(err);
                    }
                    else {
                        callback();
                    }
                });
            }
            else {
                callback();
            }
        }
        else {
            callback();
        }

    };

    this.stores = {};

    this.db = database.create(options.db);

    this.cache = require('./cache.js')();

    if (options.cache)
        this.cache = options.cache;

    this.setCache = function (cache) {
        sSelf.cache = cache;
    };

    this.sockets = io.listen(this, {
        'log level': 0
    }).sockets;

    this.events = {
        db: {
            onPreRead: function (scriptContext, collection, callback) {
                if (!scriptContext.internal && !authMngr.isAuthorized(scriptContext.me, collection, 'R')) {
                    var accessDenied = new Error('access denied');
                    accessDenied.statusCode = 401;
                    callback(accessDenied);
                }
                else {
                    callback();
                }
            },
            onPostRead: function (scriptContext, collection, object, callback) {
                callback();
            },
            onPreCreate: function (scriptContext, collection, callback) {
                if (!scriptContext.internal && !authMngr.isAuthorized(scriptContext.me, collection, 'C')) {
                    var accessDenied = new Error('access denied');
                    accessDenied.statusCode = 401;
                    callback(accessDenied);
                }
                else {
                    callback();
                }
            },
            onPostCreate: function (scriptContext, collection, object, callback) {
                logAction(scriptContext.db, scriptContext.me, collection, 'create', object.id, object, function (err, res) {
                    if (err) {
                        callback(err);
                    }
                    else {
                        if (!scriptContext.internal)
                            scriptContext.emit(collection + 'Created', object);

                        callback();
                    }
                });
            },
            onPreUpdate: function (scriptContext, collection, object, callback) {
                if (!scriptContext.internal && !authMngr.isAuthorized(scriptContext.me, collection, 'U')) {
                    var accessDenied = new Error('access denied');
                    accessDenied.statusCode = 401;
                    callback(accessDenied);
                }
                else {
                    callback();
                }
            },
            onPostUpdate: function (scriptContext, collection, object, callback) {
                logAction(scriptContext.db, scriptContext.me, collection, 'update', object.id, object, function (err, res) {
                    if (err) {
                        callback(err);
                    }
                    else {
                        if (!scriptContext.internal)
                            scriptContext.emit(collection + 'Updated', object);

                        callback();
                    }
                });
            },
            onPreDelete: function (scriptContext, collection, object, callback) {
                if (!scriptContext.internal && !authMngr.isAuthorized(scriptContext.me, collection, 'D')) {
                    var accessDenied = new Error('access denied');
                    accessDenied.statusCode = 401;
                    callback(accessDenied);
                }
                else {
                    callback();
                }
            },
            onPostDelete: function (scriptContext, collection, object, callback) {
                logAction(scriptContext.db, scriptContext.me, collection, 'delete', object.id, object, function (err, res) {
                    if (err) {
                        callback(err);
                    }
                    else {
                        if (!scriptContext.internal)
                            scriptContext.emit(collection + 'Deleted', object);

                        callback();
                    }
                });
            },
            onValidate: function (scriptContext, collection, object, callback) {
                if (server.app.config.collections[collection]) {
                    if (server.app.config.collections[collection].schema) {
                        var validator = new validation.JSONValidation();
                        var validationResult = validator.validate(object, server.app.config.collections[collection].schema);
                        if (!validationResult.ok) {
                            var validationErrors = validationResult.path + ': ' + validationResult.errors.join(' - ');
                            callback(new Error(validationErrors));
                        }
                        else {
                            callback();
                        }
                    }
                    else {
                        callback();
                    }
                }
                else {
                    callback();
                }
            }
        }
    };

    this.sessions = new SessionStore('sessions', this.db, this.sockets);

    if (options.events)
        for (var item in options.events)
            this.on(item, options.events[item]);

    this.on('listening', function () {
        server.host = optsHost;
        server.port = server.options.port;

        authMngr = require('./cms/authMngr.js')(server);

        logger.info('jsnbt server is listening on:' + server.options.port);

        started = true;

        if (server.next)
            server.next();
    });

    this.on('request', function (req, res) {
        if (started) {
            server.route(req, res);
        }
        else {
            req._routed = true;
            res.write('503 - Service is starting');
            res.end();
        }
    });

    this.on("request:error", function (err, req, res) {
        logger.error(req.method, req.url, err.stack || err);
        process.exit(1);
    });

    server.getPath = serverRoot.getPath;

    server.messager = require('./messager.js')(server);

    server.app = app;
}
util.inherits(Server, http.Server);

var getResources = function (server, cb) {

    var resources = [];
    var asyncFns = [];

    Object.keys(server.app.config.collections).forEach(function (collectionName) {

        var collectionConfig = server.app.config.collections[collectionName];

        asyncFns.push(function (fn) {
            var rType = collectionConfig.users ? require('./resources/user-collection.js') : require('./resources/collection.js');
            var resource = new rType(server, collectionConfig);
            resources.push(resource);

            if (resource.load) {
                resource.load(function () {
                    fn();
                });
            } else {
                fn();
            }
        });

    });

    async.series(asyncFns, function (err, results) {
        cb(err, resources);
    });
};

Server.prototype.start = function (next) {
    var server = this;

    getResources(server, function (err, resources) {
        if (err) {
            console.error();
            console.error("Error loading resources: ");
            console.error(err.stack || err);
            process.exit(1);
        } else {
            server.resources = resources;
            http.Server.prototype.listen.call(server, server.options.port, server.options.host);

            if (typeof (next) === 'function') {
                server.next = next;
            }
            else {
                server.next = undefined;
            }
        }

    });
};

Server.prototype.route = function route(req, res) {
    var server = this;

    if (req.url.indexOf('/socket.io/') === 0) return;

    var router = new require('./router.js')(server, req, res);
    router.process();
};

Server.prototype.createStore = function (namespace) {
    return (this.stores[namespace] = this.db.createStore(namespace));
};

module.exports = function (app, options) {
    return new Server(app, options);
};<|endoftext|>


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

/**
 * External dependencies
 */
import PropTypes from 'prop-types';
import styled from 'styled-components';
import { useEffect, useRef } from 'react';

/**
 * Internal dependencies
 */
import { useStory } from '../../app';
import withOverlay from '../overlay/withOverlay';
import InOverlay from '../overlay';
import { useUnits } from '../../units';
import useCanvas from './useCanvas';

const LassoMode = {
  OFF: 0,
  ON: 1,
  MAYBE: 2,
};

const Container = withOverlay(styled.div`
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
  user-select: none;
`);

const Lasso = styled.div`
  display: none;
  position: absolute;
  border: 1px dotted ${({ theme }) => theme.colors.selection};
  z-index: 1;
`;

function SelectionCanvas({ children }) {
  const {
    actions: { clearSelection },
    state: { selectedElements },
  } = useStory();
  const {
    state: { pageContainer },
    actions: { clearEditing, selectIntersection },
  } = useCanvas();
  const {
    actions: { editorToDataX, editorToDataY },
  } = useUnits();

  const overlayRef = useRef(null);
  const lassoRef = useRef(null);
  const offsetRef = useRef([0, 0]);
  const startRef = useRef([0, 0]);
  const endRef = useRef([0, 0]);
  const lassoModeRef = useRef(LassoMode.OFF);

  const getLassoBox = () => {
    const [x1, y1] = startRef.current;
    const [x2, y2] = endRef.current;
    const x = Math.min(x1, x2);
    const y = Math.min(y1, y2);
    const w = Math.abs(x1 - x2);
    const h = Math.abs(y1 - y2);
    return [x, y, w, h];
  };

  const updateLasso = () => {
    const lasso = lassoRef.current;
    if (!lasso) {
      return;
    }
    const lassoMode = lassoModeRef.current;
    const [x, y, w, h] = getLassoBox();
    lasso.style.left = `${x}px`;
    lasso.style.top = `${y}px`;
    lasso.style.width = `${w}px`;
    lasso.style.height = `${h}px`;
    lasso.style.display = lassoMode === LassoMode.ON ? 'block' : 'none';
  };

  const onMouseDown = (evt) => {
    if (selectedElements.length) {
      clearSelection();
      clearEditing();
    }

    const overlay = overlayRef.current;
    let offsetX = 0,
      offsetY = 0;
    for (
      let offsetNode = overlay;
      offsetNode;
      offsetNode = offsetNode.offsetParent
    ) {
      offsetX += offsetNode.offsetLeft;
      offsetY += offsetNode.offsetTop;
    }
    const x = evt.pageX - offsetX;
    const y = evt.pageY - offsetY;
    offsetRef.current = [offsetX, offsetY];
    startRef.current = [x, y];
    endRef.current = [x, y];
    lassoModeRef.current = LassoMode.MAYBE;
    updateLasso();
  };

  const onMouseMove = (evt) => {
    if (lassoModeRef.current === LassoMode.OFF) {
      return;
    }
    const [offsetX, offsetY] = offsetRef.current;
    const x2 = evt.pageX - offsetX;
    const y2 = evt.pageY - offsetY;
    endRef.current[0] = x2;
    endRef.current[1] = y2;
    lassoModeRef.current = LassoMode.ON;
    updateLasso();
  };

  const onMouseUp = () => {
    if (lassoModeRef.current === LassoMode.ON) {
      const [lx, ly, lwidth, lheight] = getLassoBox();
      const x = editorToDataX(lx - pageContainer.offsetLeft);
      const y = editorToDataY(ly - pageContainer.offsetTop);
      const width = editorToDataX(lwidth);
      const height = editorToDataY(lheight);
      clearSelection();
      clearEditing();
      selectIntersection({ x, y, width, height });
    }
    lassoModeRef.current = LassoMode.OFF;
    updateLasso();
  };

  useEffect(updateLasso);

  return (
    <Container
      onMouseDown={onMouseDown}
      onMouseMove={onMouseMove}
      onMouseUp={onMouseUp}
    >
      {children}
      <InOverlay ref={overlayRef}>
        <Lasso ref={lassoRef} />
      </InOverlay>
    </Container>
  );
}

SelectionCanvas.propTypes = {
  children: PropTypes.oneOfType([
    PropTypes.arrayOf(PropTypes.node),
    PropTypes.node,
  ]).isRequired,
};

export default SelectionCanvas;
<commit_msg>Fixes background element selection (#847)<commit_after>/*
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * External dependencies
 */
import PropTypes from 'prop-types';
import styled from 'styled-components';
import { useEffect, useRef } from 'react';

/**
 * Internal dependencies
 */
import { useStory } from '../../app';
import withOverlay from '../overlay/withOverlay';
import InOverlay from '../overlay';
import { useUnits } from '../../units';
import useCanvas from './useCanvas';

const LASSO_ACTIVE_THRESHOLD = 10;

const LassoMode = {
  OFF: 0,
  ON: 1,
  MAYBE: 2,
};

const Container = withOverlay(styled.div`
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
  user-select: none;
`);

const Lasso = styled.div`
  display: none;
  position: absolute;
  border: 1px dotted ${({ theme }) => theme.colors.selection};
  z-index: 1;
`;

function SelectionCanvas({ children }) {
  const {
    actions: { clearSelection },
    state: { selectedElements, currentPage },
  } = useStory();
  const {
    state: { pageContainer, isEditing, nodesById },
    actions: { clearEditing, selectIntersection },
  } = useCanvas();
  const {
    actions: { editorToDataX, editorToDataY },
  } = useUnits();

  const overlayRef = useRef(null);
  const lassoRef = useRef(null);
  const offsetRef = useRef([0, 0]);
  const startRef = useRef([0, 0]);
  const endRef = useRef([0, 0]);
  const lassoModeRef = useRef(LassoMode.OFF);

  const getLassoBox = () => {
    const [x1, y1] = startRef.current;
    const [x2, y2] = endRef.current;
    const x = Math.min(x1, x2);
    const y = Math.min(y1, y2);
    const w = Math.abs(x1 - x2);
    const h = Math.abs(y1 - y2);
    return [x, y, w, h];
  };

  const updateLasso = () => {
    const lasso = lassoRef.current;
    if (!lasso) {
      return;
    }
    const lassoMode = lassoModeRef.current;
    const [x, y, w, h] = getLassoBox();
    lasso.style.left = `${x}px`;
    lasso.style.top = `${y}px`;
    lasso.style.width = `${w}px`;
    lasso.style.height = `${h}px`;
    lasso.style.display = lassoMode === LassoMode.ON ? 'block' : 'none';
  };

  const onMouseDown = (evt) => {
    // Selecting the background element should be handeled at the frameElement level
    if (!nodesById[currentPage.backgroundElementId].contains(evt.target)) {
      if (selectedElements.length) {
        clearSelection();
      }
      if (isEditing) {
        clearEditing();
      }
    }
    const overlay = overlayRef.current;
    let offsetX = 0,
      offsetY = 0;
    for (
      let offsetNode = overlay;
      offsetNode;
      offsetNode = offsetNode.offsetParent
    ) {
      offsetX += offsetNode.offsetLeft;
      offsetY += offsetNode.offsetTop;
    }
    const x = evt.pageX - offsetX;
    const y = evt.pageY - offsetY;
    offsetRef.current = [offsetX, offsetY];
    startRef.current = [x, y];
    endRef.current = [x, y];
    lassoModeRef.current = LassoMode.MAYBE;
    updateLasso();
  };

  const onMouseMove = (evt) => {
    if (lassoModeRef.current === LassoMode.OFF) {
      return;
    }
    const [x1, y1] = startRef.current;
    const [offsetX, offsetY] = offsetRef.current;
    const x2 = evt.pageX - offsetX;
    const y2 = evt.pageY - offsetY;
    endRef.current[0] = x2;
    endRef.current[1] = y2;
    updateLasso();
    // Ignore clicks and unintentional selections
    if (Math.abs(x1 - x2) + Math.abs(y1 - y2) > LASSO_ACTIVE_THRESHOLD) {
      lassoModeRef.current = LassoMode.ON;
    }
  };

  const onMouseUp = () => {
    if (lassoModeRef.current === LassoMode.ON) {
      const [lx, ly, lwidth, lheight] = getLassoBox();
      const x = editorToDataX(lx - pageContainer.offsetLeft);
      const y = editorToDataY(ly - pageContainer.offsetTop);
      const width = editorToDataX(lwidth);
      const height = editorToDataY(lheight);
      clearSelection();
      clearEditing();
      selectIntersection({ x, y, width, height });
    }
    lassoModeRef.current = LassoMode.OFF;
    updateLasso();
  };

  useEffect(updateLasso);

  return (
    <Container
      onMouseDown={onMouseDown}
      onMouseMove={onMouseMove}
      onMouseUp={onMouseUp}
    >
      {children}
      <InOverlay ref={overlayRef}>
        <Lasso ref={lassoRef} />
      </InOverlay>
    </Container>
  );
}

SelectionCanvas.propTypes = {
  children: PropTypes.oneOfType([
    PropTypes.arrayOf(PropTypes.node),
    PropTypes.node,
  ]).isRequired,
};

export default SelectionCanvas;
<|endoftext|>


<commit_before>Package.describe({
  name: 'angular-typescript-compiler',
  version: '0.2.9_5',
  summary: 'Angular TypeScript Compiler Package',
  git: 'https://github.com/Urigo/angular-meteor/tree/master/atmosphere-packages/angular-typescript-compiler',
  documentation: null
});

Npm.depends({
  'meteor-typescript': '0.8.10',
  'rollup': '0.41.4',
  'rollup-plugin-node-resolve': '3.0.0',
  'rollup-plugin-hypothetical': '1.2.1',
  'rollup-plugin-commonjs': '8.2.0'
});

Package.onUse(function(api) {
  api.versionsFrom('1.6');
  api.use([
    'ecmascript',
    'babel-compiler',
    'angular-html-compiler@0.2.9',
    'angular-scss-compiler@0.2.9',
    'underscore@1.0.10',
    'tmeasday:check-npm-versions@0.3.1'
  ], 'server');
  api.mainModule('index.js', 'server');
});
<commit_msg>chore(deps): update dependency rollup-plugin-hypothetical to v2.0.0<commit_after>Package.describe({
  name: 'angular-typescript-compiler',
  version: '0.2.9_5',
  summary: 'Angular TypeScript Compiler Package',
  git: 'https://github.com/Urigo/angular-meteor/tree/master/atmosphere-packages/angular-typescript-compiler',
  documentation: null
});

Npm.depends({
  'meteor-typescript': '0.8.10',
  'rollup': '0.41.4',
  'rollup-plugin-node-resolve': '3.0.0',
  'rollup-plugin-hypothetical': '2.0.0',
  'rollup-plugin-commonjs': '8.2.0'
});

Package.onUse(function(api) {
  api.versionsFrom('1.6');
  api.use([
    'ecmascript',
    'babel-compiler',
    'angular-html-compiler@0.2.9',
    'angular-scss-compiler@0.2.9',
    'underscore@1.0.10',
    'tmeasday:check-npm-versions@0.3.1'
  ], 'server');
  api.mainModule('index.js', 'server');
});
<|endoftext|>


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

    setNextActivities();
    function setNextActivities() {

        $.ajax({
            url: "/next_activities"
        }).done(function (data) {
            var str = '';
            $.each(data, function (index, activity) {

                if(new Date(activity.field_date_1)>new Date()) {
                    str += '
';
                    str += '' + activity.field_date + '	';
                    if (activity.field_lien && activity.field_lien != '') {
                        str += '' + activity.title + '	';
                    } else {
                        str += '' + activity.title + '	';
                    }
                    str += '' + activity.field_room + '	';
                    str += '
';
                }
            });
            $('.tournaments-home-next table').html(str);
            setTimeout(setNextActivities, 10 * 60 * 1000); //each 10 min
        });

    }
})(jQuery);
<commit_msg>Fix next activities bug (date filter D8 not operational)<commit_after>(function ($) {
    'use strict';

    setNextActivities();
    function setNextActivities() {

        $.ajax({
            url: "/next_activities"
        }).done(function (data) {
            var count = 0;
            var str = '';
            $.each(data, function (index, activity) {

                if(new Date(activity.field_date_1)>new Date() && count <=10) {
                    str += '
';
                    str += '' + activity.field_date + '	';
                    if (activity.field_lien && activity.field_lien != '') {
                        str += '' + activity.title + '	';
                    } else {
                        str += '' + activity.title + '	';
                    }
                    str += '' + activity.field_room + '	';
                    str += '
';
                    count ++;
                }
            });
            $('.tournaments-home-next table').html(str);
            setTimeout(setNextActivities, 10 * 60 * 1000); //each 10 min
        });

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


<commit_before><commit_msg>Fix test fixtures<commit_after><|endoftext|>


<commit_before>Application.Directives.directive('homeSamples', homeSamplesDirective);

function homeSamplesDirective() {
    return {
        restrict: "A",
        controller: 'homeSamplesController',
        scope: {
            project: '=project'
        },
        templateUrl: 'application/core/projects/project/home/directives/home-samples.html'
    };
}

Application.Controllers.controller("homeSamplesController",
    ["$scope",
        homeSamplesController]);

function homeSamplesController($scope) {

    var rowData = [];
    $scope.project.samples.forEach(function (sample) {
        var composition = '';
        if ('composition' in sample.properties) {
            sample.properties.composition.value.forEach(function (val) {
                composition = composition + '  ' + val.element + ': ' + val.value;
            });
            composition = composition + '  ' + sample.properties.composition.unit;
        } else {
            composition = 'unknown';
        }
        rowData.push({
            name: sample.name,
            owner: sample.owner,
            mtime: sample.mtime
        });
    });
    var columnDefs = [
        {
            displayName: "",
            field: "title",
            width: 900,
            template: '' +
            '
' +
            '' +
            '{{data.owner}}' +
            '{{data.mtime | toDateString}}
',
            cellStyle: {border: 0}
        }
    ];
    $scope.gridOptions = {
        columnDefs: columnDefs,
        rowData: rowData,
        enableColResize: true,
        headerHeight: 0,
        rowHeight: 65,
        rowStyle: {'border-bottom': 'dotted #d3d3d3'},
        angularCompileRows: true
    };

}
<commit_msg>Sort samples by name.<commit_after>Application.Directives.directive('homeSamples', homeSamplesDirective);

function homeSamplesDirective() {
    return {
        restrict: "A",
        controller: 'homeSamplesController',
        scope: {
            project: '=project'
        },
        templateUrl: 'application/core/projects/project/home/directives/home-samples.html'
    };
}

Application.Controllers.controller("homeSamplesController",
    ["$scope", "$filter", homeSamplesController]);

function homeSamplesController($scope, $filter) {
    var rowData = [];
    var samples = $filter('orderBy')($scope.project.samples, 'name');
    samples.forEach(function (sample) {
        var composition = '';
        if ('composition' in sample.properties) {
            sample.properties.composition.value.forEach(function (val) {
                composition = composition + '  ' + val.element + ': ' + val.value;
            });
            composition = composition + '  ' + sample.properties.composition.unit;
        } else {
            composition = 'unknown';
        }
        rowData.push({
            name: sample.name,
            owner: sample.owner,
            mtime: sample.mtime
        });
    });
    var columnDefs = [
        {
            displayName: "",
            field: "title",
            width: 900,
            template: '' +
            '
' +
            '' +
            '{{data.owner}}' +
            '{{data.mtime | toDateString}}
',
            cellStyle: {border: 0}
        }
    ];
    $scope.gridOptions = {
        columnDefs: columnDefs,
        rowData: rowData,
        enableColResize: true,
        headerHeight: 0,
        rowHeight: 65,
        rowStyle: {'border-bottom': 'dotted #d3d3d3'},
        angularCompileRows: true
    };
}
<|endoftext|>