<commit_before>girderTest.importPlugin('jobs');
girderTest.importPlugin('worker');
girderTest.importPlugin('large_image');
girderTest.importPlugin('slicer_cli_web');
girderTest.importPlugin('HistomicsTK');

var app;
var geojsMap;
var imageId;

girderTest.promise.then(function () {
    $('body').css('overflow', 'hidden');
    girder.router.enabled(false);
    girder.events.trigger('g:appload.before');
    app = new girder.plugins.HistomicsTK.App({
        el: 'body',
        parentView: null
    });
    app.bindRoutes();
    girder.events.trigger('g:appload.after');
    return null;
});

$(function () {
    function openImage(name) {
        runs(function () {
            app.bodyView.once('h:viewerWidgetCreated', function (viewerWidget) {
                viewerWidget.once('g:beforeFirstRender', function () {
                    window.geo.util.mockVGLRenderer();
                });
            });
            $('.h-open-image').click();
        });

        girderTest.waitForDialog();

        runs(function () {
            $('#g-root-selector').val(
                girder.auth.getCurrentUser().id
            ).trigger('change');
        });

        waitsFor(function () {
            return $('#g-dialog-container .g-folder-list-link').length > 0;
        }, 'Hierarchy widget to render');

        runs(function () {
            $('.g-folder-list-link:contains("Public")').click();
        });

        waitsFor(function () {
            return $('.g-item-list-link').length > 0;
        }, 'item list to load');

        runs(function () {
            var $item = $('.g-item-list-link:contains("' + name + '")');
            imageId = $item.next().attr('href').match(/\/item\/([a-f0-9]+)\/download/)[1];
            expect($item.length).toBe(1);
            $item.click();
        });

        girderTest.waitForDialog();
        // Sometimes clicking submit fires the `g:saved` event, but doesn't actually
        // close the dialog.  Delaying the click seems to help.
        runs(function () {
            window.setTimeout(function () {
                $('.g-submit-button').click();
            }, 100);
        });

        girderTest.waitForLoad();
        waitsFor(function () {
            return $('.geojs-layer.active').length > 0;
        }, 'image to load');
        runs(function () {
            expect(girder.plugins.HistomicsTK.router.getQuery('image')).toBe(imageId);
        });
    }

    describe('Annotation tests', function () {
        describe('setup', function () {
            it('login', function () {
                girderTest.waitForLoad();

                runs(function () {
                    $('.g-login').click();
                });

                girderTest.waitForDialog();
                runs(function () {
                    $('#g-login').val('admin');
                    $('#g-password').val('password');
                    $('#g-login-button').click();
                });

                waitsFor(function () {
                    return $('.h-user-dropdown-link').length > 0;
                }, 'user to be logged in');
            });

            it('open image', function () {
                openImage('image');
                runs(function () {
                    geojsMap = app.bodyView.viewer;
                });
            });
        });

        describe('Draw panel', function () {
            it('draw a point', function () {
                runs(function () {
                    $('.h-draw[data-type="point"]').click();
                });

                waitsFor(function () {
                    return $('.geojs-map.annotation-input').length > 0;
                }, 'draw mode to activate');
                runs(function () {
                    var interactor = geojsMap.interactor();
                    interactor.simulateEvent('mousedown', {
                        map: {x: 100, y: 100},
                        button: 'left'
                    });
                    interactor.simulateEvent('mouseup', {
                        map: {x: 100, y: 100},
                        button: 'left'
                    });
                });

                waitsFor(function () {
                    return $('.h-elements-container .h-element').length === 1;
                }, 'point to be created');
                runs(function () {
                    expect($('.h-elements-container .h-element .h-element-label').text()).toBe('point');
                    expect($('.h-draw[data-type="point"]').hasClass('active')).toBe(true);
                    // turn off point drawing.
                    $('.h-draw[data-type="point"]').click();
                });
                waitsFor(function () {
                    return !$('.h-draw[data-type="point"]').hasClass('active');
                }, 'point drawing to be off');
            });

            it('edit a point element', function () {
                runs(function () {
                    $('.h-elements-container .h-edit-element').click();
                });

                girderTest.waitForDialog();
                runs(function () {
                    expect($('#g-dialog-container .modal-title').text()).toBe('Edit annotation');
                    $('#g-dialog-container #h-element-label').val('test');
                    $('#g-dialog-container .h-submit').click();
                });

                girderTest.waitForLoad();
                runs(function () {
                    expect($('.h-elements-container .h-element .h-element-label').text()).toBe('test');
                });
            });

            it('draw another point', function () {
                runs(function () {
                    $('.h-draw[data-type="point"]').click();
                });

                waitsFor(function () {
                    return $('.geojs-map.annotation-input').length > 0;
                }, 'draw mode to activate');
                runs(function () {
                    var interactor = geojsMap.interactor();
                    interactor.simulateEvent('mousedown', {
                        map: {x: 200, y: 200},
                        button: 'left'
                    });
                    interactor.simulateEvent('mouseup', {
                        map: {x: 200, y: 200},
                        button: 'left'
                    });
                });

                waitsFor(function () {
                    return $('.h-elements-container .h-element').length === 2;
                }, 'rectangle to be created');
                runs(function () {
                    expect($('.h-elements-container .h-element:last .h-element-label').text()).toBe('point');
                });
            });

            it('delete the second point', function () {
                $('.h-elements-container .h-element:last .h-delete-element').click();
                expect($('.h-elements-container .h-element').length).toBe(1);
            });

            it('save the point annotation', function () {
                var annotations = null;
                runs(function () {
                    $('.h-draw-widget .h-save-annotation').click();
                });

                girderTest.waitForDialog();
                runs(function () {
                    $('#g-dialog-container #h-annotation-name').val('single point');
                    $('#g-dialog-container .h-submit').click();
                });

                girderTest.waitForLoad();
                runs(function () {
                    expect($('.h-annotation-selector .h-annotation-name').text()).toBe('single point');
                    expect($('.h-draw-widget .h-save-widget').length).toBe(0);

                    girder.rest.restRequest({
                        path: 'annotation',
                        data: {
                            itemId: imageId
                        }
                    }).then(function (a) {
                        annotations = a;
                        return null;
                    });
                });

                waitsFor(function () {
                    return annotations !== null;
                }, 'get annotations from server');
                runs(function () {
                    expect(annotations.length).toBe(1);
                    expect(annotations[0].annotation.name).toBe('single point');
                });

                waitsFor(function () {
                    var $el = $('.h-annotation-selector .h-annotation:contains("single point")');
                    return $el.find('.icon-eye.h-toggle-annotation').length === 1;
                }, 'saved annotation to draw');
            });
        });

        describe('Annotation panel', function () {
            it('panel is rendered', function () {
                expect($('.h-annotation-selector .s-panel-title').text()).toMatch(/Annotations/);
            });

            it('toggle visibility of an annotation', function () {
                runs(function () {
                    var $el = $('.h-annotation-selector .h-annotation:contains("single point")');
                    $el.find('.h-toggle-annotation').click();
                });
                waitsFor(function () {
                    var $el = $('.h-annotation-selector .h-annotation:contains("single point")');
                    return $el.find('.icon-eye-off.h-toggle-annotation').length === 1;
                }, 'annotation to toggle off');

                runs(function () {
                    var $el = $('.h-annotation-selector .h-annotation:contains("single point")');
                    $el.find('.h-toggle-annotation').click();
                });
                waitsFor(function () {
                    var $el = $('.h-annotation-selector .h-annotation:contains("single point")');
                    return $el.find('.icon-eye.h-toggle-annotation').length === 1;
                }, 'annotation to toggle on');
            });

            it('delete an annotation', function () {
                var annotations = null;
                runs(function () {
                    $('.h-annotation-selector .h-annotation:contains("single point") .h-delete-annotation').click();
                    expect($('.h-annotation-selector .h-annotation:contains("single point")').length).toBe(0);
                });

                girderTest.waitForLoad();
                runs(function () {
                    girder.rest.restRequest({
                        path: 'annotation',
                        data: {
                            itemId: imageId
                        }
                    }).then(function (a) {
                        annotations = a;
                        return null;
                    });
                });

                waitsFor(function () {
                    return annotations !== null;
                }, 'get annotations from server');
                runs(function () {
                    expect(annotations.length).toBe(0);
                });
            });

            it('show new annotations during job events', function () {
                var uploaded = false;

                runs(function () {
                    var rect = {
                        'name': 'rectangle',
                        'description': 'the description',
                        'elements': [
                            {
                                'center': [
                                    2000,
                                    2000,
                                    0
                                ],
                                'height': 4000,
                                'rotation': 0,
                                'type': 'rectangle',
                                'width': 4000
                            }
                        ]
                    };

                    girder.rest.restRequest({
                        path: 'annotation?itemId=' + imageId,
                        contentType: 'application/json',
                        processData: false,
                        data: JSON.stringify(rect),
                        type: 'POST'
                    }).then(function () {
                        uploaded = true;
                        return null;
                    });
                });

                waitsFor(function () {
                    return uploaded;
                }, 'annotation to be uploaded');
                runs(function () {
                    girder.utilities.eventStream.trigger('g:event.job_status', {
                        data: {status: 3}
                    });
                });

                waitsFor(function () {
                    return $('.h-annotation-selector .h-annotation:contains("rectangle")').length === 1;
                }, 'new annotation to appear');
                runs(function () {
                    var $el = $('.h-annotation-selector .h-annotation:contains("rectangle")');
                    expect($el.find('.icon-eye.h-toggle-annotation').length).toBe(1);
                });
            });

            it('hover over annotation with labels off', function () {
                girderTest.waitForLoad();
                runs(function () {
                    var interactor = geojsMap.interactor();
                    interactor.simulateEvent('mousemove', {
                        map: {x: 50, y: 50}
                    });
                    expect($('#h-annotation-popover-container').hasClass('hidden')).toBe(true);
                });
            });

            it('hover over annotation with labels on', function () {
                var done = false;
                runs(function () {
                    $('#h-toggle-labels').click();

                    // Ensure the next mouse move event happens asynchronously.
                    // Without doing this, the hover event occasionally fails to
                    // fire.
                    window.setTimeout(function () {
                        done = true;
                    }, 0);
                });

                waitsFor(function () {
                    return done;
                }, 'next event loop');

                runs(function () {
                    var interactor = geojsMap.interactor();
                    interactor.simulateEvent('mousemove', {
                        map: {x: 45, y: 45}
                    });

                    var $el = $('#h-annotation-popover-container');
                    expect($el.hasClass('hidden')).toBe(false);
                    expect($el.find('.h-annotation-name').text()).toBe('rectangle');
                    expect($el.find('.h-annotation-description').text()).toMatch(/the description/);
                });
            });

            it('open a different image', function () {
                openImage('copy');
                runs(function () {
                    expect($('.h-annotation-selector .h-annotation').length).toBe(0);
                });
            });

            it('open the original image', function () {
                openImage('image');
                runs(function () {
                    expect($('.h-annotation-selector .h-annotation').length).toBe(1);
                });
            });
        });
    });

    describe('Open recently annotated image', function () {
        it('open the dialog', function () {
            $('.h-open-annotated-image').click();
            girderTest.waitForDialog();
            runs(function () {
                var $el = $('.h-annotated-image[data-id="' + imageId + '"]');
                expect($el.length).toBe(1);
                expect($el.find('.media-left img').prop('src'))
                    .toMatch(/item\/[0-9a-f]*\/tiles\/thumbnail/);
                expect($el.find('.media-heading').text()).toBe('image');
            });
        });

        it('click on the image', function () {
            var $el = $('.h-annotated-image[data-id="' + imageId + '"]');
            $el.click();
            girderTest.waitForLoad();
            runs(function () {
                expect(girder.plugins.HistomicsTK.router.getQuery('image')).toBe(imageId);
            });
        });
    });

    describe('Annotation styles', function () {
        it('open the syle group dialog', function () {
            openImage('copy');
            runs(function () {
                $('.h-configure-style-group').click();
            });
            waitsFor(function () {
                return $('body.modal-open').length > 0;
            }, 'dialog to open');
            runs(function () {
                // ensure the default style is created on load
                expect($('.h-style-selector :selected').val()).toBe('default');
            });
        });

        it('create a new style group', function () {
            $('.h-create-new-style').click();
            $('.h-new-style-name').val('new');
            $('.h-save-new-style').click();
            expect($('.h-style-selector :selected').val()).toBe('new');

            $('#h-element-line-width').val(1).trigger('change');
            $('#h-element-line-color').val('rgb(255,0,0)').trigger('change');
            $('#h-element-fill-color').val('rgb(0,0,255)').trigger('change');
            $('.h-submit').click();

            waitsFor(function () {
                return $('body.modal-open').length === 0;
            }, 'dialog to close');
        });

        it('draw a point', function () {
            runs(function () {
                $('.h-draw[data-type="point"]').removeClass('active').click();
            });

            waitsFor(function () {
                return $('.geojs-map.annotation-input').length > 0;
            }, 'draw mode to activate');
            runs(function () {
                var interactor = geojsMap.interactor();

                interactor.simulateEvent('mousedown', {
                    map: {x: 200, y: 200},
                    button: 'left'
                });
                interactor.simulateEvent('mouseup', {
                    map: {x: 200, y: 200},
                    button: 'left'
                });
            });
            waitsFor(function () {
                return app.bodyView.drawWidget.collection.length > 0;
            });
            runs(function () {
                var elements = app.bodyView.drawWidget.collection;
                expect(elements.length).toBe(1);

                var point = elements.at(0);
                expect(point.get('lineWidth')).toBe(1);
                expect(point.get('lineColor')).toBe('rgb(255, 0, 0)');
                expect(point.get('fillColor')).toBe('rgb(0, 0, 255)');
            });
        });
    });
});
<commit_msg>Fix remaining uses of the deprecated path option<commit_after>girderTest.importPlugin('jobs');
girderTest.importPlugin('worker');
girderTest.importPlugin('large_image');
girderTest.importPlugin('slicer_cli_web');
girderTest.importPlugin('HistomicsTK');

