<commit_before>
describe('geojson', function () {
    var merge, accumulate, normalize, style;
    beforeEach(function () {
        merge = minerva.geojson.merge;
        accumulate = minerva.geojson.accumulate;
        normalize = minerva.geojson.normalize;
        style = minerva.geojson.style;
    });
    describe('merge', function () {
        it('string type', function () {
            var accum = merge('value1');

            accum = merge('value2', accum);
            accum = merge('value1', accum);

            expect(accum.values.value1).toBe(2);
            expect(accum.values.value2).toBe(1);
        });

        it('number type', function () {
            var accum = merge(10);
            accum = merge(11, accum);
            accum = merge(-10, accum);
            accum = merge(undefined, accum);
            accum = merge(Number.POSITIVE_INFINITY, accum);
            accum = merge(NaN, accum);

            expect(accum).toEqual({
                count: 6,
                nFinite: 3,
                min: -10,
                max: 11,
                sum: 11,
                sumsq: 321
            });
        });
    });

    it('accumulate', function () {
        var accum = accumulate([
            {
                a: 4,
                b: 'red',
                c: 'bird'
            },
            {
                a: 0,
                b: 'blue',
                c: 'bird'
            },
            {
                a: 10,
                b: 'green',
                c: 'cat'
            },
            {
            }
        ]);

        expect(accum).toEqual({
            a: {
                count: 3,
                nFinite: 3,
                min: 0,
                max: 10,
                sum: 14,
                sumsq: 116
            },
            b: {
                count: 3,
                values: {
                    red: 1,
                    green: 1,
                    blue: 1
                }
            },
            c: {
                count: 3,
                values: {
                    bird: 2,
                    cat: 1
                }
            }
        });
    });

    describe('normalize', function () {
        it('parse string', function () {
            expect(
                minerva.geojson.normalize(
                    '{"type":"FeatureCollection", "features":[]}'
                )
            ).toEqual({type: 'FeatureCollection', features: [], summary: {}});
        });

        it('FeatureCollection', function () {
            var spec = {
                type: 'FeatureCollection',
                features: [
                    {
                        type: 'Feature',
                        geometry: {
                            type: 'Point',
                            coordinates: [0, 0]
                        },
                        properties: {
                            a: 1,
                            b: 'red'
                        }
                    }, {
                        type: 'Feature',
                        geometry: {
                            type: 'MultiPoint',
                            coordinates: [[1, 1], [2, 2]]
                        },
                        properties: {
                            a: -1,
                            b: 'red'
                        }
                    }, {
                        type: 'Feature',
                        geometry: {
                            type: 'Point',
                            coordinates: [3, 3]
                        },
                        properties: {
                            c: 0
                        }
                    }
                ]
            };
            var normalized = normalize(spec);

            expect(normalized).toBe(spec);

            var summary = normalized.summary;

            expect(summary.a.count).toBe(2);
            expect(summary.a.nFinite).toBe(2);
            expect(summary.a.min).toBe(-1);
            expect(summary.a.max).toBe(1);

            expect(summary.b.values).toEqual({
                'red': 2
            });

            expect(summary.c.count).toBe(1);
        });

        it('Feature', function () {
            var spec = {
                type: 'Feature',
                geometry: {
                    type: 'Point',
                    coordinates: [0, 0]
                },
                properties: {a: 'red'}
            };

            expect(normalize(spec)).toEqual({
                type: 'FeatureCollection',
                features: [spec],
                summary: {
                    a: {
                        count: 1,
                        values: {red: 1}
                    }
                }
            });
        });

        it('GeometryCollection', function () {
            var spec = {
                type: 'GeometryCollection',
                geometries: [
                    {
                        type: 'Point',
                        coordinates: [0, 0]
                    }
                ]
            };

            expect(normalize(spec)).toEqual({
                type: 'FeatureCollection',
                features: [{
                    type: 'Feature',
                    geometry: spec.geometries[0],
                    properties: {}
                }],
                summary: {}
            });
        });

        it('Point', function () {
            var spec = {
                type: 'Point',
                coordinates: [0, 0]
            };

            expect(normalize(spec)).toEqual({
                type: 'FeatureCollection',
                features: [{
                    type: 'Feature',
                    geometry: spec,
                    properties: {}
                }],
                summary: {}
            });
        });

        it('Invalid', function () {
            expect(function () {
                normalize({});
            }).toThrow();
        });
    });

    it('style', function () {
        var geojson = normalize({
            type: 'FeatureCollection',
            features: [
                {
                    type: 'Feature',
                    geometry: {
                        type: 'Point',
                        coordinates: [0, 0]
                    },
                    properties: {
                        a: 1,
                        b: 'red'
                    }
                }, {
                    type: 'Feature',
                    geometry: {
                        type: 'Point',
                        coordinates: [1, 1],
                    },
                    properties: {
                        a: -1,
                        b: 'blue'
                    }
                }, {
                    type: 'Feature',
                    geometry: {
                        type: 'Point',
                        coordinates: [3, 3]
                    },
                    properties: {
                        c: 0
                    }
                }
            ]
        });

        var vis = {
            point: {
                fillColor: sinon.stub().returns('green'),
                strokeWidth: sinon.stub().returns(4)
            }
        };

        expect(_.pluck(style(geojson, vis).features, 'properties'))
            .toEqual([
                {
                    "a": 1,
                    "b": "red",
                    "fillColor": "green",
                    "strokeWidth": 4
                },
                {
                    "a": -1,
                    "b": "blue",
                    "fillColor": "green",
                    "strokeWidth": 4
                },
                {
                    "c": 0,
                    "fillColor": "green",
                    "strokeWidth": 4
                }
            ]);

        sinon.assert.callCount(vis.point.fillColor, 3);
        sinon.assert.callCount(vis.point.strokeWidth, 3);

        sinon.assert.calledWithMatch(
            vis.point.fillColor.getCall(0),
            {a: 1, b: 'red'}
        );
        sinon.assert.calledWithMatch(
            vis.point.fillColor.getCall(1),
            {a: -1, b: 'blue'}
        );
        sinon.assert.calledWithMatch(
            vis.point.fillColor.getCall(2),
            {c: 0}
        );

        sinon.assert.calledWithMatch(
            vis.point.strokeWidth.getCall(0),
            {a: 1, b: 'red'}
        );
        sinon.assert.calledWithMatch(
            vis.point.strokeWidth.getCall(1),
            {a: -1, b: 'blue'}
        );
        sinon.assert.calledWithMatch(
            vis.point.strokeWidth.getCall(2),
            {c: 0}
        );
    });

    describe('colorScale', function () {
        it('invalid ramp', function () {
            expect(
                minerva.geojson.colorScale('invalid color ramp', {})()
            ).toBe('#ffffff');
        });
        describe('numeric values', function () {
            it('one value', function () {
                var scale = minerva.geojson.colorScale('Reds', {
                    min: 0,
                    max: 0
                });

                expect(scale(0)).toBe(colorbrewer.Reds[9][0]);
            });
            it('value range', function () {
                var scale = minerva.geojson.colorScale('Reds', {
                    min: 0,
                    max: 100
                });

                expect(scale(0)).toBe(colorbrewer.Reds[9][0]);
                expect(scale(100)).toBe(colorbrewer.Reds[9][8]);
            });
        });
        describe('string values', function () {
            it('two categories', function () {
                var scale = minerva.geojson.colorScale('Reds', {
                    values: {
                        one: null,
                        two: null
                    }
                });

                expect(scale('one')).toBe(colorbrewer.Reds[3][0]);
                expect(scale('two')).toBe(colorbrewer.Reds[3][1]);
            });
            it('three categories', function () {
                var scale = minerva.geojson.colorScale('Reds', {
                    values: {
                        one: null,
                        two: null,
                        three: null
                    }
                });

                expect(scale('one')).toBe(colorbrewer.Reds[3][0]);
                expect(scale('two')).toBe(colorbrewer.Reds[3][1]);
                expect(scale('three')).toBe(colorbrewer.Reds[3][2]);
            });
        });
    });
    describe('getFeatures', function () {
        it('all', function () {
            expect(
                minerva.geojson.getFeatures({type: 'FeatureCollection', features: [{}, {}]})
            ).toEqual([{}, {}]);
        });
        it('Point', function () {
            expect(
                minerva.geojson.getFeatures({
                    type: 'FeatureCollection',
                    features: [{
                    }, {
                        geometry: {
                            type: 'Point'
                        }
                    }, {
                        geometry: {
                            type: 'MultiPoint'
                        }
                    }]
            }, 'Point')).toEqual([{geometry: {type: 'Point'}}]);
        });
    });
});

