<commit_before>'use strict';
var Rect = require('./helpers/rect').Rect;
var Utils = require('./helpers/utils');
var renderer = require('./renderer.base');
var Tayberry = require('./base.js').Tayberry;

class BarRenderer extends renderer.Renderer {
    constructor(ctx, tayberry, series) {
        super(ctx, tayberry, series);

        this.barPositions = null;

        this.tb.registerCallback('onResize', this.updateBarWidths.bind(this));
        this.tb.registerCallback('onInit', this.updateBarWidths.bind(this));
    }

    updateBarWidths() {
        const categoryCount = this.renderedSeries[0].data.length;
        const isStacked = this.tb.options.barPlot.mode === 'stacked';
        const isOverlaid = this.tb.options.barPlot.mode === 'overlaid';
        const isNormal = !isStacked && !isOverlaid;
        const seriesCount = this.renderedSeries.length;
        const barsPerCategory = (isStacked || isOverlaid) ? 1 : this.renderedSeries.length;
        const categoryWidth = (this.tb.plotArea.width / this.categoryCount);

        this.barPositions = [];

        for (let categoryIndex = 0; categoryIndex<categoryCount; categoryIndex++) {
            const categoryXStart = this.tb.plotArea.left + Math.floor(categoryIndex * categoryWidth);
            const categoryXEnd = this.tb.plotArea.left + Math.floor((categoryIndex + 1) * categoryWidth);
            // FIXME: Need to map this.tb.options.barPlot.categorySpacing
            const barXStart = categoryXStart + Math.ceil(categoryWidth * this.tb.options.barPlot.categorySpacing / 2);
            const barXEnd = categoryXEnd - Math.floor(categoryWidth * this.tb.options.barPlot.categorySpacing / 2);
            const barWidth = Math.floor((barXEnd - barXStart) / barsPerCategory);

            let categoryPositions = [];
            let barIndex = 0;

            for (let seriesIndex = 0; seriesIndex<seriesCount; seriesIndex++) {
                const series = this.renderedSeries[seriesIndex];
                const xStart = Math.floor(barXStart + barIndex * barWidth) + Math.ceil(series.xAxis.mapLogicalXOrYUnit(this.tb.options.barPlot.barPadding) / 2);
                const xEnd = Math.ceil(barXStart + (barIndex + 1) * barWidth) - Math.floor(series.xAxis.mapLogicalXOrYUnit(this.tb.options.barPlot.barPadding) / 2);
                categoryPositions.push([xStart, xEnd]);

                if (isNormal) barIndex++;
            }

            this.barPositions.push(categoryPositions);
        }
    }

    drawPlot() {
        this.ctx.save();
        let barEnumerator = new BarEnumerator(this);
        let bar;
        while ((bar = barEnumerator.next())) {
            this.ctx.fillStyle = bar.selected ? bar.renderedSeries.highlightColour : bar.renderedSeries.colour;
            this.ctx.fillRect(bar.rect.left, bar.rect.top, bar.rect.width, bar.rect.height);
        }
        this.ctx.restore();
    }

    drawLabels() {
        if (this.tb.options.labels.enabled) {
            this.ctx.save();
            let barEnumerator = new BarEnumerator(this);
            let bar;
            while ((bar = barEnumerator.next())) {
                this.ctx.font = this.tb.labelFont;
                this.ctx.fillStyle = this.tb.options.labels.font.colour;
                this.drawLabel(bar.value, bar.series.yAxis.options.labelFormatter(bar.value), bar.rect);
            }
            this.ctx.restore();
        }
    }

    hitTest(x, y) {
        // TODO: Optimise
        let ret = {
            found: false,
            plotType: 'bar',
            isXRange: true
        };

        const categoryCount = this.renderedSeries[0].data.length;
        const isHorizontal = this.tb.options.swapAxes;
        let plotArea = this.tb.plotArea.clone();
        if (isHorizontal)
            plotArea.swapXY();
        const categoryIndex = Math.floor(categoryCount * ((isHorizontal ? y : x) - plotArea.left) / plotArea.width);

        let matches = [];

        let barEnumerator = new BarEnumerator(this, categoryIndex);
        let bar;
        while ((bar = barEnumerator.next())) {
            if (bar.categoryIndex > categoryIndex)
                break;
            let sortDistance, priority, realDistance;
            if (bar.rect.containsPoint(x, y)) {
                sortDistance = 0;
                priority = 0;
            }
            else if (bar.rect.containsX(x)) {
                sortDistance = y < bar.rect.top ? bar.rect.top - y : y - bar.rect.bottom;
                priority = isHorizontal ? 2 : 1;
            }
            else if (bar.rect.containsY(y)) {
                sortDistance = x < bar.rect.left ? bar.rect.left - x : x - bar.rect.right;
                priority = isHorizontal ? 1 : 2;
            }
            else {
                const xDist = Math.min(Math.abs(x - bar.rect.left), Math.abs(x - bar.rect.right));
                const yDist = Math.min(Math.abs(y - bar.rect.top), Math.abs(y - bar.rect.bottom));
                realDistance = Math.sqrt(Math.pow(xDist, 2) + Math.pow(yDist, 2));
                sortDistance = isHorizontal ? yDist : xDist;
                priority = 3;
            }

            if (typeof realDistance === 'undefined')
                realDistance = sortDistance;

            matches.push({
                sortDistance: sortDistance,
                distance: realDistance,
                priority: priority,
                data: {
                    categoryIndex: bar.categoryIndex,
                    seriesIndex: bar.seriesIndex,
                    rect: bar.rect,
                    series: this.series[bar.seriesIndex],
                    value: Tayberry.getDataValue(this.series[bar.seriesIndex].data[bar.categoryIndex])
                }
            });
        }

        if (matches.length) {
            matches.sort((a, b) => {
                let ret = a.priority - b.priority;
                if (!ret) ret = a.sortDistance - b.sortDistance;
                if (!ret) ret = a.data.rect.height - b.data.rect.height;
                return ret;
            });
            ret.found = true;
            ret.normalisedDistance = matches[0].distance + Math.sqrt(matches[0].data.rect.area);
            ret = Utils.assign(ret, matches[0].data);
        }
        return ret;
    }
}

class BarEnumerator extends renderer.ByCategoryEnumerator {
    constructor(renderer, startCategoryIndex = 0) {
        super(renderer, startCategoryIndex);
        if (this.categoryCount) {
            this.isStacked = this.tb.options.barPlot.mode === 'stacked';
            this.isOverlaid = this.tb.options.barPlot.mode === 'overlaid';
            this.isNormal = !this.isStacked && !this.isOverlaid;
            this.barCount = (this.isStacked || this.isOverlaid) ? 1 : this.seriesCount;
            this.categoryWidth = (this.plotArea.width / this.categoryCount);
            // used for stacked bar charts - must be on single y-axis
            this.yOrigin = this.renderer.series[0].yAxis.getOrigin();

            this.onNewCategory();
        }
    }

    onNewCategory() {
        this.yBottomPositive = this.yOrigin;
        this.yBottomNegative = this.yOrigin;
        this.yRunningTotalPositive = 0;
        this.yRunningTotalNegative = 0;
        this.barIndex = 0;
    }