var app;
var geojsMap;
var imageId;

girderTest.promise.then(function () {
    $('body').css('overflow', 'hidden');
    girder.router.enabled(false);
    girder.events.trigger('g:appload.before');
    app = new girder.plugins.HistomicsTK.App({
        el: 'body',
        parentView: null
    });
    app.bindRoutes();
    girder.events.trigger('g:appload.after');
    return null;
});

$(function () {
    function openImage(name) {
        runs(function () {
            app.bodyView.once('h:viewerWidgetCreated', function (viewerWidget) {
                viewerWidget.once('g:beforeFirstRender', function () {
                    window.geo.util.mockVGLRenderer();
                });
            });
            $('.h-open-image').click();
        });

        girderTest.waitForDialog();

        runs(function () {
            $('#g-root-selector').val(
                girder.auth.getCurrentUser().id
            ).trigger('change');
        });

        waitsFor(function () {
            return $('#g-dialog-container .g-folder-list-link').length > 0;
        }, 'Hierarchy widget to render');

        runs(function () {
            $('.g-folder-list-link:contains("Public")').click();
        });

        waitsFor(function () {
            return $('.g-item-list-link').length > 0;
        }, 'item list to load');

        runs(function () {
            var $item = $('.g-item-list-link:contains("' + name + '")');
            imageId = $item.next().attr('href').match(/\/item\/([a-f0-9]+)\/download/)[1];
            expect($item.length).toBe(1);
            $item.click();
        });

        girderTest.waitForDialog();
        // Sometimes clicking submit fires the `g:saved` event, but doesn't actually
        // close the dialog.  Delaying the click seems to help.
        runs(function () {
            window.setTimeout(function () {
                $('.g-submit-button').click();
            }, 100);
        });

        girderTest.waitForLoad();
        waitsFor(function () {
            return $('.geojs-layer.active').length > 0;
        }, 'image to load');
        runs(function () {
            expect(girder.plugins.HistomicsTK.router.getQuery('image')).toBe(imageId);
        });
    }

    describe('Annotation tests', function () {
        describe('setup', function () {
            it('login', function () {
                girderTest.waitForLoad();

                runs(function () {
                    $('.g-login').click();
                });

                girderTest.waitForDialog();
                runs(function () {
                    $('#g-login').val('admin');
                    $('#g-password').val('password');
                    $('#g-login-button').click();
                });

                waitsFor(function () {
                    return $('.h-user-dropdown-link').length > 0;
                }, 'user to be logged in');
            });

            it('open image', function () {
                openImage('image');
                runs(function () {
                    geojsMap = app.bodyView.viewer;
                });
            });
        });

        describe('Draw panel', function () {
            it('draw a point', function () {
                runs(function () {
                    $('.h-draw[data-type="point"]').click();
                });

                waitsFor(function () {
                    return $('.geojs-map.annotation-input').length > 0;
                }, 'draw mode to activate');
                runs(function () {
                    var interactor = geojsMap.interactor();
                    interactor.simulateEvent('mousedown', {
                        map: {x: 100, y: 100},
                        button: 'left'
                    });
                    interactor.simulateEvent('mouseup', {
                        map: {x: 100, y: 100},
                        button: 'left'
                    });
                });

                waitsFor(function () {
                    return $('.h-elements-container .h-element').length === 1;
                }, 'point to be created');
                runs(function () {
                    expect($('.h-elements-container .h-element .h-element-label').text()).toBe('point');
                    expect($('.h-draw[data-type="point"]').hasClass('active')).toBe(true);
                    // turn off point drawing.
                    $('.h-draw[data-type="point"]').click();
                });
                waitsFor(function () {
                    return !$('.h-draw[data-type="point"]').hasClass('active');
                }, 'point drawing to be off');
            });

            it('edit a point element', function () {
                runs(function () {
                    $('.h-elements-container .h-edit-element').click();
                });

                girderTest.waitForDialog();
                runs(function () {
                    expect($('#g-dialog-container .modal-title').text()).toBe('Edit annotation');
                    $('#g-dialog-container #h-element-label').val('test');
                    $('#g-dialog-container .h-submit').click();
                });

                girderTest.waitForLoad();
                runs(function () {
                    expect($('.h-elements-container .h-element .h-element-label').text()).toBe('test');
                });
            });

            it('draw another point', function () {
                runs(function () {
                    $('.h-draw[data-type="point"]').click();
                });

                waitsFor(function () {
                    return $('.geojs-map.annotation-input').length > 0;
                }, 'draw mode to activate');
                runs(function () {
                    var interactor = geojsMap.interactor();
                    interactor.simulateEvent('mousedown', {
                        map: {x: 200, y: 200},
                        button: 'left'
                    });
                    interactor.simulateEvent('mouseup', {
                        map: {x: 200, y: 200},
                        button: 'left'
                    });
                });

                waitsFor(function () {
                    return $('.h-elements-container .h-element').length === 2;
                }, 'rectangle to be created');
                runs(function () {
                    expect($('.h-elements-container .h-element:last .h-element-label').text()).toBe('point');
                });
            });

            it('delete the second point', function () {
                $('.h-elements-container .h-element:last .h-delete-element').click();
                expect($('.h-elements-container .h-element').length).toBe(1);
            });

            it('save the point annotation', function () {
                var annotations = null;
                runs(function () {
                    $('.h-draw-widget .h-save-annotation').click();
                });

                girderTest.waitForDialog();
                runs(function () {
                    $('#g-dialog-container #h-annotation-name').val('single point');
                    $('#g-dialog-container .h-submit').click();
                });

                girderTest.waitForLoad();
                runs(function () {
                    expect($('.h-annotation-selector .h-annotation-name').text()).toBe('single point');
                    expect($('.h-draw-widget .h-save-widget').length).toBe(0);

                    girder.rest.restRequest({
                        url: 'annotation',
                        data: {
                            itemId: imageId
                        }
                    }).then(function (a) {
                        annotations = a;
                        return null;
                    });
                });

                waitsFor(function () {
                    return annotations !== null;
                }, 'get annotations from server');
                runs(function () {
                    expect(annotations.length).toBe(1);
                    expect(annotations[0].annotation.name).toBe('single point');
                });

                waitsFor(function () {
                    var $el = $('.h-annotation-selector .h-annotation:contains("single point")');
                    return $el.find('.icon-eye.h-toggle-annotation').length === 1;
                }, 'saved annotation to draw');
            });
        });

        describe('Annotation panel', function () {
            it('panel is rendered', function () {
                expect($('.h-annotation-selector .s-panel-title').text()).toMatch(/Annotations/);
            });

            it('toggle visibility of an annotation', function () {
                runs(function () {
                    var $el = $('.h-annotation-selector .h-annotation:contains("single point")');
                    $el.find('.h-toggle-annotation').click();
                });
                waitsFor(function () {
                    var $el = $('.h-annotation-selector .h-annotation:contains("single point")');
                    return $el.find('.icon-eye-off.h-toggle-annotation').length === 1;
                }, 'annotation to toggle off');

                runs(function () {
                    var $el = $('.h-annotation-selector .h-annotation:contains("single point")');
                    $el.find('.h-toggle-annotation').click();
                });
                waitsFor(function () {
                    var $el = $('.h-annotation-selector .h-annotation:contains("single point")');
                    return $el.find('.icon-eye.h-toggle-annotation').length === 1;
                }, 'annotation to toggle on');
            });

            it('delete an annotation', function () {
                var annotations = null;
                runs(function () {
                    $('.h-annotation-selector .h-annotation:contains("single point") .h-delete-annotation').click();
                    expect($('.h-annotation-selector .h-annotation:contains("single point")').length).toBe(0);
                });

                girderTest.waitForLoad();
                runs(function () {
                    girder.rest.restRequest({
                        url: 'annotation',
                        data: {
                            itemId: imageId
                        }
                    }).then(function (a) {
                        annotations = a;
                        return null;
                    });
                });

                waitsFor(function () {
                    return annotations !== null;
                }, 'get annotations from server');
                runs(function () {
                    expect(annotations.length).toBe(0);
                });
            });

            it('show new annotations during job events', function () {
                var uploaded = false;

                runs(function () {
                    var rect = {
                        'name': 'rectangle',
                        'description': 'the description',
                        'elements': [
                            {
                                'center': [
                                    2000,
                                    2000,
                                    0
                                ],
                                'height': 4000,
                                'rotation': 0,
                                'type': 'rectangle',
                                'width': 4000
                            }
                        ]
                    };

                    girder.rest.restRequest({
                        url: 'annotation?itemId=' + imageId,
                        contentType: 'application/json',
                        processData: false,
                        data: JSON.stringify(rect),
                        type: 'POST'
                    }).then(function () {
                        uploaded = true;
                        return null;
                    });
                });

                waitsFor(function () {
                    return uploaded;
                }, 'annotation to be uploaded');
                runs(function () {
                    girder.utilities.eventStream.trigger('g:event.job_status', {
                        data: {status: 3}
                    });
                });

                waitsFor(function () {
                    return $('.h-annotation-selector .h-annotation:contains("rectangle")').length === 1;
                }, 'new annotation to appear');
                runs(function () {
                    var $el = $('.h-annotation-selector .h-annotation:contains("rectangle")');
                    expect($el.find('.icon-eye.h-toggle-annotation').length).toBe(1);
                });
            });

            it('hover over annotation with labels off', function () {
                girderTest.waitForLoad();
                runs(function () {
                    var interactor = geojsMap.interactor();
                    interactor.simulateEvent('mousemove', {
                        map: {x: 50, y: 50}
                    });
                    expect($('#h-annotation-popover-container').hasClass('hidden')).toBe(true);
                });
            });

            it('hover over annotation with labels on', function () {
                var done = false;
                runs(function () {
                    $('#h-toggle-labels').click();

                    // Ensure the next mouse move event happens asynchronously.
                    // Without doing this, the hover event occasionally fails to
                    // fire.
                    window.setTimeout(function () {
                        done = true;
                    }, 0);
                });

                waitsFor(function () {
                    return done;
                }, 'next event loop');

                runs(function () {
                    var interactor = geojsMap.interactor();
                    interactor.simulateEvent('mousemove', {
                        map: {x: 45, y: 45}
                    });

                    var $el = $('#h-annotation-popover-container');
                    expect($el.hasClass('hidden')).toBe(false);
                    expect($el.find('.h-annotation-name').text()).toBe('rectangle');
                    expect($el.find('.h-annotation-description').text()).toMatch(/the description/);
                });
            });

            it('open a different image', function () {
                openImage('copy');
                runs(function () {
                    expect($('.h-annotation-selector .h-annotation').length).toBe(0);
                });
            });

            it('open the original image', function () {
                openImage('image');
                runs(function () {
                    expect($('.h-annotation-selector .h-annotation').length).toBe(1);
                });
            });
        });
    });

    describe('Open recently annotated image', function () {
        it('open the dialog', function () {
            $('.h-open-annotated-image').click();
            girderTest.waitForDialog();
            runs(function () {
                var $el = $('.h-annotated-image[data-id="' + imageId + '"]');
                expect($el.length).toBe(1);
                expect($el.find('.media-left img').prop('src'))
                    .toMatch(/item\/[0-9a-f]*\/tiles\/thumbnail/);
                expect($el.find('.media-heading').text()).toBe('image');
            });
        });

        it('click on the image', function () {
            var $el = $('.h-annotated-image[data-id="' + imageId + '"]');
            $el.click();
            girderTest.waitForLoad();
            runs(function () {
                expect(girder.plugins.HistomicsTK.router.getQuery('image')).toBe(imageId);
            });
        });
    });

    describe('Annotation styles', function () {
        it('open the syle group dialog', function () {
            openImage('copy');
            runs(function () {
                $('.h-configure-style-group').click();
            });
            waitsFor(function () {
                return $('body.modal-open').length > 0;
            }, 'dialog to open');
            runs(function () {
                // ensure the default style is created on load
                expect($('.h-style-selector :selected').val()).toBe('default');
            });
        });

        it('create a new style group', function () {
            $('.h-create-new-style').click();
            $('.h-new-style-name').val('new');
            $('.h-save-new-style').click();
            expect($('.h-style-selector :selected').val()).toBe('new');

            $('#h-element-line-width').val(1).trigger('change');
            $('#h-element-line-color').val('rgb(255,0,0)').trigger('change');
            $('#h-element-fill-color').val('rgb(0,0,255)').trigger('change');
            $('.h-submit').click();

            waitsFor(function () {
                return $('body.modal-open').length === 0;
            }, 'dialog to close');
        });

        it('draw a point', function () {
            runs(function () {
                $('.h-draw[data-type="point"]').removeClass('active').click();
            });

            waitsFor(function () {
                return $('.geojs-map.annotation-input').length > 0;
            }, 'draw mode to activate');
            runs(function () {
                var interactor = geojsMap.interactor();

                interactor.simulateEvent('mousedown', {
                    map: {x: 200, y: 200},
                    button: 'left'
                });
                interactor.simulateEvent('mouseup', {
                    map: {x: 200, y: 200},
                    button: 'left'
                });
            });
            waitsFor(function () {
                return app.bodyView.drawWidget.collection.length > 0;
            });
            runs(function () {
                var elements = app.bodyView.drawWidget.collection;
                expect(elements.length).toBe(1);

                var point = elements.at(0);
                expect(point.get('lineWidth')).toBe(1);
                expect(point.get('lineColor')).toBe('rgb(255, 0, 0)');
                expect(point.get('fillColor')).toBe('rgb(0, 0, 255)');
            });
        });
    });
});
<|endoftext|>