<commit_msg>Add unittest for logScale function<commit_after>
describe('geojson', function () {
    var merge, accumulate, normalize, style;
    beforeEach(function () {
        merge = minerva.geojson.merge;
        accumulate = minerva.geojson.accumulate;
        normalize = minerva.geojson.normalize;
        style = minerva.geojson.style;
    });
    describe('merge', function () {
        it('string type', function () {
            var accum = merge('value1');

            accum = merge('value2', accum);
            accum = merge('value1', accum);

            expect(accum.values.value1).toBe(2);
            expect(accum.values.value2).toBe(1);
        });

        it('number type', function () {
            var accum = merge(10);
            accum = merge(11, accum);
            accum = merge(-10, accum);
            accum = merge(undefined, accum);
            accum = merge(Number.POSITIVE_INFINITY, accum);
            accum = merge(NaN, accum);

            expect(accum).toEqual({
                count: 6,
                nFinite: 3,
                min: -10,
                max: 11,
                sum: 11,
                sumsq: 321
            });
        });
    });

    it('accumulate', function () {
        var accum = accumulate([
            {
                a: 4,
                b: 'red',
                c: 'bird'
            },
            {
                a: 0,
                b: 'blue',
                c: 'bird'
            },
            {
                a: 10,
                b: 'green',
                c: 'cat'
            },
            {
            }
        ]);

        expect(accum).toEqual({
            a: {
                count: 3,
                nFinite: 3,
                min: 0,
                max: 10,
                sum: 14,
                sumsq: 116
            },
            b: {
                count: 3,
                values: {
                    red: 1,
                    green: 1,
                    blue: 1
                }
            },
            c: {
                count: 3,
                values: {
                    bird: 2,
                    cat: 1
                }
            }
        });
    });

    describe('normalize', function () {
        it('parse string', function () {
            expect(
                minerva.geojson.normalize(
                    '{"type":"FeatureCollection", "features":[]}'
                )
            ).toEqual({type: 'FeatureCollection', features: [], summary: {}});
        });

        it('FeatureCollection', function () {
            var spec = {
                type: 'FeatureCollection',
                features: [
                    {
                        type: 'Feature',
                        geometry: {
                            type: 'Point',
                            coordinates: [0, 0]
                        },
                        properties: {
                            a: 1,
                            b: 'red'
                        }
                    }, {
                        type: 'Feature',
                        geometry: {
                            type: 'MultiPoint',
                            coordinates: [[1, 1], [2, 2]]
                        },
                        properties: {
                            a: -1,
                            b: 'red'
                        }
                    }, {
                        type: 'Feature',
                        geometry: {
                            type: 'Point',
                            coordinates: [3, 3]
                        },
                        properties: {
                            c: 0
                        }
                    }
                ]
            };
            var normalized = normalize(spec);

            expect(normalized).toBe(spec);

            var summary = normalized.summary;

            expect(summary.a.count).toBe(2);
            expect(summary.a.nFinite).toBe(2);
            expect(summary.a.min).toBe(-1);
            expect(summary.a.max).toBe(1);

            expect(summary.b.values).toEqual({
                'red': 2
            });

            expect(summary.c.count).toBe(1);
        });

        it('Feature', function () {
            var spec = {
                type: 'Feature',
                geometry: {
                    type: 'Point',
                    coordinates: [0, 0]
                },
                properties: {a: 'red'}
            };

            expect(normalize(spec)).toEqual({
                type: 'FeatureCollection',
                features: [spec],
                summary: {
                    a: {
                        count: 1,
                        values: {red: 1}
                    }
                }
            });
        });

        it('GeometryCollection', function () {
            var spec = {
                type: 'GeometryCollection',
                geometries: [
                    {
                        type: 'Point',
                        coordinates: [0, 0]
                    }
                ]
            };

            expect(normalize(spec)).toEqual({
                type: 'FeatureCollection',
                features: [{
                    type: 'Feature',
                    geometry: spec.geometries[0],
                    properties: {}
                }],
                summary: {}
            });
        });

        it('Point', function () {
            var spec = {
                type: 'Point',
                coordinates: [0, 0]
            };

            expect(normalize(spec)).toEqual({
                type: 'FeatureCollection',
                features: [{
                    type: 'Feature',
                    geometry: spec,
                    properties: {}
                }],
                summary: {}
            });
        });

        it('Invalid', function () {
            expect(function () {
                normalize({});
            }).toThrow();
        });
    });

    it('style', function () {
        var geojson = normalize({
            type: 'FeatureCollection',
            features: [
                {
                    type: 'Feature',
                    geometry: {
                        type: 'Point',
                        coordinates: [0, 0]
                    },
                    properties: {
                        a: 1,
                        b: 'red'
                    }
                }, {
                    type: 'Feature',
                    geometry: {
                        type: 'Point',
                        coordinates: [1, 1],
                    },
                    properties: {
                        a: -1,
                        b: 'blue'
                    }
                }, {
                    type: 'Feature',
                    geometry: {
                        type: 'Point',
                        coordinates: [3, 3]
                    },
                    properties: {
                        c: 0
                    }
                }
            ]
        });

        var vis = {
            point: {
                fillColor: sinon.stub().returns('green'),
                strokeWidth: sinon.stub().returns(4)
            }
        };

        expect(_.pluck(style(geojson, vis).features, 'properties'))
            .toEqual([
                {
                    "a": 1,
                    "b": "red",
                    "fillColor": "green",
                    "strokeWidth": 4
                },
                {
                    "a": -1,
                    "b": "blue",
                    "fillColor": "green",
                    "strokeWidth": 4
                },
                {
                    "c": 0,
                    "fillColor": "green",
                    "strokeWidth": 4
                }
            ]);

        sinon.assert.callCount(vis.point.fillColor, 3);
        sinon.assert.callCount(vis.point.strokeWidth, 3);

        sinon.assert.calledWithMatch(
            vis.point.fillColor.getCall(0),
            {a: 1, b: 'red'}
        );
        sinon.assert.calledWithMatch(
            vis.point.fillColor.getCall(1),
            {a: -1, b: 'blue'}
        );
        sinon.assert.calledWithMatch(
            vis.point.fillColor.getCall(2),
            {c: 0}
        );

        sinon.assert.calledWithMatch(
            vis.point.strokeWidth.getCall(0),
            {a: 1, b: 'red'}
        );
        sinon.assert.calledWithMatch(
            vis.point.strokeWidth.getCall(1),
            {a: -1, b: 'blue'}
        );
        sinon.assert.calledWithMatch(
            vis.point.strokeWidth.getCall(2),
            {c: 0}
        );
    });

    describe('colorScale', function () {
        it('invalid ramp', function () {
            expect(
                minerva.geojson.colorScale('invalid color ramp', {})()
            ).toBe('#ffffff');
        });
        describe('numeric values', function () {
            it('one value', function () {
                var scale = minerva.geojson.colorScale('Reds', {
                    min: 0,
                    max: 0
                });

                expect(scale(0)).toBe(colorbrewer.Reds[9][0]);
            });
            it('value range', function () {
                var scale = minerva.geojson.colorScale('Reds', {
                    min: 0,
                    max: 100
                });

                expect(scale(0)).toBe(colorbrewer.Reds[9][0]);
                expect(scale(100)).toBe(colorbrewer.Reds[9][8]);
            });
        });
        describe('string values', function () {
            it('two categories', function () {
                var scale = minerva.geojson.colorScale('Reds', {
                    values: {
                        one: null,
                        two: null
                    }
                });

                expect(scale('one')).toBe(colorbrewer.Reds[3][0]);
                expect(scale('two')).toBe(colorbrewer.Reds[3][1]);
            });
            it('three categories', function () {
                var scale = minerva.geojson.colorScale('Reds', {
                    values: {
                        one: null,
                        two: null,
                        three: null
                    }
                });

                expect(scale('one')).toBe(colorbrewer.Reds[3][0]);
                expect(scale('two')).toBe(colorbrewer.Reds[3][1]);
                expect(scale('three')).toBe(colorbrewer.Reds[3][2]);
            });
        });
    });
    describe('getFeatures', function () {
        it('all', function () {
            expect(
                minerva.geojson.getFeatures({type: 'FeatureCollection', features: [{}, {}]})
            ).toEqual([{}, {}]);
        });
        it('Point', function () {
            expect(
                minerva.geojson.getFeatures({
                    type: 'FeatureCollection',
                    features: [{
                    }, {
                        geometry: {
                            type: 'Point'
                        }
                    }, {
                        geometry: {
                            type: 'MultiPoint'
                        }
                    }]
            }, 'Point')).toEqual([{geometry: {type: 'Point'}}]);
        });
    });
    describe('logScale', function () {
        it('logScale', function () {
            var domain = minerva.geojson.logScale(1, 100, 3);
            expect(domain.length).toBe(3);
            expect(domain[0]).toBeCloseTo(1, 6);
            expect(domain[1]).toBeCloseTo(10, 6);
            expect(domain[2]).toBeCloseTo(100, 6);
        });
        it('nonZeroLog', function () {
            var domain = minerva.geojson.logScale(0, 100, 3);
            expect(domain[0]).toBeCloseTo(1, 6);
            expect(domain[1]).toBeCloseTo(10, 6);
            expect(domain[2]).toBeCloseTo(100, 6);
        });
    });
});

<|endoftext|>


<commit_before>var domain;

$(document).ready(function() {
	domain = window.location.href.substring(0, window.location.href.lastIndexOf("/"));
	// Form overrides to callback functions
    $("#queue").submit(ajax_queue);
    $("#upload").submit(ajax_upload);
	// Ajax polling to update page
    playlist_refresh();
});

var progress_bar_html = `

`;

function ajax_queue(event) {
    // Stop the normal button behaviour
    event.preventDefault();
    // Set form button to Submitting...
    $("#queuebutton").val("Submitting...");
    $("#queuebutton").attr("disabled", true);
    // Get form data
    var formData = {
		"video_link": $("input[name=video_link]").val(),
    }
    // The ajax request
    $.ajax({
		type: "POST",
		url: domain + "/ajax/queue",
		data: formData,
    })
    .done(function(data) {
        // Reset form button and link input
    	$("#queuebutton").attr("disabled", false);
        $("#queuebutton").val("Go");
        $("#queueinput").val("");
        // Notify user from response data
        $("#queue").notify(data.Response, data.Type);
    });
}

function ajax_upload(event) {
    // Stop normal button behaviour
    event.preventDefault();
    // Set form button to Submitting...
    $("#filebutton").val("Submitting...");
    $("#filebutton").attr("disabled", true);
	// Add progress bar to DOM
    $("#vid-input").append(progress_bar_html);
    // The ajax request
    $.ajax({
		type: "POST",
		url: domain + "/ajax/upload",
		data: new FormData($("#upload")[0]),
		cache: false,
		processData: false,
		contentType: false,
        // Custom XMLHttpRequest for progress bar
		xhr: function() {
            var myXhr = $.ajaxSettings.xhr();
            if (myXhr.upload) {
                // For handling the progress of the upload
                myXhr.upload.addEventListener('progress', function(e) {
                    if (e.lengthComputable) {
                        var percent = Math.round((e.loaded / e.total) * 100) + "%";
                        $("#meter").css("width", percent)
                    }
                }, false);
            }
            return myXhr;
        }
    })
    // Function on done
    .done(function(data) {
        // Reset form button, file input and progress bar
        $("#filebutton").attr("disabled", false);
        $("#filebutton").val("Go");
        $("#fileinput").val("");
		// Remove progress bar
		$("#progress-outer").remove();
        // Notify user from response data
        $("#upload").notify(data.Response, data.Type);
    });
}