    next() {
        let ret;

        if (this.categoryIndex < this.categoryCount) {
            const series = this.renderer.renderedSeries[this.seriesIndex];
            const value = Tayberry.getDataValue(series.data[this.categoryIndex]);
            let categoryXStart = this.plotArea.left + Math.floor(this.categoryIndex * this.categoryWidth);
            let categoryXEnd = this.plotArea.left + Math.floor((this.categoryIndex + 1) * this.categoryWidth);
            let barXStart = categoryXStart + Math.ceil(this.categoryWidth * this.tb.options.barPlot.categorySpacing / 2);
            let barXEnd = categoryXEnd - Math.floor(this.categoryWidth * this.tb.options.barPlot.categorySpacing / 2);

            const barWidth = Math.floor((barXEnd - barXStart) / this.barCount);
            const xStart = Math.floor(barXStart + this.barIndex * barWidth);
            const xEnd = Math.ceil(barXStart + (this.barIndex + 1) * barWidth);

            const yTop = series.yAxis.getValueDisplacement(value + (value > 0 ? this.yRunningTotalPositive : this.yRunningTotalNegative));
            let rect = new Rect(xStart, yTop, xEnd, this.isStacked ? (value > 0 ? this.yBottomPositive : this.yBottomNegative) : series.yAxis.getOrigin());
            rect.left += Math.ceil(series.xAxis.mapLogicalXOrYUnit(this.tb.options.barPlot.barPadding) / 2);
            rect.right -= Math.floor(series.xAxis.mapLogicalXOrYUnit(this.tb.options.barPlot.barPadding) / 2);
            if (rect.right < rect.left)
                rect.right = rect.left;
            if (this.isHorizontal)
                rect.swapXY();
            rect.clip(this.tb.plotArea);

            ret = {
                seriesIndex: this.seriesIndex,
                categoryIndex: this.categoryIndex,
                series: this.renderer.series[this.seriesIndex],
                renderedSeries: this.renderer.renderedSeries[this.seriesIndex],
                value: Tayberry.getDataValue(this.renderer.series[this.seriesIndex].data[this.categoryIndex]),
                renderedValue: Tayberry.getDataValue(this.renderer.renderedSeries[this.seriesIndex].data[this.categoryIndex]),
                rect: rect,
                selected: this.tb.selectedItem.categoryIndex === this.categoryIndex && (this.tb.options.tooltips.shared || this.tb.selectedItem.series === this.renderer.series[this.seriesIndex])
            };

            if (this.isStacked) {
                if (value > 0) {
                    this.yRunningTotalPositive += value;
                    this.yBottomPositive = yTop;
                }
                else {
                    this.yRunningTotalNegative += value;
                    this.yBottomNegative = yTop;
                }
            } else if (this.isNormal) {
                this.barIndex++;
            }

            this.nextValue();

        }
        return ret;
    }
}

exports.BarRenderer = BarRenderer;<commit_msg>use new cached bar positions<commit_after>'use strict';
var Rect = require('./helpers/rect').Rect;
var Utils = require('./helpers/utils');
var renderer = require('./renderer.base');
var Tayberry = require('./base.js').Tayberry;

class BarRenderer extends renderer.Renderer {
    constructor(ctx, tayberry, series) {
        super(ctx, tayberry, series);

        this.barPositions = null;

        this.tb.registerCallback('onResize', this.updateBarWidths.bind(this));
        this.tb.registerCallback('onInit', this.updateBarWidths.bind(this));
    }

    updateBarWidths() {
        const categoryCount = this.renderedSeries[0].data.length;
        const isStacked = this.tb.options.barPlot.mode === 'stacked';
        const isOverlaid = this.tb.options.barPlot.mode === 'overlaid';
        const isNormal = !isStacked && !isOverlaid;
        const seriesCount = this.renderedSeries.length;
        const barsPerCategory = (isStacked || isOverlaid) ? 1 : this.renderedSeries.length;
        const plotArea = this.tb.options.swapAxes ? this.tb.plotArea.clone().swapXY() : this.tb.plotArea;
        const categoryWidth = (plotArea.width / categoryCount);

        this.barPositions = [];

        for (let categoryIndex = 0; categoryIndex<categoryCount; categoryIndex++) {
            const categoryXStart = plotArea.left + Math.floor(categoryIndex * categoryWidth);
            const categoryXEnd = plotArea.left + Math.floor((categoryIndex + 1) * categoryWidth);
            // FIXME: Need to map this.tb.options.barPlot.categorySpacing
            const barXStart = categoryXStart + Math.ceil(categoryWidth * this.tb.options.barPlot.categorySpacing / 2);
            const barXEnd = categoryXEnd - Math.floor(categoryWidth * this.tb.options.barPlot.categorySpacing / 2);
            const barWidth = Math.floor((barXEnd - barXStart) / barsPerCategory);

            let categoryPositions = [];
            let barIndex = 0;

            for (let seriesIndex = 0; seriesIndex<seriesCount; seriesIndex++) {
                const series = this.renderedSeries[seriesIndex];
                const xStart = Math.floor(barXStart + barIndex * barWidth) + Math.ceil(series.xAxis.mapLogicalXOrYUnit(this.tb.options.barPlot.barPadding) / 2);
                const xEnd = Math.ceil(barXStart + (barIndex + 1) * barWidth) - Math.floor(series.xAxis.mapLogicalXOrYUnit(this.tb.options.barPlot.barPadding) / 2);
                categoryPositions.push([xStart, xEnd]);

                if (isNormal) barIndex++;
            }

            this.barPositions.push(categoryPositions);
        }
    }

    drawPlot() {
        this.ctx.save();
        let barEnumerator = new BarEnumerator(this);
        let bar;
        while ((bar = barEnumerator.next())) {
            this.ctx.fillStyle = bar.selected ? bar.renderedSeries.highlightColour : bar.renderedSeries.colour;
            this.ctx.fillRect(bar.rect.left, bar.rect.top, bar.rect.width, bar.rect.height);
        }
        this.ctx.restore();
    }

    drawLabels() {
        if (this.tb.options.labels.enabled) {
            this.ctx.save();
            let barEnumerator = new BarEnumerator(this);
            let bar;
            while ((bar = barEnumerator.next())) {
                this.ctx.font = this.tb.labelFont;
                this.ctx.fillStyle = this.tb.options.labels.font.colour;
                this.drawLabel(bar.value, bar.series.yAxis.options.labelFormatter(bar.value), bar.rect);
            }
            this.ctx.restore();
        }
    }

    hitTest(x, y) {
        // TODO: Optimise
        let ret = {
            found: false,
            plotType: 'bar',
            isXRange: true
        };

        const categoryCount = this.renderedSeries[0].data.length;
        const isHorizontal = this.tb.options.swapAxes;
        let plotArea = this.tb.plotArea.clone();
        if (isHorizontal)
            plotArea.swapXY();
        const categoryIndex = Math.floor(categoryCount * ((isHorizontal ? y : x) - plotArea.left) / plotArea.width);

        let matches = [];

        let barEnumerator = new BarEnumerator(this, categoryIndex);
        let bar;
        while ((bar = barEnumerator.next())) {
            if (bar.categoryIndex > categoryIndex)
                break;
            let sortDistance, priority, realDistance;
            if (bar.rect.containsPoint(x, y)) {
                sortDistance = 0;
                priority = 0;
            }
            else if (bar.rect.containsX(x)) {
                sortDistance = y < bar.rect.top ? bar.rect.top - y : y - bar.rect.bottom;
                priority = isHorizontal ? 2 : 1;
            }
            else if (bar.rect.containsY(y)) {
                sortDistance = x < bar.rect.left ? bar.rect.left - x : x - bar.rect.right;
                priority = isHorizontal ? 1 : 2;
            }
            else {
                const xDist = Math.min(Math.abs(x - bar.rect.left), Math.abs(x - bar.rect.right));
                const yDist = Math.min(Math.abs(y - bar.rect.top), Math.abs(y - bar.rect.bottom));
                realDistance = Math.sqrt(Math.pow(xDist, 2) + Math.pow(yDist, 2));
                sortDistance = isHorizontal ? yDist : xDist;
                priority = 3;
            }

            if (typeof realDistance === 'undefined')
                realDistance = sortDistance;

            matches.push({
                sortDistance: sortDistance,
                distance: realDistance,
                priority: priority,
                data: {
                    categoryIndex: bar.categoryIndex,
                    seriesIndex: bar.seriesIndex,
                    rect: bar.rect,
                    series: this.series[bar.seriesIndex],
                    value: Tayberry.getDataValue(this.series[bar.seriesIndex].data[bar.categoryIndex])
                }
            });
        }

        if (matches.length) {
            matches.sort((a, b) => {
                let ret = a.priority - b.priority;
                if (!ret) ret = a.sortDistance - b.sortDistance;
                if (!ret) ret = a.data.rect.height - b.data.rect.height;
                return ret;
            });
            ret.found = true;
            ret.normalisedDistance = matches[0].distance + Math.sqrt(matches[0].data.rect.area);
            ret = Utils.assign(ret, matches[0].data);
        }
        return ret;
    }
}