<commit_before>'use strict';

exports = module.exports = function(sequelize, DataTypes) {
  var Wine = sequelize.define('Wine', {
    id: { type: String, default: '' },
    grape: { type: String, default: '' },
    estate: { type: String, default: '' },
    name: { type: String, default: '' },
    notes: { type: String, default: '' },
    rating: { type: String, default: '' },
    createdAt: { type: Date, default: Date.now },
    createdBy: { type: String, default: '' }
  });

  //return Wine;
  return Wine;

};<commit_msg>updated wine schema<commit_after>'use strict';

exports = module.exports = function(sequelize, DataTypes) {
  var Wine = sequelize.define('Wine', {
    id: { type: Sequelize.INTEGER, autoIncrement: true },
    grape: { type: Sequelize.STRING },
    estate: { type: Sequelize.STRING },
    name: { type: Sequelize.STRING },
    notes: { type: Sequelize.STRING },
    rating: { type: Sequelize.STRING },
    createdBy: { type: Sequelize.STRING }
  });

  //createdAt and updatedAt are auto-created by sequelize
  //return Wine;
  return Wine;

};<|endoftext|>


<commit_before>$.extend({
  feature: function(body_class, callback) {
    // calling $.feature('bclass', function () {}) means that the function will
    // only get called when your body tag has the correct class.
    if ($('body').hasClass(body_class)) {
      $(callback);
    }
  }
});

$(function() {
  var csrftoken = $.cookie('csrftoken');

  function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
  }

  $.ajaxSetup({
    beforeSend: function(xhr, settings) {
      if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
        xhr.setRequestHeader('X-CSRFToken', csrftoken);
      }
    }
  });
});

$.feature('f_reminders_create', function() {
  var elem = $('select[name=frequency]');

  var update = function() {
    var val = parseInt(elem.val(), 10);

    $('[data-time_field]').each(function() {
      var x = parseInt($(this).data('time_field'), 10);

      $(this).toggleClass('hide', val < x);
    });
  };

  elem.on('change', update);
  update();
});

$.feature('f_reminders_create', function() {
  var update = function() {
    var val = $('input[name=message_type]:checked').val();

    $('[data-message_type]').each(function() {
      $(this).toggleClass('hide', $(this).data('message_type') !== val);
    });
  };

  $('input[name=message_type]').on('change', update);

  // Pageload
  update();
});

$.feature('f_reminders_create', function() {
  var wrapper = $('.js-record-request');

  var update = function() {
    var val = $('select[name=audio_url]').val();

    wrapper
      .toggleClass('hide', val !== '')
      .removeClass('has-error')
      .find('button')
        .button('reset')
      .end()
      .find('.help-block')
        .remove()
      .end()
      ;
  };

  $('select[name=audio_url]').on('change', update);

  // Pageload
  update();

  wrapper.find('button').on('click', function () {
    var button = $(this);

    button.button('loading');

    wrapper
      .find('.help-block')
        .remove()
      .end()
      ;

    wrapper.removeClass('has-error');

    var phone_number = wrapper
      .find('.js-record-request-phone-number')
      .val()
      ;

    $.post($(this).data('url'), {
      'phone_number': phone_number
    }, function (data) {
      // Display validatoin errors
      if (data.errors) {
        wrapper.addClass('has-error');

        $.each(data.errors, function (field, errors) {
          $.each(errors, function (idx, error) {
            $('

')
              .text(error.message)
              .insertBefore(button)
              ;
          });
        });

        return;
      }

    }).always(function() {
      button.button('reset');
    });
  });
});
<commit_msg>Start polling<commit_after>$.extend({
  feature: function(body_class, callback) {
    // calling $.feature('bclass', function () {}) means that the function will
    // only get called when your body tag has the correct class.
    if ($('body').hasClass(body_class)) {
      $(callback);
    }
  }
});

$(function() {
  var csrftoken = $.cookie('csrftoken');

  function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
  }

  $.ajaxSetup({
    beforeSend: function(xhr, settings) {
      if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
        xhr.setRequestHeader('X-CSRFToken', csrftoken);
      }
    }
  });
});