function playlist_refresh() {
    $("#main").load(domain + "/ajax/playlist", function(response, status) {
        // Set timeout dependant on success or error of previous request
        const timeout = status === "success" ? 2000 : 15000;
        window.setTimeout(function() {
            playlist_refresh();
        }, timeout);
    });
}
<commit_msg>Fixed error in JS which would dertmine incorrect domain for AJAX requests<commit_after>var domain;

$(document).ready(function() {
	domain = window.location.href;
	// Form overrides to callback functions
    $("#queue").submit(ajax_queue);
    $("#upload").submit(ajax_upload);
	// Ajax polling to update page
    playlist_refresh();
});

var progress_bar_html = `

`;

function ajax_queue(event) {
    // Stop the normal button behaviour
    event.preventDefault();
    // Set form button to Submitting...
    $("#queuebutton").val("Submitting...");
    $("#queuebutton").attr("disabled", true);
    // Get form data
    var formData = {
		"video_link": $("input[name=video_link]").val(),
    }
    // The ajax request
    $.ajax({
		type: "POST",
		url: domain + "/ajax/queue",
		data: formData,
    })
    .done(function(data) {
        // Reset form button and link input
    	$("#queuebutton").attr("disabled", false);
        $("#queuebutton").val("Go");
        $("#queueinput").val("");
        // Notify user from response data
        $("#queue").notify(data.Response, data.Type);
    });
}

function ajax_upload(event) {
    // Stop normal button behaviour
    event.preventDefault();
    // Set form button to Submitting...
    $("#filebutton").val("Submitting...");
    $("#filebutton").attr("disabled", true);
	// Add progress bar to DOM
    $("#vid-input").append(progress_bar_html);
    // The ajax request
    $.ajax({
		type: "POST",
		url: domain + "/ajax/upload",
		data: new FormData($("#upload")[0]),
		cache: false,
		processData: false,
		contentType: false,
        // Custom XMLHttpRequest for progress bar
		xhr: function() {
            var myXhr = $.ajaxSettings.xhr();
            if (myXhr.upload) {
                // For handling the progress of the upload
                myXhr.upload.addEventListener('progress', function(e) {
                    if (e.lengthComputable) {
                        var percent = Math.round((e.loaded / e.total) * 100) + "%";
                        $("#meter").css("width", percent)
                    }
                }, false);
            }
            return myXhr;
        }
    })
    // Function on done
    .done(function(data) {
        // Reset form button, file input and progress bar
        $("#filebutton").attr("disabled", false);
        $("#filebutton").val("Go");
        $("#fileinput").val("");
		// Remove progress bar
		$("#progress-outer").remove();
        // Notify user from response data
        $("#upload").notify(data.Response, data.Type);
    });
}

function playlist_refresh() {
    $("#main").load(domain + "/ajax/playlist", function(response, status) {
        // Set timeout dependant on success or error of previous request
        const timeout = status === "success" ? 2000 : 15000;
        window.setTimeout(function() {
            playlist_refresh();
        }, timeout);
    });
}
<|endoftext|>


<commit_before>/*
 * StatusNet - a distributed open-source microblogging tool
 * Copyright (C) 2008, StatusNet, Inc.
 *
 * Add a notice encoded as JSON into the current timeline
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 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
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @category  Plugin
 * @package   StatusNet
 * @author    Evan Prodromou <evan@status.net>
 * @author    Sarven Capadisli <csarven@status.net>
 * @copyright 2009 StatusNet, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link      http://status.net/
 */

// TODO: i18n

RealtimeUpdate = {
     _userid: 0,
     _replyurl: '',
     _favorurl: '',
     _deleteurl: '',
     _updatecounter: 0,

     init: function(userid, replyurl, favorurl, deleteurl)
     {
        RealtimeUpdate._userid = userid;
        RealtimeUpdate._replyurl = replyurl;
        RealtimeUpdate._favorurl = favorurl;
        RealtimeUpdate._deleteurl = deleteurl;

        DT = document.title;

        $(window).blur(function() {
          $('#notices_primary .notice').removeClass('mark-top');

          $('#notices_primary .notice:first').addClass('mark-top');

          RealtimeUpdate._updatecounter = 0;
          document.title = DT;

          return false;
        });
     },

     receive: function(data)
     {
          setTimeout(function() {
              id = data.id;

              // Don't add it if it already exists
              if ($("#notice-"+id).length > 0) {
                   return;
              }

              var noticeItem = RealtimeUpdate.makeNoticeItem(data);
              $("#notices_primary .notices").prepend(noticeItem);
              $("#notices_primary .notice:first").css({display:"none"});
              $("#notices_primary .notice:first").fadeIn(1000);
              SN.U.NoticeReply();

              RealtimeUpdate._updatecounter += 1;
              document.title = '('+RealtimeUpdate._updatecounter+') ' + DT;
          }, 500);
     },

     makeNoticeItem: function(data)
     {
          user = data['user'];
          html = data['html'].replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"');
          source = data['source'].replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"');

          ni = "
"+
               "
"+
               ""+
               ""+
               ""+
               ""+user['screen_name']+""+
               ""+
               ""+
               "
"+html+"
"+
               "
"+
               "
"+
               ""+
               "a few seconds ago"+
               " "+
               ""+
               "from "+
                ""+source+""+ // may have a link
               "";
          if (data['in_reply_to_status_id']) {
               ni = ni+" in context";
          }

          ni = ni+"
"+
            "
";

          if (RealtimeUpdate._userid != 0) {
               var input = $("form#form_notice fieldset input#token");
               var session_key = input.val();
               ni = ni+RealtimeUpdate.makeFavoriteForm(data['id'], session_key);
               ni = ni+RealtimeUpdate.makeReplyLink(data['id'], data['user']['screen_name']);
               if (RealtimeUpdate._userid == data['user']['id']) {
                    ni = ni+RealtimeUpdate.makeDeleteLink(data['id']);
               }
          }

          ni = ni+"
"+
               "
";
          return ni;
     },

     makeFavoriteForm: function(id, session_key)
     {
          var ff;

          ff = "<form id=\"favor-"+id+"\" class=\"form_favor\" method=\"post\" action=\""+RealtimeUpdate._favorurl+"\">"+
                "<fieldset>"+
               "<legend>Favor this notice</legend>"+
               "<input name=\"token-"+id+"\" type=\"hidden\" id=\"token-"+id+"\" value=\""+session_key+"\"/>"+
               "<input name=\"notice\" type=\"hidden\" id=\"notice-n"+id+"\" value=\""+id+"\"/>"+
               "<input type=\"submit\" id=\"favor-submit-"+id+"\" name=\"favor-submit-"+id+"\" class=\"submit\" value=\"Favor\" title=\"Favor this notice\"/>"+
                "</fieldset>"+
               "</form>";
          return ff;
     },

     makeReplyLink: function(id, nickname)
     {
          var rl;
          rl = "Reply "+id+"";
          return rl;
        },

     makeDeleteLink: function(id)
     {
          var dl, delurl;
          delurl = RealtimeUpdate._deleteurl.replace("0000000000", id);

          dl = "Delete";

          return dl;
     },

     addPopup: function(url, timeline, iconurl)
     {
         var NP = $('#notices_primary');
         NP.css({'position':'relative'});
         NP.prepend('<button id="realtime_timeline" title="Pop up in a window">Pop up</button>');

         var RT = $('#realtime_timeline');
         RT.css({
             'margin':'0 0 11px 0',
             'background':'transparent url('+ iconurl + ') no-repeat 0% 30%',
             'padding':'0 0 0 20px',
             'display':'block',
             'position':'absolute',
             'top':'-20px',
             'right':'0',
             'border':'none',
             'cursor':'pointer',
             'color':$('a').css('color'),
             'font-weight':'bold',
             'font-size':'1em'
         });

         RT.click(function() {
             window.open(url,
                         timeline,
                         'toolbar=no,resizable=yes,scrollbars=yes,status=yes');

             return false;
         });
     },

     initPopupWindow: function()
     {
         window.resizeTo(500, 550);
         $('address').hide();
         $('#content').css({'width':'93.5%'});

         $('#form_notice').css({
            'margin':'18px 0 18px 1.795%',
            'width':'93%',
            'max-width':'451px'
         });

         $('#form_notice label[for=notice_data-text], h1').css({'display': 'none'});

         $('.notices li:first-child').css({'border-top-color':'transparent'});

         $('#form_notice label[for="notice_data-attach"], #form_notice #notice_data-attach').css({'top':'0'});

         $('#form_notice #notice_data-attach').css({
            'left':'auto',
            'right':'0'
         });
     }
}

<commit_msg>Set window resize before openning it up<commit_after>/*
 * StatusNet - a distributed open-source microblogging tool
 * Copyright (C) 2008, StatusNet, Inc.
 *
 * Add a notice encoded as JSON into the current timeline
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 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
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @category  Plugin
 * @package   StatusNet
 * @author    Evan Prodromou <evan@status.net>
 * @author    Sarven Capadisli <csarven@status.net>
 * @copyright 2009 StatusNet, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link      http://status.net/
 */

// TODO: i18n

