<commit_before>/* global appendChartID, coordsFromTranslate, loadDateFixture */
describe('dc.legend', function () {
    var id, chart, dateDimension, dateValueSumGroup, dateIdSumGroup;

    beforeEach(function () {
        var data = crossfilter(loadDateFixture());
        dateDimension = data.dimension(function (d) { return d3.time.day.utc(d.dd); });
        dateValueSumGroup = dateDimension.group().reduceSum(function (d) { return d.value; });
        dateIdSumGroup = dateDimension.group().reduceSum(function (d) { return d.id; });

        id = 'legend-chart';
        appendChartID(id);
        chart = dc.lineChart('#' + id);

        chart
            .dimension(dateDimension)
            .group(dateIdSumGroup, 'Id Sum')
            .stack(dateValueSumGroup, 'Value Sum')
            .stack(dateValueSumGroup, 'Fixed', function () {})
            .x(d3.time.scale.utc().domain([new Date(2012, 4, 20), new Date(2012, 7, 15)]))
            .legend(dc.legend().x(400).y(10).itemHeight(13).gap(5));
    });

    describe('rendering the legend', function () {
        beforeEach(function () {
            chart.render();
        });

        it('should generate a legend', function () {
            expect(chart.select('g.dc-legend').empty()).toBeFalsy();
        });

        it('should place the legend using the provided x and y values', function () {
            expect(chart.select('g.dc-legend').attr('transform')).toMatchTranslate(400, 10);
        });

        it('should generate a legend item for each stacked line', function () {
            expect(chart.select('g.dc-legend').selectAll('g.dc-legend-item').size()).toBe(3);
        });

        it('should generate legend item boxes', function () {
            expect(legendIcon(0).attr('width')).toBeWithinDelta(13, 2);
            expect(legendIcon(0).attr('height')).toBeWithinDelta(13, 2);
        });

        it('should color the legend item boxes using the chart line colors', function () {
            expect(legendIcon(0).attr('fill')).toMatch(/#1f77b4/i);
            expect(legendIcon(1).attr('fill')).toMatch(/#ff7f0e/i);
            expect(legendIcon(2).attr('fill')).toMatch(/#2ca02c/i);
        });

        it('should generate a legend label for each chart line', function () {
            expect(chart.selectAll('g.dc-legend g.dc-legend-item text').size()).toBe(3);
        });

        it('should position the legend labels', function () {
            expect(legendLabel(0).attr('x')).toBeWithinDelta(15, 2);
            expect(legendLabel(0).attr('y')).toBeWithinDelta(11.75, 2);
            expect(legendLabel(1).attr('x')).toBeWithinDelta(15, 2);
            expect(legendLabel(1).attr('y')).toBeWithinDelta(11.75, 2);
            expect(legendLabel(2).attr('x')).toBeWithinDelta(15, 2);
            expect(legendLabel(2).attr('y')).toBeWithinDelta(11.75, 2);
        });

        it('should label the legend items with the names of their associated stacks', function () {
            expect(legendLabel(0).text()).toBe('Id Sum');
            expect(legendLabel(1).text()).toBe('Value Sum');
            expect(legendLabel(2).text()).toBe('Fixed');
        });

        it('not allow hiding stacks be default', function () {
            legendItem(0).on('click').call(legendItem(0)[0][0], legendItem(0).datum());
            expect(chart.selectAll('path.line').size()).toBe(3);
        });

        describe('without .horizontal(true)', function () {
            it('should place legend items vertically', function () {
                expect(coordsFromTranslate(legendItem(0).attr('transform')).y).toBeWithinDelta(0, 1);
                expect(coordsFromTranslate(legendItem(1).attr('transform')).y).toBeWithinDelta(18, 2);
                expect(coordsFromTranslate(legendItem(2).attr('transform')).y).toBeWithinDelta(36, 4);
            });
        });

        describe('with .horizontal(true)', function () {
            beforeEach(function () {
                chart.legend(dc.legend().horizontal(true));
                chart.render();
            });

            it('should place legend items horizontally', function () {
                expect(coordsFromTranslate(legendItem(0).attr('transform')).x).toBeWithinDelta(0, 1);
                expect(coordsFromTranslate(legendItem(1).attr('transform')).x).toBeWithinDelta(65, 5);
                expect(coordsFromTranslate(legendItem(2).attr('transform')).x).toBeWithinDelta(155, 15);
            });
        });

        describe('with .horizontal(true) and defined legendWidth and itemWidth', function () {
            beforeEach(function () {
                chart.legend(dc.legend().horizontal(true).legendWidth(60).itemWidth(30));
                chart.render();
            });

            it('should place legend items in two columns. third item is new row', function () {
                expect(coordsFromTranslate(legendItem(0).attr('transform')).x).toBeWithinDelta(0, 1);
                expect(coordsFromTranslate(legendItem(1).attr('transform')).x).toBeWithinDelta(30, 5);
                expect(coordsFromTranslate(legendItem(2).attr('transform')).x).toBeWithinDelta(0, 1);
                expect(coordsFromTranslate(legendItem(0).attr('transform')).y).toBeWithinDelta(0, 1);
                expect(coordsFromTranslate(legendItem(1).attr('transform')).y).toBeWithinDelta(0, 1);
                expect(coordsFromTranslate(legendItem(2).attr('transform')).y).toBeWithinDelta(13, 5);
            });
        });

        describe('with .autoItemWidth not called', function () {
            beforeEach(function () {
                chart.legend(dc.legend());
            });

            it('_autoItemWidth should be false', function () {
                expect(chart.legend().autoItemWidth()).toBe(false);
            });
        });

        describe('with .autoItemWidth(false)', function () {
            beforeEach(function () {
                chart.legend(dc.legend().autoItemWidth(false));
            });

            it('_autoItemWidth should be false', function () {
                expect(chart.legend().autoItemWidth()).toBe(false);
            });
        });

        describe('with .autoItemWidth(true)', function () {
            beforeEach(function () {
                chart.legend(dc.legend().autoItemWidth(true));
            });
            it('_autoItemWidth should be true', function () {
                expect(chart.legend().autoItemWidth()).toBe(true);
            });
        });

        describe('with .horizontal(true) and .autoItemWidth(true)', function () {

            var
                autoWidthOffset1, fixedWidthOffset1,
                autoWidthOffset2, fixedWidthOffset2;

            beforeEach(function () {
                chart.legend(dc.legend().horizontal(true).itemWidth(30).autoItemWidth(false));
                chart.render();
                fixedWidthOffset1 = coordsFromTranslate(legendItem(1).attr('transform')).x;
                fixedWidthOffset2 = coordsFromTranslate(legendItem(2).attr('transform')).x;
                chart.legend(dc.legend().horizontal(true).itemWidth(30).autoItemWidth(true));
                chart.render();
                autoWidthOffset1  = coordsFromTranslate(legendItem(1).attr('transform')).x;
                autoWidthOffset2  = coordsFromTranslate(legendItem(2).attr('transform')).x;
            });

            it('autoWidth x offset should be greater than fixedWidth x offset for some legend items', function () {
                expect(autoWidthOffset1).toBeGreaterThan(fixedWidthOffset1);
                expect(autoWidthOffset2).toBeGreaterThan(fixedWidthOffset2);
            });
        });

        describe('with .legendText()', function () {
            beforeEach(function () {
                chart.legend(dc.legend().legendText(function (d, i) {
                    var _i = i + 1;

                    return _i + '. ' + d.name;
                }));
                chart.render();
            });

            it('should label the legend items with the names of their associated stacks', function () {
                expect(legendLabel(0).text()).toBe('1. Id Sum');
                expect(legendLabel(1).text()).toBe('2. Value Sum');
                expect(legendLabel(2).text()).toBe('3. Fixed');
            });
        });
    });

    describe('legends with dashed lines', function () {
        beforeEach(function () {
            id = 'legend-chart-dashed';
            appendChartID(id);
            chart = dc.compositeChart('#' + id);

            var subChart1 = dc.lineChart(chart);
            subChart1
                .dimension(dateDimension)
                .group(dateIdSumGroup, 'Id Sum')
                .dashStyle([10,1]);

            var subChart2 = dc.lineChart(chart);
            subChart2
                .dimension(dateDimension)
                .group(dateValueSumGroup, 'Value Sum')
                .dashStyle([2,1]);

            chart
                .x(d3.scale.linear().domain([0,20]))
                .legend(dc.legend().x(400).y(10).itemHeight(13).gap(5))
                .compose([subChart1, subChart2])
                .render();
        });

        it('should style legend line correctly', function () {
            expect(legendLine(0).attr('stroke-dasharray')).toEqualIntList('10,1');
            expect(legendLine(1).attr('stroke-dasharray')).toEqualIntList('2,1');
        });
    });

    describe('legends with hidable stacks', function () {
        beforeEach(function () {
            chart.hidableStacks(true).render();
        });

        describe('clicking on a legend item', function () {
            beforeEach(function () {
                legendItem(0).on('click').call(legendItem(0)[0][0], legendItem(0).datum());
            });

            it('should fade out the legend item', function () {
                expect(legendItem(0).classed('fadeout')).toBeTruthy();
            });

            it('should hide its associated stack', function () {
                expect(chart.selectAll('path.line').size()).toEqual(2);
            });

            it('disable hover highlighting for that legend item', function () {
                legendItem(0).on('mouseover')(legendItem(0).datum());
                expect(d3.select(chart.selectAll('path.line')[0][1]).classed('fadeout')).toBeFalsy();
            });

            describe('clicking on a faded out legend item', function () {
                beforeEach(function () {
                    legendItem(0).on('click').call(legendItem(0)[0][0], legendItem(0).datum());
                });

                it('should unfade the legend item', function () {
                    expect(legendItem(0).classed('fadeout')).toBeFalsy();
                });

                it('should unfade its associated stack', function () {
                    expect(chart.selectAll('path.line').size()).toEqual(3);
                });
            });
        });
    });

    function legendItem (n) {
        return d3.select(chart.selectAll('g.dc-legend g.dc-legend-item')[0][n]);
    }
    function legendLabel (n) {
        return d3.select(chart.selectAll('g.dc-legend g.dc-legend-item text')[0][n]);
    }
    function legendIcon (n) {
        return d3.select(chart.selectAll('g.dc-legend g.dc-legend-item rect')[0][n]);
    }
    function legendLine (n) {
        return d3.select(chart.selectAll('g.dc-legend g.dc-legend-item line')[0][n]);
    }
});

<commit_msg>test #1114<commit_after>/* global appendChartID, coordsFromTranslate, loadDateFixture */
describe('dc.legend', function () {
    var id, chart, dateDimension, dateValueSumGroup, dateIdSumGroup;

    beforeEach(function () {
        var data = crossfilter(loadDateFixture());
        dateDimension = data.dimension(function (d) { return d3.time.day.utc(d.dd); });
        dateValueSumGroup = dateDimension.group().reduceSum(function (d) { return d.value; });
        dateIdSumGroup = dateDimension.group().reduceSum(function (d) { return d.id; });

        id = 'legend-chart';
        appendChartID(id);
        chart = dc.lineChart('#' + id);

        chart
            .dimension(dateDimension)
            .group(dateIdSumGroup, 'Id Sum')
            .stack(dateValueSumGroup, 'Value Sum')
            .stack(dateValueSumGroup, 'Fixed', function () {})
            .x(d3.time.scale.utc().domain([new Date(2012, 4, 20), new Date(2012, 7, 15)]))
            .legend(dc.legend().x(400).y(10).itemHeight(13).gap(5));
    });

    describe('rendering the legend', function () {
        beforeEach(function () {
            chart.render();
        });

        it('should generate a legend', function () {
            expect(chart.select('g.dc-legend').empty()).toBeFalsy();
        });

        it('should place the legend using the provided x and y values', function () {
            expect(chart.select('g.dc-legend').attr('transform')).toMatchTranslate(400, 10);
        });

        it('should generate a legend item for each stacked line', function () {
            expect(chart.select('g.dc-legend').selectAll('g.dc-legend-item').size()).toBe(3);
        });

        it('should generate legend item boxes', function () {
            expect(legendIcon(0).attr('width')).toBeWithinDelta(13, 2);
            expect(legendIcon(0).attr('height')).toBeWithinDelta(13, 2);
        });

        it('should color the legend item boxes using the chart line colors', function () {
            expect(legendIcon(0).attr('fill')).toMatch(/#1f77b4/i);
            expect(legendIcon(1).attr('fill')).toMatch(/#ff7f0e/i);
            expect(legendIcon(2).attr('fill')).toMatch(/#2ca02c/i);
        });

        it('should generate a legend label for each chart line', function () {
            expect(chart.selectAll('g.dc-legend g.dc-legend-item text').size()).toBe(3);
        });

        it('should position the legend labels', function () {
            expect(legendLabel(0).attr('x')).toBeWithinDelta(15, 2);
            expect(legendLabel(0).attr('y')).toBeWithinDelta(11.75, 2);
            expect(legendLabel(1).attr('x')).toBeWithinDelta(15, 2);
            expect(legendLabel(1).attr('y')).toBeWithinDelta(11.75, 2);
            expect(legendLabel(2).attr('x')).toBeWithinDelta(15, 2);
            expect(legendLabel(2).attr('y')).toBeWithinDelta(11.75, 2);
        });

        it('should label the legend items with the names of their associated stacks', function () {
            expect(legendLabel(0).text()).toBe('Id Sum');
            expect(legendLabel(1).text()).toBe('Value Sum');
            expect(legendLabel(2).text()).toBe('Fixed');
        });

        it('not allow hiding stacks be default', function () {
            legendItem(0).on('click').call(legendItem(0)[0][0], legendItem(0).datum());
            expect(chart.selectAll('path.line').size()).toBe(3);
        });

        describe('without .horizontal(true)', function () {
            it('should place legend items vertically', function () {
                expect(coordsFromTranslate(legendItem(0).attr('transform')).y).toBeWithinDelta(0, 1);
                expect(coordsFromTranslate(legendItem(1).attr('transform')).y).toBeWithinDelta(18, 2);
                expect(coordsFromTranslate(legendItem(2).attr('transform')).y).toBeWithinDelta(36, 4);
            });
        });

        describe('with .horizontal(true)', function () {
            beforeEach(function () {
                chart.legend(dc.legend().horizontal(true));
                chart.render();
            });

            it('should place legend items horizontally', function () {
                expect(coordsFromTranslate(legendItem(0).attr('transform')).x).toBeWithinDelta(0, 1);
                expect(coordsFromTranslate(legendItem(1).attr('transform')).x).toBeWithinDelta(65, 5);
                expect(coordsFromTranslate(legendItem(2).attr('transform')).x).toBeWithinDelta(155, 15);
            });
        });

        describe('with .horizontal(true) and defined legendWidth and itemWidth', function () {
            beforeEach(function () {
                chart.legend(dc.legend().horizontal(true).legendWidth(60).itemWidth(30));
                chart.render();
            });

            it('should place legend items in two columns. third item is new row', function () {
                expect(coordsFromTranslate(legendItem(0).attr('transform')).x).toBeWithinDelta(0, 1);
                expect(coordsFromTranslate(legendItem(1).attr('transform')).x).toBeWithinDelta(30, 5);
                expect(coordsFromTranslate(legendItem(2).attr('transform')).x).toBeWithinDelta(0, 1);
                expect(coordsFromTranslate(legendItem(0).attr('transform')).y).toBeWithinDelta(0, 1);
                expect(coordsFromTranslate(legendItem(1).attr('transform')).y).toBeWithinDelta(0, 1);
                expect(coordsFromTranslate(legendItem(2).attr('transform')).y).toBeWithinDelta(13, 5);
            });
        });

        describe('with .autoItemWidth not called', function () {
            beforeEach(function () {
                chart.legend(dc.legend());
            });

            it('_autoItemWidth should be false', function () {
                expect(chart.legend().autoItemWidth()).toBe(false);
            });
        });

        describe('with .autoItemWidth(false)', function () {
            beforeEach(function () {
                chart.legend(dc.legend().autoItemWidth(false));
            });

            it('_autoItemWidth should be false', function () {
                expect(chart.legend().autoItemWidth()).toBe(false);
            });
        });

        describe('with .autoItemWidth(true)', function () {
            beforeEach(function () {
                chart.legend(dc.legend().autoItemWidth(true));
            });
            it('_autoItemWidth should be true', function () {
                expect(chart.legend().autoItemWidth()).toBe(true);
            });
        });

        describe('with .horizontal(true) and .autoItemWidth(true)', function () {

            var
                autoWidthOffset1, fixedWidthOffset1,
                autoWidthOffset2, fixedWidthOffset2;

            beforeEach(function () {
                chart.legend(dc.legend().horizontal(true).itemWidth(30).autoItemWidth(false));
                chart.render();
                fixedWidthOffset1 = coordsFromTranslate(legendItem(1).attr('transform')).x;
                fixedWidthOffset2 = coordsFromTranslate(legendItem(2).attr('transform')).x;
                chart.legend(dc.legend().horizontal(true).itemWidth(30).autoItemWidth(true));
                chart.render();
                autoWidthOffset1  = coordsFromTranslate(legendItem(1).attr('transform')).x;
                autoWidthOffset2  = coordsFromTranslate(legendItem(2).attr('transform')).x;
            });

            it('autoWidth x offset should be greater than fixedWidth x offset for some legend items', function () {
                expect(autoWidthOffset1).toBeGreaterThan(fixedWidthOffset1);
                expect(autoWidthOffset2).toBeGreaterThan(fixedWidthOffset2);
            });
        });

        describe('with .legendText()', function () {
            beforeEach(function () {
                chart.legend(dc.legend().legendText(function (d, i) {
                    var _i = i + 1;

                    return _i + '. ' + d.name;
                }));
                chart.render();
            });

            it('should label the legend items with the names of their associated stacks', function () {
                expect(legendLabel(0).text()).toBe('1. Id Sum');
                expect(legendLabel(1).text()).toBe('2. Value Sum');
                expect(legendLabel(2).text()).toBe('3. Fixed');
            });
        });

        describe('with .maxItems(2)', function () {
            beforeEach(function () {
                chart.legend()
                    .maxItems(2);
                chart.render();
            });
            it('should display two items', function () {
                expect(chart.select('g.dc-legend').selectAll('g.dc-legend-item').size()).toBe(2);
            });
        });

        describe('with invalid .maxItems', function () {
            beforeEach(function () {
                chart.legend()
                    .maxItems('foo');
                chart.render();
            });
            it('should display three items', function () {
                expect(chart.select('g.dc-legend').selectAll('g.dc-legend-item').size()).toBe(3);
            });
        });
    });

    describe('legends with dashed lines', function () {
        beforeEach(function () {
            id = 'legend-chart-dashed';
            appendChartID(id);
            chart = dc.compositeChart('#' + id);

            var subChart1 = dc.lineChart(chart);
            subChart1
                .dimension(dateDimension)
                .group(dateIdSumGroup, 'Id Sum')
                .dashStyle([10,1]);

            var subChart2 = dc.lineChart(chart);
            subChart2
                .dimension(dateDimension)
                .group(dateValueSumGroup, 'Value Sum')
                .dashStyle([2,1]);

            chart
                .x(d3.scale.linear().domain([0,20]))
                .legend(dc.legend().x(400).y(10).itemHeight(13).gap(5))
                .compose([subChart1, subChart2])
                .render();
        });

        it('should style legend line correctly', function () {
            expect(legendLine(0).attr('stroke-dasharray')).toEqualIntList('10,1');
            expect(legendLine(1).attr('stroke-dasharray')).toEqualIntList('2,1');
        });
    });

    describe('legends with hidable stacks', function () {
        beforeEach(function () {
            chart.hidableStacks(true).render();
        });

        describe('clicking on a legend item', function () {
            beforeEach(function () {
                legendItem(0).on('click').call(legendItem(0)[0][0], legendItem(0).datum());
            });

            it('should fade out the legend item', function () {
                expect(legendItem(0).classed('fadeout')).toBeTruthy();
            });

            it('should hide its associated stack', function () {
                expect(chart.selectAll('path.line').size()).toEqual(2);
            });

            it('disable hover highlighting for that legend item', function () {
                legendItem(0).on('mouseover')(legendItem(0).datum());
                expect(d3.select(chart.selectAll('path.line')[0][1]).classed('fadeout')).toBeFalsy();
            });

            describe('clicking on a faded out legend item', function () {
                beforeEach(function () {
                    legendItem(0).on('click').call(legendItem(0)[0][0], legendItem(0).datum());
                });

                it('should unfade the legend item', function () {
                    expect(legendItem(0).classed('fadeout')).toBeFalsy();
                });

                it('should unfade its associated stack', function () {
                    expect(chart.selectAll('path.line').size()).toEqual(3);
                });
            });
        });
    });

    function legendItem (n) {
        return d3.select(chart.selectAll('g.dc-legend g.dc-legend-item')[0][n]);
    }
    function legendLabel (n) {
        return d3.select(chart.selectAll('g.dc-legend g.dc-legend-item text')[0][n]);
    }
    function legendIcon (n) {
        return d3.select(chart.selectAll('g.dc-legend g.dc-legend-item rect')[0][n]);
    }
    function legendLine (n) {
        return d3.select(chart.selectAll('g.dc-legend g.dc-legend-item line')[0][n]);
    }
});

<|endoftext|>


<commit_before>export function getChartSetting ({colors}) {
    return [{
        label: "Punti di misurazione",
        key: "siteNavigator",
        iconClass: "map",
        hoverColor: colors.white,
        color: colors.iconDropdown
    },
    {
        label: "Periodo",
        key: "dateFilter",
        iconClass: "calendar",
        hoverColor: colors.white,
        color: colors.iconDropdown
    },
    {
        label: "Confronto tra sensori",
        key: "siteCompare",
        iconClass: "confront",
        hoverColor: colors.white,
        color: colors.iconDropdown
    },
    {
        label: "Confronto tra periodi",
        key: "dateCompare",
        iconClass: "confront",
        hoverColor: colors.white,
        color: colors.iconDropdown
    },
    {
        label: "Esporta",
        key: "export",
        iconClass: "export",
        hoverColor: colors.white,
        color: colors.iconDropdown
    }];
}

export function getMeasurementTypes () {
    return [
        {label: "Energia attiva", key: "activeEnergy"},
        {label: "Potenza massima", key: "maxPower"},
        {label: "Energia reattiva", key: "reactiveEnergy"}
    ];
}

export function getSources (theme) {
    // PER DEMO 10/10/16
    // return [
    //     {label: "Reale", color: theme.colors.lineReale, key: "reading"},
    //     {label: "Previsionale", color: theme.colors.linePrevisionale, key: "forecast"}
    // ];
    return [
        {label: "Reale", color: theme.colors.lineReale, key: "reading"},
    ];
}

export function getExportType () {
    return [
        {
            label: "Png",
            key: "png",
            iconClass: "png"
        },
        {
            label: "Csv",
            key: "csv",
            iconClass: "csv"
        }
    ];
}

export function getDateCompare () {
    return [
        {label: "IERI", key: "days"},
        {label: "7 GG FA", key: "7 days before"},
        {label: "SETTIMANA SCORSA", key: "week"},
        {label: "MESE SCORSO", key: "months"},
        {label: "12 MESI FA", key: "years"}
    ];
}
<commit_msg>Fixed lint error.<commit_after>export function getChartSetting ({colors}) {
    return [{
        label: "Punti di misurazione",
        key: "siteNavigator",
        iconClass: "map",
        hoverColor: colors.white,
        color: colors.iconDropdown
    },
    {
        label: "Periodo",
        key: "dateFilter",
        iconClass: "calendar",
        hoverColor: colors.white,
        color: colors.iconDropdown
    },
    {
        label: "Confronto tra sensori",
        key: "siteCompare",
        iconClass: "confront",
        hoverColor: colors.white,
        color: colors.iconDropdown
    },
    {
        label: "Confronto tra periodi",
        key: "dateCompare",
        iconClass: "confront",
        hoverColor: colors.white,
        color: colors.iconDropdown
    },
    {
        label: "Esporta",
        key: "export",
        iconClass: "export",
        hoverColor: colors.white,
        color: colors.iconDropdown
    }];
}

export function getMeasurementTypes () {
    return [
        {label: "Energia attiva", key: "activeEnergy"},
        {label: "Potenza massima", key: "maxPower"},
        {label: "Energia reattiva", key: "reactiveEnergy"}
    ];
}

export function getSources (theme) {
    // PER DEMO 10/10/16
    // return [
    //     {label: "Reale", color: theme.colors.lineReale, key: "reading"},
    //     {label: "Previsionale", color: theme.colors.linePrevisionale, key: "forecast"}
    // ];
    return [
        {label: "Reale", color: theme.colors.lineReale, key: "reading"}
    ];
}

export function getExportType () {
    return [
        {
            label: "Png",
            key: "png",
            iconClass: "png"
        },
        {
            label: "Csv",
            key: "csv",
            iconClass: "csv"
        }
    ];
}

export function getDateCompare () {
    return [
        {label: "IERI", key: "days"},
        {label: "7 GG FA", key: "7 days before"},
        {label: "SETTIMANA SCORSA", key: "week"},
        {label: "MESE SCORSO", key: "months"},
        {label: "12 MESI FA", key: "years"}
    ];
}
<|endoftext|>


<commit_before>// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.

define([
    "nbextensions/widgets/widgets/js/widget",
    "base/js/utils",
], function(widget, utils) {
    'use strict';

    var Button = widget.DOMWidgetView.extend({
        /* Very simple view for a gamepad button. */

        render : function(){
            this.$support = $('<div />').css({
                    'position': 'relative',
                    'margin': '1px',
                    'width': '16px',
                    'height': '16px',
                    'border': '1px solid black',
                    'background': 'lightgray',
                })
                .appendTo(this.$el);
            this.$bar = $('<div />')
                .css({
                    'position': 'absolute',
                    'width': '100%',
                    'bottom': 0,
                    'background': 'gray',
                })
                .appendTo(this.$support);
            this.$label = $('<div />')
                .text(this.model.get('description'))
                .css('text-align', 'center')
                .appendTo(this.$el);
            this.update();
        },

        update : function() {
            this.$bar.css('height', 100 * this.model.get('value') + '%');
        },

    });

    var Axis = widget.DOMWidgetView.extend({
        /* Very simple view for a gamepad axis. */

        render : function() {
            this.$el.css({
                    'width': '16px',
                    'padding': '4px',
                });
            this.$support = $('<div />').css({
                    'position': 'relative',
                    'margin': '1px',
                    'width': '4px',
                    'height': '64px',
                    'border': '1px solid black',
                    'background': 'lightgray',
                })
                .appendTo(this.$el);
            this.$bullet = $('<div />')
                .css({
                    'position': 'absolute',
                    'margin': '-4px',
                    'width': '10px',
                    'height': '10px',
                    'background': 'gray',
                })
                .appendTo(this.$support);
            this.$label = $('<div />')
                .text(this.model.get('description'))
                .css('text-align', 'center')
                .appendTo(this.$el);
            this.update();
        },

        update : function() {
            this.$bullet.css('top', 50 * (this.model.get('value') + 1) + '%');
        },

    });

    var Controller = widget.WidgetModel.extend({
        /* The Controller model. */

        initialize: function() {
            if (navigator.getGamepads === void 0) {
                // Checks if the browser supports the gamepad API
                console.error('This browser does not support gamepads.');
            } else {
                // Start the wait loop, and listen to updates of the only
                // user-provided attribute, the gamepad index.
                this.wait_loop();
            }
        },

        wait_loop: function() {
            /* Waits for a gamepad to be connected at the provided index.
             * Once one is connected, it will start the update loop, which
             * populates the update of axes and button values.
             */
            var index = this.get('index');
            var pad = navigator.getGamepads()[index];
            if (pad) {
                this.index = index;
                var that = this;
                this.setup(pad).then(function(controls) {
                    that.set(controls);
                    that.save_changes();
                    window.requestAnimationFrame(that.update_loop.bind(that));
                });
            } else {
                window.requestAnimationFrame(this.wait_loop.bind(this));
            }
        },

        setup: function(pad) {
            /* Given a native gamepad object, returns a promise for a dictionary of
             * controls, of the form
             * {
             *     buttons: list of Button models,
             *     axes: list of Axis models,
             * }
             */
            // Set up the main gamepad attributes
            this.set({
                name: pad.id,
                mapping: pad.mapping,
                connected: pad.connected,
                timestamp: pad.timestamp,
            });
            // Create buttons and axes. When done, start the update loop
            var that = this;
            return utils.resolve_promises_dict({
                buttons: Promise.all(pad.buttons.map(function(btn, index) {
                    return that._create_button_model(index);
                })),
                axes: Promise.all(pad.axes.map(function(axis, index) {
                    return that._create_axis_model(index);
                })),
            });
        },

        update_loop: function() {
            /* Populates axes and button values, until the gamepad is disconnected.
             * When the gamepad is disconnected, this.reset_gamepad is called.
             */
            var index = this.get('index');
            var pad = navigator.getGamepads()[index];
            if (pad && this.index === index) {
                this.set({
                    timestamp: pad.timestamp,
                    connected: pad.connected,
                });
                this.save_changes();
                this.get('buttons').forEach(function(model, index) {
                    model.set({
                        value: pad.buttons[index].value,
                        pressed: pad.buttons[index].pressed,
                    });
                    model.save_changes();
                });
                this.get('axes').forEach(function(model, index) {
                    model.set('value', pad.axes[index]);
                    model.save_changes();
                });
                window.requestAnimationFrame(this.update_loop.bind(this));
            } else {
                this.reset_gamepad();
            }
        },

        reset_gamepad: function() {
            /* Resets the gamepad attributes, and calls the wait_loop.
             */
            this.get('buttons').forEach(function(button) {
                button.close();
            });
            this.get('axes').forEach(function(axis) {
                axis.close();
            });
            this.set({
                name: '',
                mapping: '',
                connected: false,
                timestamp: 0.0,
                buttons: [],
                axes: [],
            });
            this.save_changes();
            window.requestAnimationFrame(this.wait_loop.bind(this));
        },

        _create_button_model: function(index) {
            /* Creates a gamepad button widget.
             */
            return this.widget_manager.new_widget({
                 model_name: 'WidgetModel',
                 widget_class: 'ipywidgets.widgets.widget_controller.Button',
            }).then(function(model) {
                 model.set('description', index);
                 return model;
            });
        },

        _create_axis_model: function(index) {
            /* Creates a gamepad axis widget.
             */
            return this.widget_manager.new_widget({
                 model_name: 'WidgetModel',
                 widget_class: 'ipywidgets.widgets.widget_controller.Axis',
            }).then(function(model) {
                 model.set('description', index);
                 return model;
            });
        },

    }, {

        serializers: _.extend({
            buttons: {deserialize: widget.unpack_models},
            axes: {deserialize: widget.unpack_models},
        }, widget.WidgetModel.serializers)

    });

    var ControllerView = widget.DOMWidgetView.extend({
        /* A simple view for a gamepad. */

        initialize: function() {
            ControllerView.__super__.initialize.apply(this, arguments);

            this.button_views = new widget.ViewList(this.add_button, null, this);
            this.listenTo(this.model, 'change:buttons', function(model, value) {
                this.button_views.update(value);
            }, this);

            this.axis_views = new widget.ViewList(this.add_axis, null, this);
            this.listenTo(this.model, 'change:axes', function(model, value) {
                this.axis_views.update(value);
            }, this);

            this.listenTo(this.model, 'change:name', this.update_label, this);
        },

        render: function(){
            this.$box = this.$el;

            this.$label = $('<div />')
                .appendTo(this.$box);

            this.$axis_box = $('<div />')
                .css('display', 'flex')
                .appendTo(this.$box);

            this.$button_box = $('<div />')
                .css('display', 'flex')
                .appendTo(this.$box);

            this.button_views.update(this.model.get('buttons'));
            this.axis_views.update(this.model.get('axes'));

            this.update_label();
        },

        update_label: function() {
            this.$label.text(this.model.get('name') ||
                             'Connect gamepad and press any button');
        },

        add_button: function(model) {
            var that = this;
            var dummy = $('<div/>');
            that.$button_box.append(dummy);
            return this.create_child_view(model).then(function(view) {
                dummy.replaceWith(view.el);
                that.displayed.then(function() {
                    view.trigger('displayed');
                });
                return view;
            }).catch(utils.reject('Could not add button view', true));
        },

        add_axis: function(model) {
            var that = this;
            var dummy = $('<div/>');
            that.$axis_box.append(dummy);
            return this.create_child_view(model).then(function(view) {
                dummy.replaceWith(view.el);
                that.displayed.then(function() {
                    view.trigger('displayed');
                });
                return view;
            }).catch(utils.reject('Could not add axis view', true));
        },

        remove: function() {
            ControllerView.__super__.remove.apply(this, arguments);
            this.button_views.remove();
            this.axis_views.remove();
        },

    });

    return {
        ControllerButton: Button,
        ControllerAxis: Axis,
        Controller: Controller,
        ControllerView: ControllerView,
    };
});
<commit_msg>Readout for unsupported gamepad API<commit_after>// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.

define([
    "nbextensions/widgets/widgets/js/widget",
    "base/js/utils",
], function(widget, utils) {
    'use strict';

    var Button = widget.DOMWidgetView.extend({
        /* Very simple view for a gamepad button. */

        render : function(){
            this.$support = $('<div />').css({
                    'position': 'relative',
                    'margin': '1px',
                    'width': '16px',
                    'height': '16px',
                    'border': '1px solid black',
                    'background': 'lightgray',
                })
                .appendTo(this.$el);
            this.$bar = $('<div />')
                .css({
                    'position': 'absolute',
                    'width': '100%',
                    'bottom': 0,
                    'background': 'gray',
                })
                .appendTo(this.$support);
            this.$label = $('<div />')
                .text(this.model.get('description'))
                .css('text-align', 'center')
                .appendTo(this.$el);
            this.update();
        },

        update : function() {
            this.$bar.css('height', 100 * this.model.get('value') + '%');
        },

    });

    var Axis = widget.DOMWidgetView.extend({
        /* Very simple view for a gamepad axis. */

        render : function() {
            this.$el.css({
                    'width': '16px',
                    'padding': '4px',
                });
            this.$support = $('<div />').css({
                    'position': 'relative',
                    'margin': '1px',
                    'width': '4px',
                    'height': '64px',
                    'border': '1px solid black',
                    'background': 'lightgray',
                })
                .appendTo(this.$el);
            this.$bullet = $('<div />')
                .css({
                    'position': 'absolute',
                    'margin': '-4px',
                    'width': '10px',
                    'height': '10px',
                    'background': 'gray',
                })
                .appendTo(this.$support);
            this.$label = $('<div />')
                .text(this.model.get('description'))
                .css('text-align', 'center')
                .appendTo(this.$el);
            this.update();
        },

        update : function() {
            this.$bullet.css('top', 50 * (this.model.get('value') + 1) + '%');
        },

    });

    var Controller = widget.WidgetModel.extend({
        /* The Controller model. */

        initialize: function() {
            if (navigator.getGamepads === void 0) {
                // Checks if the browser supports the gamepad API
                this.readout = 'This browser does not support gamepads.';
                console.error(this.readout);
            } else {
                // Start the wait loop, and listen to updates of the only
                // user-provided attribute, the gamepad index.
                this.readout = 'Connect gamepad and press any button.';
                this.wait_loop();
            }
        },

        wait_loop: function() {
            /* Waits for a gamepad to be connected at the provided index.
             * Once one is connected, it will start the update loop, which
             * populates the update of axes and button values.
             */
            var index = this.get('index');
            var pad = navigator.getGamepads()[index];
            if (pad) {
                this.index = index;
                var that = this;
                this.setup(pad).then(function(controls) {
                    that.set(controls);
                    that.save_changes();
                    window.requestAnimationFrame(that.update_loop.bind(that));
                });
            } else {
                window.requestAnimationFrame(this.wait_loop.bind(this));
            }
        },

        setup: function(pad) {
            /* Given a native gamepad object, returns a promise for a dictionary of
             * controls, of the form
             * {
             *     buttons: list of Button models,
             *     axes: list of Axis models,
             * }
             */
            // Set up the main gamepad attributes
            this.set({
                name: pad.id,
                mapping: pad.mapping,
                connected: pad.connected,
                timestamp: pad.timestamp,
            });
            // Create buttons and axes. When done, start the update loop
            var that = this;
            return utils.resolve_promises_dict({
                buttons: Promise.all(pad.buttons.map(function(btn, index) {
                    return that._create_button_model(index);
                })),
                axes: Promise.all(pad.axes.map(function(axis, index) {
                    return that._create_axis_model(index);
                })),
            });
        },

        update_loop: function() {
            /* Populates axes and button values, until the gamepad is disconnected.
             * When the gamepad is disconnected, this.reset_gamepad is called.
             */
            var index = this.get('index');
            var pad = navigator.getGamepads()[index];
            if (pad && this.index === index) {
                this.set({
                    timestamp: pad.timestamp,
                    connected: pad.connected,
                });
                this.save_changes();
                this.get('buttons').forEach(function(model, index) {
                    model.set({
                        value: pad.buttons[index].value,
                        pressed: pad.buttons[index].pressed,
                    });
                    model.save_changes();
                });
                this.get('axes').forEach(function(model, index) {
                    model.set('value', pad.axes[index]);
                    model.save_changes();
                });
                window.requestAnimationFrame(this.update_loop.bind(this));
            } else {
                this.reset_gamepad();
            }
        },

        reset_gamepad: function() {
            /* Resets the gamepad attributes, and calls the wait_loop.
             */
            this.get('buttons').forEach(function(button) {
                button.close();
            });
            this.get('axes').forEach(function(axis) {
                axis.close();
            });
            this.set({
                name: '',
                mapping: '',
                connected: false,
                timestamp: 0.0,
                buttons: [],
                axes: [],
            });
            this.save_changes();
            window.requestAnimationFrame(this.wait_loop.bind(this));
        },

        _create_button_model: function(index) {
            /* Creates a gamepad button widget.
             */
            return this.widget_manager.new_widget({
                 model_name: 'WidgetModel',
                 widget_class: 'ipywidgets.widgets.widget_controller.Button',
            }).then(function(model) {
                 model.set('description', index);
                 return model;
            });
        },

        _create_axis_model: function(index) {
            /* Creates a gamepad axis widget.
             */
            return this.widget_manager.new_widget({
                 model_name: 'WidgetModel',
                 widget_class: 'ipywidgets.widgets.widget_controller.Axis',
            }).then(function(model) {
                 model.set('description', index);
                 return model;
            });
        },

    }, {

        serializers: _.extend({
            buttons: {deserialize: widget.unpack_models},
            axes: {deserialize: widget.unpack_models},
        }, widget.WidgetModel.serializers)

    });

    var ControllerView = widget.DOMWidgetView.extend({
        /* A simple view for a gamepad. */

        initialize: function() {
            ControllerView.__super__.initialize.apply(this, arguments);

            this.button_views = new widget.ViewList(this.add_button, null, this);
            this.listenTo(this.model, 'change:buttons', function(model, value) {
                this.button_views.update(value);
            }, this);

            this.axis_views = new widget.ViewList(this.add_axis, null, this);
            this.listenTo(this.model, 'change:axes', function(model, value) {
                this.axis_views.update(value);
            }, this);

            this.listenTo(this.model, 'change:name', this.update_label, this);
        },

        render: function(){
            this.$box = this.$el;

            this.$label = $('<div />')
                .appendTo(this.$box);

            this.$axis_box = $('<div />')
                .css('display', 'flex')
                .appendTo(this.$box);

            this.$button_box = $('<div />')
                .css('display', 'flex')
                .appendTo(this.$box);

            this.button_views.update(this.model.get('buttons'));
            this.axis_views.update(this.model.get('axes'));

            this.update_label();
        },

        update_label: function() {
            this.$label.text(this.model.get('name') || this.model.readout);
        },

        add_button: function(model) {
            var that = this;
            var dummy = $('<div/>');
            that.$button_box.append(dummy);
            return this.create_child_view(model).then(function(view) {
                dummy.replaceWith(view.el);
                that.displayed.then(function() {
                    view.trigger('displayed');
                });
                return view;
            }).catch(utils.reject('Could not add button view', true));
        },

        add_axis: function(model) {
            var that = this;
            var dummy = $('<div/>');
            that.$axis_box.append(dummy);
            return this.create_child_view(model).then(function(view) {
                dummy.replaceWith(view.el);
                that.displayed.then(function() {
                    view.trigger('displayed');
                });
                return view;
            }).catch(utils.reject('Could not add axis view', true));
        },

        remove: function() {
            ControllerView.__super__.remove.apply(this, arguments);
            this.button_views.remove();
            this.axis_views.remove();
        },

    });

    return {
        ControllerButton: Button,
        ControllerAxis: Axis,
        Controller: Controller,
        ControllerView: ControllerView,
    };
});
<|endoftext|>


<commit_before><commit_msg>add simple logger spec<commit_after>import logger from "../src/logger";

describe("logger",function() {
  it("is the console",function() {
    expect(logger).toBe(console);
  });
});
<|endoftext|>


<commit_before>import React from 'react';
import { Text, TouchableOpacity, TouchableNativeFeedback } from 'react-native';
import { platformAndroid } from '../../util/general';

class Touchable extends React.Component {
	constructor(props) {
		super(props);
	}

	render() {
		if (this.props.onPress && this.props.children) {
			if (platformAndroid()) {
				return (
					<TouchableNativeFeedback onPress={this.props.onPress} style={this.props.customStyle}>
						{this.props.children}
					</TouchableNativeFeedback>
				);
			} else {
				return (
					<TouchableOpacity onPress={this.props.onPress} activeOpacity={.7} style={this.props.customStyle}>
						{this.props.children}
					</TouchableOpacity>
				);
			}
		} else {
			return null;
		}
	}
}

export default Touchable;<commit_msg>Change touchable customStyle to style<commit_after>import React from 'react';
import { Text, TouchableOpacity, TouchableNativeFeedback } from 'react-native';
import { platformAndroid } from '../../util/general';

class Touchable extends React.Component {
	constructor(props) {
		super(props);
	}

	render() {
		if (this.props.onPress && this.props.children) {
			if (platformAndroid()) {
				return (
					<TouchableNativeFeedback onPress={this.props.onPress} style={this.props.style}>
						{this.props.children}
					</TouchableNativeFeedback>
				);
			} else {
				return (
					<TouchableOpacity onPress={this.props.onPress} activeOpacity={.7} style={this.props.style}>
						{this.props.children}
					</TouchableOpacity>
				);
			}
		} else {
			return null;
		}
	}
}

export default Touchable;<|endoftext|>


<commit_before>var Request = require('../lib/request'),
	request,
	Entity,
	defaults;

describe('request', function() {
	beforeEach(function() {
		Entity = {
			wasCalled: false,
			action: function(req, res) {
				this.wasCalled = true;
				console.log('wasCalled', this.wasCalled);
				res.send(req.params.id + 1);
			}
		};

		request = new Request(Entity.action);
	});

	describe('initialization', function() {
		beforeEach(function() {
			defaults = {
				req: {
					params: 123
				},
				res: {
					set: function() {}
				}
			};
		});

		it('should initialize with an action', function() {
			expect(request.action).toEqual(Entity.action);
		});

		it('should initialize with an empty req object if no defaults are passed in', function() {
			expect(request.req).toEqual({});
		});

		it('should initialize with an empty res object if no defaults are passed in', function() {
			expect(request.res).toEqual({});
		});

		it('should accept a default object to set req', function() {
			request = new Request(Entity.action, defaults);
			expect(request.req).toEqual(defaults.req);
		});

		it('should accept a default object to set res', function() {
			request = new Request(Entity.action, defaults);
			expect(request.res).toEqual(defaults.res);
		});
	});

	describe('params', function() {
		it('should set the params property of a request', function() {
			var params = {id: 123};
			request.params(params);
			expect(request.req.params).toEqual(params);
		});
	});

	describe('body', function() {
		it('should set the body property of a request', function() {
			var body = {entity: {}};
			request.body(body);
			expect(request.req.body).toEqual(body);
		});
	});

	describe('extendReq', function() {
		it('should extend the req object', function() {
			var extension = {
				somethingElse: function() {}
			};

			request.extendReq(extension);
			expect(request.req.somethingElse).toBeDefined();
		});
	});

	describe('extendRes', function() {
		it('should extend the res object', function() {
			var extension = {
				somethingElse: function() {}
			};

			request.extendRes(extension);
			expect(request.res.somethingElse).toBeDefined();
		});
	});

	describe('expect', function() {
		beforeEach(function() {
			request.params({id: 1});
		});

		it('should assert an expectation', function() {
			request.expect(2);
		});

		it('should assert an expectation', function() {
			var SomeObj = {
				callback: function() {}
			};

			spyOn(SomeObj, 'callback');
			request.expect(2, SomeObj.callback);
			expect(SomeObj.callback).toHaveBeenCalled();
		});
	});

	describe('end', function() {
		var callback;

		beforeEach(function() {
			request.params({id: 1});
			callback = function() {};
		});

		it('should set res.send to a callback', function() {
			request.end(callback);
			expect(request.res.send).toEqual(callback);
		});
	});
});
<commit_msg>Remove console log.<commit_after>var Request = require('../lib/request'),
	request,
	Entity,
	defaults;

describe('request', function() {
	beforeEach(function() {
		Entity = {
			wasCalled: false,
			action: function(req, res) {
				res.send(req.params.id + 1);
			}
		};

		request = new Request(Entity.action);
	});

	describe('initialization', function() {
		beforeEach(function() {
			defaults = {
				req: {
					params: 123
				},
				res: {
					set: function() {}
				}
			};
		});

		it('should initialize with an action', function() {
			expect(request.action).toEqual(Entity.action);
		});

		it('should initialize with an empty req object if no defaults are passed in', function() {
			expect(request.req).toEqual({});
		});

		it('should initialize with an empty res object if no defaults are passed in', function() {
			expect(request.res).toEqual({});
		});

		it('should accept a default object to set req', function() {
			request = new Request(Entity.action, defaults);
			expect(request.req).toEqual(defaults.req);
		});

		it('should accept a default object to set res', function() {
			request = new Request(Entity.action, defaults);
			expect(request.res).toEqual(defaults.res);
		});
	});

	describe('params', function() {
		it('should set the params property of a request', function() {
			var params = {id: 123};
			request.params(params);
			expect(request.req.params).toEqual(params);
		});
	});

	describe('body', function() {
		it('should set the body property of a request', function() {
			var body = {entity: {}};
			request.body(body);
			expect(request.req.body).toEqual(body);
		});
	});

	describe('extendReq', function() {
		it('should extend the req object', function() {
			var extension = {
				somethingElse: function() {}
			};

			request.extendReq(extension);
			expect(request.req.somethingElse).toBeDefined();
		});
	});

	describe('extendRes', function() {
		it('should extend the res object', function() {
			var extension = {
				somethingElse: function() {}
			};

			request.extendRes(extension);
			expect(request.res.somethingElse).toBeDefined();
		});
	});

	describe('expect', function() {
		beforeEach(function() {
			request.params({id: 1});
		});

		it('should assert an expectation', function() {
			request.expect(2);
		});

		it('should assert an expectation', function() {
			var SomeObj = {
				callback: function() {}
			};

			spyOn(SomeObj, 'callback');
			request.expect(2, SomeObj.callback);
			expect(SomeObj.callback).toHaveBeenCalled();
		});
	});

	describe('end', function() {
		var callback;

		beforeEach(function() {
			request.params({id: 1});
			callback = function() {};
		});

		it('should set res.send to a callback', function() {
			request.end(callback);
			expect(request.res.send).toEqual(callback);
		});
	});
});
<|endoftext|>


<commit_before>require('./helper');
var Router = require('../lib/router');

var App = React.createClass({
  render: function () {
    return React.DOM.div();
  }
});

describe("when a router's pattern matches the URL", function () {
  it('match() returns an array with that router', function () {
    var router = Router('/a/b/c', App);

    var match = router.match('a/b/c');
    expect(match.length).toEqual(1);

    var rootMatch = lastItem(match);
    expect(rootMatch.router).toBe(router);
    expect(rootMatch.params).toEqual({});
  });

  describe('and it contains dynamic segments', function () {
    it('match() returns an array with that router and its params', function () {
      var router = Router('/posts/:id/edit', App);

      var match = router.match('posts/abc/edit');
      expect(match.length).toEqual(1);

      var rootMatch = lastItem(match);
      expect(rootMatch.router).toBe(router);
      expect(rootMatch.params).toEqual({ id: 'abc' });
    });
  });
});

describe("when a nested router matches the URL", function () {
  describe('and it has all the dynamic segments of its ancestors', function () {
    it('match() returns the appropriate params for each match', function () {
      var nestedRouter;
      var router = Router('/posts/:id', App, function (route) {
        nestedRouter = route('/posts/:id/comments/:commentId', App);
      });

      var match = router.match('posts/abc/comments/123');
      expect(match.length).toEqual(2);

      var rootMatch = lastItem(match);
      expect(rootMatch.router).toBe(nestedRouter);
      expect(rootMatch.params).toEqual({ id: 'abc', commentId: '123' });

      var firstMatch = match[0];
      expect(firstMatch.router).toBe(router);
      expect(firstMatch.params).toEqual({ id: 'abc' });
    });
  });

  describe('but it is missing some dynamic segments of its ancestors', function () {
    it('match() throws an Error', function () {
      var router = Router('/comments/:id', App, function (route) {
        route('/comments/:commentId/edit', App);
      });

      expect(function () {
        router.match('comments/abc/edit');
      }).toThrow(Error);
    });
  });
});

describe('when multiple nested routes match the URL', function () {
  it('match() returns the first one in the subtree, depth-first', function () {
    var expectedRouter;
    var router = Router('/', App, function (route) {
      route('/a', App, function (route) {
        expectedRouter = route('/a/b', App);
      });

      route('/a/b', App);
    });

    var match = router.match('a/b');

    expect(match.length).toEqual(3);

    var rootMatch = lastItem(match);

    expect(rootMatch.router).toBe(expectedRouter);
  });
});

function lastItem(array) {
  return array[array.length - 1];
}
<commit_msg>Fix typo<commit_after>require('./helper');
var Router = require('../lib/router');

var App = React.createClass({
  render: function () {
    return React.DOM.div();
  }
});

describe("when a router's pattern matches the URL", function () {
  it('match() returns an array with that router', function () {
    var router = Router('/a/b/c', App);

    var match = router.match('a/b/c');
    expect(match.length).toEqual(1);

    var rootMatch = lastItem(match);
    expect(rootMatch.router).toBe(router);
    expect(rootMatch.params).toEqual({});
  });

  describe('and it contains dynamic segments', function () {
    it('match() returns an array with that router and its params', function () {
      var router = Router('/posts/:id/edit', App);

      var match = router.match('posts/abc/edit');
      expect(match.length).toEqual(1);

      var rootMatch = lastItem(match);
      expect(rootMatch.router).toBe(router);
      expect(rootMatch.params).toEqual({ id: 'abc' });
    });
  });
});

describe("when a nested router matches the URL", function () {
  describe('and it has all the dynamic segments of its ancestors', function () {
    it('match() returns the appropriate params for each match', function () {
      var nestedRouter;
      var router = Router('/posts/:id', App, function (route) {
        nestedRouter = route('/posts/:id/comments/:commentId', App);
      });

      var match = router.match('posts/abc/comments/123');
      expect(match.length).toEqual(2);

      var rootMatch = lastItem(match);
      expect(rootMatch.router).toBe(nestedRouter);
      expect(rootMatch.params).toEqual({ id: 'abc', commentId: '123' });

      var firstMatch = match[0];
      expect(firstMatch.router).toBe(router);
      expect(firstMatch.params).toEqual({ id: 'abc' });
    });
  });

  describe('but it is missing some dynamic segments of its ancestors', function () {
    it('match() throws an Error', function () {
      var router = Router('/comments/:id', App, function (route) {
        route('/comments/:commentId/edit', App);
      });

      expect(function () {
        router.match('comments/abc/edit');
      }).toThrow(Error);
    });
  });
});

describe('when multiple nested routers match the URL', function () {
  it('match() returns the first one in the subtree, depth-first', function () {
    var expectedRouter;
    var router = Router('/', App, function (route) {
      route('/a', App, function (route) {
        expectedRouter = route('/a/b', App);
      });

      route('/a/b', App);
    });

    var match = router.match('a/b');

    expect(match.length).toEqual(3);

    var rootMatch = lastItem(match);

    expect(rootMatch.router).toBe(expectedRouter);
  });
});

function lastItem(array) {
  return array[array.length - 1];
}
<|endoftext|>


<commit_before>/* global describe, expect, it */

describe('emoji searches', function () {
  it('returns an expected result of "fire" search', function () {
    var getEmoji = require('../get_emoji')({});

    var result = getEmoji.bySearch('fire').trim();
    var expectedResults = [':fire:', ':fireworks:', ':fire_engine:', ':name_badge:', ':sparkle:'];
    expect(expectedResults.indexOf(result) > -1).toBe(true);
  });

  it('returns a result for a search with no matches', function () {
    var getEmoji = require('../get_emoji')({});

    var result = getEmoji.bySearch('bagel');
    expect(result).not.toBe(null);
  });

  it('returns the expected emoji for "bug" commit type', function () {
    var getEmoji = require('../get_emoji')({});

    var result = getEmoji.byCommitType('bug');
    expect(result).toBe(':bug: ');
  });

  it('returns an emoji for random get', function () {
    var getEmoji = require('../get_emoji')({});

    var result = getEmoji.random();
    expect(result).not.toBe(':bug :');
  });
});
<commit_msg>:white_check_mark: Added test for random emoji function. Closes #8.<commit_after>/* global describe, expect, it */

describe('emoji searches', function () {
  it('returns an expected result of "fire" search', function () {
    var getEmoji = require('../get_emoji')({});

    var result = getEmoji.bySearch('fire').trim();
    var expectedResults = [':fire:', ':fireworks:', ':fire_engine:', ':name_badge:', ':sparkle:'];
    expect(expectedResults.indexOf(result) > -1).toBe(true);
  });

  it('returns a result for a search with no matches', function () {
    var getEmoji = require('../get_emoji')({});

    var result = getEmoji.bySearch('bagel');
    expect(result).not.toBe(null);
  });

  it('returns the expected emoji for "bug" commit type', function () {
    var getEmoji = require('../get_emoji')({});

    var result = getEmoji.byCommitType('bug');
    expect(result).toBe(':bug: ');
  });

  it('returns an emoji for random get', function () {
    var getEmoji = require('../get_emoji')({});

    var result = getEmoji.random();
    expect(result).toMatch(/:.*: /);
  });
});
<|endoftext|>


<commit_before>  if(navigator.geolocation) {
    browserSupportFlag = true;
    navigator.geolocation.getCurrentPosition(function(position) {
      initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
      map.setCenter(initialLocation);
    }, function() {
      handleNoGeolocation(browserSupportFlag);
    });
  }

//var points=$.load(http://0.0.0.0:3000/assets.json);
//var markerpoints=points;

var markerpoints=[44.64850, -63.57566, 44.85704, -63.58930, 44.50392, -63.78921, 44.343523, -65.193912];

function initialize() {
  var myLatlng = new google.maps.LatLng(45.000, -63.000);
  var mapOptions = {
    zoom: 8,
    center: myLatlng
  };

var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

for(var i=0; i<markerpoints.length; i+=2){

	var markerLatlng= new google.maps.LatLng(markerpoints[i], markerpoints[i+1]);

	var marker = new google.maps.Marker({
      position: markerLatlng,
      map: map,
      title:'Nova Scotia '+markerLatlng
  	});

  var contentString = '
'+
      '
'+
      '
'+
      '
'+markerLatlng+'
'+
      '
'+
      '
';

    google.maps.event.addListener(marker, 'click', (function(marker, i) {
      return function(){
        var infowindow = new google.maps.InfoWindow({
      content: contentString});

      infowindow.open(map,marker);
      }
  })(marker, i));
}

}

google.maps.event.addDomListener(window, 'load', initialize);<commit_msg>New JS that handles opening and closing map infowindows<commit_after>  if(navigator.geolocation) {
    browserSupportFlag = true;
    navigator.geolocation.getCurrentPosition(function(position) {
      initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
      map.setCenter(initialLocation);
    }, function() {
      handleNoGeolocation(browserSupportFlag);
    });
  }

//var points=$.load('http://0.0.0.0:3000/assets.json');
//var markerpoints=points;

var markerpoints=[44.64850, -63.57566, 44.85704, -63.58930, 44.50392, -63.78921, 44.343523, -65.193912];

function initialize() {
  var myLatlng = new google.maps.LatLng(45.000, -63.000);
  var mapOptions = {
    zoom: 8,
    center: myLatlng
  };

var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

for(var i=0; i<markerpoints.length; i+=2){

	var markerLatlng= new google.maps.LatLng(markerpoints[i], markerpoints[i+1]);
  var clicked=false;

	var marker = new google.maps.Marker({
      position: markerLatlng,
      map: map,
      title:'Nova Scotia '+markerLatlng
  	});

  var contentString = '
'+
      '
'+
      '
'+
      '
'+markerLatlng+'
'+
      '
'+
      '
';

  var infowindow = new google.maps.InfoWindow();
    google.maps.event.addListener(marker, 'mouseover', (function(marker, i) {
      return function(){
        infowindow.setContent(contentString);
        infowindow.open(map,marker);
      }

  })(marker, i));

  google.maps.event.addListener(marker, 'mouseout', (function(marker, i) {
      return function(){
        infowindow.close();}}));

}

}

google.maps.event.addDomListener(window, 'load', initialize);

<|endoftext|>


<commit_before>var path = require('path'),
    fs = require('fs'),
    istanbul = require('istanbul'),
    hook = istanbul.hook,
    Instrumenter = istanbul.Instrumenter,
    Collector = istanbul.Collector,
    instrumenter = new Instrumenter(),
    Report = istanbul.Report,
    collector,
    globalAdded = false,
    fileMap = {};

/**
 * Facade for all coverage operations support node as well as browser cases
 *
 * Usage:
 * ```
 *  //Node unit tests
 *  var coverage = require('/path/to/this/file');
 *  coverage.hookRequire(); // hooks require for instrumentation
 *  coverage.addInstrumentCandidate(file); // adds a file that needs to be instrumented; should be called before file is `require`d
 *
 *  //Browser tests
 *  var coverage = require('/path/to/this/file');
 *  var instrumentedCode = coverage.instrumentFile(file); //alternatively, use `instrumentCode` if you have already loaded the code
 *  //collect coverage from the browser
 *  // this coverage will be stored as `window.__coverage__`
 *  // and...
 *  coverage.addCoverage(coverageObject); // rinse and repeat
 *  ```
 *
 *  //in all cases, add an exit handler to the process
 *  process.once('exit', function () { coverage.writeReports(outputDir); }); //write coverage reports
 */

/**
 * adds a file as a candidate for instrumentation when require is hooked
 * @method addInstrumentCandidate
 * @param file the file to add as an instrumentation candidate
 */
function addInstrumentCandidate(file) {
    file = path.resolve(file);
    fileMap[file] = true;
}
/**
 * hooks require to instrument all files that have been specified as instrumentation candidates
 * @method hookRequire
 * @param verbose true for debug messages
 */
function hookRequire(verbose) {

    var matchFn = function (file) {
        var match = fileMap[file],
            what = match ? 'Hooking' : 'NOT hooking';
        if (verbose) { console.log(what + file); }
        return match;
    }, transformFn = instrumenter.instrumentSync.bind(instrumenter);

    hook.hookRequire(matchFn, transformFn);
}
/**
 * unhooks require hooks that have been installed
 * @method unhookRequire
 */
function unhookRequire() {
    hook.unhookRequire();
}
/**
 * returns the coverage collector, creating one if necessary and automatically
 * adding the contents of the global coverage object. You can use this method
 * in an exit handler to get the accumulated coverage.
 */
function getCollector() {
    if (!collector) {
        collector = new Collector();
    }

    if (globalAdded) { return collector; }

    if (global['__coverage__']) {
        collector.add(global['__coverage__']);
        globalAdded = true;
    } else {
        console.error('No global coverage found for the node process');
    }
    return collector();
}
/**
 * adds coverage to the collector for browser test cases
 * @param coverageObject the coverage object to add
 */
function addCoverage(coverageObject) {
    if (!collector) { collector = new Collector(); }
    collector.add(coverageObject);
}
/**
 * writes reports for everything accumulated by the collector
 * @method writeReports
 * @param dir the output directory for reports
 */
function writeReports(dir) {
    dir = dir || process.cwd();
    var reports = [
        Report.create('lcov', { dir: dir }),
        Report.create('text'),
        Report.create('text-summary')
    ],
        collector = getCollector();

    reports.forEach(function (report) { report.writeReport(collector, true); })
}
/**
 * returns the instrumented version of the code specified
 * @param {String} code the code to instrument
 * @param {String} file the file from which the code was load
 * @return {String} the instrumented version of the code in the file
 */
function instrumentCode(code, filename) {
    filename = path.resolve(filename);
    return instrumenter.instrumentSync(code, filename);
}
/**
 * returns the instrumented version of the code present in the specified file
 * @param file the file to load
 * @return {String} the instrumented version of the code in the file
 */
function instrumentFile(file) {
    filename = path.resolve(file);
    return instrumentCode(fs.readFileSync(file, 'utf8'), file);
}

module.exports = {
    addInstrumentCandidate: addInstrumentCandidate,
    hookRequire: hookRequire,
    unhookRequire: unhookRequire,
    instrumentCode: instrumentCode,
    instrumentFile: instrumentFile,
    addCoverage: addCoverage,
    writeReports: writeReports
};<commit_msg>Fix typo, add some sample methods<commit_after>var path = require('path'),
    fs = require('fs'),
    istanbul = require('istanbul'),
    hook = istanbul.hook,
    Instrumenter = istanbul.Instrumenter,
    Collector = istanbul.Collector,
    instrumenter = new Instrumenter(),
    Report = istanbul.Report,
    collector,
    globalAdded = false,
    fileMap = {};

/**
 * Facade for all coverage operations support node as well as browser cases
 *
 * Usage:
 * ```
 *  //Node unit tests
 *  var coverage = require('/path/to/this/file');
 *  coverage.hookRequire(); // hooks require for instrumentation
 *  coverage.addInstrumentCandidate(file); // adds a file that needs to be instrumented; should be called before file is `require`d
 *
 *  //Browser tests
 *  var coverage = require('/path/to/this/file');
 *  var instrumentedCode = coverage.instrumentFile(file); //alternatively, use `instrumentCode` if you have already loaded the code
 *  //collect coverage from the browser
 *  // this coverage will be stored as `window.__coverage__`
 *  // and...
 *  coverage.addCoverage(coverageObject); // rinse and repeat
 *  ```
 *
 *  //in all cases, add an exit handler to the process
 *  process.once('exit', function () { coverage.writeReports(outputDir); }); //write coverage reports
 */

/**
 * adds a file as a candidate for instrumentation when require is hooked
 * @method addInstrumentCandidate
 * @param file the file to add as an instrumentation candidate
 */
function addInstrumentCandidate(file) {
    file = path.resolve(file);
    fileMap[file] = true;
}
/**
 * hooks require to instrument all files that have been specified as instrumentation candidates
 * @method hookRequire
 * @param verbose true for debug messages
 */
function hookRequire(verbose) {

    var matchFn = function (file) {
        var match = fileMap[file],
            what = match ? 'Hooking' : 'NOT hooking';
        if (verbose) { console.log(what + file); }
        return match;
    }, transformFn = instrumenter.instrumentSync.bind(instrumenter);

    hook.hookRequire(matchFn, transformFn);
}
/**
 * unhooks require hooks that have been installed
 * @method unhookRequire
 */
function unhookRequire() {
    hook.unhookRequire();
}
/**
 * returns the coverage collector, creating one if necessary and automatically
 * adding the contents of the global coverage object. You can use this method
 * in an exit handler to get the accumulated coverage.
 */
function getCollector() {
    if (!collector) {
        collector = new Collector();
    }

    if (globalAdded) { return collector; }

    if (global['__coverage__']) {
        collector.add(global['__coverage__']);
        globalAdded = true;
    } else {
        console.error('No global coverage found for the node process');
    }
    return collector;
}
/**
 * adds coverage to the collector for browser test cases
 * @param coverageObject the coverage object to add
 */
function addCoverage(coverageObject) {
    if (!collector) { collector = new Collector(); }
    collector.add(coverageObject);
}
/**
 * returns the merged coverage for the collector
 */
function getFinalCoverage() {
    return getCollector().getFinalCoverage();
}

/**
 * writes reports for an array of JSON files representing partial coverage information
 * @method writeReportsFor
 * @param fileList array of file names containing partial coverage objects
 * @param dir the output directory for reports
 */
function writeReportsFor(fileList, dir) {
    var collector = new Collector();
    fileList.forEach(function (file) {
        var coverage = JSON.parse(fs.readFileSync(file, 'utf8'));
        collector.addCoverage(coverage);
    });
    writeReportsInternal(dir, collector);
}

/**
 * writes reports for everything accumulated by the collector
 * @method writeReports
 * @param dir the output directory for reports
 */
function writeReports(dir) {
    writeReportsInternal(dir, getCollector());
}

function writeReportsInternal(dir, collector) {
    dir = dir || process.cwd();
    var reports = [
        Report.create('lcov', { dir: dir }),
        Report.create('text'),
        Report.create('text-summary')
    ];
    reports.forEach(function (report) { report.writeReport(collector, true); })
}
/**
 * returns the instrumented version of the code specified
 * @param {String} code the code to instrument
 * @param {String} file the file from which the code was load
 * @return {String} the instrumented version of the code in the file
 */
function instrumentCode(code, filename) {
    filename = path.resolve(filename);
    return instrumenter.instrumentSync(code, filename);
}
/**
 * returns the instrumented version of the code present in the specified file
 * @param file the file to load
 * @return {String} the instrumented version of the code in the file
 */
function instrumentFile(file) {
    filename = path.resolve(file);
    return instrumentCode(fs.readFileSync(file, 'utf8'), file);
}

module.exports = {
    addInstrumentCandidate: addInstrumentCandidate,
    hookRequire: hookRequire,
    unhookRequire: unhookRequire,
    instrumentCode: instrumentCode,
    instrumentFile: instrumentFile,
    addCoverage: addCoverage,
    writeReports: writeReports
};<|endoftext|>


<commit_before>import { Meteor } from 'meteor/meteor'
import { Session } from 'meteor/session'
import { FlowRouter } from 'meteor/kadira:flow-router'
import { BlazeLayout } from 'meteor/kadira:blaze-layout'
import moment from 'moment'

import { doIfLoggedIn } from '../../../framework/Managers/RouteManager.Helpers'
import RouteManager from '../../../framework/Managers/RouteManager'

RouteManager.registerEntity('dashboard', {
  details: ''
})
RouteManager.registerEntity('dashboard.myProjects', {
  details: 'myProjects'
})
RouteManager.registerEntity('dashboard.missingShiftReports', {
  details: 'missingShiftReports'
})
RouteManager.registerEntity('dashboard.upcomingShifts', {
  details: 'upcomingShifts'
})
RouteManager.registerEntity('dashboard.pendingRequests', {
  details: 'pendingRequests'
})
RouteManager.registerEntity('dashboard.olderShifts', {
  details: 'olderShifts'
})
RouteManager.registerEntity('project', {
  search: 'projects',
  insert: 'projects/new'
})
RouteManager.registerEntity('users.online', {
  details: 'users/online'
})
RouteManager.registerEntity('user', {
  search: 'users',
  details: 'user/:userId'
})
RouteManager.registerEntity('language', {
  details: 'language',
  update: 'language/:key'
})
RouteManager.registerProjectEntity('project', {
  details: ''
})
RouteManager.registerProjectEntity('publisher.password', {
  insert: 'publishers/:userId/password',
  forwarding: {
    route: 'publishers/:userId/password/forwarding',
    name: 'publisher.password.details',
    link: 'publisher.details'
  }
})
RouteManager.registerProjectEntity('publisher.profile.availability', {
  insert: 'publishers/:userId/availability/:key/new',
  details: 'publishers/:userId/availability/:key'
})
RouteManager.registerProjectEntity('publisher.profile.vacation', {
  insert: 'publishers/:userId/vacation/new',
  forwarding: {
    route: 'publishers/:userId/vacation/forwarding',
    name: 'publisher.profile.vacation.details',
    link: 'publisher.details'
  }
})
RouteManager.registerProjectEntity('publisher.permissions', {
  details: 'publishers/:userId/permissions',
  update: 'publishers/:userId/permissions/:key'
})
RouteManager.registerProjectEntity('publisher.permissions.tag', {
  details: 'publishers/:userId/permissions/tag/:tagId',
  update: 'publishers/:userId/permissions/tag/:tagId/:key'
})
RouteManager.registerProjectEntity('publisher', {
  search: 'publishers',
  insert: 'publishers/new',
  details: 'publishers/:userId',
  update: 'publishers/:userId/:key'
})
RouteManager.registerProjectEntity('vessel', {
  search: 'vessels',
  insert: 'vessels/new',
  details: 'vessels/:vesselId',
  update: 'vessels/:vesselId/:key'
})
RouteManager.registerProjectEntity('vessel.visit', {
  insert: 'vessels/:vesselId/visits/new',
  details: 'vessels/:vesselId/visits/:visitId',
  update: 'vessels/:vesselId/visits/:visitId/:key'
})
RouteManager.registerProjectEntity('vessel.visit.language', {
  insert: 'vessels/:vesselId/visits/:visitId/languages/new',
  forwarding: {
    route: 'vessels/:vesselId/visits/:visitId/language/forwarding',
    name: 'vessel.visit.language.details',
    link: 'vessel.visit.details'
  }
})
RouteManager.registerProjectEntity('note', {
  search: 'notes',
  insert: 'notes/new',
  details: 'notes/:noteId',
  update: 'notes/:noteId/:key'
})

RouteManager.registerProjectEntity('project.support', {
  details: 'support'
})

FlowRouter.route('/:projectId/publisherActions', {
  name: 'publisherActions',
  action () {
    doIfLoggedIn(() => {
      Session.set('parent', 'project.details')
      BlazeLayout.render('mainLayout', { content: 'publisherActions' })
    })
  }
})

FlowRouter.route('/:projectId/calendar/:year?/:month?/:day?', {
  name: 'calendar',
  action () {
    doIfLoggedIn(() => {
      Session.set('parent', 'project.details')
      BlazeLayout.render('mainLayout', { content: 'calendar' })
    })
  }
})

FlowRouter.route('/:projectId/kb', {
  name: 'wiki',
  action () {
    doIfLoggedIn(() => {
      Session.set('parent', 'project.details')
      BlazeLayout.render('mainLayout', { content: 'wiki' })
    })
  }
})

FlowRouter.route('/:projectId/shifts', {
  name: 'shifts',
  action () {
    doIfLoggedIn(() => {
      let parent = Session.get('parent')

      if (parent !== 'settings') {
        Session.set('parent', 'project.details')
        Session.set('target', null)
      }

      BlazeLayout.render('mainLayout', { content: 'shifts' })
    })
  }
})

FlowRouter.route('/goToShift/:shiftId', {
  name: 'shift.details',
  action () {
    doIfLoggedIn(() => {
      Meteor.call('shift.getShiftOverview', {
        shiftId: FlowRouter.getParam('shiftId')
      }, (e, shift) => {
        const momentObj = moment(shift.date, 'YYYYDDDD')
        const year = parseInt(momentObj.format('YYYY'), 10)
        const month = parseInt(momentObj.format('MM'), 10)
        const day = parseInt(momentObj.format('DD'), 10)

        FlowRouter.go('calendar', {
          projectId: shift.projectId,
          year: year,
          month: month,
          day: day
        }, {
          showShift: FlowRouter.getParam('shiftId')
        })
      })
    })
  }
})

FlowRouter.route('/:projectId/settings', {
  name: 'settings',
  action () {
    doIfLoggedIn(() => {
      Session.set('parent', 'project.details')
      BlazeLayout.render('mainLayout', { content: 'settings' })
    })
  }
})

FlowRouter.route('/:projectId/reports', {
  name: 'reports',
  action () {
    doIfLoggedIn(() => {
      Session.set('parent', 'project.details')
      BlazeLayout.render('mainLayout', { content: 'reports' })
    })
  }
})

FlowRouter.route('/:projectId/store', {
  name: 'store',
  action () {
    doIfLoggedIn(() => {
      Session.set('parent', 'project.details')
      BlazeLayout.render('mainLayout', { content: 'store' })
    })
  }
})
<commit_msg>fix links of users that end in an error, currently<commit_after>import { Meteor } from 'meteor/meteor'
import { Session } from 'meteor/session'
import { FlowRouter } from 'meteor/kadira:flow-router'
import { BlazeLayout } from 'meteor/kadira:blaze-layout'
import moment from 'moment'

import { doIfLoggedIn } from '../../../framework/Managers/RouteManager.Helpers'
import RouteManager from '../../../framework/Managers/RouteManager'

RouteManager.registerEntity('dashboard', {
  details: ''
})
RouteManager.registerEntity('dashboard.myProjects', {
  details: 'myProjects'
})
RouteManager.registerEntity('dashboard.missingShiftReports', {
  details: 'missingShiftReports'
})
RouteManager.registerEntity('dashboard.upcomingShifts', {
  details: 'upcomingShifts'
})
RouteManager.registerEntity('dashboard.pendingRequests', {
  details: 'pendingRequests'
})
RouteManager.registerEntity('dashboard.olderShifts', {
  details: 'olderShifts'
})
RouteManager.registerEntity('project', {
  search: 'projects',
  insert: 'projects/new'
})
RouteManager.registerEntity('users.online', {
  details: 'users/online'
})
RouteManager.registerEntity('user', {
  search: 'users',
  details: 'user/:userId'
})
RouteManager.registerEntity('language', {
  details: 'language',
  update: 'language/:key'
})
FlowRouter.route('/:projectId', {
  name: 'project.details',
  action (params) {
    if (params.projectId.length === 2) {
      FlowRouter.go(FlowRouter.path('dashboard.details'))
    }

    doIfLoggedIn(() => {
      BlazeLayout.render('project.details')
    })
  }
})
RouteManager.registerProjectEntity('publisher.password', {
  insert: 'publishers/:userId/password',
  forwarding: {
    route: 'publishers/:userId/password/forwarding',
    name: 'publisher.password.details',
    link: 'publisher.details'
  }
})
RouteManager.registerProjectEntity('publisher.profile.availability', {
  insert: 'publishers/:userId/availability/:key/new',
  details: 'publishers/:userId/availability/:key'
})
RouteManager.registerProjectEntity('publisher.profile.vacation', {
  insert: 'publishers/:userId/vacation/new',
  forwarding: {
    route: 'publishers/:userId/vacation/forwarding',
    name: 'publisher.profile.vacation.details',
    link: 'publisher.details'
  }
})
RouteManager.registerProjectEntity('publisher.permissions', {
  details: 'publishers/:userId/permissions',
  update: 'publishers/:userId/permissions/:key'
})
RouteManager.registerProjectEntity('publisher.permissions.tag', {
  details: 'publishers/:userId/permissions/tag/:tagId',
  update: 'publishers/:userId/permissions/tag/:tagId/:key'
})
RouteManager.registerProjectEntity('publisher', {
  search: 'publishers',
  insert: 'publishers/new',
  details: 'publishers/:userId',
  update: 'publishers/:userId/:key'
})
RouteManager.registerProjectEntity('vessel', {
  search: 'vessels',
  insert: 'vessels/new',
  details: 'vessels/:vesselId',
  update: 'vessels/:vesselId/:key'
})
RouteManager.registerProjectEntity('vessel.visit', {
  insert: 'vessels/:vesselId/visits/new',
  details: 'vessels/:vesselId/visits/:visitId',
  update: 'vessels/:vesselId/visits/:visitId/:key'
})
RouteManager.registerProjectEntity('vessel.visit.language', {
  insert: 'vessels/:vesselId/visits/:visitId/languages/new',
  forwarding: {
    route: 'vessels/:vesselId/visits/:visitId/language/forwarding',
    name: 'vessel.visit.language.details',
    link: 'vessel.visit.details'
  }
})
RouteManager.registerProjectEntity('note', {
  search: 'notes',
  insert: 'notes/new',
  details: 'notes/:noteId',
  update: 'notes/:noteId/:key'
})

RouteManager.registerProjectEntity('project.support', {
  details: 'support'
})

FlowRouter.route('/:projectId/publisherActions', {
  name: 'publisherActions',
  action () {
    doIfLoggedIn(() => {
      Session.set('parent', 'project.details')
      BlazeLayout.render('mainLayout', { content: 'publisherActions' })
    })
  }
})

FlowRouter.route('/:projectId/calendar/:year?/:month?/:day?', {
  name: 'calendar',
  action () {
    doIfLoggedIn(() => {
      Session.set('parent', 'project.details')
      BlazeLayout.render('mainLayout', { content: 'calendar' })
    })
  }
})

FlowRouter.route('/:projectId/kb', {
  name: 'wiki',
  action () {
    doIfLoggedIn(() => {
      Session.set('parent', 'project.details')
      BlazeLayout.render('mainLayout', { content: 'wiki' })
    })
  }
})

FlowRouter.route('/:projectId/shifts', {
  name: 'shifts',
  action () {
    doIfLoggedIn(() => {
      let parent = Session.get('parent')

      if (parent !== 'settings') {
        Session.set('parent', 'project.details')
        Session.set('target', null)
      }

      BlazeLayout.render('mainLayout', { content: 'shifts' })
    })
  }
})

FlowRouter.route('/goToShift/:shiftId', {
  name: 'shift.details',
  action () {
    doIfLoggedIn(() => {
      Meteor.call('shift.getShiftOverview', {
        shiftId: FlowRouter.getParam('shiftId')
      }, (e, shift) => {
        const momentObj = moment(shift.date, 'YYYYDDDD')
        const year = parseInt(momentObj.format('YYYY'), 10)
        const month = parseInt(momentObj.format('MM'), 10)
        const day = parseInt(momentObj.format('DD'), 10)

        FlowRouter.go('calendar', {
          projectId: shift.projectId,
          year: year,
          month: month,
          day: day
        }, {
          showShift: FlowRouter.getParam('shiftId')
        })
      })
    })
  }
})

FlowRouter.route('/:projectId/settings', {
  name: 'settings',
  action () {
    doIfLoggedIn(() => {
      Session.set('parent', 'project.details')
      BlazeLayout.render('mainLayout', { content: 'settings' })
    })
  }
})

FlowRouter.route('/:projectId/reports', {
  name: 'reports',
  action () {
    doIfLoggedIn(() => {
      Session.set('parent', 'project.details')
      BlazeLayout.render('mainLayout', { content: 'reports' })
    })
  }
})

FlowRouter.route('/:projectId/store', {
  name: 'store',
  action () {
    doIfLoggedIn(() => {
      Session.set('parent', 'project.details')
      BlazeLayout.render('mainLayout', { content: 'store' })
    })
  }
})
<|endoftext|>