$.feature('f_reminders_create', function() {
  var elem = $('select[name=frequency]');

  var update = function() {
    var val = parseInt(elem.val(), 10);

    $('[data-time_field]').each(function() {
      var x = parseInt($(this).data('time_field'), 10);

      $(this).toggleClass('hide', val < x);
    });
  };

  elem.on('change', update);
  update();
});

$.feature('f_reminders_create', function() {
  var update = function() {
    var val = $('input[name=message_type]:checked').val();

    $('[data-message_type]').each(function() {
      $(this).toggleClass('hide', $(this).data('message_type') !== val);
    });
  };

  $('input[name=message_type]').on('change', update);

  // Pageload
  update();
});

$.feature('f_reminders_create', function() {
  var wrapper = $('.js-record-request');

  var update = function() {
    var val = $('select[name=audio_url]').val();

    wrapper
      .toggleClass('hide', val !== '')
      .removeClass('has-error')
      .find('button')
        .button('reset')
      .end()
      .find('.help-block')
        .remove()
      .end()
      ;
  };

  $('select[name=audio_url]').on('change', update);

  // Pageload
  update();

  wrapper.find('button').on('click', function () {
    var button = $(this);

    button.button('loading');

    wrapper
      .find('.help-block')
        .remove()
      .end()
      ;

    wrapper.removeClass('has-error');

    var phone_number = wrapper
      .find('.js-record-request-phone-number')
      .val()
      ;

    $.post($(this).data('url'), {
      'phone_number': phone_number
    }, function (data) {
      // Display validatoin errors
      if (data.errors) {
        wrapper.addClass('has-error');

        $.each(data.errors, function (field, errors) {
          $.each(errors, function (idx, error) {
            $('

')
              .text(error.message)
              .insertBefore(button)
              ;
          });
        });

        return;
      }

      (function poll() {
        $.ajax({
            url: data.url,
            type: 'POST',
            success: function(data) {
              console.log("polling");
              console.log("data");
            },
            dataType: 'son',
            complete: setTimeout(function() {
              poll();
            }, 1000),
            timeout: 2000
        });
      })();
    }).always(function() {
      button.button('reset');
    });
  });
});
<|endoftext|>


<commit_before>module('users.timfelgentreff.reactive.reactive').requires('users.timfelgentreff.babelsberg.constraintinterpreter', 'cop.Layers').toRun(function() {

	JSLoader.loadJs(module('users.timfelgentreff.csp.underscore-min').uri());

	/***************************************************************
	 * Abstract Reactive Solver
	 ***************************************************************/

	Object.subclass("ReactiveSolver", {
	    isConstraintObject: true,
	    always: function(opts, func) {
	        var ctx = opts.ctx;
	        func.varMapping = ctx;
	        var cobj = new Constraint(func, this);
			cobj.allowFailing = true;
	        cobj.addPrimitiveConstraint(new ReactiveSolver.Constraint(this, cobj, func));
			try {
				if(!opts.postponeEnabling) { cobj.enable(); }
			} catch(e) {
				if(e instanceof ContinuousAssertError) {
					cobj.disable();
				}
				throw e;
			}
	        return cobj;
	    },
	    constraintVariableFor: function(value, ivarname, bbbCVar) {
	    	return new ReactiveSolver.Variable(this, value, ivarname, bbbCVar);
	    },
	    weight: 10000
	});

	Object.subclass("ReactiveSolver.Variable", {
	    isConstraintObject: true,
		initialize: function(solver, value, ivarname, bbbCVar) {
			this.solver = solver;
			this.__val__ = value;
			this.enabled = false;
		},
	    suggestValue: function(value) {
			if(this.__val__ === value) { return value; }
			var prev = this.__val__;
	    	this.__val__ = value;
			try {
				this.solver.solve();
			} catch(e) {
				// revert value in case of a violated assertion
				if(e instanceof ContinuousAssertError) {
					this.__val__ = prev;
				}
				throw e;
			}

			// re-constrain variables
			if (typeof(value) == 'object' || typeof(value) == 'function') {
			    // only recalculate to reconstraint complex objects
                var bbbConstraint = this.solver.constraint.bbbConstraint;
                var enabled = bbbConstraint._enabled;
                bbbConstraint.initialize(bbbConstraint.predicate, bbbConstraint.solver);
                bbbConstraint.addPrimitiveConstraint(this.solver.constraint);
                if(enabled) bbbConstraint.enable();
			}

	    	return this.__val__;
	    },
	    value: function() {
	    	return this.__val__;
	    },
	    setReadonly: function(bool) {
	    	this.readonly = bool;
	    },
	    isReadonly: function() {
	        return this.readonly;
	    },
	    cnEquals: function() {
	        return new ReactiveSolver.PrimitiveConstraint(this, arguments);
	    },
	    enable: function() {
			this.enabled = true;
	    },
	    disable: function() {
			this.enabled = false;
	    }
	});

	Object.subclass("ReactiveSolver.PrimitiveConstraint", {
	    isConstraintObject: true,
	    initialize: function(variable, args) {
			this.enabled = false;
	    	this.solver = variable.solver;
	    },
	    enable: function() {
			this.enabled = true;
	    },
	    disable: function() {
			this.enabled = false;
	    }
	});

	Object.subclass("ReactiveSolver.Constraint", {
	    isConstraintObject: true,
	    initialize: function(solver, bbbConstraint, func) {
			this.enabled = false;
	    	this.solver = solver;
	    	this.solver.constraint = this;
			this.bbbConstraint = bbbConstraint;

	    	this.predicate = func;
	    },
	    enable: function() {
			this.enabled = true;
	    },
	    disable: function() {
			this.enabled = false;
	    }
	});

	/***************************************************************
	 * Continuous asserts
	 ***************************************************************/

	// TODO: integration with other solvers

	Error.subclass("ContinuousAssertError", {
		initialize: function ContinuousAssertError(msg) {
			if (Error.captureStackTrace) {
				Error.captureStackTrace(this, ContinuousAssertError);
			} else {
				this.stack = (new Error).stack || '';
			}
			this.message = msg;
		},
		name: "ContinuousAssertError"
	});

	ReactiveSolver.subclass("AssertSolver", {
		initialize: function(message) {
			this.message = message;
		},
	    solve: function() {
	    	if(this.constraint && this.constraint.enabled && typeof this.constraint.predicate === "function")
	    		if(!this.constraint.predicate())
	    			throw new ContinuousAssertError(this.message);
	    }
	});

	Object.extend(Babelsberg.prototype, {
		assert: function(opts, func) {
			opts.solver = new AssertSolver(opts.message);
			opts.allowUnsolvableOperations = true;
			opts.allowTests = true;
			//opts.debugging = true;
	        return this.always(opts, func);
		}
	});

	/***************************************************************
	 * Triggering
	 ***************************************************************/
	ReactiveSolver.subclass("TriggerSolver", {
		initialize: function(callback) {
			this.callback = callback;
			this.triggeredOnce = false;
		},
	    solve: function() {
	    	if(this.constraint &&
				this.constraint.enabled &&
				typeof this.constraint.predicate === "function"
			) {
	    		if(this.constraint.predicate()) {
					if(!this.triggeredOnce) {
						this.triggeredOnce = true;
						bbb.addCallback(this.callback, this.constraint.bbbConstraint, []);
					}
				} else {
					this.triggeredOnce = false;
				}
			}
	    },
	    weight: 10
	});

	Object.subclass("__TriggerDefinition__", {
		initialize: function(opts, func) {
			this.opts = opts;
			this.func = func;
		},
	    trigger: function(callback) {
			this.opts.callback = callback;
			return bbb.trigger(this.opts, this.func);
		}
	});

	Object.extend(Babelsberg.prototype, {
		trigger: function(opts, func) {
			opts.solver = new TriggerSolver(opts.callback);
			opts.allowUnsolvableOperations = true;
			opts.allowTests = true;
			//opts.debugging = true;
	        return this.always(opts, func);
		},
		when: function(opts, func) {
			return new __TriggerDefinition__(opts, func);
		}
	});

	/***************************************************************
	 * Layer activation
	 ***************************************************************/
	ReactiveSolver.subclass("LayerActivationSolver", {
		initialize: function(layer) {
			this.layer = layer;
		},
	    solve: function() {
	    	if(this.constraint &&
				this.constraint.enabled &&
				typeof this.constraint.predicate === "function"
			) {
				var predicateFulfilled = this.constraint.predicate();
	    		if(predicateFulfilled && !this.layer.isGlobal()) {
	    			this.layer.beGlobal();
				} else  if(!predicateFulfilled && this.layer.isGlobal()) {
	    			this.layer.beNotGlobal();
				}
			}
	    },
	    weight: 10
	});

    var activator = function(opts, func, layer) {
        opts.solver = new LayerActivationSolver(layer);
        opts.allowUnsolvableOperations = true;
        opts.allowTests = true;
        //opts.debugging = true;
        return bbb.always(opts, func);
    }

	Object.extend(Layer.prototype, {
		activeOn: function(opts, func) {
		    activator(opts, func, this);

			return this;
		}
	});

	/***************************************************************
	 * Scoped constraints
	 ***************************************************************/
	Object.extend(Layer.prototype, {
		always: function(opts, func) {
			opts.postponeEnabling = !this.isGlobal();
			var cobj = bbb.always(opts, func);

			this.constraintObjects = this.constraintObjects || [];
			this.constraintObjects.push(cobj);

			return cobj;
		},
		assert: function(opts, func) {
			opts.postponeEnabling = !this.isGlobal();
			var cobj = bbb.assert(opts, func);

			this.constraintObjects = this.constraintObjects || [];
			this.constraintObjects.push(cobj);

			return cobj;
		},
		trigger: function(opts, func) {
			opts.postponeEnabling = !this.isGlobal();
			var cobj = bbb.trigger(opts, func);

			this.constraintObjects = this.constraintObjects || [];
			this.constraintObjects.push(cobj);

			return cobj;
		},
		_activate: function() {
			this.constraintObjects = this.constraintObjects || [];
			this.constraintObjects.forEach(function(cobj) {
				cobj.enable();
			});
		},
		_deactivate: function() {
			this.constraintObjects = this.constraintObjects || [];
			this.constraintObjects.forEach(function(cobj) {
				cobj.disable();
			});
		}
	});

	/* Layer Activation */
	cop.withLayers = cop.withLayers.wrap(function(callOriginal, layers, func) {
		layers.forEach(function(layer) { layer._activate(); });

		try {
			return callOriginal(layers, func);
		} finally {
			layers.forEach(function(layer) { layer._deactivate(); });
		}
	});

	cop.withoutLayers = cop.withoutLayers.wrap(function(callOriginal, layers, func) {
		layers.forEach(function(layer) { layer._deactivate(); });

		try {
			return callOriginal(layers, func);
		} finally {
			layers.forEach(function(layer) { layer._activate(); });
		}
	});

	/* Global Layer Activation */
	cop.enableLayer = cop.enableLayer.wrap(function(callOriginal, layer) {
		layer._activate();
		return callOriginal(layer);
	});

	cop.disableLayer = cop.disableLayer.wrap(function(callOriginal, layer) {
		layer._deactivate();
		return callOriginal(layer);
	});

	/***************************************************************
	 * Unified Notation
	 ***************************************************************/

	Object.subclass("Predicate", {
	    initialize: function(func, opts) {
            this.func = func;
            this.opts = opts;
	    },
	    _mergeOptions: function(options1, options2) {
	        var mergedOptions = {};

            Object.extend(mergedOptions, options1);
            Object.extend(mergedOptions, options2);

            return mergedOptions;
	    },
	    once: function(opts) {
	    	return bbb.once(
	    	    this._mergeOptions(this.opts, opts),
	    	    this.func
	    	);
	    },
	    always: function(opts) {
	    	return bbb.always(
	    	    this._mergeOptions(this.opts, opts),
	    	    this.func
	    	);
	    },
	    assert: function(opts) {
	    	return bbb.assert(
	    	    this._mergeOptions(this.opts, opts),
	    	    this.func
	    	);
	    },
	    trigger: function(callback) {
	    	return bbb.trigger(
                this._mergeOptions(this.opts, { callback: callback }),
                this.func
	    	);
	    },
	    activate: function(layer) {
	    	return activator(
                this.opts,
                this.func,
                layer
	    	);
	    }
	});

	Predicate.subclass("LayeredPredicate", {
	    initialize: function($super, func, opts, layer) {
            $super(func, opts);
            this.layer = layer;
	    },
	    once: function($super, opts) {
	        if(!this.layer.isGlobal()) return;

	    	return $super(opts);
	    },
	    always: function(opts) {
	    	return this.layer.always(
	    	    this._mergeOptions(this.opts, opts),
	    	    this.func
	    	);
	    },
	    assert: function(opts) {
	    	return this.layer.assert(
	    	    this._mergeOptions(this.opts, opts),
	    	    this.func
	    	);
	    },
	    trigger: function(callback) {
            return this.layer.trigger(
                this._mergeOptions(this.opts, { callback: callback }),
                this.func
            );
	    },
	    activate: function(layer) {
			var cobj = activator(
                this._mergeOptions(this.opts, { postponeEnabling: !this.layer.isGlobal() }),
                this.func,
                layer
	    	);

			this.layer.constraintObjects = this.layer.constraintObjects || [];
			this.layer.constraintObjects.push(cobj);

			return cobj;
	    }
	});

	predicate = function(func, opts) {
        return new Predicate(func, opts);
	}

	Object.extend(Layer.prototype, {
		predicate: function(func, opts) {
		    return new LayeredPredicate(func,opts, this);
		}
	});
});
<commit_msg>extracted code to superclass as constraintEnabled function<commit_after>module('users.timfelgentreff.reactive.reactive').requires('users.timfelgentreff.babelsberg.constraintinterpreter', 'cop.Layers').toRun(function() {

	JSLoader.loadJs(module('users.timfelgentreff.csp.underscore-min').uri());

	/***************************************************************
	 * Abstract Reactive Solver
	 ***************************************************************/

	Object.subclass("ReactiveSolver", {
	    isConstraintObject: true,
	    always: function(opts, func) {
	        var ctx = opts.ctx;
	        func.varMapping = ctx;
	        var cobj = new Constraint(func, this);
			cobj.allowFailing = true;
	        cobj.addPrimitiveConstraint(new ReactiveSolver.Constraint(this, cobj, func));
			try {
				if(!opts.postponeEnabling) { cobj.enable(); }
			} catch(e) {
				if(e instanceof ContinuousAssertError) {
					cobj.disable();
				}
				throw e;
			}
	        return cobj;
	    },
	    constraintVariableFor: function(value, ivarname, bbbCVar) {
	    	return new ReactiveSolver.Variable(this, value, ivarname, bbbCVar);
	    },
		constraintEnabled: function() {
	    	return this.constraint &&
				this.constraint.enabled &&
				typeof this.constraint.predicate === "function";
		},
	    weight: 10000
	});

	Object.subclass("ReactiveSolver.Variable", {
	    isConstraintObject: true,
		initialize: function(solver, value, ivarname, bbbCVar) {
			this.solver = solver;
			this.__val__ = value;
			this.enabled = false;
		},
	    suggestValue: function(value) {
			if(this.__val__ === value) { return value; }
			var prev = this.__val__;
	    	this.__val__ = value;
			try {
				this.solver.solve();
			} catch(e) {
				// revert value in case of a violated assertion
				if(e instanceof ContinuousAssertError) {
					this.__val__ = prev;
				}
				throw e;
			}

			// re-constrain variables
			if (typeof(value) == 'object' || typeof(value) == 'function') {
			    // only recalculate to reconstraint complex objects
                var bbbConstraint = this.solver.constraint.bbbConstraint;
                var enabled = bbbConstraint._enabled;
                bbbConstraint.initialize(bbbConstraint.predicate, bbbConstraint.solver);
                bbbConstraint.addPrimitiveConstraint(this.solver.constraint);
                if(enabled) bbbConstraint.enable();
			}

	    	return this.__val__;
	    },
	    value: function() {
	    	return this.__val__;
	    },
	    setReadonly: function(bool) {
	    	this.readonly = bool;
	    },
	    isReadonly: function() {
	        return this.readonly;
	    },
	    cnEquals: function() {
	        return new ReactiveSolver.PrimitiveConstraint(this, arguments);
	    },
	    enable: function() {
			this.enabled = true;
	    },
	    disable: function() {
			this.enabled = false;
	    }
	});

	Object.subclass("ReactiveSolver.PrimitiveConstraint", {
	    isConstraintObject: true,
	    initialize: function(variable, args) {
			this.enabled = false;
	    	this.solver = variable.solver;
	    },
	    enable: function() {
			this.enabled = true;
	    },
	    disable: function() {
			this.enabled = false;
	    }
	});

	Object.subclass("ReactiveSolver.Constraint", {
	    isConstraintObject: true,
	    initialize: function(solver, bbbConstraint, func) {
			this.enabled = false;
	    	this.solver = solver;
	    	this.solver.constraint = this;
			this.bbbConstraint = bbbConstraint;

	    	this.predicate = func;
	    },
	    enable: function() {
			this.enabled = true;
	    },
	    disable: function() {
			this.enabled = false;
	    }
	});

	/***************************************************************
	 * Continuous asserts
	 ***************************************************************/

	// TODO: integration with other solvers

	Error.subclass("ContinuousAssertError", {
		initialize: function ContinuousAssertError(msg) {
			if (Error.captureStackTrace) {
				Error.captureStackTrace(this, ContinuousAssertError);
			} else {
				this.stack = (new Error).stack || '';
			}
			this.message = msg;
		},
		name: "ContinuousAssertError"
	});

	ReactiveSolver.subclass("AssertSolver", {
		initialize: function(message) {
			this.message = message;
		},
	    solve: function() {
	    	if(!this.constraintEnabled()) { return; }
            if(!this.constraint.predicate())
                throw new ContinuousAssertError(this.message);
	    }
	});

	Object.extend(Babelsberg.prototype, {
		assert: function(opts, func) {
			opts.solver = new AssertSolver(opts.message);
			opts.allowUnsolvableOperations = true;
			opts.allowTests = true;
			//opts.debugging = true;
	        return this.always(opts, func);
		}
	});

	/***************************************************************
	 * Triggering
	 ***************************************************************/
	ReactiveSolver.subclass("TriggerSolver", {
		initialize: function(callback) {
			this.callback = callback;
			this.triggeredOnce = false;
		},
	    solve: function() {
	    	if(!this.constraintEnabled()) { return; }
            if(this.constraint.predicate()) {
                if(!this.triggeredOnce) {
                    this.triggeredOnce = true;
                    bbb.addCallback(this.callback, this.constraint.bbbConstraint, []);
                }
            } else {
                this.triggeredOnce = false;
            }
	    },
	    weight: 10
	});

	Object.subclass("__TriggerDefinition__", {
		initialize: function(opts, func) {
			this.opts = opts;
			this.func = func;
		},
	    trigger: function(callback) {
			this.opts.callback = callback;
			return bbb.trigger(this.opts, this.func);
		}
	});

	Object.extend(Babelsberg.prototype, {
		trigger: function(opts, func) {
			opts.solver = new TriggerSolver(opts.callback);
			opts.allowUnsolvableOperations = true;
			opts.allowTests = true;
			//opts.debugging = true;
	        return this.always(opts, func);
		},
		when: function(opts, func) {
			return new __TriggerDefinition__(opts, func);
		}
	});

	/***************************************************************
	 * Layer activation
	 ***************************************************************/
	// TODO: rename to ActivatorSolver
	ReactiveSolver.subclass("LayerActivationSolver", {
		initialize: function(layer) {
			this.layer = layer;
		},
	    solve: function() {
	    	if(!this.constraintEnabled()) { return; }
            var predicateFulfilled = this.constraint.predicate();
            if(predicateFulfilled && !this.layer.isGlobal()) {
                this.layer.beGlobal();
            } else  if(!predicateFulfilled && this.layer.isGlobal()) {
                this.layer.beNotGlobal();
            }
	    },
	    weight: 10
	});

    var activator = function(opts, func, layer) {
        opts.solver = new LayerActivationSolver(layer);
        opts.allowUnsolvableOperations = true;
        opts.allowTests = true;
        //opts.debugging = true;
        return bbb.always(opts, func);
    }

	Object.extend(Layer.prototype, {
		activeOn: function(opts, func) {
		    activator(opts, func, this);

			return this;
		}
	});

	/***************************************************************
	 * Scoped constraints
	 ***************************************************************/
	Object.extend(Layer.prototype, {
		always: function(opts, func) {
			opts.postponeEnabling = !this.isGlobal();
			var cobj = bbb.always(opts, func);

			this.constraintObjects = this.constraintObjects || [];
			this.constraintObjects.push(cobj);

			return cobj;
		},
		assert: function(opts, func) {
			opts.postponeEnabling = !this.isGlobal();
			var cobj = bbb.assert(opts, func);

			this.constraintObjects = this.constraintObjects || [];
			this.constraintObjects.push(cobj);

			return cobj;
		},
		trigger: function(opts, func) {
			opts.postponeEnabling = !this.isGlobal();
			var cobj = bbb.trigger(opts, func);

			this.constraintObjects = this.constraintObjects || [];
			this.constraintObjects.push(cobj);

			return cobj;
		},
		_activate: function() {
			this.constraintObjects = this.constraintObjects || [];
			this.constraintObjects.forEach(function(cobj) {
				cobj.enable();
			});
		},
		_deactivate: function() {
			this.constraintObjects = this.constraintObjects || [];
			this.constraintObjects.forEach(function(cobj) {
				cobj.disable();
			});
		}
	});

	/* Layer Activation */
	cop.withLayers = cop.withLayers.wrap(function(callOriginal, layers, func) {
		layers.forEach(function(layer) { layer._activate(); });

		try {
			return callOriginal(layers, func);
		} finally {
			layers.forEach(function(layer) { layer._deactivate(); });
		}
	});

	cop.withoutLayers = cop.withoutLayers.wrap(function(callOriginal, layers, func) {
		layers.forEach(function(layer) { layer._deactivate(); });

		try {
			return callOriginal(layers, func);
		} finally {
			layers.forEach(function(layer) { layer._activate(); });
		}
	});

	/* Global Layer Activation */
	cop.enableLayer = cop.enableLayer.wrap(function(callOriginal, layer) {
		layer._activate();
		return callOriginal(layer);
	});

	cop.disableLayer = cop.disableLayer.wrap(function(callOriginal, layer) {
		layer._deactivate();
		return callOriginal(layer);
	});

	/***************************************************************
	 * Unified Notation
	 ***************************************************************/

	Object.subclass("Predicate", {
	    initialize: function(func, opts) {
            this.func = func;
            this.opts = opts;
	    },
	    _mergeOptions: function(options1, options2) {
	        var mergedOptions = {};

            Object.extend(mergedOptions, options1);
            Object.extend(mergedOptions, options2);

            return mergedOptions;
	    },
	    once: function(opts) {
	    	return bbb.once(
	    	    this._mergeOptions(this.opts, opts),
	    	    this.func
	    	);
	    },
	    always: function(opts) {
	    	return bbb.always(
	    	    this._mergeOptions(this.opts, opts),
	    	    this.func
	    	);
	    },
	    assert: function(opts) {
	    	return bbb.assert(
	    	    this._mergeOptions(this.opts, opts),
	    	    this.func
	    	);
	    },
	    trigger: function(callback) {
	    	return bbb.trigger(
                this._mergeOptions(this.opts, { callback: callback }),
                this.func
	    	);
	    },
	    activate: function(layer) {
	    	return activator(
                this.opts,
                this.func,
                layer
	    	);
	    }
	});

	Predicate.subclass("LayeredPredicate", {
	    initialize: function($super, func, opts, layer) {
            $super(func, opts);
            this.layer = layer;
	    },
	    once: function($super, opts) {
	        if(!this.layer.isGlobal()) return;

	    	return $super(opts);
	    },
	    always: function(opts) {
	    	return this.layer.always(
	    	    this._mergeOptions(this.opts, opts),
	    	    this.func
	    	);
	    },
	    assert: function(opts) {
	    	return this.layer.assert(
	    	    this._mergeOptions(this.opts, opts),
	    	    this.func
	    	);
	    },
	    trigger: function(callback) {
            return this.layer.trigger(
                this._mergeOptions(this.opts, { callback: callback }),
                this.func
            );
	    },
	    activate: function(layer) {
			var cobj = activator(
                this._mergeOptions(this.opts, { postponeEnabling: !this.layer.isGlobal() }),
                this.func,
                layer
	    	);

			this.layer.constraintObjects = this.layer.constraintObjects || [];
			this.layer.constraintObjects.push(cobj);

			return cobj;
	    }
	});

	predicate = function(func, opts) {
        return new Predicate(func, opts);
	}

	Object.extend(Layer.prototype, {
		predicate: function(func, opts) {
		    return new LayeredPredicate(func,opts, this);
		}
	});
});
<|endoftext|>


<commit_before>Polymer({
  is: 'rest-resource',

  properties: {

    /**
     * A pattern for the REST URL. Can contain colon-parameters and data bindings, for example:
     *
     * `url="/users/:userId?q={{searchText}}"`
     *
     * Default URLS:
     *
     *

     *

     * Method
     * HTTP method
     * URL
     *

     *

     * index
     * GET
     * /users
     *

     *

     * show
     * GET
     * /users/1
     *

     *

     * create
     * POST
     * /users
     *

     *

     * update
     * PUT
     * /users
     *

     *

     * destroy
     * DELETE
     * /users/1
     *

     *

     * member foo
     * PUT
     * /users/1/foo
     *

     *

     *
     */
    url: String,

    /**
     * A hash that binds URL parameters to actual values, for example:
     *
     * `params='{{ {"userId":user.id} }}'`
     */
    params: Object,

    /**
     * Use this URL instead of the default one for "GET /resources" requests.
     */
    indexUrl: String,

    /**
     * Use this URL instead of the default one for "GET /resources/:id" requests.
     */
    showUrl: String,

    /**
     * Use this URL instead of the default one for "POST /resources" requests.
     */
    createUrl: String,

    /**
     * Use this URL instead of the default one for "PUT /resources/:id" requests.
     */
    updateUrl: String,

    /**
     * Use this URL instead of the default one for "DELETE /resources/:id" requests.
     */
    destroyUrl: String,

    /**
     * Use this URL instead of the default one for "PUT /resources/:id/action" requests.
     */
    memberUrl: String,

    /**
     * Set additional headers on the request.
     */
    headers: Object,

    /**
     * Set an authorization header with the specified token text.
     */
    token: Object
  },

  // Element Behavior

  /**
   * Is fired when a REST call is initiated.
   *
   * @event request
   * @detail {{request: Object}}
   */

  /**
   * Is fired when a REST call returns successful response.
   *
   * @event response
   * @detail {{request: Object, response: Object}}
   */

  /**
   * Is fired when a REST call returns failure response.
   *
   * @event error
   * @detail {{request: Object, response: Object}}
   */

  _handleSuccess: function(request, successCallback) {
    var me = this;
    return function() {
      me.fire('response', {
        request: request,
        response: request.response
      });
      return typeof successCallback === 'function' ? successCallback(request.response, request) : void 0;
    };
  },

  _handleError: function(request, errorCallback) {
    var me = this;
    return function() {
      me.fire('error', {
        request: request,
        response: request.response
      });
      return typeof errorCallback === 'function' ? errorCallback(request.response, request) : void 0;
    };
  },

  _createRequest: function() {
    var me = this, request = document.createElement('iron-request');
    me.fire('request', {
      request: request
    });
    return request;
  },

  /**
   * The callback function to be invoked for successful response.
   *
   * @callback successCallback
   * @param {Object}
   *          response
   * @param {Object}
   *          request
   */

  /**
   * The callback function to be invoked for failure response.
   *
   * @callback errorCallback
   * @param {Object}
   *          response
   * @param {Object}
   *          request
   */

  /**
   * Performs a HTTP GET on the index URL and returns the response data.
   *
   * @param {successCallback}
   *          successCallback - the callback function will be invoked with response data on successful response.
   * @param {errorCallback}
   *          errorCallback- the callback function will be invoked with response data on error response.
   */
  index: function(successCallback, errorCallback) {
    var me = this, request = me._createRequest();
    return request.send({
      url: me._prepareUrl(me.indexUrl || me.url, me.params),
      headers: me._prepareHeaders(),
      handleAs: 'json'
    }).then(me._handleSuccess(request, successCallback), me._handleError(request, errorCallback));
  },

  /**
   * Performs a HTTP GET on the show URL with the specified resource id and returns the response data.
   *
   * @param {string}
   *          id - the id of the resource to be fetched.
   * @param {successCallback}
   *          successCallback - the callback function will be invoked with response data on successful response.
   * @param {errorCallback}
   *          errorCallback- the callback function will be invoked with response data on error response.
   */
  show: function(id, successCallback, errorCallback) {
    var me = this, request = me._createRequest();
    return request.send({
      url: me._prepareUrl(me.showUrl || me.url, me.params, id),
      headers: me._prepareHeaders(),
      handleAs: 'json'
    }).then(me._handleSuccess(request, successCallback), me._handleError(request, errorCallback));
  },

  /**
   * Performs a HTTP POST on the create URL with the specified resource data and returns the response data.
   *
   * @param {Object}
   *          data - data for new resource to be created.
   * @param {successCallback}
   *          successCallback - the callback function will be invoked with response data on successful response.
   * @param {errorCallback}
   *          errorCallback- the callback function will be invoked with response data on error response.
   */
  create: function(data, successCallback, errorCallback) {
    var me = this, request = me._createRequest();
    return request.send({
      method: 'POST',
      url: me._prepareUrl(me.createUrl || me.url, me.params),
      headers: me._prepareHeaders(),
      body: JSON.stringify(data),
      handleAs: 'json'
    }).then(me._handleSuccess(request, successCallback), me._handleError(request, errorCallback));
  },

  /**
   * Performs a HTTP PUT on the update URL with the specified resource id and data and returns the response data.
   *
   * @param {string}
   *          id - the id of the resource to be updated.
   * @param {Object}
   *          data - updated resource data.
   * @param {successCallback}
   *          successCallback - the callback function will be invoked with response data on successful response.
   * @param {errorCallback}
   *          errorCallback- the callback function will be invoked with response data on error response.
   */
  update: function(id, data, successCallback, errorCallback) {
    var me = this, request = me._createRequest();
    return request.send({
      method: 'PUT',
      url: me._prepareUrl(me.updateUrl || me.url, me.params, id),
      headers: me._prepareHeaders(),
      body: JSON.stringify(data),
      handleAs: 'json'
    }).then(me._handleSuccess(request, successCallback), me._handleError(request, errorCallback));
  },

  /**
   * Performs a HTTP DELETE on the destroy URL with the specified resource id and returns the response data.
   *
   * @param {string}
   *          id - the id of the resource to be destroyed.
   * @param {successCallback}
   *          successCallback - the callback function will be invoked with response data on successful response.
   * @param {errorCallback}
   *          errorCallback- the callback function will be invoked with response data on error response.
   */
  destroy: function(id, successCallback, errorCallback) {
    var me = this, request = me._createRequest();
    return request.send({
      method: 'DELETE',
      url: me._prepareUrl(me.destroyUrl || me.url, me.params, id),
      headers: me._prepareHeaders(),
      handleAs: 'json'
    }).then(me._handleSuccess(request, successCallback), me._handleError(request, errorCallback));
  },

  /**
   * Performs a HTTP PUT on the member URL with "/action" appended to it and the specified resource id and returns the response data.
   *
   * @param {string}
   *          id - the id of the resource on which a member action is to be performed.
   * @param {action}
   *          the url suffix for an action.
   * @param {successCallback}
   *          successCallback - the callback function will be invoked with response data on successful response.
   * @param {errorCallback}
   *          errorCallback- the callback function will be invoked with response data on error response.
   */
  memberAction: function(id, action, successCallback, errorCallback) {
    var me = this, request = me._createRequest();
    return request.send({
      method: 'PUT',
      url: me._prepareUrl(me.memberUrl || me.url, me.params, id, action),
      headers: me._prepareHeaders(),
      handleAs: 'json'
    }).then(me._handleSuccess(request, successCallback), me._handleError(request, errorCallback));
  },

  _prepareUrl: function(url, params, id, action) {
    var name, value;
    if (params === null) {
      params = {};
    }
    if (id === null) {
      id = null;
    }
    if (action === null) {
      action = null;
    }
    if (typeof params === 'string') {
      params = JSON.parse(params);
    }
    for (name in params) {
      value = params[name];
      if (typeof value === 'undefined' || value === null || '' === String(value).trim()) {
        continue;
      }
      if (-1 === url.indexOf('?')) {
        url = url + '?' + name + '=' + value;
      } else {
        url = url + '&' + name + '=' + value;
      }
    }
    url = url.replace(':id', id || '');
    url = url.replace(/\/\/+/g, '/');
    url = url.replace(/^(\w+):\//, '$1://');
    url = url.replace(/\/$/, '');
    if (action) {
      url += '/' + action;
    }
    return url;
  },

  _prepareHeaders: function() {
    var h, key, val, _ref;
    h = {
      'Accept': 'application/json'
    };
    _ref = this.headers;
    for (key in _ref) {
      val = _ref[key];
      h[key] = val;
    }
    if (this.token) {
      h.Authorization = this.token;
    }
    return h;
  }
});
<commit_msg>default content-type set<commit_after>Polymer({
  is: 'rest-resource',

  properties: {

    /**
     * A pattern for the REST URL. Can contain colon-parameters and data bindings, for example:
     *
     * `url="/users/:userId?q={{searchText}}"`
     *
     * Default URLS:
     *
     *

     *

     * Method
     * HTTP method
     * URL
     *

     *

     * index
     * GET
     * /users
     *

     *

     * show
     * GET
     * /users/1
     *

     *

     * create
     * POST
     * /users
     *

     *

     * update
     * PUT
     * /users
     *

     *

     * destroy
     * DELETE
     * /users/1
     *

     *

     * member foo
     * PUT
     * /users/1/foo
     *

     *

     *
     */
    url: String,

    /**
     * A hash that binds URL parameters to actual values, for example:
     *
     * `params='{{ {"userId":user.id} }}'`
     */
    params: Object,

    /**
     * Use this URL instead of the default one for "GET /resources" requests.
     */
    indexUrl: String,

    /**
     * Use this URL instead of the default one for "GET /resources/:id" requests.
     */
    showUrl: String,

    /**
     * Use this URL instead of the default one for "POST /resources" requests.
     */
    createUrl: String,

    /**
     * Use this URL instead of the default one for "PUT /resources/:id" requests.
     */
    updateUrl: String,

    /**
     * Use this URL instead of the default one for "DELETE /resources/:id" requests.
     */
    destroyUrl: String,

    /**
     * Use this URL instead of the default one for "PUT /resources/:id/action" requests.
     */
    memberUrl: String,

    /**
     * Set additional headers on the request.
     */
    headers: Object,

    /**
     * Set an authorization header with the specified token text.
     */
    token: Object
  },

  // Element Behavior

  /**
   * Is fired when a REST call is initiated.
   *
   * @event request
   * @detail {{request: Object}}
   */

  /**
   * Is fired when a REST call returns successful response.
   *
   * @event response
   * @detail {{request: Object, response: Object}}
   */

  /**
   * Is fired when a REST call returns failure response.
   *
   * @event error
   * @detail {{request: Object, response: Object}}
   */

  _handleSuccess: function(request, successCallback) {
    var me = this;
    return function() {
      me.fire('response', {
        request: request,
        response: request.response
      });
      return typeof successCallback === 'function' ? successCallback(request.response, request) : void 0;
    };
  },

  _handleError: function(request, errorCallback) {
    var me = this;
    return function() {
      me.fire('error', {
        request: request,
        response: request.response
      });
      return typeof errorCallback === 'function' ? errorCallback(request.response, request) : void 0;
    };
  },

  _createRequest: function() {
    var me = this, request = document.createElement('iron-request');
    me.fire('request', {
      request: request
    });
    return request;
  },

  /**
   * The callback function to be invoked for successful response.
   *
   * @callback successCallback
   * @param {Object}
   *          response
   * @param {Object}
   *          request
   */

  /**
   * The callback function to be invoked for failure response.
   *
   * @callback errorCallback
   * @param {Object}
   *          response
   * @param {Object}
   *          request
   */

  /**
   * Performs a HTTP GET on the index URL and returns the response data.
   *
   * @param {successCallback}
   *          successCallback - the callback function will be invoked with response data on successful response.
   * @param {errorCallback}
   *          errorCallback- the callback function will be invoked with response data on error response.
   */
  index: function(successCallback, errorCallback) {
    var me = this, request = me._createRequest();
    return request.send({
      url: me._prepareUrl(me.indexUrl || me.url, me.params),
      headers: me._prepareHeaders(),
      handleAs: 'json'
    }).then(me._handleSuccess(request, successCallback), me._handleError(request, errorCallback));
  },

  /**
   * Performs a HTTP GET on the show URL with the specified resource id and returns the response data.
   *
   * @param {string}
   *          id - the id of the resource to be fetched.
   * @param {successCallback}
   *          successCallback - the callback function will be invoked with response data on successful response.
   * @param {errorCallback}
   *          errorCallback- the callback function will be invoked with response data on error response.
   */
  show: function(id, successCallback, errorCallback) {
    var me = this, request = me._createRequest();
    return request.send({
      url: me._prepareUrl(me.showUrl || me.url, me.params, id),
      headers: me._prepareHeaders(),
      handleAs: 'json'
    }).then(me._handleSuccess(request, successCallback), me._handleError(request, errorCallback));
  },

  /**
   * Performs a HTTP POST on the create URL with the specified resource data and returns the response data.
   *
   * @param {Object}
   *          data - data for new resource to be created.
   * @param {successCallback}
   *          successCallback - the callback function will be invoked with response data on successful response.
   * @param {errorCallback}
   *          errorCallback- the callback function will be invoked with response data on error response.
   */
  create: function(data, successCallback, errorCallback) {
    var me = this, request = me._createRequest();
    return request.send({
      method: 'POST',
      url: me._prepareUrl(me.createUrl || me.url, me.params),
      headers: me._prepareHeaders(),
      body: JSON.stringify(data),
      handleAs: 'json'
    }).then(me._handleSuccess(request, successCallback), me._handleError(request, errorCallback));
  },

  /**
   * Performs a HTTP PUT on the update URL with the specified resource id and data and returns the response data.
   *
   * @param {string}
   *          id - the id of the resource to be updated.
   * @param {Object}
   *          data - updated resource data.
   * @param {successCallback}
   *          successCallback - the callback function will be invoked with response data on successful response.
   * @param {errorCallback}
   *          errorCallback- the callback function will be invoked with response data on error response.
   */
  update: function(id, data, successCallback, errorCallback) {
    var me = this, request = me._createRequest();
    return request.send({
      method: 'PUT',
      url: me._prepareUrl(me.updateUrl || me.url, me.params, id),
      headers: me._prepareHeaders(),
      body: JSON.stringify(data),
      handleAs: 'json'
    }).then(me._handleSuccess(request, successCallback), me._handleError(request, errorCallback));
  },

  /**
   * Performs a HTTP DELETE on the destroy URL with the specified resource id and returns the response data.
   *
   * @param {string}
   *          id - the id of the resource to be destroyed.
   * @param {successCallback}
   *          successCallback - the callback function will be invoked with response data on successful response.
   * @param {errorCallback}
   *          errorCallback- the callback function will be invoked with response data on error response.
   */
  destroy: function(id, successCallback, errorCallback) {
    var me = this, request = me._createRequest();
    return request.send({
      method: 'DELETE',
      url: me._prepareUrl(me.destroyUrl || me.url, me.params, id),
      headers: me._prepareHeaders(),
      handleAs: 'json'
    }).then(me._handleSuccess(request, successCallback), me._handleError(request, errorCallback));
  },

  /**
   * Performs a HTTP PUT on the member URL with "/action" appended to it and the specified resource id and returns the response data.
   *
   * @param {string}
   *          id - the id of the resource on which a member action is to be performed.
   * @param {action}
   *          the url suffix for an action.
   * @param {successCallback}
   *          successCallback - the callback function will be invoked with response data on successful response.
   * @param {errorCallback}
   *          errorCallback- the callback function will be invoked with response data on error response.
   */
  memberAction: function(id, action, successCallback, errorCallback) {
    var me = this, request = me._createRequest();
    return request.send({
      method: 'PUT',
      url: me._prepareUrl(me.memberUrl || me.url, me.params, id, action),
      headers: me._prepareHeaders(),
      handleAs: 'json'
    }).then(me._handleSuccess(request, successCallback), me._handleError(request, errorCallback));
  },

  _prepareUrl: function(url, params, id, action) {
    var name, value;
    if (params === null) {
      params = {};
    }
    if (id === null) {
      id = null;
    }
    if (action === null) {
      action = null;
    }
    if (typeof params === 'string') {
      params = JSON.parse(params);
    }
    for (name in params) {
      value = params[name];
      if (typeof value === 'undefined' || value === null || '' === String(value).trim()) {
        continue;
      }
      if (-1 === url.indexOf('?')) {
        url = url + '?' + name + '=' + value;
      } else {
        url = url + '&' + name + '=' + value;
      }
    }
    url = url.replace(':id', id || '');
    url = url.replace(/\/\/+/g, '/');
    url = url.replace(/^(\w+):\//, '$1://');
    url = url.replace(/\/$/, '');
    if (action) {
      url += '/' + action;
    }
    return url;
  },

  _prepareHeaders: function() {
    var h, key, val, _ref;
    h = {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    };
    _ref = this.headers;
    for (key in _ref) {
      val = _ref[key];
      h[key] = val;
    }
    if (this.token) {
      h.Authorization = this.token;
    }
    return h;
  }
});
<|endoftext|>


<commit_before>module.exports = function (dir, filter, callback) {
  var fs = require('fs')
  var regex = new RegExp('\\.' + filter + '$')

  fs.readdir(dir, function (err, list) {
    if (err)
      return callback(err)

    list = list.filter(function (file) {
      return regex.test(file)
    })

    callback(null, list)
  })
}
<commit_msg>rename `filter` to `filterStr`<commit_after>module.exports = function (dir, filterStr, callback) {
  var fs = require('fs')
  var regex = new RegExp('\\.' + filterStr + '$')

  fs.readdir(dir, function (err, list) {
    if (err)
      return callback(err)

    list = list.filter(function (file) {
      return regex.test(file)
    })

    callback(null, list)
  })
}
<|endoftext|>


<commit_before>import test from 'ava';
import 'babel-core/register';

import { isFunction, getReturnObject, getNestedValue, getDefaultOptions } from '../util';

test('isFunction', t => {
  t.truthy(isFunction, 'isFunction is truthy.');
  t.true(typeof isFunction === 'function', 'isFunction itself is a function.');

  t.false(isFunction(undefined), 'undefined is not function.');
  t.false(isFunction(null), 'null is not function.');
  t.false(isFunction(1), 'number is not function.');
  t.false(isFunction({}), 'object is not function.');
  t.false(isFunction([]), 'array is not function.');

  t.true(isFunction(() => 1), '() => is function.');
  function func() {}
  t.true(isFunction(func), 'function () {} is function.');
});

test('getReturnObject', t => {
  t.true(isFunction(getReturnObject), 'getReturnObject is a function.');

  const obj = getReturnObject();

  t.truthy(obj, 'getReturnObject return valid value.');
  t.truthy(obj, 'getReturnObject return valid value.');

  t.false(obj.success, '.success is false.');
  t.is(obj.statusCode, null, '.success is false.');
  t.is(obj.body, null, '.success is false.');

  t.is(Object.keys(obj).length, 3, 'obj only contains 3 keys.');
});

test('getNestedValue', t => {
  t.true(isFunction(getNestedValue), 'getNestedValue is a function.');

  t.is(getNestedValue(undefined, []), undefined, 'get undefined if obj is undefined.');

  t.is(getNestedValue(null, []), null, 'get undefined if obj is null.');

  let obj = {};
  t.is(getNestedValue(obj, []), obj, 'get origin if keys is [].');

  t.is(getNestedValue(obj, ['key']), undefined, 'get undefined if key not exist.');

  obj = { key: 1 };
  t.is(getNestedValue(obj, ['key']), 1, 'get correct value.');

  t.is(getNestedValue(obj, ['key', 'inside']), undefined, 'get undefined if no nested key.');

  obj = { key0: { key1: { key2: { key3: 1 } } } };

  t.is(getNestedValue(obj, ['key0', 'key1', 'key2', 'key3']), 1, 'get correct value.');

  t.is(getNestedValue(obj, ['key0', 'invalidKey', 'key2', 'key3']), undefined, 'get undefined.');
});

test('getDefaultOptions', t => {
  t.true(isFunction(getDefaultOptions), 'getDefaultOptions is a function.');

  const defaultOptions = getDefaultOptions();
  t.true(typeof defaultOptions === 'object', 'defaultOptions is an object.');

  const {
    apiPath,
    standAlone,
    allowCORS,
    sslEnabled,
    listenPort,
    listenHost,
    authToken,
    privateKeyFile,
    certificateFile,
    timeOut,
  } = defaultOptions;

  t.is(apiPath, 'collectionapi', 'default apiPath is /collectionapi .');
  t.is(standAlone, false, 'default standAlone is false.');

  t.is(allowCORS, false, 'default allowCORS is false.');
  t.is(sslEnabled, false, 'default sslEnabled is false.');

  t.is(listenHost, null, 'default listenHost is null.');
  t.is(listenPort, 3005, 'default listenPort is 3005.');

  t.is(authToken, null, 'default authToken is null.');

  t.is(privateKeyFile, 'privatekey.pem', 'default privateKeyFile is privatekey.pem');
  t.is(certificateFile, 'certificate.pem', 'default certificateFile is certificate.pem.');
  t.is(timeOut, 120000, 'default timeOut is 2 minutes.');
});
<commit_msg>test coverage report<commit_after>import test from 'ava';
import 'babel-core/register';

import { isFunction, getReturnObject, getNestedValue, getDefaultOptions } from '../util';

test('isFunction', t => {
  t.truthy(isFunction, 'isFunction is truthy.');
  t.true(typeof isFunction === 'function', 'isFunction itself is a function.');

  t.false(isFunction(undefined), 'undefined is not function.');
  t.false(isFunction(null), 'null is not function.');
  t.false(isFunction(1), 'number is not function.');
  t.false(isFunction({}), 'object is not function.');
  t.false(isFunction([]), 'array is not function.');

  t.true(isFunction(() => 1), '() => is function.');
  function func() {}
  t.true(isFunction(func), 'function () {} is function.');
});

test('getReturnObject', t => {
  t.true(isFunction(getReturnObject), 'getReturnObject is a function.');

  const obj = getReturnObject();

  t.truthy(obj, 'getReturnObject return valid value.');
  t.truthy(obj, 'getReturnObject return valid value.');

  t.false(obj.success, '.success is false.');
  t.is(obj.statusCode, null, '.success is false.');
  t.is(obj.body, null, '.success is false.');

  t.is(Object.keys(obj).length, 3, 'obj only contains 3 keys.');
});

test('getNestedValue', t => {
  t.true(isFunction(getNestedValue), 'getNestedValue is a function.');

  t.is(getNestedValue(undefined, []), undefined, 'get undefined if obj is undefined.');

  t.is(getNestedValue(null, []), null, 'get undefined if obj is null.');

  // let obj = {};
  // t.is(getNestedValue(obj, []), obj, 'get origin if keys is [].');
  //
  // t.is(getNestedValue(obj, ['key']), undefined, 'get undefined if key not exist.');
  //
  // obj = { key: 1 };
  // t.is(getNestedValue(obj, ['key']), 1, 'get correct value.');
  //
  // t.is(getNestedValue(obj, ['key', 'inside']), undefined, 'get undefined if no nested key.');
  //
  // obj = { key0: { key1: { key2: { key3: 1 } } } };
  //
  // t.is(getNestedValue(obj, ['key0', 'key1', 'key2', 'key3']), 1, 'get correct value.');
  //
  // t.is(getNestedValue(obj, ['key0', 'invalidKey', 'key2', 'key3']), undefined, 'get undefined.');
});

test('getDefaultOptions', t => {
  t.true(isFunction(getDefaultOptions), 'getDefaultOptions is a function.');

  const defaultOptions = getDefaultOptions();
  t.true(typeof defaultOptions === 'object', 'defaultOptions is an object.');

  const {
    apiPath,
    standAlone,
    allowCORS,
    sslEnabled,
    listenPort,
    listenHost,
    authToken,
    privateKeyFile,
    certificateFile,
    timeOut,
  } = defaultOptions;

  t.is(apiPath, 'collectionapi', 'default apiPath is /collectionapi .');
  t.is(standAlone, false, 'default standAlone is false.');

  t.is(allowCORS, false, 'default allowCORS is false.');
  t.is(sslEnabled, false, 'default sslEnabled is false.');

  t.is(listenHost, null, 'default listenHost is null.');
  t.is(listenPort, 3005, 'default listenPort is 3005.');

  t.is(authToken, null, 'default authToken is null.');

  t.is(privateKeyFile, 'privatekey.pem', 'default privateKeyFile is privatekey.pem');
  t.is(certificateFile, 'certificate.pem', 'default certificateFile is certificate.pem.');
  t.is(timeOut, 120000, 'default timeOut is 2 minutes.');
});
<|endoftext|>


<commit_before>'use strict';

var $ = require('jquery'),
    Marionette = require('../shim/backbone.marionette'),
    Backbone = require('../shim/backbone'),
    views = require('./core/views'),
    models = require('./core/models'),
    router = require('./router').router;

var App = Marionette.Application.extend({
    initialize: function() {
        //this.setupMap();
        this.setupNavigation();
    },

    setupMap: function() {
        this.map = new models.MapModel();

        // This view is intentionally not attached to any region.
        this._mapView = new views.MapView({
            model: this.map,
            el: '#map'
        });
    },

    setupNavigation: function() {
        $('#container').on('click', '[data-url]', function(e) {
            e.preventDefault();
            router.navigate($(this).data('url'), { trigger: true });
        });
        Backbone.history.start({ pushState: true });
    }
});

module.exports = App;
<commit_msg>Remove map from Application<commit_after>'use strict';

var $ = require('jquery'),
    Marionette = require('../shim/backbone.marionette'),
    Backbone = require('../shim/backbone'),
    models = require('./core/models'),
    router = require('./router').router;

var App = Marionette.Application.extend({
    initialize: function() {
        this.setupNavigation();
    },

    setupNavigation: function() {
        $('#container').on('click', '[data-url]', function(e) {
            e.preventDefault();
            router.navigate($(this).data('url'), { trigger: true });
        });
        Backbone.history.start({ pushState: true });
    }
});

module.exports = App;
<|endoftext|>