class BarEnumerator extends renderer.ByCategoryEnumerator {
    constructor(renderer, startCategoryIndex = 0) {
        super(renderer, startCategoryIndex);
        if (this.categoryCount) {
            this.isStacked = this.tb.options.barPlot.mode === 'stacked';
            this.isOverlaid = this.tb.options.barPlot.mode === 'overlaid';
            this.isNormal = !this.isStacked && !this.isOverlaid;
            // used for stacked bar charts - must be on single y-axis
            this.yOrigin = this.renderer.series[0].yAxis.getOrigin();

            this.onNewCategory();
        }
    }

    onNewCategory() {
        this.yBottomPositive = this.yOrigin;
        this.yBottomNegative = this.yOrigin;
        this.yRunningTotalPositive = 0;
        this.yRunningTotalNegative = 0;
        this.barIndex = 0;
    }

    next() {
        let ret;

        if (this.categoryIndex < this.categoryCount) {
            const series = this.renderer.renderedSeries[this.seriesIndex];
            const value = Tayberry.getDataValue(series.data[this.categoryIndex]);

            const [xStart, xEnd] = this.renderer.barPositions[this.categoryIndex][this.seriesIndex];

            const yTop = series.yAxis.getValueDisplacement(value + (value > 0 ? this.yRunningTotalPositive : this.yRunningTotalNegative));
            let rect = new Rect(xStart, yTop, xEnd, this.isStacked ? (value > 0 ? this.yBottomPositive : this.yBottomNegative) : series.yAxis.getOrigin());

            if (rect.right < rect.left)
                rect.right = rect.left;
            if (this.isHorizontal)
                rect.swapXY();
            rect.clip(this.tb.plotArea);

            ret = {
                seriesIndex: this.seriesIndex,
                categoryIndex: this.categoryIndex,
                series: this.renderer.series[this.seriesIndex],
                renderedSeries: this.renderer.renderedSeries[this.seriesIndex],
                value: Tayberry.getDataValue(this.renderer.series[this.seriesIndex].data[this.categoryIndex]),
                renderedValue: Tayberry.getDataValue(this.renderer.renderedSeries[this.seriesIndex].data[this.categoryIndex]),
                rect: rect,
                selected: this.tb.selectedItem.categoryIndex === this.categoryIndex && (this.tb.options.tooltips.shared || this.tb.selectedItem.series === this.renderer.series[this.seriesIndex])
            };

            if (this.isStacked) {
                if (value > 0) {
                    this.yRunningTotalPositive += value;
                    this.yBottomPositive = yTop;
                }
                else {
                    this.yRunningTotalNegative += value;
                    this.yBottomNegative = yTop;
                }
            } else if (this.isNormal) {
                this.barIndex++;
            }

            this.nextValue();

        }
        return ret;
    }
}

exports.BarRenderer = BarRenderer;<|endoftext|>


<commit_before>/**
 * @file Require resource loading implementation
 */
/*#ifndef(UMD)*/
"use strict";
/*global _GPF_FS_OPENFOR*/ // File system stream opening mode
/*global _GPF_HOST*/ // Host types
/*global _GPF_HTTP_METHODS*/ // HTTP Methods
/*global _GpfStreamWritableString*/ // gpf.stream.WritableString
/*global _gpfFileStorageByHost*/ // gpf.interfaces.IFileStorage per host
/*global _gpfHost*/ // Host type
/*global _gpfHttpRequest*/ // HTTP request common implementation
/*global _gpfPathExtension*/
/*exported _gpfRequireLoad*/ // Load the resource
/*exported _gpfRequireProcessor*/ // Mapping of resource extension to processor function
/*#endif*/

/* this is globally used as the current context in this module */
/*jshint -W040*/
/*eslint-disable no-invalid-this*/

var _gpfRequireLoadImpl;

function _gpfRequireLoadHTTP (name) {
    return _gpfHttpRequest({
        method: _GPF_HTTP_METHODS.GET,
        url: name
    }).then(function (response) {
        return response.responseText;
    });
}

function _gpfRequireLoadFS (name) {
    var fs = _gpfFileStorageByHost[_gpfHost],
        iWritableStream = new _GpfStreamWritableString();
    if (name.charAt(0) === "/") {
        // Must be relative to the current execution path
        name = "." + name;
    }
    return fs.openTextStream(name, _GPF_FS_OPENFOR.READING)
        .then(function (iReadStream) {
            return iReadStream.read(iWritableStream);
        })
        .then(function () {
            return iWritableStream.toString();
        });
}

if (_gpfHost === _GPF_HOST.BROWSER || _gpfHost === _GPF_HOST.PHANTOM_JS) {
    _gpfRequireLoadImpl = _gpfRequireLoadHTTP;
} else {
    _gpfRequireLoadImpl = _gpfRequireLoadFS;
}

/**
 * Mapping of resource extension to processor function
 *
 * @type {Object}
 */
var _gpfRequireProcessor = {};

/**
 * Load the resource
 *
 * @param {String} name Resource name
 * @return {Promise<*>} Resolved with the resource result
 */
function _gpfRequireLoad (name) {
    var me = this;
    return _gpfRequireLoadImpl(name)
        .then(function (content) {
            var processor = _gpfRequireProcessor[_gpfPathExtension(name).toLowerCase()];
            if (processor) {
                return processor.call(me, name, content);
            }
            // Treated as simple text file by default
            return content;
        });
}