RealtimeUpdate = {
     _userid: 0,
     _replyurl: '',
     _favorurl: '',
     _deleteurl: '',
     _updatecounter: 0,

     init: function(userid, replyurl, favorurl, deleteurl)
     {
        RealtimeUpdate._userid = userid;
        RealtimeUpdate._replyurl = replyurl;
        RealtimeUpdate._favorurl = favorurl;
        RealtimeUpdate._deleteurl = deleteurl;

        DT = document.title;

        $(window).blur(function() {
          $('#notices_primary .notice').removeClass('mark-top');

          $('#notices_primary .notice:first').addClass('mark-top');

          RealtimeUpdate._updatecounter = 0;
          document.title = DT;

          return false;
        });
     },

     receive: function(data)
     {
          setTimeout(function() {
              id = data.id;

              // Don't add it if it already exists
              if ($("#notice-"+id).length > 0) {
                   return;
              }

              var noticeItem = RealtimeUpdate.makeNoticeItem(data);
              $("#notices_primary .notices").prepend(noticeItem);
              $("#notices_primary .notice:first").css({display:"none"});
              $("#notices_primary .notice:first").fadeIn(1000);
              SN.U.NoticeReply();

              RealtimeUpdate._updatecounter += 1;
              document.title = '('+RealtimeUpdate._updatecounter+') ' + DT;
          }, 500);
     },

     makeNoticeItem: function(data)
     {
          user = data['user'];
          html = data['html'].replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"');
          source = data['source'].replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"');

          ni = "
"+
               "
"+
               ""+
               ""+
               ""+
               ""+user['screen_name']+""+
               ""+
               ""+
               "
"+html+"
"+
               "
"+
               "
"+
               ""+
               "a few seconds ago"+
               " "+
               ""+
               "from "+
                ""+source+""+ // may have a link
               "";
          if (data['in_reply_to_status_id']) {
               ni = ni+" in context";
          }

          ni = ni+"
"+
            "
";

          if (RealtimeUpdate._userid != 0) {
               var input = $("form#form_notice fieldset input#token");
               var session_key = input.val();
               ni = ni+RealtimeUpdate.makeFavoriteForm(data['id'], session_key);
               ni = ni+RealtimeUpdate.makeReplyLink(data['id'], data['user']['screen_name']);
               if (RealtimeUpdate._userid == data['user']['id']) {
                    ni = ni+RealtimeUpdate.makeDeleteLink(data['id']);
               }
          }

          ni = ni+"
"+
               "
";
          return ni;
     },

     makeFavoriteForm: function(id, session_key)
     {
          var ff;

          ff = "<form id=\"favor-"+id+"\" class=\"form_favor\" method=\"post\" action=\""+RealtimeUpdate._favorurl+"\">"+
                "<fieldset>"+
               "<legend>Favor this notice</legend>"+
               "<input name=\"token-"+id+"\" type=\"hidden\" id=\"token-"+id+"\" value=\""+session_key+"\"/>"+
               "<input name=\"notice\" type=\"hidden\" id=\"notice-n"+id+"\" value=\""+id+"\"/>"+
               "<input type=\"submit\" id=\"favor-submit-"+id+"\" name=\"favor-submit-"+id+"\" class=\"submit\" value=\"Favor\" title=\"Favor this notice\"/>"+
                "</fieldset>"+
               "</form>";
          return ff;
     },

     makeReplyLink: function(id, nickname)
     {
          var rl;
          rl = "Reply "+id+"";
          return rl;
        },

     makeDeleteLink: function(id)
     {
          var dl, delurl;
          delurl = RealtimeUpdate._deleteurl.replace("0000000000", id);

          dl = "Delete";

          return dl;
     },

     addPopup: function(url, timeline, iconurl)
     {
         var NP = $('#notices_primary');
         NP.css({'position':'relative'});
         NP.prepend('<button id="realtime_timeline" title="Pop up in a window">Pop up</button>');

         var RT = $('#realtime_timeline');
         RT.css({
             'margin':'0 0 11px 0',
             'background':'transparent url('+ iconurl + ') no-repeat 0% 30%',
             'padding':'0 0 0 20px',
             'display':'block',
             'position':'absolute',
             'top':'-20px',
             'right':'0',
             'border':'none',
             'cursor':'pointer',
             'color':$('a').css('color'),
             'font-weight':'bold',
             'font-size':'1em'
         });

         RT.click(function() {
             window.open(url,
                         timeline,
                         'toolbar=no,resizable=yes,scrollbars=yes,status=yes,width=500,height=550');

             return false;
         });
     },

     initPopupWindow: function()
     {
         $('address').hide();
         $('#content').css({'width':'93.5%'});

         $('#form_notice').css({
            'margin':'18px 0 18px 1.795%',
            'width':'93%',
            'max-width':'451px'
         });

         $('#form_notice label[for=notice_data-text], h1').css({'display': 'none'});

         $('.notices li:first-child').css({'border-top-color':'transparent'});

         $('#form_notice label[for="notice_data-attach"], #form_notice #notice_data-attach').css({'top':'0'});

         $('#form_notice #notice_data-attach').css({
            'left':'auto',
            'right':'0'
         });
     }
}

<|endoftext|>


<commit_before>'use strict';

angular.module('alchemy').directive('alchTable', function(){
    return {
        restrict: 'A',
        scope: {
            'table' : '=alchTable',
            'rowSelect' : '@'
        },
        templateUrl: 'component/templates/table.html',

        controller: ['$scope', function($scope){
            if (!$scope.table.scroll_distance) {
                $scope.table.scroll_distance = 0;
            }

            $scope.show_cell = function(cell){
                var to_show;

                angular.forEach($scope.table.data.columns, function(header){
                    if( header.id === cell.column_id ){
                        to_show = header.show;
                    }
                });

                return to_show;
            };

            $scope.show_row = function(row){
                return row.show;
            };

            $scope.adjust_num_selected = function(selected){
                $scope.table.num_selected += selected ? 1 : -1;
            };

            $scope.table.select_all = function(selected){
                var table = $scope.table;

                if( selected !== undefined ){
                    table.all_selected = selected;
                }

                table.num_selected = table.all_selected ? table.data.rows.length : 0;

                angular.forEach(table.data.rows, function(row){
                    row.selected = table.all_selected;
                });
            };

            $scope.table.more_results = function(){
                var more = $scope.table.total > $scope.table.offset;

                more = more && $scope.table.all_selected;
                return more;
            };
        }]
    };
});

angular.module('alchemy').directive('alchTableToolbar', function(){
    return {
        restrict: 'A',
        transclude: true,
        scope: {
            'table' : '=alchTableToolbar'
        },
        templateUrl: 'component/templates/tool_bar.html',

        controller: ['$scope', function($scope){
            $scope.deselect_all = function(){
                $scope.table.select_all(false);
            };
        }]
    };
});
<commit_msg>Initializing table properties so number selected based logic can work.<commit_after>'use strict';

angular.module('alchemy').directive('alchTable', function(){
    return {
        restrict: 'A',
        scope: {
            'table' : '=alchTable',
            'rowSelect' : '@'
        },
        templateUrl: 'component/templates/table.html',

        controller: ['$scope', function($scope){
            // Initialize table properties
            $scope.table.num_selected = 0;
            $scope.table.all_selected = false;

            if (!$scope.table.scroll_distance) {
                $scope.table.scroll_distance = 0;
            }

            $scope.show_cell = function(cell){
                var to_show;

                angular.forEach($scope.table.data.columns, function(header){
                    if( header.id === cell.column_id ){
                        to_show = header.show;
                    }
                });

                return to_show;
            };

            $scope.show_row = function(row){
                return row.show;
            };

            $scope.adjust_num_selected = function(selected){
                $scope.table.num_selected += selected ? 1 : -1;
            };

            $scope.table.select_all = function(selected){
                var table = $scope.table;

                if( selected !== undefined ){
                    table.all_selected = selected;
                }

                table.num_selected = table.all_selected ? table.data.rows.length : 0;

                angular.forEach(table.data.rows, function(row){
                    row.selected = table.all_selected;
                });
            };

            $scope.table.more_results = function(){
                var more = $scope.table.total > $scope.table.offset;

                more = more && $scope.table.all_selected;
                return more;
            };
        }]
    };
});

angular.module('alchemy').directive('alchTableToolbar', function(){
    return {
        restrict: 'A',
        transclude: true,
        scope: {
            'table' : '=alchTableToolbar'
        },
        templateUrl: 'component/templates/tool_bar.html',

        controller: ['$scope', function($scope){
            $scope.deselect_all = function(){
                $scope.table.select_all(false);
            };
        }]
    };
});
<|endoftext|>


<commit_before>// add a notice encoded as JSON into the current timeline
//
// TODO: i18n

RealtimeUpdate = {
     _userid: 0,
     _replyurl: '',
     _favorurl: '',
     _deleteurl: '',

     init: function(userid, replyurl, favorurl, deleteurl)
     {
          RealtimeUpdate._userid = userid;
          RealtimeUpdate._replyurl = replyurl;
          RealtimeUpdate._favorurl = favorurl;
          RealtimeUpdate._deleteurl = deleteurl;
     },

     receive: function(data)
     {
          id = data.id;

          // Don't add it if it already exists

          if ($("#notice-"+id).length > 0) {
               return;
          }

          var noticeItem = RealtimeUpdate.makeNoticeItem(data);
          $("#notices_primary .notices").prepend(noticeItem, true);
          $("#notices_primary .notice:first").css({display:"none"});
          $("#notices_primary .notice:first").fadeIn(1000);
          NoticeReply();
     },

     makeNoticeItem: function(data)
     {
          user = data['user'];
          html = data['html'].replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"');
          source = data['source'].replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"');

          ni = "
"+
               "
"+
               ""+
               ""+
               ""+
               ""+user['screen_name']+""+
               ""+
               ""+
               "
"+html+"
"+
               "
"+
               "
"+
               ""+
               "a few seconds ago"+
               " "+
               ""+
               "from "+
               "+source+"+ // may have a link
               "";
          if (data['in_reply_to_status_id']) {
               ni = ni+" in context";
          }

          ni = ni+"
"+
               "
";

          if (RealtimeUpdate._userid != 0) {
               var input = $("form#form_notice fieldset input#token");
               var session_key = input.val();
               ni = ni+RealtimeUpdate.makeFavoriteForm(data['id'], session_key);
               ni = ni+RealtimeUpdate.makeReplyLink(data['id'], data['user']['screen_name']);
               if (RealtimeUpdate._userid == data['user']['id']) {
                    ni = ni+RealtimeUpdate.makeDeleteLink(data['id']);
               }
          }

          ni = ni+"
"+
               "
";
          return ni;
     },

     makeFavoriteForm: function(id, session_key)
     {
          var ff;

          ff = "<form id=\"favor-"+id+"\" class=\"form_favor\" method=\"post\" action=\""+RealtimeUpdate._favorurl+"\">"+
               "<fieldset>"+
               "<legend>Favor this notice</legend>"+
               "<input name=\"token-"+id+"\" type=\"hidden\" id=\"token-"+id+"\" value=\""+session_key+"\"/>"+
               "<input name=\"notice\" type=\"hidden\" id=\"notice-n"+id+"\" value=\""+id+"\"/>"+
               "<input type=\"submit\" id=\"favor-submit-"+id+"\" name=\"favor-submit-"+id+"\" class=\"submit\" value=\"Favor\" title=\"Favor this notice\"/>"+
               "</fieldset>"+
               "</form>";
          return ff;
     },

     makeReplyLink: function(id, nickname)
     {
          var rl;
          rl = "Reply "+id+"";
          return rl;
     },

     makeDeleteLink: function(id)
     {
          var dl, delurl;
          delurl = RealtimeUpdate._deleteurl.replace("0000000000", id);

          dl = "Delete";

          return dl;
     },
}
<commit_msg>Fixed missing quotes<commit_after>// add a notice encoded as JSON into the current timeline
//
// TODO: i18n

RealtimeUpdate = {
     _userid: 0,
     _replyurl: '',
     _favorurl: '',
     _deleteurl: '',

     init: function(userid, replyurl, favorurl, deleteurl)
     {
          RealtimeUpdate._userid = userid;
          RealtimeUpdate._replyurl = replyurl;
          RealtimeUpdate._favorurl = favorurl;
          RealtimeUpdate._deleteurl = deleteurl;
     },

     receive: function(data)
     {
          id = data.id;

          // Don't add it if it already exists

          if ($("#notice-"+id).length > 0) {
               return;
          }

          var noticeItem = RealtimeUpdate.makeNoticeItem(data);
          $("#notices_primary .notices").prepend(noticeItem, true);
          $("#notices_primary .notice:first").css({display:"none"});
          $("#notices_primary .notice:first").fadeIn(1000);
          NoticeReply();
     },

     makeNoticeItem: function(data)
     {
          user = data['user'];
          html = data['html'].replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"');
          source = data['source'].replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"');

          ni = "
"+
               "
"+
               ""+
               ""+
               ""+
               ""+user['screen_name']+""+
               ""+
               ""+
               "
"+html+"
"+
               "
"+
               "
"+
               ""+
               "a few seconds ago"+
               " "+
               ""+
               "from "+
               ""+source+""+ // may have a link
               "";
          if (data['in_reply_to_status_id']) {
               ni = ni+" in context";
          }

          ni = ni+"
"+
               "
";

          if (RealtimeUpdate._userid != 0) {
               var input = $("form#form_notice fieldset input#token");
               var session_key = input.val();
               ni = ni+RealtimeUpdate.makeFavoriteForm(data['id'], session_key);
               ni = ni+RealtimeUpdate.makeReplyLink(data['id'], data['user']['screen_name']);
               if (RealtimeUpdate._userid == data['user']['id']) {
                    ni = ni+RealtimeUpdate.makeDeleteLink(data['id']);
               }
          }

          ni = ni+"
"+
               "
";
          return ni;
     },

     makeFavoriteForm: function(id, session_key)
     {
          var ff;

          ff = "<form id=\"favor-"+id+"\" class=\"form_favor\" method=\"post\" action=\""+RealtimeUpdate._favorurl+"\">"+
               "<fieldset>"+
               "<legend>Favor this notice</legend>"+
               "<input name=\"token-"+id+"\" type=\"hidden\" id=\"token-"+id+"\" value=\""+session_key+"\"/>"+
               "<input name=\"notice\" type=\"hidden\" id=\"notice-n"+id+"\" value=\""+id+"\"/>"+
               "<input type=\"submit\" id=\"favor-submit-"+id+"\" name=\"favor-submit-"+id+"\" class=\"submit\" value=\"Favor\" title=\"Favor this notice\"/>"+
               "</fieldset>"+
               "</form>";
          return ff;
     },

     makeReplyLink: function(id, nickname)
     {
          var rl;
          rl = "Reply "+id+"";
          return rl;
     },

     makeDeleteLink: function(id)
     {
          var dl, delurl;
          delurl = RealtimeUpdate._deleteurl.replace("0000000000", id);

          dl = "Delete";

          return dl;
     },
}
<|endoftext|>


<commit_before>/* global window */

import { router } from 'utils'
import { stringify } from 'qs'
import store from 'store'
import { ROLE_TYPE } from 'utils/constant'
import { queryLayout, pathMatchRegexp } from 'utils'
import { CANCEL_REQUEST_MESSAGE } from 'utils/constant'
import api from 'api'
import config from 'config'

const { queryRouteList, logoutUser, queryUserInfo } = api

export default {
  namespace: 'app',
  state: {
    user: {},
    permissions: {
      visit: [],
    },
    routeList: [
      {
        id: '1',
        icon: 'laptop',
        name: 'Dashboard',
        zhName: '仪表盘',
        router: '/dashboard',
      },
    ],
    locationPathname: '',
    locationQuery: {},
    theme: store.get('theme') || 'light',
    collapsed: store.get('collapsed') || false,
    notifications: [
      {
        title: 'New User is registered.',
        date: new Date(Date.now() - 10000000),
      },
      {
        title: 'Application has been approved.',
        date: new Date(Date.now() - 50000000),
      },
    ],
  },
  subscriptions: {
    setupHistory({ dispatch, history }) {
      history.listen(location => {
        dispatch({
          type: 'updateState',
          payload: {
            locationPathname: location.pathname,
            locationQuery: location.query,
          },
        })
      })
    },

    setupRequestCancel({ history }) {
      history.listen(() => {
        const { cancelRequest = new Map() } = window

        cancelRequest.forEach((value, key) => {
          if (value.pathname !== window.location.pathname) {
            value.cancel(CANCEL_REQUEST_MESSAGE)
            cancelRequest.delete(key)
          }
        })
      })
    },

    setup({ dispatch }) {
      dispatch({ type: 'query' })
    },
  },
  effects: {
    *query({ payload }, { call, put, select }) {
      const { success, user } = yield call(queryUserInfo, payload)
      const { locationPathname } = yield select(_ => _.app)

      if (success && user) {
        const { list } = yield call(queryRouteList)
        const { permissions } = user
        let routeList = list
        if (
          permissions.role === ROLE_TYPE.ADMIN ||
          permissions.role === ROLE_TYPE.DEVELOPER
        ) {
          permissions.visit = list.map(item => item.id)
        } else {
          routeList = list.filter(item => {
            const cases = [
              permissions.visit.includes(item.id),
              item.mpid
                ? permissions.visit.includes(item.mpid) || item.mpid === '-1'
                : true,
              item.bpid ? permissions.visit.includes(item.bpid) : true,
            ]
            return cases.every(_ => _)
          })
        }
        yield put({
          type: 'updateState',
          payload: {
            user,
            permissions,
            routeList,
          },
        })
        if (pathMatchRegexp('/login', window.location.pathname)) {
          router.push({
            pathname: '/dashboard',
          })
        }
      } else if (queryLayout(config.layouts, locationPathname) !== 'public') {
        router.push({
          pathname: '/login',
          search: stringify({
            from: locationPathname,
          }),
        })
      }
    },

    *signOut({ payload }, { call, put }) {
      const data = yield call(logoutUser)
      if (data.success) {
        yield put({
          type: 'updateState',
          payload: {
            user: {},
            permissions: { visit: [] },
            menu: [
              {
                id: '1',
                icon: 'laptop',
                name: 'Dashboard',
                zhName: '仪表盘',
                router: '/dashboard',
              },
            ],
          },
        })
        yield put({ type: 'query' })
      } else {
        throw data
      }
    },
  },
  reducers: {
    updateState(state, { payload }) {
      return {
        ...state,
        ...payload,
      }
    },

    handleThemeChange(state, { payload }) {
      store.set('theme', payload)
      state.theme = payload
    },

    handleCollapseChange(state, { payload }) {
      store.set('collapsed', payload)
      state.collapsed = payload
    },

    allNotificationsRead(state) {
      state.notifications = []
    },
  },
}
<commit_msg>fix #935 root path / will be not found after login<commit_after>/* global window */

import { router } from 'utils'
import { stringify } from 'qs'
import store from 'store'
import { ROLE_TYPE } from 'utils/constant'
import { queryLayout, pathMatchRegexp } from 'utils'
import { CANCEL_REQUEST_MESSAGE } from 'utils/constant'
import api from 'api'
import config from 'config'

const { queryRouteList, logoutUser, queryUserInfo } = api