<commit_msg>Documentation (#192)<commit_after>/**
 * @file Require resource loading implementation
 * @since 0.2.2
 */
/*#ifndef(UMD)*/
"use strict";
/*global _GPF_FS_OPENFOR*/ // File system stream opening mode
/*global _GPF_HOST*/ // Host types
/*global _GPF_HTTP_METHODS*/ // HTTP Methods
/*global _GpfStreamWritableString*/ // gpf.stream.WritableString
/*global _gpfFileStorageByHost*/ // gpf.interfaces.IFileStorage per host
/*global _gpfHost*/ // Host type
/*global _gpfHttpRequest*/ // HTTP request common implementation
/*global _gpfPathExtension*/ // Get the extension of the last name of a path (including dot)
/*exported _gpfRequireLoad*/ // Load the resource
/*exported _gpfRequireProcessor*/ // Mapping of resource extension to processor function
/*#endif*/

/* this is globally used as the current context in this module */
/*jshint -W040*/
/*eslint-disable no-invalid-this*/

var _gpfRequireLoadImpl;

function _gpfRequireLoadHTTP (name) {
    return _gpfHttpRequest({
        method: _GPF_HTTP_METHODS.GET,
        url: name
    }).then(function (response) {
        return response.responseText;
    });
}

function _gpfRequireLoadFS (name) {
    var fs = _gpfFileStorageByHost[_gpfHost],
        iWritableStream = new _GpfStreamWritableString();
    if (name.charAt(0) === "/") {
        // Must be relative to the current execution path
        name = "." + name;
    }
    return fs.openTextStream(name, _GPF_FS_OPENFOR.READING)
        .then(function (iReadStream) {
            return iReadStream.read(iWritableStream);
        })
        .then(function () {
            return iWritableStream.toString();
        });
}

if (_gpfHost === _GPF_HOST.BROWSER || _gpfHost === _GPF_HOST.PHANTOM_JS) {
    _gpfRequireLoadImpl = _gpfRequireLoadHTTP;
} else {
    _gpfRequireLoadImpl = _gpfRequireLoadFS;
}

/**
 * Mapping of resource extension to processor function
 *
 * @type {Object}
 * @since 0.2.2
 */
var _gpfRequireProcessor = {};

/**
 * Load the resource
 *
 * @param {String} name Resource name
 * @return {Promise<*>} Resolved with the resource result
 * @since 0.2.2
 */
function _gpfRequireLoad (name) {
    var me = this;
    return _gpfRequireLoadImpl(name)
        .then(function (content) {
            var processor = _gpfRequireProcessor[_gpfPathExtension(name).toLowerCase()];
            if (processor) {
                return processor.call(me, name, content);
            }
            // Treated as simple text file by default
            return content;
        });
}

<|endoftext|>


<commit_before>/*
 * ShinyProxy
 *
 * Copyright (C) 2016-2020 Open Analytics
 *
 * ===========================================================================
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the Apache License as published by
 * The Apache Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * Apache License for more details.
 *
 * You should have received a copy of the Apache License
 * along with this program.  If not, see <http://www.apache.org/licenses/>
 */
document.addEventListener('DOMContentLoaded', function() {
	document.getElementById('new-version-btn').addEventListener("click", function() {
		 $.get("api/proxy", function(data, status){
		 	if (data.length > 0) {
		 		if (confirm("Warning: you have " + data.length + " apps running, your existing session(s) will be closed once you switch to the new version.")) {
		 			update();
				}
		 	} else {
		 		update();
		 	}
		 });

	});

	var spInstanceCookie = Cookies.get('sp-instance');
	var spLatestInstanceCookie = Cookies.get('sp-latest-instance');

	if (typeof spInstanceCookie !== 'undefined' && typeof spLatestInstanceCookie !== 'undefined') {
		if (spInstanceCookie !== spLatestInstanceCookie) {
			document.getElementById('new-version-banner').style.display = "block";
		}
	}

	function update() {
		// skipper sets cookie on the domain without any subdomain
		// we have to do this too
		var parts = location.hostname.split('.');
		if (parts.length <= 2) {
			var domain = location.hostname;
		} else {
			var domain = parts.slice(1).join('.');
		}

		Cookies.set('sp-instance', Cookies.get('sp-latest-instance'),  { domain: domain});
		location.reload();
	}

}, false);<commit_msg>Set path property when modifying cookie.<commit_after>/*
 * ShinyProxy
 *
 * Copyright (C) 2016-2020 Open Analytics
 *
 * ===========================================================================
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the Apache License as published by
 * The Apache Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * Apache License for more details.
 *
 * You should have received a copy of the Apache License
 * along with this program.  If not, see <http://www.apache.org/licenses/>
 */
document.addEventListener('DOMContentLoaded', function() {
	document.getElementById('new-version-btn').addEventListener("click", function() {
		 $.get("api/proxy", function(data, status){
		 	if (data.length > 0) {
		 		if (confirm("Warning: you have " + data.length + " apps running, your existing session(s) will be closed once you switch to the new version.")) {
		 			update();
				}
		 	} else {
		 		update();
		 	}
		 });

	});

	var spInstanceCookie = Cookies.get('sp-instance');
	var spLatestInstanceCookie = Cookies.get('sp-latest-instance');

	if (typeof spInstanceCookie !== 'undefined' && typeof spLatestInstanceCookie !== 'undefined') {
		if (spInstanceCookie !== spLatestInstanceCookie) {
			document.getElementById('new-version-banner').style.display = "block";
		}
	}

	function update() {
		var path = location.pathname;

		Cookies.set('sp-instance', Cookies.get('sp-latest-instance'),  {path: path});
		location.reload();
	}

}, false);<|endoftext|>


<commit_before>import Vue from 'vue'
import Router from 'vue-router'
import Index from 'components/index/Index'
import Reg from 'components/reg/Reg'
import NotFound from 'components/404/NotFound'

import Main from 'components/main/Main'
import Map from 'components/main/map/Map'

Vue.use(Router)

export default new Router({
  routes: [
    // {
    //   path: '/',
    //   name: 'Hello',
    //   component: Hello
    // },
    {
      path: '/',
      name: 'index',
      component: Index
    },
    {
      path: '/reg',
      name: 'reg',
      component: Reg
    },
    {
      path: '/main',
      name: 'main',
      component: Main,
      children: [
        {
          path: 'map',
          name: 'map',
          component: Map
        },
      ]
    },
    {
      path: '*',
      name: '404',
      component: NotFound
    }
  ]
})
<commit_msg>router redirect<commit_after>import Vue from 'vue'
import Router from 'vue-router'
import Index from 'components/index/Index'
import Reg from 'components/reg/Reg'
import NotFound from 'components/404/NotFound'

import Main from 'components/main/Main'
import Map from 'components/main/map/Map'

Vue.use(Router)

export default new Router({
  routes: [
    // {
    //   path: '/',
    //   name: 'Hello',
    //   component: Hello
    // },
    {
      path: '/',
      name: 'index',
      component: Index
    },
    {
      path: '/reg',
      name: 'reg',
      component: Reg
    },
    {
      path: '/main',
      redirect: '/main/map',
      name: 'main',
      component: Main,
      children: [
        {
          path: 'map',
          name: 'map',
          component: Map
        },
      ]
    },
    {
      path: '*',
      name: '404',
      component: NotFound
    }
  ]
})
<|endoftext|>


<commit_before>app.Legend = function() {

	var params, colors, featureCollection, categories;
	var $select = $('#select-location').find('select');
	var $showAll = $('#show-all');
	var $fullName = $('#full-name');

	var $legend = $('#legend')
		.on('click', 'input[type="checkbox"]', function() {
			var $checkbox = $(this);
			var action = ($checkbox.prop('checked') ? 'add' : 'remove');
			toggleCluster($checkbox.data().id, action);
		})
		.on('click', '.cat', function(e) {
			var catName = params.category && params.category[0];
			if (catName && $(this).data().name === catName) {
				return removeCategory(catName, e);
			}
		});

	// this.colors = colors;
	initSelectLoc(app.config.locations); // TODO global

	function initSelectLoc(locations) {
		$select.on('change', function() {
			// window.location.hash = '#!' + this.value;
			window.location.href = '/#!' + this.value;
			window.location.reload();
		});

		_(locations).keys().forEach(function(locName) {
			$('<option />')
				.text(locName)
				.val(locName)
				.appendTo($select)
		})
	}

	function clusterIds(from) {
		return from.map(function(cluster) { return cluster.properties.clusterId; });
	}

	function removeCategory(catName, e) {
		var removeClusters = clusterIds(categories[catName]);
		params.clusters = _.difference(params.clusters, removeClusters);
		location.hash = '#!' + params.location +
			/clusters/ + params.clusters.join(';');
		return !!e.preventDefault;
	}

	function toggleCluster(clusterId, action) {

		var clusters = params.clusters || [];

		if (action === 'add') {
			clusters.push(clusterId);
		}
		else if (action === 'remove') {
			clusters.splice(clusters.indexOf(clusterId), 1);
		}

		clusters = clusters.sort(function(n1, n2) {
			return n1 - n2;
		});

		location.hash = '#!' + params.location +
			// (params.category ? ('/category/' + params.category) : '') +
			/clusters/ + clusters.join(';');
	}

	function update(clusters, _params_, _colors_) {

		params = _params_;
		colors = _colors_;

		$fullName.html('' + params.locationParams.jsonUrl.replace(/^.*\/(.*)$/, '$1') + '');

		$showAll.on('click', function() {
			window.location.href = '#!' + params.location;
		});
		$select.find('option[value="' + params.location + '"]').prop('selected', true);

		clusters.fetch(function(_featureCollection_) {

			featureCollection = _featureCollection_;

			var selectAll = !params.category && !params.clusters;
			if (selectAll) {
				params.clusters = clusterIds(featureCollection.features);
			}

			categories = _.groupBy(featureCollection.features, function(feature) {
				return feature.properties.name;
			});

			var list = _(categories).keys().sort().map(function(catName) {

				var niceName = /c\((.*?)\)/.exec(catName)[1].replace(/,/g, ', ');
				var label = niceName + ' (' + categories[catName].length + ')';
				var sublist = [], subListStr = '';
				var colorCategory = colors[catName];
				var hrefCategory = '#!' + params.location + '/category/' + catName;
				var isChecked = params.category && params.category[0] === catName;
				if (isChecked) {
					params.clusters = clusterIds(categories[catName]);
				}

				if (categories[catName].length > 0) {
					sublist = categories[catName]
						.sort(function(cluster1, cluster2) {
							return cluster1.properties.clusterId - cluster2.properties.clusterId;
						})
						.map(function(cluster) {
							var clusterId = cluster.properties.clusterId;
							var sse = cluster.properties.sse ? cluster.properties.sse.toFixed(2) : 0;
							var label = 'cluster ' + clusterId +
								' (' + cluster.properties.venues.length +
								' venues, SSE = ' + sse  + ')';
							var hrefCluster = '#!' + params.location + '/clusters/' + clusterId;
							var isChecked = params.clusters && params.clusters.indexOf(clusterId) >= 0;
							isChecked = isChecked || selectAll;

							return '
' +
										'' +
											'<input data-id="' + clusterId + '" type="checkbox" ' + (isChecked ? 'checked' : '' )+ '/>' +
											label +
										'' +
									'
';
						});
				}

				if (sublist.length > 0) {
					subListStr = '
' + sublist.join('\n') + '
';
				}

				return 	'
' +
							' ' + label + '' +
							subListStr +
						'
';
			});

			$legend.html(list.join('\n'));
		});
	}

	return {
		update: update
	};

};<commit_msg>[ui] show density, coverage, heterogeneity measures<commit_after>app.Legend = function() {

	var params, colors, featureCollection, categories;
	var $select = $('#select-location').find('select');
	var $showAll = $('#show-all');
	var $fullName = $('#full-name');

	var $legend = $('#legend')
		.on('click', 'input[type="checkbox"]', function() {
			var $checkbox = $(this);
			var action = ($checkbox.prop('checked') ? 'add' : 'remove');
			toggleCluster($checkbox.data().id, action);
		})
		.on('click', '.cat', function(e) {
			var catName = params.category && params.category[0];
			if (catName && $(this).data().name === catName) {
				return removeCategory(catName, e);
			}
		});

	// this.colors = colors;
	initSelectLoc(app.config.locations); // TODO global

	function initSelectLoc(locations) {
		$select.on('change', function() {
			// window.location.hash = '#!' + this.value;
			window.location.href = '/#!' + this.value;
			window.location.reload();
		});

		_(locations).keys().forEach(function(locName) {
			$('<option />')
				.text(locName)
				.val(locName)
				.appendTo($select)
		})
	}

	function clusterIds(from) {
		return from.map(function(cluster) { return cluster.properties.clusterId; });
	}

	function removeCategory(catName, e) {
		var removeClusters = clusterIds(categories[catName]);
		params.clusters = _.difference(params.clusters, removeClusters);
		location.hash = '#!' + params.location +
			/clusters/ + params.clusters.join(';');
		return !!e.preventDefault;
	}

	function toggleCluster(clusterId, action) {

		var clusters = params.clusters || [];

		if (action === 'add') {
			clusters.push(clusterId);
		}
		else if (action === 'remove') {
			clusters.splice(clusters.indexOf(clusterId), 1);
		}

		clusters = clusters.sort(function(n1, n2) {
			return n1 - n2;
		});

		location.hash = '#!' + params.location +
			// (params.category ? ('/category/' + params.category) : '') +
			/clusters/ + clusters.join(';');
	}

	function update(clusters, _params_, _colors_) {

		params = _params_;
		colors = _colors_;

		$fullName.html('' + params.locationParams.jsonUrl.replace(/^.*\/(.*)$/, '$1') + '');

		$showAll.on('click', function() {
			window.location.href = '#!' + params.location;
		});
		$select.find('option[value="' + params.location + '"]').prop('selected', true);

		clusters.fetch(function(_featureCollection_) {

			featureCollection = _featureCollection_;

			var selectAll = !params.category && !params.clusters;
			if (selectAll) {
				params.clusters = clusterIds(featureCollection.features);
			}

			categories = _.groupBy(featureCollection.features, function(feature) {
				return feature.properties.name;
			});

			var list = _(categories).keys().sort().map(function(catName) {

				var niceName = /c\((.*?)\)/.exec(catName)[1].replace(/,/g, ', ');
				var label = niceName + ' (' + categories[catName].length + ')';
				var sublist = [], subListStr = '';
				var colorCategory = colors[catName];
				var hrefCategory = '#!' + params.location + '/category/' + catName;
				var isChecked = params.category && params.category[0] === catName;
				if (isChecked) {
					params.clusters = clusterIds(categories[catName]);
				}

				if (categories[catName].length > 0) {
					sublist = categories[catName]
						.sort(function(cluster1, cluster2) {
							return cluster1.properties.clusterId - cluster2.properties.clusterId;
						})
						.map(function(cluster) {
							var clusterId = cluster.properties.clusterId;
							var heterogeneity = cluster.properties.heterogeneity ? cluster.properties.heterogeneity.toFixed(2) : 0;
							var surface = cluster.properties.heterogeneity ? cluster.properties.surface.toFixed(2) : 0;
							var density = cluster.properties.density ? cluster.properties.density.toFixed(2) : 0;
							var sse = cluster.properties.sse ? cluster.properties.sse.toFixed(2) : 0;
							var label = 'cluster ' + clusterId +
								' (' + cluster.properties.venues.length +
								' venues; SSE=' + sse  +
								', surface=' + surface +
								', density=' + density +
								', heterogeneity=' + heterogeneity +
								')';
							var hrefCluster = '#!' + params.location + '/clusters/' + clusterId;
							var isChecked = params.clusters && params.clusters.indexOf(clusterId) >= 0;
							isChecked = isChecked || selectAll;

							return '
' +
										'' +
											'<input data-id="' + clusterId + '" type="checkbox" ' + (isChecked ? 'checked' : '' )+ '/>' +
											label +
										'' +
									'
';
						});
				}

				if (sublist.length > 0) {
					subListStr = '
' + sublist.join('\n') + '
';
				}

				return 	'
' +
							' ' + label + '' +
							subListStr +
						'
';
			});

			$legend.html(list.join('\n'));
		});
	}

	return {
		update: update
	};

};<|endoftext|>


<commit_before>import { Object3D } from '../core/Object3D';

/**
 * @author mrdoob / http://mrdoob.com/
 */

function Scene () {

	Object3D.call( this );

	this.type = 'Scene';

	this.background = null;
	this.fog = null;
	this.overrideMaterial = null;

	this.autoUpdate = true; // checked by the renderer

}

Scene.prototype = Object.create( Object3D.prototype );

Scene.prototype.constructor = Scene;

Scene.prototype.copy = function ( source, recursive ) {

	Object3D.prototype.copy.call( this, source, recursive );

	if ( source.background !== null ) this.background = source.background.clone();
	if ( source.fog !== null ) this.fog = source.fog.clone();
	if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();

	this.autoUpdate = source.autoUpdate;
	this.matrixAutoUpdate = source.matrixAutoUpdate;

	return this;

};

Scene.prototype.toJSON = function ( meta ) {

	var data = Object3D.prototype.toJSON.call( this, meta );

	if ( this.fog != null ) {

		data.object.fog = this.fog.toJSON();

	}

	return data;

};

export { Scene };
<commit_msg>Scene: Clean up.<commit_after>import { Object3D } from '../core/Object3D';

/**
 * @author mrdoob / http://mrdoob.com/
 */

function Scene () {

	Object3D.call( this );

	this.type = 'Scene';

	this.background = null;
	this.fog = null;
	this.overrideMaterial = null;

	this.autoUpdate = true; // checked by the renderer

}

Scene.prototype = Object.create( Object3D.prototype );

Scene.prototype.constructor = Scene;

Scene.prototype.copy = function ( source, recursive ) {

	Object3D.prototype.copy.call( this, source, recursive );

	if ( source.background !== null ) this.background = source.background.clone();
	if ( source.fog !== null ) this.fog = source.fog.clone();
	if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();

	this.autoUpdate = source.autoUpdate;
	this.matrixAutoUpdate = source.matrixAutoUpdate;

	return this;

};

Scene.prototype.toJSON = function ( meta ) {

	var data = Object3D.prototype.toJSON.call( this, meta );

	if ( this.fog !== null ) data.object.fog = this.fog.toJSON();

	return data;

};

export { Scene };
<|endoftext|>


<commit_before>/*
$.material.init();
$.material.ripples();
$.material.input();
$.material.checkbox();
$.material.radio();
*/
<commit_msg>Deleted src/scirpts/init.js<commit_after><|endoftext|>


<commit_before>'use strict';

import { remote } from 'electron';
import path from 'path';
import i18n from '../i18n/index.js';

const { Tray, Menu } = remote;

const mainWindow = remote.getCurrentWindow();

const icons = {
    win32: {
        dir: 'windows'
    },
    linux: {
        dir: 'linux'
    },
    darwin: {
        dir: 'osx'
    }
};

const statusBullet = {
    online: '\u001B[32m•',
    away: '\u001B[33m•',
    busy: '\u001B[31m•',
    offline: '\u001B[30m•'
};

const messageCountColor = {
    white: '\u001B[37m',
    black: '\u001B[0m'
};

function getTrayImagePath (badge) {
    let iconFilename;
    if (badge.title === '•') {
        iconFilename = "icon-tray-dot";
    } else if (badge.count > 0) {
        if (badge.count > 9) {
            iconFilename = "icon-tray-9plus";
        } else {
            iconFilename = `icon-tray-${badge.count}`;
        }
    } else if (badge.showAlert) {
        iconFilename = "icon-tray-alert";
    } else {
        iconFilename = "icon-tray-Template";
    }

    if (process.platform === 'win32') {
        iconFilename += ".ico";
    } else {
        iconFilename += ".png";
    }

    return path.join(__dirname, 'images', icons[process.platform].dir, iconFilename);
}

function createAppTray () {
    const _tray = new Tray(getTrayImagePath({title:'', count:0, showAlert:false}));
    mainWindow.tray = _tray;

    const contextMenuShow = Menu.buildFromTemplate([{
        label: i18n.__('Show'),
        click () {
            mainWindow.show();
        }
    }, {
        label: i18n.__('Quit'),
        click () {
            remote.app.quit();
        }
    }]);

    const contextMenuHide = Menu.buildFromTemplate([{
        label: i18n.__('Hide'),
        click () {
            mainWindow.hide();
        }
    }, {
        label: i18n.__('Quit'),
        click () {
            remote.app.quit();
        }
    }]);

    if (!mainWindow.isMinimized() && !mainWindow.isVisible()) {
        _tray.setContextMenu(contextMenuShow);
    } else {
        _tray.setContextMenu(contextMenuHide);
    }

    const onShow = function () {
        _tray.setContextMenu(contextMenuHide);
    };

    const onHide = function () {
        _tray.setContextMenu(contextMenuShow);
    };

    mainWindow.on('show', onShow);
    mainWindow.on('restore', onShow);

    mainWindow.on('hide', onHide);
    mainWindow.on('minimize', onHide);

    _tray.setToolTip(remote.app.getName());

    _tray.on('right-click', function (e, b) {
        _tray.popUpContextMenu(undefined, b);
    });

    _tray.on('click', () => {
        if (mainWindow.isVisible()) {
            return mainWindow.hide();
        }

        mainWindow.show();
    });

    mainWindow.destroyTray = function () {
        mainWindow.removeListener('show', onShow);
        mainWindow.removeListener('hide', onHide);
        _tray.destroy();
    };
}

function showTrayAlert (badge, status = 'online') {
    if (mainWindow.tray === null || mainWindow.tray === undefined) {
        return;
    }

    const trayDisplayed = localStorage.getItem('hideTray') === 'true';
    const hasMentions = badge.showAlert && badge.count > 0;

    if (!mainWindow.isFocused()) {
        mainWindow.flashFrame(hasMentions);
    }

    if (process.platform === 'win32') {
        if (hasMentions) {
            mainWindow.webContents.send('render-taskbar-icon', badge.count);
        } else {
            mainWindow.setOverlayIcon(null, '');
        }
    }

    if (process.platform === 'darwin') {
        let countColor = messageCountColor['black'];
        if (remote.systemPreferences.isDarkMode()) {
            countColor = messageCountColor['white'];
        }

        let trayTitle = `${statusBullet[status]}`;
        if (hasMentions) {
            trayTitle = `${statusBullet[status]} ${countColor}${badge.title}`;
        }
        remote.app.dock.setBadge(badge.title);
        if (trayDisplayed) {
            mainWindow.tray.setTitle(trayTitle);
        }
    }

    if (process.platform === 'linux') {
        remote.app.setBadgeCount(badge.count);
    }

    if (trayDisplayed) {
        mainWindow.tray.setImage(getTrayImagePath(badge));
    }
}

function removeAppTray () {
    mainWindow.destroyTray();
}

function toggle () {
    if (localStorage.getItem('hideTray') === 'true') {
        createAppTray();
        localStorage.setItem('hideTray', 'false');
    } else {
        removeAppTray();
        localStorage.setItem('hideTray', 'true');
    }
}

if (localStorage.getItem('hideTray') !== 'true') {
    createAppTray();
}

export default {
    showTrayAlert,
    toggle
};
<commit_msg>Show tray icon status again<commit_after>'use strict';

import { remote } from 'electron';
import path from 'path';
import i18n from '../i18n/index.js';

const { Tray, Menu } = remote;

const mainWindow = remote.getCurrentWindow();

const icons = {
    win32: {
        dir: 'windows'
    },
    linux: {
        dir: 'linux'
    },
    darwin: {
        dir: 'osx'
    }
};

const statusBullet = {
    online: '\u001B[32m•',
    away: '\u001B[33m•',
    busy: '\u001B[31m•',
    offline: '\u001B[37m•'
};

const messageCountColor = {
    white: '\u001B[37m',
    black: '\u001B[0m'
};

function getTrayImagePath (badge) {
    let iconFilename;
    if (badge.title === '•') {
        iconFilename = "icon-tray-dot";
    } else if (badge.count > 0) {
        if (badge.count > 9) {
            iconFilename = "icon-tray-9plus";
        } else {
            iconFilename = `icon-tray-${badge.count}`;
        }
    } else if (badge.showAlert) {
        iconFilename = "icon-tray-alert";
    } else {
        iconFilename = "icon-tray-Template";
    }

    if (process.platform === 'win32') {
        iconFilename += ".ico";
    } else {
        iconFilename += ".png";
    }

    return path.join(__dirname, 'images', icons[process.platform].dir, iconFilename);
}

function createAppTray () {
    const _tray = new Tray(getTrayImagePath({title:'', count:0, showAlert:false}));
    mainWindow.tray = _tray;

    const contextMenuShow = Menu.buildFromTemplate([{
        label: i18n.__('Show'),
        click () {
            mainWindow.show();
        }
    }, {
        label: i18n.__('Quit'),
        click () {
            remote.app.quit();
        }
    }]);

    const contextMenuHide = Menu.buildFromTemplate([{
        label: i18n.__('Hide'),
        click () {
            mainWindow.hide();
        }
    }, {
        label: i18n.__('Quit'),
        click () {
            remote.app.quit();
        }
    }]);

    if (!mainWindow.isMinimized() && !mainWindow.isVisible()) {
        _tray.setContextMenu(contextMenuShow);
    } else {
        _tray.setContextMenu(contextMenuHide);
    }

    const onShow = function () {
        _tray.setContextMenu(contextMenuHide);
    };

    const onHide = function () {
        _tray.setContextMenu(contextMenuShow);
    };

    mainWindow.on('show', onShow);
    mainWindow.on('restore', onShow);

    mainWindow.on('hide', onHide);
    mainWindow.on('minimize', onHide);

    _tray.setToolTip(remote.app.getName());

    _tray.on('right-click', function (e, b) {
        _tray.popUpContextMenu(undefined, b);
    });

    _tray.on('click', () => {
        if (mainWindow.isVisible()) {
            return mainWindow.hide();
        }

        mainWindow.show();
    });

    mainWindow.destroyTray = function () {
        mainWindow.removeListener('show', onShow);
        mainWindow.removeListener('hide', onHide);
        _tray.destroy();
    };
}

function showTrayAlert (badge, status = 'online') {
    if (mainWindow.tray === null || mainWindow.tray === undefined) {
        return;
    }

    const trayDisplayed = localStorage.getItem('hideTray') !== 'true';
    const hasMentions = badge.showAlert && badge.count > 0;

    if (!mainWindow.isFocused()) {
        mainWindow.flashFrame(hasMentions);
    }

    if (process.platform === 'win32') {
        if (hasMentions) {
            mainWindow.webContents.send('render-taskbar-icon', badge.count);
        } else {
            mainWindow.setOverlayIcon(null, '');
        }
    }

    if (process.platform === 'darwin') {
        let countColor = messageCountColor['black'];
        if (remote.systemPreferences.isDarkMode()) {
            countColor = messageCountColor['white'];
        }

        let trayTitle = `${statusBullet[status]}`;
        if (hasMentions) {
            trayTitle = `${statusBullet[status]} ${countColor}${badge.title}`;
        }
        remote.app.dock.setBadge(badge.title);
        if (trayDisplayed) {
            mainWindow.tray.setTitle(trayTitle);
        }
    }

    if (process.platform === 'linux') {
        remote.app.setBadgeCount(badge.count);
    }

    if (trayDisplayed) {
        mainWindow.tray.setImage(getTrayImagePath(badge));
    }
}

function removeAppTray () {
    mainWindow.destroyTray();
}

function toggle () {
    if (localStorage.getItem('hideTray') === 'true') {
        createAppTray();
        localStorage.setItem('hideTray', 'false');
    } else {
        removeAppTray();
        localStorage.setItem('hideTray', 'true');
    }
}

if (localStorage.getItem('hideTray') !== 'true') {
    createAppTray();
}

export default {
    showTrayAlert,
    toggle
};
<|endoftext|>


<commit_before>(function(module) {

	var _messages = piggydb.server.messages;

	var _markItUpSettings = {
		nameSpace: 'markItUp-root',
    previewAutoRefresh: false,
    previewParserPath:  '', // path to your Wiki parser
    onShiftEnter:   {keepDefault:false, replaceWith:'\n\n'},
    markupSet: [
      {name: _messages["editor-bold"], key: 'B', openWith: "'''", closeWith: "'''"},
      {name: _messages["editor-italic"], key: 'I', openWith: "''", closeWith: "''"},
      {name: _messages["editor-strike"], key: 'S', openWith: '__', closeWith: '__'},
      {separator: '---------------' },
      {name: _messages["editor-bulleted-list"], openWith: '-'},
      {name: _messages["editor-numeric-list"], openWith: '+'},
      {separator: '---------------' },
      {name: _messages["editor-link"], key: "L", openWith: "[[![URL:!:http://]!] ",
        closeWith: ']', placeHolder: _messages["editor-link-label"] },
      {name: _messages["editor-embed-another-fragment"], key: 'E',
        openWith: "fragment:[![" + _messages["editor-fragment-id"] + "]!]:embed "},
      {separator: '---------------' },
      {name: _messages["editor-quote"], openWith: '>', placeHolder: ''},
      {separator: '---------------' },
      {name: _messages["help"]}
    ]
  };

	var _wikiHelp = new piggydb.widget.Facebox("facebox-wiki-help");

	var _class = function(element, id) {
		module.Widget.call(this, element);
		this.id = id;
		this.textarea = this.element.find("textarea.fragment-content");
		this.indicator = this.element.find("span.indicator");
		this.prepare();
	};

	_class.addToolBar = function(textarea, resizeHandle) {
		_markItUpSettings.resizeHandle = resizeHandle;
		textarea.markItUp(_markItUpSettings);
	};

	_class.linkToWikiHelp = function(a) {
		a.attr("href", piggydb.server.wikiHelpUrl).click(function() {
	  	_wikiHelp.show(this.href);
	    return false;
	  });
	};

	_class.openToCreate = function() {
		piggydb.util.blockPageDuringAjaxRequest();

		jQuery("#fragment-editor-new").remove();
		jQuery.get("html/fragment-editor.htm", function(html) {
			jQuery("body").append(html);
			var form = new _class(jQuery("#fragment-editor-new"), "fragment-editor-new");
			form.open();
		});
	};

	_class.prototype = jQuery.extend({

		prepare: function() {
			jQuery.updnWatermark.attachAll();

			this.element.find("input.fragment-as-tag").button({
	      icons: {
	      	primary: "ui-icon-piggydb-tag"
	      },
	      text: false
		  });

			this.element.find("input[name=tags]").autocomplete(piggydb.server.autoCompleteUrl, {
		    minChars: 1,
		    selectFirst: true,
		    multiple: true,
		    multipleSeparator: ', ',
		    scrollHeight: 300
		  });

			var outer = this;
			var palette = new piggydb.widget.TagPalette(this.element.find("div.tag-palette"));
			palette.onTagSelect = function(source, tagId, tagName, palette) {
        var input = outer.element.find("input[name='tags']");
        var tags = jQuery.trim(input.val());
        if (tags == null || tags == "")
          tags = tagName;
        else
          tags = tags + ", " + tagName;
        input.val(tags);
        input.focus();
      };
      palette.decideMaxHeight = function() {
      	return outer.textarea.height() + 50;
      };
      palette.flatColumnWidth = 100;
      palette.autoFlatWidth = true;
      palette.init(this.element.find("button.pulldown"));

			_class.addToolBar(this.textarea, false);
			_class.linkToWikiHelp(this.element.find(".markItUp .markItUpButton9 a"));
		},

		open: function() {
			var outer = this;

			this.element.dialog({
		    modal: false,
		    width: 600,
		    height: 450,
		    resize: function() {
		    	outer.adjustEditorHeight();
				}
		  });

			this.element.find("button.preview").click(function() {
				outer.block();
				// TODO
			});
			this.element.find("button.cancel").click(function() {
				outer.element.dialog("close");
			});

			this.adjustEditorHeight();
			this.textarea.get(0).focus();

			// test
			this.setFormError("qTip utilises a special positioning system using corners.");
			this.setInputError("title", "You must enter the title if the fragment will be used as a tag.");
			this.setInputError("tags", "Tag name must be at least 2 characters.");
			this.element.find("button.preview").click(function() {
				outer.clearErrors();
			});
		},

		block: function() {
			this.element.block({
				message: '',
				css: {
					border: '0px solid #aaa',
					width: '30px',
					padding: '15px',
					fadeIn: 0,
					fadeOut: 0
				}
			});
		},

		adjustEditorHeight: function() {
			var baseHeight = this.element.find("form").height()
				- this.element.find("div.title").height()
				- this.element.find("div.tags").height()
				- this.element.find("div.buttons").height();
			this.textarea.height(baseHeight - 55);
		},

		setFormError: function(message) {
			piggydb.widget.putErrorMessage(this.indicator, this.id, message, this.element);
		},

		setInputError: function(name, message) {
			var input = this.element.find("form :input[name='" + name + "']");
			piggydb.widget.setInputError(input, this.id + "-" + name, message, this.element);
		},

		clearErrors: function() {
			piggydb.widget.clearErrorMessage(this.indicator);
			this.element.find("form :input").each(function() {
				piggydb.widget.clearInputError(this);
			});
		}

	}, module.Widget.prototype);

	module.FragmentForm = _class;

})(piggydb.widget);
<commit_msg>#new_fragment_form: modified the style of FragmentForm.block()<commit_after>(function(module) {

	var _messages = piggydb.server.messages;

	var _markItUpSettings = {
		nameSpace: 'markItUp-root',
    previewAutoRefresh: false,
    previewParserPath:  '', // path to your Wiki parser
    onShiftEnter:   {keepDefault:false, replaceWith:'\n\n'},
    markupSet: [
      {name: _messages["editor-bold"], key: 'B', openWith: "'''", closeWith: "'''"},
      {name: _messages["editor-italic"], key: 'I', openWith: "''", closeWith: "''"},
      {name: _messages["editor-strike"], key: 'S', openWith: '__', closeWith: '__'},
      {separator: '---------------' },
      {name: _messages["editor-bulleted-list"], openWith: '-'},
      {name: _messages["editor-numeric-list"], openWith: '+'},
      {separator: '---------------' },
      {name: _messages["editor-link"], key: "L", openWith: "[[![URL:!:http://]!] ",
        closeWith: ']', placeHolder: _messages["editor-link-label"] },
      {name: _messages["editor-embed-another-fragment"], key: 'E',
        openWith: "fragment:[![" + _messages["editor-fragment-id"] + "]!]:embed "},
      {separator: '---------------' },
      {name: _messages["editor-quote"], openWith: '>', placeHolder: ''},
      {separator: '---------------' },
      {name: _messages["help"]}
    ]
  };

	var _wikiHelp = new piggydb.widget.Facebox("facebox-wiki-help");

	var _class = function(element, id) {
		module.Widget.call(this, element);
		this.id = id;
		this.textarea = this.element.find("textarea.fragment-content");
		this.indicator = this.element.find("span.indicator");
		this.prepare();
	};

	_class.addToolBar = function(textarea, resizeHandle) {
		_markItUpSettings.resizeHandle = resizeHandle;
		textarea.markItUp(_markItUpSettings);
	};

	_class.linkToWikiHelp = function(a) {
		a.attr("href", piggydb.server.wikiHelpUrl).click(function() {
	  	_wikiHelp.show(this.href);
	    return false;
	  });
	};

	_class.openToCreate = function() {
		piggydb.util.blockPageDuringAjaxRequest();

		jQuery("#fragment-editor-new").remove();
		jQuery.get("html/fragment-editor.htm", function(html) {
			jQuery("body").append(html);
			var form = new _class(jQuery("#fragment-editor-new"), "fragment-editor-new");
			form.open();
		});
	};

	_class.prototype = jQuery.extend({

		prepare: function() {
			jQuery.updnWatermark.attachAll();

			this.element.find("input.fragment-as-tag").button({
	      icons: {
	      	primary: "ui-icon-piggydb-tag"
	      },
	      text: false
		  });

			this.element.find("input[name=tags]").autocomplete(piggydb.server.autoCompleteUrl, {
		    minChars: 1,
		    selectFirst: true,
		    multiple: true,
		    multipleSeparator: ', ',
		    scrollHeight: 300
		  });

			var outer = this;
			var palette = new piggydb.widget.TagPalette(this.element.find("div.tag-palette"));
			palette.onTagSelect = function(source, tagId, tagName, palette) {
        var input = outer.element.find("input[name='tags']");
        var tags = jQuery.trim(input.val());
        if (tags == null || tags == "")
          tags = tagName;
        else
          tags = tags + ", " + tagName;
        input.val(tags);
        input.focus();
      };
      palette.decideMaxHeight = function() {
      	return outer.textarea.height() + 50;
      };
      palette.flatColumnWidth = 100;
      palette.autoFlatWidth = true;
      palette.init(this.element.find("button.pulldown"));

			_class.addToolBar(this.textarea, false);
			_class.linkToWikiHelp(this.element.find(".markItUp .markItUpButton9 a"));
		},

		open: function() {
			var outer = this;

			this.element.dialog({
		    modal: false,
		    width: 600,
		    height: 450,
		    resize: function() {
		    	outer.adjustEditorHeight();
				}
		  });

			this.element.find("button.preview").click(function() {
				outer.block();
				// TODO
			});
			this.element.find("button.cancel").click(function() {
				outer.element.dialog("close");
			});

			this.adjustEditorHeight();
			this.textarea.get(0).focus();

			// test
			this.setFormError("qTip utilises a special positioning system using corners.");
			this.setInputError("title", "You must enter the title if the fragment will be used as a tag.");
			this.setInputError("tags", "Tag name must be at least 2 characters.");
			this.element.find("button.preview").click(function() {
				outer.clearErrors();
			});
		},

		block: function() {
			this.element.block({
				message: '',
				centerX: true,
		    centerY: true,
				css: {
					border: '0px solid #aaa',
					width: '30px',
					padding: '15px',
					fadeIn: 0,
					fadeOut: 0
				},
				overlayCSS:  {
	      	opacity: 0.4
				}
			});
		},

		adjustEditorHeight: function() {
			var baseHeight = this.element.find("form").height()
				- this.element.find("div.title").height()
				- this.element.find("div.tags").height()
				- this.element.find("div.buttons").height();
			this.textarea.height(baseHeight - 55);
		},

		setFormError: function(message) {
			piggydb.widget.putErrorMessage(this.indicator, this.id, message, this.element);
		},

		setInputError: function(name, message) {
			var input = this.element.find("form :input[name='" + name + "']");
			piggydb.widget.setInputError(input, this.id + "-" + name, message, this.element);
		},

		clearErrors: function() {
			piggydb.widget.clearErrorMessage(this.indicator);
			this.element.find("form :input").each(function() {
				piggydb.widget.clearInputError(this);
			});
		}

	}, module.Widget.prototype);

	module.FragmentForm = _class;

})(piggydb.widget);
<|endoftext|>