export default {
  namespace: 'app',
  state: {
    user: {},
    permissions: {
      visit: [],
    },
    routeList: [
      {
        id: '1',
        icon: 'laptop',
        name: 'Dashboard',
        zhName: '仪表盘',
        router: '/dashboard',
      },
    ],
    locationPathname: '',
    locationQuery: {},
    theme: store.get('theme') || 'light',
    collapsed: store.get('collapsed') || false,
    notifications: [
      {
        title: 'New User is registered.',
        date: new Date(Date.now() - 10000000),
      },
      {
        title: 'Application has been approved.',
        date: new Date(Date.now() - 50000000),
      },
    ],
  },
  subscriptions: {
    setupHistory({ dispatch, history }) {
      history.listen(location => {
        dispatch({
          type: 'updateState',
          payload: {
            locationPathname: location.pathname,
            locationQuery: location.query,
          },
        })
      })
    },

    setupRequestCancel({ history }) {
      history.listen(() => {
        const { cancelRequest = new Map() } = window

        cancelRequest.forEach((value, key) => {
          if (value.pathname !== window.location.pathname) {
            value.cancel(CANCEL_REQUEST_MESSAGE)
            cancelRequest.delete(key)
          }
        })
      })
    },

    setup({ dispatch }) {
      dispatch({ type: 'query' })
    },
  },
  effects: {
    *query({ payload }, { call, put, select }) {
      const { success, user } = yield call(queryUserInfo, payload)
      const { locationPathname } = yield select(_ => _.app)

      if (success && user) {
        const { list } = yield call(queryRouteList)
        const { permissions } = user
        let routeList = list
        if (
          permissions.role === ROLE_TYPE.ADMIN ||
          permissions.role === ROLE_TYPE.DEVELOPER
        ) {
          permissions.visit = list.map(item => item.id)
        } else {
          routeList = list.filter(item => {
            const cases = [
              permissions.visit.includes(item.id),
              item.mpid
                ? permissions.visit.includes(item.mpid) || item.mpid === '-1'
                : true,
              item.bpid ? permissions.visit.includes(item.bpid) : true,
            ]
            return cases.every(_ => _)
          })
        }
        yield put({
          type: 'updateState',
          payload: {
            user,
            permissions,
            routeList,
          },
        })
        if (pathMatchRegexp(['/','/login'], window.location.pathname)) {
          router.push({
            pathname: '/dashboard',
          })
        }
      } else if (queryLayout(config.layouts, locationPathname) !== 'public') {
        router.push({
          pathname: '/login',
          search: stringify({
            from: locationPathname,
          }),
        })
      }
    },

    *signOut({ payload }, { call, put }) {
      const data = yield call(logoutUser)
      if (data.success) {
        yield put({
          type: 'updateState',
          payload: {
            user: {},
            permissions: { visit: [] },
            menu: [
              {
                id: '1',
                icon: 'laptop',
                name: 'Dashboard',
                zhName: '仪表盘',
                router: '/dashboard',
              },
            ],
          },
        })
        yield put({ type: 'query' })
      } else {
        throw data
      }
    },
  },
  reducers: {
    updateState(state, { payload }) {
      return {
        ...state,
        ...payload,
      }
    },

    handleThemeChange(state, { payload }) {
      store.set('theme', payload)
      state.theme = payload
    },

    handleCollapseChange(state, { payload }) {
      store.set('collapsed', payload)
      state.collapsed = payload
    },

    allNotificationsRead(state) {
      state.notifications = []
    },
  },
}
<|endoftext|>


<commit_before>/*global describe it before after  =*/

"use client";

require(["lib/architect/architect", "lib/chai/chai"], function (architect, chai) {
    var expect = chai.expect;

    expect.setupArchitectTest([
        {
            packagePath : "plugins/c9.core/c9",
            workspaceId : "ubuntu/ip-10-35-77-180",
            startdate   : new Date(),
            debug       : true,
            hosted      : true,
            local       : false,
            davPrefix   : "/"
        },

        "plugins/c9.core/ext",
        "plugins/c9.core/http",
        "plugins/c9.core/util",
        "plugins/c9.ide.ui/lib_apf",
        "plugins/c9.ide.ui/menus",
        {
            packagePath: "plugins/c9.core/settings",
            testing: true
        },
        "plugins/c9.ide.api/api.js",
        {
            packagePath  : "plugins/c9.ide.ui/ui",
            staticPrefix : "plugins/c9.ide.ui"
        },
        "plugins/c9.ide.editors/document",
        "plugins/c9.ide.editors/undomanager",
        {
            packagePath: "plugins/c9.ide.editors/editors",
            defaultEditor: "ace"
        },
        "plugins/c9.ide.editors/editor",
        "plugins/c9.ide.editors/tabmanager",
        "plugins/c9.ide.ui/focus",
        "plugins/c9.ide.editors/pane",
        "plugins/c9.ide.editors/tab",
        "plugins/c9.ide.ace/ace",
        {
            packagePath  : "plugins/c9.ide.ace.statusbar/statusbar",
            staticPrefix : "plugins/c9.ide.layout.classic"
        },
        "plugins/c9.ide.keys/commands",
        "plugins/c9.fs/proc",
        "plugins/c9.vfs.client/vfs_client",
        "plugins/c9.vfs.client/endpoint",
        "plugins/c9.ide.auth/auth",
        "plugins/c9.fs/fs",

        // Mock plugins
        {
            consumes : ["apf", "ui", "Plugin"],
            provides : [
                "commands", "menus", "layout", "watcher",
                "save", "preferences", "anims", "gotoline", "clipboard",
                "dialog.alert", "auth.bootstrap", "info", "ace.gotoline"
            ],
            setup    : expect.html.mocked
        },
        {
            consumes : ["tabManager", "ace"],
            provides : [],
            setup    : main
        }
    ], architect);

    function main(options, imports, register) {
        var tabs    = imports.tabManager;
        var ace     = imports.ace;

        function getTabHtml(tab){
            return tab.pane.aml.getPage("editor::" + tab.editorType).$ext
        }

        expect.html.setConstructor(function(tab){
            if (typeof tab == "object")
                return tab.$ext;
        });

        describe('statusbar', function() {
            before(function(done){
                apf.config.setProperty("allow-select", false);
                apf.config.setProperty("allow-blur", false);

                bar.$ext.style.background = "rgba(220, 220, 220, 0.93)";
                bar.$ext.style.position = "fixed";
                bar.$ext.style.left = "20px";
                bar.$ext.style.right = "20px";
                bar.$ext.style.bottom = "20px";
                bar.$ext.style.height = "33%";

                document.body.style.marginBottom = "33%";

                tabs.on("ready", function(){
                    tabs.getPanes()[0].focus();
                    done();
                })
            });

            describe("open", function(){
                this.timeout(10000);

                it('should open a pane with just an editor', function(done) {
                    tabs.openFile("/file.txt", function(err, tab){
                        expect(tabs.getTabs()).length(1);

                        var sb  = tab.document.getSession().statusBar;
                        var bar = sb.getElement("bar");
                        expect.html(bar, "rowcol").text("1:1");

                        tab.document.editor.ace.selectAll();
                        setTimeout(function(){
                            expect.html(bar, "rowcol sel").text("2:1");
                            expect.html(bar, "sel").text("23 Bytes");

                            done();
                        }, 100);
                    });
                });
                it('should handle multiple documents in the same pane', function(done) {
                    tabs.openFile("/listing.json", function(err, tab){
                        expect(tabs.getTabs()).length(2);

                        tab.activate();

                        setTimeout(function(){
                            var sb = tab.document.getSession().statusBar;
                            expect.html(sb.getElement("bar"), "caption").text("1:1");

                            done();
                        }, 100);
                    });
                });
            });
            describe("split(), pane.unload()", function(){
                it('should split a pane horizontally, making the existing pane the left one', function(done) {
                    var pane = tabs.focussedTab.pane;
                    var righttab = pane.hsplit(true);
                    tabs.focussedTab.attachTo(righttab);

                    setTimeout(function(){
                        expect.html(pane.aml, "pane").text("2:1");
                        expect.html(righttab.aml, "righttab").text("1:1");

                        done();
                    }, 100);
                });
//                it('should remove the left pane from a horizontal split', function(done) {
//                    var pane  = tabs.getPanes()[0];
//                    var tab = tabs.getPanes()[1].getTab();
//                    pane.unload();
//                    expect(tabs.getPanes()).length(1);
//                    expect(tabs.getTabs()).length(2);
//                    tabs.focusTab(tab);
//                    done();
//                });
            });
//            describe("Change Theme", function(){
//                this.timeout(10000);
//
//                it('should change a theme', function(done) {
//                    var editor = tabs.focussedTab.editor;
//                    ace.on("themeInit", function setTheme(){
//                        ace.off("theme.init", setTheme);
//                        expect.html(getTabHtml(tabs.focussedTab).childNodes[1]).className("ace-monokai");
//                        editor.setOption("theme", "ace/theme/textmate");
//                        done();
//                    });
//                    editor.setOption("theme", "ace/theme/monokai");
//                });
//            });

            // @todo test split api and menu

           if (!onload.remain){
               after(function(done){
                   tabs.unload();

                   document.body.style.marginBottom = "";
                   done();
               });
           }
        });

        onload && onload();
    }
});<commit_msg>Better error handler + refactor c9.ide.api/api to c9.core/api<commit_after>/*global describe it before after  =*/

"use client";

require(["lib/architect/architect", "lib/chai/chai"], function (architect, chai) {
    var expect = chai.expect;

    expect.setupArchitectTest([
        {
            packagePath : "plugins/c9.core/c9",
            workspaceId : "ubuntu/ip-10-35-77-180",
            startdate   : new Date(),
            debug       : true,
            hosted      : true,
            local       : false,
            davPrefix   : "/"
        },

        "plugins/c9.core/ext",
        "plugins/c9.core/http",
        "plugins/c9.core/util",
        "plugins/c9.ide.ui/lib_apf",
        "plugins/c9.ide.ui/menus",
        {
            packagePath: "plugins/c9.core/settings",
            testing: true
        },
        "plugins/c9.core/api.js",
        {
            packagePath  : "plugins/c9.ide.ui/ui",
            staticPrefix : "plugins/c9.ide.ui"
        },
        "plugins/c9.ide.editors/document",
        "plugins/c9.ide.editors/undomanager",
        {
            packagePath: "plugins/c9.ide.editors/editors",
            defaultEditor: "ace"
        },
        "plugins/c9.ide.editors/editor",
        "plugins/c9.ide.editors/tabmanager",
        "plugins/c9.ide.ui/focus",
        "plugins/c9.ide.editors/pane",
        "plugins/c9.ide.editors/tab",
        "plugins/c9.ide.ace/ace",
        {
            packagePath  : "plugins/c9.ide.ace.statusbar/statusbar",
            staticPrefix : "plugins/c9.ide.layout.classic"
        },
        "plugins/c9.ide.keys/commands",
        "plugins/c9.fs/proc",
        "plugins/c9.vfs.client/vfs_client",
        "plugins/c9.vfs.client/endpoint",
        "plugins/c9.ide.auth/auth",
        "plugins/c9.fs/fs",

        // Mock plugins
        {
            consumes : ["apf", "ui", "Plugin"],
            provides : [
                "commands", "menus", "layout", "watcher",
                "save", "preferences", "anims", "gotoline", "clipboard",
                "dialog.alert", "auth.bootstrap", "info", "ace.gotoline"
            ],
            setup    : expect.html.mocked
        },
        {
            consumes : ["tabManager", "ace"],
            provides : [],
            setup    : main
        }
    ], architect);

    function main(options, imports, register) {
        var tabs    = imports.tabManager;
        var ace     = imports.ace;

        function getTabHtml(tab){
            return tab.pane.aml.getPage("editor::" + tab.editorType).$ext
        }

        expect.html.setConstructor(function(tab){
            if (typeof tab == "object")
                return tab.$ext;
        });

        describe('statusbar', function() {
            before(function(done){
                apf.config.setProperty("allow-select", false);
                apf.config.setProperty("allow-blur", false);

                bar.$ext.style.background = "rgba(220, 220, 220, 0.93)";
                bar.$ext.style.position = "fixed";
                bar.$ext.style.left = "20px";
                bar.$ext.style.right = "20px";
                bar.$ext.style.bottom = "20px";
                bar.$ext.style.height = "33%";

                document.body.style.marginBottom = "33%";

                tabs.on("ready", function(){
                    tabs.getPanes()[0].focus();
                    done();
                })
            });

            describe("open", function(){
                this.timeout(10000);

                it('should open a pane with just an editor', function(done) {
                    tabs.openFile("/file.txt", function(err, tab){
                        expect(tabs.getTabs()).length(1);

                        var sb  = tab.document.getSession().statusBar;
                        var bar = sb.getElement("bar");
                        expect.html(bar, "rowcol").text("1:1");

                        tab.document.editor.ace.selectAll();
                        setTimeout(function(){
                            expect.html(bar, "rowcol sel").text("2:1");
                            expect.html(bar, "sel").text("23 Bytes");

                            done();
                        }, 100);
                    });
                });
                it('should handle multiple documents in the same pane', function(done) {
                    tabs.openFile("/listing.json", function(err, tab){
                        expect(tabs.getTabs()).length(2);

                        tab.activate();

                        setTimeout(function(){
                            var sb = tab.document.getSession().statusBar;
                            expect.html(sb.getElement("bar"), "caption").text("1:1");

                            done();
                        }, 100);
                    });
                });
            });
            describe("split(), pane.unload()", function(){
                it('should split a pane horizontally, making the existing pane the left one', function(done) {
                    var pane = tabs.focussedTab.pane;
                    var righttab = pane.hsplit(true);
                    tabs.focussedTab.attachTo(righttab);

                    setTimeout(function(){
                        expect.html(pane.aml, "pane").text("2:1");
                        expect.html(righttab.aml, "righttab").text("1:1");

                        done();
                    }, 100);
                });
//                it('should remove the left pane from a horizontal split', function(done) {
//                    var pane  = tabs.getPanes()[0];
//                    var tab = tabs.getPanes()[1].getTab();
//                    pane.unload();
//                    expect(tabs.getPanes()).length(1);
//                    expect(tabs.getTabs()).length(2);
//                    tabs.focusTab(tab);
//                    done();
//                });
            });
//            describe("Change Theme", function(){
//                this.timeout(10000);
//
//                it('should change a theme', function(done) {
//                    var editor = tabs.focussedTab.editor;
//                    ace.on("themeInit", function setTheme(){
//                        ace.off("theme.init", setTheme);
//                        expect.html(getTabHtml(tabs.focussedTab).childNodes[1]).className("ace-monokai");
//                        editor.setOption("theme", "ace/theme/textmate");
//                        done();
//                    });
//                    editor.setOption("theme", "ace/theme/monokai");
//                });
//            });

            // @todo test split api and menu

           if (!onload.remain){
               after(function(done){
                   tabs.unload();

                   document.body.style.marginBottom = "";
                   done();
               });
           }
        });

        onload && onload();
    }
});<|endoftext|>


<commit_before>/*global describe it before after  =*/

"use client";

require(["lib/architect/architect", "lib/chai/chai"], function (architect, chai) {
    var expect = chai.expect;

    architect.resolveConfig([
        {
            packagePath : "plugins/c9.core/c9",
            workspaceId : "ubuntu/ip-10-35-77-180",
            startdate   : new Date(),
            debug       : true,
            hosted      : true,
            local       : false,
            davPrefix   : "/"
        },

        "plugins/c9.core/ext",
        "plugins/c9.core/http",
        "plugins/c9.core/util",
        "plugins/c9.ide.ui/lib_apf",
        "plugins/c9.ide.ui/menus",
        {
            packagePath: "plugins/c9.core/settings",
            testing: true
        },
        {
            packagePath  : "plugins/c9.ide.ui/ui",
            staticPrefix : "plugins/c9.ide.ui"
        },
        "plugins/c9.ide.editors/document",
        "plugins/c9.ide.editors/undomanager",
        {
            packagePath: "plugins/c9.ide.editors/editors",
            defaultEditor: "ace"
        },
        "plugins/c9.ide.editors/editor",
        "plugins/c9.ide.editors/tabmanager",
        "plugins/c9.ide.editors/pane",
        "plugins/c9.ide.editors/tab",
        "plugins/c9.ide.ace/ace",
        {
            packagePath  : "plugins/c9.ide.ace.statusbar/statusbar",
            staticPrefix : "plugins/c9.ide.layout.classic"
        },
        "plugins/c9.ide.keys/commands",
        "plugins/c9.fs/proc",
        "plugins/c9.vfs.client/vfs_client",
        "plugins/c9.vfs.client/endpoint",
        "plugins/c9.ide.auth/auth",
        "plugins/c9.fs/fs",

        // Mock plugins
        {
            consumes : ["apf", "ui", "Plugin"],
            provides : [
                "commands", "menus", "layout", "watcher",
                "save", "preferences", "anims", "gotoline", "clipboard",
                "dialog.alert", "auth.bootstrap", "ace.gotoline"
            ],
            setup    : expect.html.mocked
        },
        {
            consumes : ["tabManager", "ace"],
            provides : [],
            setup    : main
        }
    ], function (err, config) {
        if (err) throw err;
        var app = architect.createApp(config);
        app.on("service", function(name, plugin){ plugin.name = name; });
    });

    function main(options, imports, register) {
        var tabs    = imports.tabManager;
        var ace     = imports.ace;

        function getTabHtml(tab){
            return tab.pane.aml.getPage("editor::" + tab.editorType).$ext
        }

        expect.html.setConstructor(function(tab){
            if (typeof tab == "object")
                return tab.$ext;
        });

        describe('statusbar', function() {
            before(function(done){
                apf.config.setProperty("allow-select", false);
                apf.config.setProperty("allow-blur", false);
                tabs.getPanes()[0].focus();

                bar.$ext.style.background = "rgba(220, 220, 220, 0.93)";
                bar.$ext.style.position = "fixed";
                bar.$ext.style.left = "20px";
                bar.$ext.style.right = "20px";
                bar.$ext.style.bottom = "20px";
                bar.$ext.style.height = "33%";

                document.body.style.marginBottom = "33%";
                done();
            });

            describe("open", function(){
                this.timeout(10000);

                it('should open a pane with just an editor', function(done) {
                    tabs.openFile("/file.txt", function(err, tab){
                        expect(tabs.getTabs()).length(1);

                        var sb  = tab.document.getSession().statusBar;
                        var bar = sb.getElement("bar");
                        expect.html(bar, "rowcol").text("1:1");

                        tab.document.editor.ace.selectAll();
                        setTimeout(function(){
                            expect.html(bar, "rowcol sel").text("2:1");
                            expect.html(bar, "sel").text("23 Bytes");

                            done();
                        }, 100);
                    });
                });
                it('should handle multiple documents in the same pane', function(done) {
                    tabs.openFile("/listing.json", function(err, tab){
                        expect(tabs.getTabs()).length(2);

                        tab.activate();

                        setTimeout(function(){
                            var sb = tab.document.getSession().statusBar;
                            expect.html(sb.getElement("bar"), "caption").text("1:1");

                            done();
                        }, 100);
                    });
                });
            });
            describe("split(), pane.unload()", function(){
                it('should split a pane horizontally, making the existing pane the left one', function(done) {
                    var pane = tabs.focussedTab.pane;
                    var righttab = pane.hsplit(true);
                    tabs.focussedTab.attachTo(righttab);

                    setTimeout(function(){
                        expect.html(pane.aml, "pane").text("2:1");
                        expect.html(righttab.aml, "righttab").text("1:1");

                        done();
                    }, 100);
                });
//                it('should remove the left pane from a horizontal split', function(done) {
//                    var pane  = tabs.getPanes()[0];
//                    var tab = tabs.getPanes()[1].getTab();
//                    pane.unload();
//                    expect(tabs.getPanes()).length(1);
//                    expect(tabs.getTabs()).length(2);
//                    tabs.focusTab(tab);
//                    done();
//                });
            });
//            describe("Change Theme", function(){
//                this.timeout(10000);
//
//                it('should change a theme', function(done) {
//                    var editor = tabs.focussedTab.editor;
//                    ace.on("themeInit", function setTheme(){
//                        ace.off("theme.init", setTheme);
//                        expect.html(getTabHtml(tabs.focussedTab).childNodes[1]).className("ace-monokai");
//                        editor.setOption("theme", "ace/theme/textmate");
//                        done();
//                    });
//                    editor.setOption("theme", "ace/theme/monokai");
//                });
//            });

            // @todo test split api and menu

           if (!onload.remain){
               after(function(done){
                   tabs.unload();

                   document.body.style.marginBottom = "";
                   done();
               });
           }
        });

        onload && onload();
    }
});<commit_msg>fix remaining tests<commit_after>/*global describe it before after  =*/

"use client";

require(["lib/architect/architect", "lib/chai/chai"], function (architect, chai) {
    var expect = chai.expect;

    expect.setupArchitectTest([
        {
            packagePath : "plugins/c9.core/c9",
            workspaceId : "ubuntu/ip-10-35-77-180",
            startdate   : new Date(),
            debug       : true,
            hosted      : true,
            local       : false,
            davPrefix   : "/"
        },

        "plugins/c9.core/ext",
        "plugins/c9.core/http",
        "plugins/c9.core/util",
        "plugins/c9.ide.ui/lib_apf",
        "plugins/c9.ide.ui/menus",
        {
            packagePath: "plugins/c9.core/settings",
            testing: true
        },
        {
            packagePath  : "plugins/c9.ide.ui/ui",
            staticPrefix : "plugins/c9.ide.ui"
        },
        "plugins/c9.ide.editors/document",
        "plugins/c9.ide.editors/undomanager",
        {
            packagePath: "plugins/c9.ide.editors/editors",
            defaultEditor: "ace"
        },
        "plugins/c9.ide.editors/editor",
        "plugins/c9.ide.editors/tabmanager",
        "plugins/c9.ide.editors/pane",
        "plugins/c9.ide.editors/tab",
        "plugins/c9.ide.ace/ace",
        {
            packagePath  : "plugins/c9.ide.ace.statusbar/statusbar",
            staticPrefix : "plugins/c9.ide.layout.classic"
        },
        "plugins/c9.ide.keys/commands",
        "plugins/c9.fs/proc",
        "plugins/c9.vfs.client/vfs_client",
        "plugins/c9.vfs.client/endpoint",
        "plugins/c9.ide.auth/auth",
        "plugins/c9.fs/fs",

        // Mock plugins
        {
            consumes : ["apf", "ui", "Plugin"],
            provides : [
                "commands", "menus", "layout", "watcher",
                "save", "preferences", "anims", "gotoline", "clipboard",
                "dialog.alert", "auth.bootstrap", "ace.gotoline"
            ],
            setup    : expect.html.mocked
        },
        {
            consumes : ["tabManager", "ace"],
            provides : [],
            setup    : main
        }
    ], architect);

    function main(options, imports, register) {
        var tabs    = imports.tabManager;
        var ace     = imports.ace;

        function getTabHtml(tab){
            return tab.pane.aml.getPage("editor::" + tab.editorType).$ext
        }

        expect.html.setConstructor(function(tab){
            if (typeof tab == "object")
                return tab.$ext;
        });

        describe('statusbar', function() {
            before(function(done){
                apf.config.setProperty("allow-select", false);
                apf.config.setProperty("allow-blur", false);
                tabs.getPanes()[0].focus();

                bar.$ext.style.background = "rgba(220, 220, 220, 0.93)";
                bar.$ext.style.position = "fixed";
                bar.$ext.style.left = "20px";
                bar.$ext.style.right = "20px";
                bar.$ext.style.bottom = "20px";
                bar.$ext.style.height = "33%";

                document.body.style.marginBottom = "33%";
                done();
            });

            describe("open", function(){
                this.timeout(10000);

                it('should open a pane with just an editor', function(done) {
                    tabs.openFile("/file.txt", function(err, tab){
                        expect(tabs.getTabs()).length(1);

                        var sb  = tab.document.getSession().statusBar;
                        var bar = sb.getElement("bar");
                        expect.html(bar, "rowcol").text("1:1");

                        tab.document.editor.ace.selectAll();
                        setTimeout(function(){
                            expect.html(bar, "rowcol sel").text("2:1");
                            expect.html(bar, "sel").text("23 Bytes");

                            done();
                        }, 100);
                    });
                });
                it('should handle multiple documents in the same pane', function(done) {
                    tabs.openFile("/listing.json", function(err, tab){
                        expect(tabs.getTabs()).length(2);

                        tab.activate();

                        setTimeout(function(){
                            var sb = tab.document.getSession().statusBar;
                            expect.html(sb.getElement("bar"), "caption").text("1:1");

                            done();
                        }, 100);
                    });
                });
            });
            describe("split(), pane.unload()", function(){
                it('should split a pane horizontally, making the existing pane the left one', function(done) {
                    var pane = tabs.focussedTab.pane;
                    var righttab = pane.hsplit(true);
                    tabs.focussedTab.attachTo(righttab);

                    setTimeout(function(){
                        expect.html(pane.aml, "pane").text("2:1");
                        expect.html(righttab.aml, "righttab").text("1:1");

                        done();
                    }, 100);
                });
//                it('should remove the left pane from a horizontal split', function(done) {
//                    var pane  = tabs.getPanes()[0];
//                    var tab = tabs.getPanes()[1].getTab();
//                    pane.unload();
//                    expect(tabs.getPanes()).length(1);
//                    expect(tabs.getTabs()).length(2);
//                    tabs.focusTab(tab);
//                    done();
//                });
            });
//            describe("Change Theme", function(){
//                this.timeout(10000);
//
//                it('should change a theme', function(done) {
//                    var editor = tabs.focussedTab.editor;
//                    ace.on("themeInit", function setTheme(){
//                        ace.off("theme.init", setTheme);
//                        expect.html(getTabHtml(tabs.focussedTab).childNodes[1]).className("ace-monokai");
//                        editor.setOption("theme", "ace/theme/textmate");
//                        done();
//                    });
//                    editor.setOption("theme", "ace/theme/monokai");
//                });
//            });

            // @todo test split api and menu

           if (!onload.remain){
               after(function(done){
                   tabs.unload();

                   document.body.style.marginBottom = "";
                   done();
               });
           }
        });

        onload && onload();
    }
});<|endoftext|>


<commit_before>#!/usr/bin/env node
var MongoClient = require('mongodb').MongoClient

var mongoUri = process.env.MONGOLAB_URI ||
    process.env.MONGOHQ_URL ||
    'mongodb://localhost/test';

var args = process.argv.splice(2)
var firstArg = args[0] || 'find'
var todayIsoDate = new Date().toISOString().split('T')[0]
//db.tennishelsinki.createIndex({"expireAt":1}, {expireAfterSeconds:0})
//db.tennishelsinki.createIndex({"date":1}, {expireAfterSeconds:86400})
MongoClient.connect(mongoUri, function (err, db) {
    var collection = db.collection('tennishelsinki')
    if (firstArg === 'find') {
        var filter = args[1] ? {date: args[1]} : {}
        collection.find(filter).toArray(function (err, docs) {
            var transformedDoc = docs.map(function (doc) {
                doc.timestamp = doc._id.getTimestamp && doc._id.getTimestamp().toISOString()
                return doc
            })
            console.log(err, transformedDoc)
            db.close()
        })
    } else if (firstArg === 'insert') {
        var obj = {
            date:   new Date(args[1] || '2015-09-28'),
            courts: {foo: 'bar2'}
        }

        collection.insertOne(obj, {safe: true}, function (er, rs) {
            console.log(er, rs.result, rs.ops)
            db.close()
        })
    } else if (firstArg === 'remove') {
        collection.removeMany({mykey: 'myvalue'}, function (er, rs) {
            console.log(er, rs && rs.result)
            db.close()
        })
    } else if (firstArg === 'update') {
        var date = new Date(args[1] || '2015-09-28')
        collection.updateOne({date: date}, {
            date:   date,
            courts: {foo: 'bar3'}
        }, function (err, rs) {
            console.log(er, rs && rs.result)
            db.close()
        })
    }
});

<commit_msg>Update mongo example<commit_after>#!/usr/bin/env node
var MongoClient = require('mongodb').MongoClient

var mongoUri = process.env.MONGOLAB_URI ||
    process.env.MONGOHQ_URL ||
    'mongodb://localhost/test';

var args = process.argv.splice(2)
var firstArg = args[0] || 'find'
var todayIsoDate = new Date().toISOString().split('T')[0]
//db.tennishelsinki.createIndex({"expireAt":1}, {expireAfterSeconds:0})
//db.tennishelsinki.createIndex({"date":1}, {expireAfterSeconds:86400})
MongoClient.connect(mongoUri, function (err, db) {
    var collection = db.collection('tennishelsinki')
    if (firstArg === 'find') {
        var filter = args[1] ? {date: new Date(args[1])} : {}
        collection.find(filter).toArray(function (err, docs) {
            var transformedDoc = docs.map(function (doc) {
                doc.timestamp = doc._id.getTimestamp && doc._id.getTimestamp().toISOString()
                return doc
            })
            console.log(err, transformedDoc)
            db.close()
        })
    } else if (firstArg === 'remove') {
        collection.removeMany({mykey: 'myvalue'}, function (er, rs) {
            console.log(er, rs && rs.result)
            db.close()
        })
    } else if (firstArg === 'update') {
        var date = new Date(args[1] || '2015-09-30')
        collection.updateOne({date: date}, {
            date:   date,
            courts: {court: args[2] || 'bar5'}
        }, {
            upsert: true
        }, function (err, rs) {
            console.log(err, rs && rs.result)
            db.close()
        })
    }
});

<|endoftext|>