<commit_before>/* global girder girderTest describe it expect beforeEach afterEach runs waitsFor _ */

girderTest.addCoveredScripts([
    '/clients/web/static/built/plugins/treeview/plugin.min.js'
]);

girderTest.importStylesheet('/static/built/plugins/treeview/plugin.min.css');

var treeview;
beforeEach(function () {
    treeview = girder.plugins.treeview;
});

describe('treeview type registry', function () {
    it('register a new type', function () {
        var lastCall;

        function assertArguments(method, resolve) {
            return function (doc, options) {
                lastCall = method;
                expect(doc).toBe(doc);
                expect(options).toBe(options);
                return $.when(resolve);
            };
        }

        var doc = {
            type: 'testtype',
            id: 'testtypeid',
            children: false
        };
        var load = assertArguments('load', doc);
        var parent = assertArguments('parent', {id: '#', type: '#'});
        var children = assertArguments('children', []);
        var options = {};

        treeview.types.register('testtype', {
            load: load,
            parent: parent,
            children: children,
            options: options,
            icon: 'icon-test'
        });
        var def = treeview.types.getDefinition('testtype');

        expect(def.load).toBe(load);
        expect(def.parent).toBe(parent);
        expect(def.children).toBe(children);
        expect(def.options).toBe(options);
        expect(treeview.types.icons.testtype).toEqual({icons: 'icon-test'});

        expect(function () {
            treeview.types.callMethod({type: 'testtype', id: 'notanid'}, 'notamethod');
        }).toThrow();

        treeview.types.load(doc);
        expect(lastCall).toBe('load');
        expect(function () {
            treeview.types.load({type: 'notatype', id: 'notanid'});
        }).toThrow();

        treeview.types.parent(doc);
        expect(lastCall).toBe('parent');
        expect(function () {
            treeview.types.parent({type: 'notatype', id: 'notanid'});
        }).toThrow();

        treeview.types.children(doc);
        expect(lastCall).toBe('children');
        expect(function () {
            treeview.types.children({type: 'notatype', id: 'notanid'});
        }).toThrow();

        expect(treeview.types.unregister('notatype')).toBe(undefined);
        expect(treeview.types.unregister('testtype')).toBe(def);
    });
});

describe('builtin types', function () {
    var lastRequest;
    var response;
    var onrequest;

    function asyncCall(func) {
        var called = false;
        var failed = false;
        runs(function () {
            func().done(function () {
                called = true;
            }).fail(function () {
                console.log('failed');
                failed = true;
            });
        });
        waitsFor(function () {
            if (failed) {
                throw new Error('Promise was rejected');
            }
            return called;
        });
    }

    beforeEach(function () {
        window.girderTreeViewRest = function (opts) {
            lastRequest = opts;
            if (onrequest) {
                onrequest(opts);
            }
            return $.when(response);
        };
    });

    afterEach(function () {
        delete window.girderTreeViewRest;
        lastRequest = undefined;
        response = undefined;
        onrequest = undefined;
    });

    it('collections', function () {
        var doc = {
            id: '#collections',
            type: 'collections'
        };

        asyncCall(function () {
            return treeview.types.load(doc)
                .done(function (node) {
                    expect(node.parent).toBe('#');
                    expect(node.children).toBe(true);
                    expect(node.text).toBe('Collections');
                });
        });

        asyncCall(function () {
            return treeview.types.parent(doc)
                .done(function (parent) {
                    expect(parent).toBe(null);
                });
        });

        asyncCall(function () {
            response = [];
            return treeview.types.children(doc)
                .done(function (children) {
                    expect(children).toEqual([]);
                    expect(lastRequest.path).toBe('collection');
                });
        });
    });

    it('users', function () {
        var doc = {
            id: '#users',
            type: 'users'
        };

        asyncCall(function () {
            return treeview.types.load(doc)
                .done(function (node) {
                    expect(node.parent).toBe('#');
                    expect(node.children).toBe(true);
                    expect(node.text).toBe('Users');
                });
        });

        asyncCall(function () {
            return treeview.types.parent(doc)
                .done(function (parent) {
                    expect(parent).toBe(null);
                });
        });

        asyncCall(function () {
            response = [];
            return treeview.types.children(doc)
                .done(function (children) {
                    expect(children).toEqual([]);
                    expect(lastRequest.path).toBe('user');
                });
        });
    });

    it('home', function () {
        var doc = {
            id: 'userid',
            type: 'home',
            model: {
                _id: 'userid',
                _modelType: 'user',
                login: 'login'
            }
        };

        asyncCall(function () {
            response = doc.model;
            return treeview.types.load(doc)
                .done(function (node) {
                    expect(node.parent).toBe('#');
                    expect(node.children).toBe(true);
                    expect(node.text).toBe('Home');
                });
        });

        asyncCall(function () {
            return treeview.types.parent(doc)
                .done(function (parent) {
                    expect(parent).toBe(null);
                });
        });

        asyncCall(function () {
            response = [];
            return treeview.types.children(doc)
                .done(function (children) {
                    expect(children).toEqual([]);
                    expect(lastRequest.path).toBe('folder');
                    expect(lastRequest.data.parentType).toBe('user');
                    expect(lastRequest.data.parentId).toBe(doc.id);
                });
        });
    });

    it('user', function () {
        var doc = {
            id: 'userid',
            type: 'user',
            model: {
                _id: 'userid',
                _modelType: 'user',
                login: 'login'
            }
        };

        asyncCall(function () {
            response = doc.model;
            return treeview.types.load(doc)
                .done(function (node) {
                    expect(node.parent).toBe('#users');
                    expect(node.children).toBe(true);
                    expect(node.text).toBe('login');
                });
        });

        asyncCall(function () {
            return treeview.types.parent(doc)
                .done(function (parent) {
                    expect(parent.type).toBe('users');
                });
        });

        asyncCall(function () {
            response = [];
            return treeview.types.children(doc)
                .done(function (children) {
                    expect(children).toEqual([]);
                    expect(lastRequest.path).toBe('folder');
                    expect(lastRequest.data.parentType).toBe('user');
                    expect(lastRequest.data.parentId).toBe(doc.id);
                });
        });
    });

    it('collection', function () {
        var doc = {
            id: 'collection',
            type: 'collection'
        };

        asyncCall(function () {
            response = _.extend(doc, {
                name: 'a'
            });

            return treeview.types.load(doc)
                .done(function (node) {
                    expect(lastRequest.path).toBe('collection/' + doc.id);
                    expect(node.parent).toBe('#collections');
                    expect(node.children).toBe(true);
                    expect(node.text).toBe('a');
                });
        });

        asyncCall(function () {
            return treeview.types.parent(doc)
                .done(function (parent) {
                    expect(parent.type).toBe('collections');
                });
        });

        asyncCall(function () {
            response = [];
            return treeview.types.children(doc)
                .done(function (children) {
                    expect(children).toEqual([]);
                    expect(lastRequest.path).toBe('folder');
                    expect(lastRequest.data.parentType).toBe('collection');
                    expect(lastRequest.data.parentId).toBe(doc.id);
                });
        });
    });

    it('folder', function () {
        var doc = {
            id: 'folder',
            type: 'folder',
            model: {
                _id: 'folder',
                _modelType: 'folder',
                name: 'a',
                parentCollection: 'collection',
                parentId: 'parent'
            }
        };

        asyncCall(function () {
            response = _.extend(doc, {
                name: 'a',
                parentCollection: 'collection',
                parentId: 'ca'
            });

            return treeview.types.load(doc)
                .done(function (node) {
                    expect(lastRequest.path).toBe('folder/' + doc.id);
                    expect(node.parent).toBe('ca');
                    expect(node.children).toBe(true);
                    expect(node.text).toBe('a');
                });
        });

        asyncCall(function () {
            response = {
                _id: 'parent',
                _modelType: 'collection',
                name: 'parent'
            };
            return treeview.types.parent(doc)
                .done(function (parent) {
                    expect(lastRequest.path).toBe('collection/' + doc.model.parentId);
                    expect(parent.type).toBe('collection');
                });
        });

        asyncCall(function () {
            response = {
                _id: 'parent',
                _modelType: 'user',
                name: 'parent'
            };
            doc.model.parentCollection = 'user';

            return treeview.types.parent(doc)
                .done(function (parent) {
                    expect(lastRequest.path).toBe('user/' + doc.model.parentId);
                    expect(parent.type).toBe('user');
                });
        });

        asyncCall(function () {
            response = {
                _id: 'parent',
                _modelType: 'folder',
                name: 'parent'
            };
            doc.model.parentCollection = 'folder';

            return treeview.types.parent(doc)
                .done(function (parent) {
                    expect(lastRequest.path).toBe('folder/' + doc.model.parentId);
                    expect(parent.type).toBe('folder');
                });
        });

        asyncCall(function () {
            onrequest = function (opts) {
                if (opts.path.match(/^folder/)) {
                    response = [[{
                        _id: 'childfolder',
                        _modelType: 'folder',
                        name: 'child folder',
                        parentCollection: 'folder',
                        parentId: doc.id
                    }]];
                } else {
                    response = [[{
                        _id: 'childitem',
                        _modelType: 'item',
                        name: 'child item',
                        parentCollection: 'folder',
                        parentId: doc.id
                    }]];
                }
            };
            response = [];
            return treeview.types.children(doc)
                .done(function (children) {
                    var child;
                    expect(children.length).toBe(2);

                    child = children[0];
                    expect(child.type).toBe('folder');
                    expect(child.id).toBe('childfolder');

                    child = children[1];
                    expect(child.type).toBe('item');
                    expect(child.id).toBe('childitem');
                });
        });
    });

    it('item', function () {
        var doc = {
            id: 'item',
            type: 'item',
            model: {
                _id: 'item',
                _modelType: 'item',
                name: 'a',
                folderId: 'folder'
            }
        };

        asyncCall(function () {
            response = _.extend({}, doc.model);

            return treeview.types.load(doc)
                .done(function (node) {
                    expect(lastRequest.path).toBe('item/' + doc.id);
                    expect(node.parent).toBe('folder');
                    expect(node.children).toBe(true);
                    expect(node.text).toBe('a');
                });
        });

        asyncCall(function () {
            response = {
                _id: 'folder',
                _modelType: 'folder',
                name: 'parent'
            };
            return treeview.types.parent(doc)
                .done(function (parent) {
                    expect(lastRequest.path).toBe('folder/' + doc.model.folderId);
                    expect(parent.type).toBe('folder');
                    expect(parent.id).toBe(doc.model.folderId);
                });
        });

        asyncCall(function () {
            response = [];
            return treeview.types.children(doc)
                .done(function (children) {
                    expect(children).toEqual([]);
                    expect(lastRequest.path).toBe('item/' + doc.id + '/files');
                });
        });
    });

    it('file', function () {
        var doc = {
            id: 'file',
            type: 'file',
            model: {
                _id: 'file',
                _modelType: 'file',
                name: 'a.csv',
                exts: ['csv'],
                mimeType: 'text/csv',
                itemId: 'item',
                size: 10000
            }
        };

        asyncCall(function () {
            response = _.extend({}, doc.model);

            return treeview.types.load(doc)
                .done(function (node) {
                    expect(lastRequest.path).toBe('file/' + doc.id);
                    expect(node.parent).toBe('item');
                    expect(!node.children).toBe(true);
                    expect(node.text).toBe('a.csv');
                });
        });

        asyncCall(function () {
            response = {
                _id: 'item',
                _modelType: 'item',
                name: 'parent'
            };
            return treeview.types.parent(doc)
                .done(function (parent) {
                    expect(lastRequest.path).toBe('item/' + doc.model.itemId);
                    expect(parent.type).toBe('item');
                    expect(parent.id).toBe(doc.model.itemId);
                });
        });

        asyncCall(function () {
            return treeview.types.children(doc)
                .done(function (children) {
                    expect(children).toEqual([]);
                });
        });
    });
});
<commit_msg>Add full unit testing to the type registry<commit_after>/* global girder girderTest describe it expect beforeEach afterEach runs waitsFor _ */

girderTest.addCoveredScripts([
    '/clients/web/static/built/plugins/treeview/plugin.min.js'
]);

girderTest.importStylesheet('/static/built/plugins/treeview/plugin.min.css');

function asyncCall(func) {
    var called = false;
    var failed = false;
    runs(function () {
        func().done(function () {
            called = true;
        }).fail(function () {
            console.log('failed');
            failed = true;
        });
    });
    waitsFor(function () {
        if (failed) {
            throw new Error('Promise was rejected');
        }
        return called;
    });
}

var treeview;
beforeEach(function () {
    treeview = girder.plugins.treeview;
});

describe('treeview type registry', function () {
    it('register a new type', function () {
        var lastCall;

        function assertArguments(method, resolve) {
            return function (doc, options) {
                lastCall = method;
                expect(doc).toBe(doc);
                expect(options).toBe(options);
                return $.when(resolve);
            };
        }

        var doc = {
            type: 'testtype',
            id: 'testtypeid',
            children: false
        };
        var load = assertArguments('load', doc);
        var parent = assertArguments('parent', {id: '#', type: '#'});
        var children = assertArguments('children', []);
        var options = {};

        treeview.types.register('testtype', {
            load: load,
            parent: parent,
            children: children,
            options: options,
            icon: 'icon-test'
        });
        var def = treeview.types.getDefinition('testtype');

        expect(def.load).toBe(load);
        expect(def.parent).toBe(parent);
        expect(def.children).toBe(children);
        expect(def.options).toBe(options);
        expect(treeview.types.icons.testtype).toEqual({icons: 'icon-test'});

        expect(function () {
            treeview.types.callMethod({type: 'testtype', id: 'notanid'}, 'notamethod');
        }).toThrow();

        treeview.types.load(doc);
        expect(lastCall).toBe('load');
        expect(function () {
            treeview.types.load({type: 'notatype', id: 'notanid'});
        }).toThrow();

        treeview.types.parent(doc);
        expect(lastCall).toBe('parent');
        expect(function () {
            treeview.types.parent({type: 'notatype', id: 'notanid'});
        }).toThrow();

        treeview.types.children(doc);
        expect(lastCall).toBe('children');
        expect(function () {
            treeview.types.children({type: 'notatype', id: 'notanid'});
        }).toThrow();

        expect(treeview.types.unregister('notatype')).toBe(undefined);
        expect(treeview.types.unregister('testtype')).toBe(def);
    });

    it('register requires a load method', function () {
        expect(function () {
            treeview.types.register('invalid');
        }).toThrow();
    });

    it('node aliases', function () {
        expect(treeview.types.unalias('aliased'))
            .toBe(undefined);

        treeview.types.alias('aliased', 'home');
        expect(treeview.types.isAliased({'id': 'aliased'}))
            .toBe(true);
        expect(treeview.types.unalias('aliased'))
            .toBe('home');

        treeview.types.alias('#collections', 'home');
        asyncCall(function () {
            return treeview.types.load({id: '#collections', type: 'collections'})
                .done(function (node) {
                    expect(node.type).toBe('home');
                });
        });

        asyncCall(function () {
            var doc = {
                type: 'collection',
                id: 'collection',
                node: {
                    id: 'collection',
                    name: 'collection'
                }
            };
            return treeview.types.parent(doc)
                .done(function (parent) {
                    expect(parent.type).toBe('home');
                });
        });

        runs(function () {
            treeview.types.unalias('#collections');
        });
    });
});

describe('builtin types', function () {
    var lastRequest;
    var response;
    var onrequest;

    beforeEach(function () {
        window.girderTreeViewRest = function (opts) {
            lastRequest = opts;
            if (onrequest) {
                onrequest(opts);
            }
            return $.when(response);
        };
    });

    afterEach(function () {
        delete window.girderTreeViewRest;
        lastRequest = undefined;
        response = undefined;
        onrequest = undefined;
    });

    it('collections', function () {
        var doc = {
            id: '#collections',
            type: 'collections'
        };

        expect(treeview.builtin.collections.mutate(doc))
            .toBe(doc);

        asyncCall(function () {
            return treeview.types.load(doc)
                .done(function (node) {
                    expect(node.parent).toBe('#');
                    expect(node.children).toBe(true);
                    expect(node.text).toBe('Collections');
                });
        });

        asyncCall(function () {
            return treeview.types.parent(doc)
                .done(function (parent) {
                    expect(parent).toBe(null);
                });
        });

        asyncCall(function () {
            response = [];
            return treeview.types.children(doc)
                .done(function (children) {
                    expect(children).toEqual([]);
                    expect(lastRequest.path).toBe('collection');
                });
        });
    });

    it('users', function () {
        var doc = {
            id: '#users',
            type: 'users'
        };

        expect(treeview.builtin.users.mutate(doc))
            .toBe(doc);

        asyncCall(function () {
            return treeview.types.load(doc)
                .done(function (node) {
                    expect(node.parent).toBe('#');
                    expect(node.children).toBe(true);
                    expect(node.text).toBe('Users');
                });
        });

        asyncCall(function () {
            return treeview.types.parent(doc)
                .done(function (parent) {
                    expect(parent).toBe(null);
                });
        });

        asyncCall(function () {
            response = [];
            return treeview.types.children(doc)
                .done(function (children) {
                    expect(children).toEqual([]);
                    expect(lastRequest.path).toBe('user');
                });
        });
    });

    it('home', function () {
        var doc = {
            id: 'userid',
            type: 'home',
            model: {
                _id: 'userid',
                _modelType: 'user',
                login: 'login'
            }
        };

        asyncCall(function () {
            response = doc.model;
            return treeview.types.load(doc)
                .done(function (node) {
                    expect(node.parent).toBe('#');
                    expect(node.children).toBe(true);
                    expect(node.text).toBe('Home');
                });
        });

        asyncCall(function () {
            return treeview.types.parent(doc)
                .done(function (parent) {
                    expect(parent).toBe(null);
                });
        });

        asyncCall(function () {
            response = [];
            return treeview.types.children(doc)
                .done(function (children) {
                    expect(children).toEqual([]);
                    expect(lastRequest.path).toBe('folder');
                    expect(lastRequest.data.parentType).toBe('user');
                    expect(lastRequest.data.parentId).toBe(doc.id);
                });
        });
    });

    it('user', function () {
        var doc = {
            id: 'userid',
            type: 'user',
            model: {
                _id: 'userid',
                _modelType: 'user',
                login: 'login'
            }
        };

        asyncCall(function () {
            response = doc.model;
            return treeview.types.load(doc)
                .done(function (node) {
                    expect(node.parent).toBe('#users');
                    expect(node.children).toBe(true);
                    expect(node.text).toBe('login');
                });
        });

        asyncCall(function () {
            return treeview.types.parent(doc)
                .done(function (parent) {
                    expect(parent.type).toBe('users');
                });
        });

        asyncCall(function () {
            response = [];
            return treeview.types.children(doc)
                .done(function (children) {
                    expect(children).toEqual([]);
                    expect(lastRequest.path).toBe('folder');
                    expect(lastRequest.data.parentType).toBe('user');
                    expect(lastRequest.data.parentId).toBe(doc.id);
                });
        });
    });

    it('collection', function () {
        var doc = {
            id: 'collection',
            type: 'collection'
        };

        asyncCall(function () {
            response = _.extend(doc, {
                name: 'a'
            });

            return treeview.types.load(doc)
                .done(function (node) {
                    expect(lastRequest.path).toBe('collection/' + doc.id);
                    expect(node.parent).toBe('#collections');
                    expect(node.children).toBe(true);
                    expect(node.text).toBe('a');
                });
        });

        asyncCall(function () {
            return treeview.types.parent(doc)
                .done(function (parent) {
                    expect(parent.type).toBe('collections');
                });
        });

        asyncCall(function () {
            response = [];
            return treeview.types.children(doc)
                .done(function (children) {
                    expect(children).toEqual([]);
                    expect(lastRequest.path).toBe('folder');
                    expect(lastRequest.data.parentType).toBe('collection');
                    expect(lastRequest.data.parentId).toBe(doc.id);
                });
        });
    });

    it('folder', function () {
        var doc = {
            id: 'folder',
            type: 'folder',
            model: {
                _id: 'folder',
                _modelType: 'folder',
                name: 'a',
                parentCollection: 'collection',
                parentId: 'parent'
            }
        };

        expect(function () {
            treeview.types.parent({
                id: 'folder',
                type: 'folder',
                model: {
                    _id: 'folder',
                    _modelType: 'folder',
                    name: 'a',
                    parentCollection: 'invalid',
                    parentId: 'parent'
                }
            });
        }).toThrow();

        asyncCall(function () {
            response = _.extend(doc, {
                name: 'a',
                parentCollection: 'collection',
                parentId: 'ca'
            });

            return treeview.types.load(doc)
                .done(function (node) {
                    expect(lastRequest.path).toBe('folder/' + doc.id);
                    expect(node.parent).toBe('ca');
                    expect(node.children).toBe(true);
                    expect(node.text).toBe('a');
                });
        });

        asyncCall(function () {
            response = {
                _id: 'parent',
                _modelType: 'collection',
                name: 'parent'
            };
            return treeview.types.parent(doc)
                .done(function (parent) {
                    expect(lastRequest.path).toBe('collection/' + doc.model.parentId);
                    expect(parent.type).toBe('collection');
                });
        });

        asyncCall(function () {
            response = {
                _id: 'parent',
                _modelType: 'user',
                name: 'parent'
            };
            doc.model.parentCollection = 'user';

            return treeview.types.parent(doc)
                .done(function (parent) {
                    expect(lastRequest.path).toBe('user/' + doc.model.parentId);
                    expect(parent.type).toBe('user');
                });
        });

        asyncCall(function () {
            response = {
                _id: 'parent',
                _modelType: 'folder',
                name: 'parent'
            };
            doc.model.parentCollection = 'folder';

            return treeview.types.parent(doc)
                .done(function (parent) {
                    expect(lastRequest.path).toBe('folder/' + doc.model.parentId);
                    expect(parent.type).toBe('folder');
                });
        });

        asyncCall(function () {
            onrequest = function (opts) {
                if (opts.path.match(/^folder/)) {
                    response = [[{
                        _id: 'childfolder',
                        _modelType: 'folder',
                        name: 'child folder',
                        parentCollection: 'folder',
                        parentId: doc.id
                    }]];
                } else {
                    response = [[{
                        _id: 'childitem',
                        _modelType: 'item',
                        name: 'child item',
                        parentCollection: 'folder',
                        parentId: doc.id
                    }]];
                }
            };
            response = [];
            return treeview.types.children(doc)
                .done(function (children) {
                    var child;
                    expect(children.length).toBe(2);

                    child = children[0];
                    expect(child.type).toBe('folder');
                    expect(child.id).toBe('childfolder');

                    child = children[1];
                    expect(child.type).toBe('item');
                    expect(child.id).toBe('childitem');
                });
        });
    });

    it('item', function () {
        var doc = {
            id: 'item',
            type: 'item',
            model: {
                _id: 'item',
                _modelType: 'item',
                name: 'a',
                folderId: 'folder'
            }
        };

        asyncCall(function () {
            response = _.extend({}, doc.model);

            return treeview.types.load(doc)
                .done(function (node) {
                    expect(lastRequest.path).toBe('item/' + doc.id);
                    expect(node.parent).toBe('folder');
                    expect(node.children).toBe(true);
                    expect(node.text).toBe('a');
                });
        });

        asyncCall(function () {
            response = {
                _id: 'folder',
                _modelType: 'folder',
                name: 'parent'
            };
            return treeview.types.parent(doc)
                .done(function (parent) {
                    expect(lastRequest.path).toBe('folder/' + doc.model.folderId);
                    expect(parent.type).toBe('folder');
                    expect(parent.id).toBe(doc.model.folderId);
                });
        });

        asyncCall(function () {
            response = [];
            return treeview.types.children(doc)
                .done(function (children) {
                    expect(children).toEqual([]);
                    expect(lastRequest.path).toBe('item/' + doc.id + '/files');
                });
        });
    });

    it('file', function () {
        var doc = {
            id: 'file',
            type: 'file',
            model: {
                _id: 'file',
                _modelType: 'file',
                name: 'a.csv',
                exts: ['csv'],
                mimeType: 'text/csv',
                itemId: 'item',
                size: 10000
            }
        };

        asyncCall(function () {
            response = _.extend({}, doc.model);

            return treeview.types.load(doc)
                .done(function (node) {
                    expect(lastRequest.path).toBe('file/' + doc.id);
                    expect(node.parent).toBe('item');
                    expect(!node.children).toBe(true);
                    expect(node.text).toBe('a.csv');
                });
        });

        asyncCall(function () {
            response = {
                _id: 'item',
                _modelType: 'item',
                name: 'parent'
            };
            return treeview.types.parent(doc)
                .done(function (parent) {
                    expect(lastRequest.path).toBe('item/' + doc.model.itemId);
                    expect(parent.type).toBe('item');
                    expect(parent.id).toBe(doc.model.itemId);
                });
        });

        asyncCall(function () {
            return treeview.types.children(doc)
                .done(function (children) {
                    expect(children).toEqual([]);
                });
        });
    });
});
<|endoftext|>


<commit_before>'use strict';
angular.module('ngAudio', [])
.directive('ngAudio', ['$compile', '$q', 'ngAudio', function($compile, $q, ngAudio) {
    return {
        restrict: 'AEC',
        scope: {
            volume: '=',
            start: '=',
            currentTime: '=',
            loop: '=',
            clickPlay: '='
        },
        controller: function($scope, $attrs, $element, $timeout) {

            var audio = ngAudio.load($attrs.ngAudio);
            $scope.$audio = audio;
            // audio.unbind();

            $element.on('click', function() {
                if ($scope.clickPlay === false) {
                    return;
                }

                audio.audio.play();

                audio.volume = $scope.volume || audio.volume;
                audio.loop = $scope.loop;
                audio.currentTime = $scope.start || 0;

                $timeout(function() {
                    audio.play();
                }, 5);
            });
        }
    };
}])

.service('localAudioFindingService', ['$q', function($q) {

    this.find = function(id) {
        var deferred = $q.defer();
        var $sound = document.getElementById(id);
        if ($sound) {
            deferred.resolve($sound);
        } else {
            deferred.reject(id);
        }

        return deferred.promise;
    };
}])

.service('remoteAudioFindingService', ['$q', function($q) {

    this.find = function(url) {
        var deferred = $q.defer();
        var audio = new Audio();

        audio.addEventListener('error', function() {
            deferred.reject();
        });

        audio.addEventListener('loadstart', function() {
            deferred.resolve(audio);
        });

        // bugfix for chrome...
        setTimeout(function() {
            audio.src = url;
        }, 1);

        return deferred.promise;

    };
}])

.service('cleverAudioFindingService', ['$q', 'localAudioFindingService', 'remoteAudioFindingService', function($q, localAudioFindingService, remoteAudioFindingService) {
    this.find = function(id) {
        var deferred = $q.defer();

        id = id.replace('|', '/');

        localAudioFindingService.find(id)
            .then(deferred.resolve, function() {
                return remoteAudioFindingService.find(id);
            })
            .then(deferred.resolve, deferred.reject);

        return deferred.promise;
    };
}])

.value('ngAudioGlobals', {
    muting: false,
    songmuting: false
})

.factory('NgAudioObject', ['cleverAudioFindingService', '$rootScope', '$interval', '$timeout', 'ngAudioGlobals', function(cleverAudioFindingService, $rootScope, $interval, $timeout, ngAudioGlobals) {
    return function(id) {

        // window.onclick = function(){
        //     // alert("Clicked");

        //     audio.audio.play();
        //     audio.audio.pause();

        // }

        window.addEventListener("click",function twiddle(){
            // audio.currentTime = 1219043;
            audio.play();
            audio.pause();
        //     audio.currentTime = 0;

            window.removeEventListener("click",twiddle);
        });

        var $audioWatch,
            $willPlay = false,
            $willPause = false,
            $willRestart = false,
            $volumeToSet,
            $looping,
            $isMuting = false,
            $observeProperties = true,
            audio,
            audioObject = this;

        this.id = id;
        this.safeId = id.replace('/', '|');
        this.loop = 0;

        this.unbind = function() {
            $observeProperties = false;
        };

        this.play = function() {
            // alert("Play sound");
            $willPlay = true;
        };

        this.pause = function() {
            $willPause = true;
        };

        this.restart = function() {
            $willRestart = true;
        };

        this.stop = function() {
            this.restart();
        };

        this.setVolume = function(volume) {
            $volumeToSet = volume;
        };

        this.setMuting = function(muting) {
            $isMuting = muting;
        };

        this.setProgress = function(progress) {
            if (audio && audio.duration) {
                audio.currentTime = audio.duration * progress;
            }
        };

        this.setCurrentTime = function(currentTime) {
            if (audio && audio.duration) {
                audio.currentTime = currentTime;
            }
        };

        function $setWatch() {
            $audioWatch = $rootScope.$watch(function() {
                return {
                    volume: audioObject.volume,
                    currentTime: audioObject.currentTime,
                    progress: audioObject.progress,
                    muting: audioObject.muting,
                    loop: audioObject.loop,
                };
            }, function(newValue, oldValue) {
                if (newValue.currentTime !== oldValue.currentTime) {
                    audioObject.setCurrentTime(newValue.currentTime);
                }

                if (newValue.progress !== oldValue.progress) {
                    audioObject.setProgress(newValue.progress);
                }
                if (newValue.volume !== oldValue.volume) {
                    audioObject.setVolume(newValue.volume);
                }

                if (newValue.volume !== oldValue.volume) {
                    audioObject.setVolume(newValue.volume);
                }

                $looping = newValue.loop;

                if (newValue.muting !== oldValue.muting) {
                    audioObject.setMuting(newValue.muting);
                }
            }, true);
        }

        cleverAudioFindingService.find(id)
            .then(function(nativeAudio) {
                audio = nativeAudio;
                audio.addEventListener('canplay', function() {
                    audioObject.canPlay = true;
                });
            }, function(error) {
                audioObject.error = true;
                console.warn(error);
            });

        $interval(function() {
            if ($audioWatch) {
                $audioWatch();
            }
            if (audio) {

                if ($isMuting || ngAudioGlobals.isMuting) {
                    audio.volume = 0;
                } else {
                    audio.volume = audioObject.volume !== undefined ? audioObject.volume : 1;
                }

                if ($willPlay) {
                    audio.play();
                    $willPlay = false;
                }

                if ($willRestart) {
                    audio.pause();
                    audio.currentTime = 0;
                    $willRestart = false;
                }

                if ($willPause) {
                    audio.pause();
                    $willPause = false;
                }

                if ($volumeToSet) {
                    audio.volume = $volumeToSet;
                    $volumeToSet = undefined;
                }

                if ($observeProperties) {
                    audioObject.currentTime = audio.currentTime;
                    audioObject.duration = audio.duration;
                    audioObject.remaining = audio.duration - audio.currentTime;
                    audioObject.progress = audio.currentTime / audio.duration;
                    audioObject.paused = audio.paused;
                    audioObject.src = audio.src;

                    if ($looping && audioObject.currentTime === audioObject.duration) {
                        if ($looping !== true) {
                            $looping--;
                            audioObject.loop--;
                            // if (!$looping) return;
                        }
                        audioObject.setCurrentTime(0);
                        audioObject.play();

                    }
                }

                if (!$isMuting && !ngAudioGlobals.isMuting) {
                    audioObject.volume = audio.volume;
                }

                audioObject.audio = audio;
            }

            $setWatch();
        }, 25);
    };
}])
.service('ngAudio', ['NgAudioObject', 'ngAudioGlobals', function(NgAudioObject, ngAudioGlobals) {
    this.play = function(id) {

        var audio = new NgAudioObject(id);
        audio.play();
        return audio;
    };

    this.load = function(id) {
        return new NgAudioObject(id);
    };

    this.mute = function() {
        ngAudioGlobals.muting = true;
    };

    this.unmute = function() {
        ngAudioGlobals.muting = false;
    };

    this.toggleMute = function() {
        ngAudioGlobals.muting = !ngAudioGlobals.muting;
    };
}]);
<commit_msg>clean up<commit_after>'use strict';
angular.module('ngAudio', [])
.directive('ngAudio', ['$compile', '$q', 'ngAudio', function($compile, $q, ngAudio) {
    return {
        restrict: 'AEC',
        scope: {
            volume: '=',
            start: '=',
            currentTime: '=',
            loop: '=',
            clickPlay: '='
        },
        controller: function($scope, $attrs, $element, $timeout) {

            var audio = ngAudio.load($attrs.ngAudio);
            $scope.$audio = audio;
            // audio.unbind();

            $element.on('click', function() {
                if ($scope.clickPlay === false) {
                    return;
                }

                audio.audio.play();

                audio.volume = $scope.volume || audio.volume;
                audio.loop = $scope.loop;
                audio.currentTime = $scope.start || 0;

                $timeout(function() {
                    audio.play();
                }, 5);
            });
        }
    };
}])

.service('localAudioFindingService', ['$q', function($q) {

    this.find = function(id) {
        var deferred = $q.defer();
        var $sound = document.getElementById(id);
        if ($sound) {
            deferred.resolve($sound);
        } else {
            deferred.reject(id);
        }

        return deferred.promise;
    };
}])

.service('remoteAudioFindingService', ['$q', function($q) {

    this.find = function(url) {
        var deferred = $q.defer();
        var audio = new Audio();

        audio.addEventListener('error', function() {
            deferred.reject();
        });

        audio.addEventListener('loadstart', function() {
            deferred.resolve(audio);
        });

        // bugfix for chrome...
        setTimeout(function() {
            audio.src = url;
        }, 1);

        return deferred.promise;

    };
}])

.service('cleverAudioFindingService', ['$q', 'localAudioFindingService', 'remoteAudioFindingService', function($q, localAudioFindingService, remoteAudioFindingService) {
    this.find = function(id) {
        var deferred = $q.defer();

        id = id.replace('|', '/');

        localAudioFindingService.find(id)
            .then(deferred.resolve, function() {
                return remoteAudioFindingService.find(id);
            })
            .then(deferred.resolve, deferred.reject);

        return deferred.promise;
    };
}])

.value('ngAudioGlobals', {
    muting: false,
    songmuting: false
})

.factory('NgAudioObject', ['cleverAudioFindingService', '$rootScope', '$interval', '$timeout', 'ngAudioGlobals', function(cleverAudioFindingService, $rootScope, $interval, $timeout, ngAudioGlobals) {
    return function(id) {

        window.addEventListener("click",function twiddle(){
            audio.play();
            audio.pause();
            window.removeEventListener("click",twiddle);
        });

        var $audioWatch,
            $willPlay = false,
            $willPause = false,
            $willRestart = false,
            $volumeToSet,
            $looping,
            $isMuting = false,
            $observeProperties = true,
            audio,
            audioObject = this;

        this.id = id;
        this.safeId = id.replace('/', '|');
        this.loop = 0;

        this.unbind = function() {
            $observeProperties = false;
        };

        this.play = function() {
            $willPlay = true;
        };

        this.pause = function() {
            $willPause = true;
        };

        this.restart = function() {
            $willRestart = true;
        };

        this.stop = function() {
            this.restart();
        };

        this.setVolume = function(volume) {
            $volumeToSet = volume;
        };

        this.setMuting = function(muting) {
            $isMuting = muting;
        };

        this.setProgress = function(progress) {
            if (audio && audio.duration) {
                audio.currentTime = audio.duration * progress;
            }
        };

        this.setCurrentTime = function(currentTime) {
            if (audio && audio.duration) {
                audio.currentTime = currentTime;
            }
        };

        function $setWatch() {
            $audioWatch = $rootScope.$watch(function() {
                return {
                    volume: audioObject.volume,
                    currentTime: audioObject.currentTime,
                    progress: audioObject.progress,
                    muting: audioObject.muting,
                    loop: audioObject.loop,
                };
            }, function(newValue, oldValue) {
                if (newValue.currentTime !== oldValue.currentTime) {
                    audioObject.setCurrentTime(newValue.currentTime);
                }

                if (newValue.progress !== oldValue.progress) {
                    audioObject.setProgress(newValue.progress);
                }
                if (newValue.volume !== oldValue.volume) {
                    audioObject.setVolume(newValue.volume);
                }

                if (newValue.volume !== oldValue.volume) {
                    audioObject.setVolume(newValue.volume);
                }

                $looping = newValue.loop;

                if (newValue.muting !== oldValue.muting) {
                    audioObject.setMuting(newValue.muting);
                }
            }, true);
        }

        cleverAudioFindingService.find(id)
            .then(function(nativeAudio) {
                audio = nativeAudio;
                audio.addEventListener('canplay', function() {
                    audioObject.canPlay = true;
                });
            }, function(error) {
                audioObject.error = true;
                console.warn(error);
            });

        $interval(function() {
            if ($audioWatch) {
                $audioWatch();
            }
            if (audio) {

                if ($isMuting || ngAudioGlobals.isMuting) {
                    audio.volume = 0;
                } else {
                    audio.volume = audioObject.volume !== undefined ? audioObject.volume : 1;
                }

                if ($willPlay) {
                    audio.play();
                    $willPlay = false;
                }

                if ($willRestart) {
                    audio.pause();
                    audio.currentTime = 0;
                    $willRestart = false;
                }

                if ($willPause) {
                    audio.pause();
                    $willPause = false;
                }

                if ($volumeToSet) {
                    audio.volume = $volumeToSet;
                    $volumeToSet = undefined;
                }

                if ($observeProperties) {
                    audioObject.currentTime = audio.currentTime;
                    audioObject.duration = audio.duration;
                    audioObject.remaining = audio.duration - audio.currentTime;
                    audioObject.progress = audio.currentTime / audio.duration;
                    audioObject.paused = audio.paused;
                    audioObject.src = audio.src;

                    if ($looping && audioObject.currentTime === audioObject.duration) {
                        if ($looping !== true) {
                            $looping--;
                            audioObject.loop--;
                            // if (!$looping) return;
                        }
                        audioObject.setCurrentTime(0);
                        audioObject.play();

                    }
                }

                if (!$isMuting && !ngAudioGlobals.isMuting) {
                    audioObject.volume = audio.volume;
                }

                audioObject.audio = audio;
            }

            $setWatch();
        }, 25);
    };
}])
.service('ngAudio', ['NgAudioObject', 'ngAudioGlobals', function(NgAudioObject, ngAudioGlobals) {
    this.play = function(id) {

        var audio = new NgAudioObject(id);
        audio.play();
        return audio;
    };

    this.load = function(id) {
        return new NgAudioObject(id);
    };

    this.mute = function() {
        ngAudioGlobals.muting = true;
    };

    this.unmute = function() {
        ngAudioGlobals.muting = false;
    };

    this.toggleMute = function() {
        ngAudioGlobals.muting = !ngAudioGlobals.muting;
    };
}]);
<|endoftext|>


<commit_before>export const blockTradesAPIs = {
    BASE: "https://api.blocktrades.us/v2",
    // BASE_OL: "https://api.blocktrades.us/ol/v2",
    BASE_OL: "https://ol-api1.openledger.info/api/v0/ol/support",
    COINS_LIST: "/coins",
    ACTIVE_WALLETS: "/active-wallets",
    TRADING_PAIRS: "/trading-pairs",
    DEPOSIT_LIMIT: "/deposit-limits",
    ESTIMATE_OUTPUT: "/estimate-output-amount",
    ESTIMATE_INPUT: "/estimate-input-amount"
};

export const rudexAPIs = {
    BASE: "https://gateway.rudex.org/api/v0_1",
    COINS_LIST: "/coins",
    NEW_DEPOSIT_ADDRESS: "/new-deposit-address"
};

export const widechainAPIs = {
    BASE : "https://gateway.winex.pro/api/v0/ol/support",
    COINS_LIST: "/coins",
    ACTIVE_WALLETS: "/active-wallets",
    NEW_DEPOSIT_ADDRESS: "/new-deposit-address",
    WITHDRAW_HISTORY:"/latelyWithdraw",
    TRADING_PAIRS: "/trading-pairs",
    DEPOSIT_HISTORY:"/latelyRecharge"
};

export const settingsAPIs = {
    DEFAULT_WS_NODE: "wss://fake.automatic-selection.com",
    WS_NODE_LIST: [
        {url: "wss://fake.automatic-selection.com", location: {translate: "settings.api_closest"}},
        {url: "ws://127.0.0.1:8090", location: "Locally hosted"},
        {url: "wss://bitshares.openledger.info/ws", location: "Nuremberg, Germany"},
        {url: "wss://eu.openledger.info/ws", location: "Berlin, Germany"},
        {url: "wss://bit.btsabc.org/ws", location: "Hong Kong"},
        {url: "wss://bts.ai.la/ws", location: "Hong Kong"},
        {url: "wss://bitshares.apasia.tech/ws", location: "Bangkok, Thailand"},
        {url: "wss://japan.bitshares.apasia.tech/ws", location: "Tokyo, Japan"},
        {url: "wss://bitshares.dacplay.org/ws", location:  "Hangzhou, China"},
        {url: "wss://bitshares-api.wancloud.io/ws", location:  "China"},
        {url: "wss://openledger.hk/ws", location: "Hong Kong"},
        {url: "wss://bitshares.crypto.fans/ws", location: "Munich, Germany"},
        {url: "wss://node.testnet.bitshares.eu", location: "Public Testnet Server (Frankfurt, Germany)"},
        {url: "wss://ws.gdex.top", location: "China"},
        {url: "wss://dex.rnglab.org", location: "Netherlands"},
        {url: "wss://dexnode.net/ws", location: "Dallas, USA"},
        {url: "wss://kc-us-dex.xeldal.com/ws", location: "Kansas City, USA"},
        {url: "wss://la.dexnode.net/ws", location: "Los Angeles, USA"},
        {url: "wss://btsza.co.za:8091/ws", location: "Cape Town, South Africa"},
        {url: "wss://api.bts.blckchnd.com", location: "Falkenstein, Germany"}
    ],
    DEFAULT_FAUCET: "https://faucet.bitshares.eu/onboarding",  // 2017-12-infrastructure worker proposal
    TESTNET_FAUCET: "https://faucet.testnet.bitshares.eu",
    RPC_URL: "https://openledger.info/api/"
};

export const  gdexAPIs = {
    BASE: "https://api.gdex.io",
    ASSET_LIST: "/gateway/asset/assetList",
    ASSET_DETAIL: "/gateway/asset/assetDetail",
    GET_DEPOSIT_ADDRESS: "/gateway/address/getAddress",
    CHECK_WITHDRAY_ADDRESS: "/gateway/address/checkAddress",
    DEPOSIT_RECORD_LIST: "/gateway/deposit/recordList",
    DEPOSIT_RECORD_DETAIL: "/gateway/deposit/recordDetail",
    WITHDRAW_RECORD_LIST: "/gateway/withdraw/recordList",
    WITHDRAW_RECORD_DETAIL: "/gateway/withdraw/recordDetail",
    GET_USER_INFO: "/gateway/user/getUserInfo",
    USER_AGREEMENT: "/gateway/user/isAgree",
    WITHDRAW_RULE: "/gateway/withdraw/rule"
}
<commit_msg>New API endpoints (#1057)<commit_after>export const blockTradesAPIs = {
    BASE: "https://api.blocktrades.us/v2",
    // BASE_OL: "https://api.blocktrades.us/ol/v2",
    BASE_OL: "https://ol-api1.openledger.info/api/v0/ol/support",
    COINS_LIST: "/coins",
    ACTIVE_WALLETS: "/active-wallets",
    TRADING_PAIRS: "/trading-pairs",
    DEPOSIT_LIMIT: "/deposit-limits",
    ESTIMATE_OUTPUT: "/estimate-output-amount",
    ESTIMATE_INPUT: "/estimate-input-amount"
};

export const rudexAPIs = {
    BASE: "https://gateway.rudex.org/api/v0_1",
    COINS_LIST: "/coins",
    NEW_DEPOSIT_ADDRESS: "/new-deposit-address"
};

export const widechainAPIs = {
    BASE : "https://gateway.winex.pro/api/v0/ol/support",
    COINS_LIST: "/coins",
    ACTIVE_WALLETS: "/active-wallets",
    NEW_DEPOSIT_ADDRESS: "/new-deposit-address",
    WITHDRAW_HISTORY:"/latelyWithdraw",
    TRADING_PAIRS: "/trading-pairs",
    DEPOSIT_HISTORY:"/latelyRecharge"
};

export const settingsAPIs = {
    DEFAULT_WS_NODE: "wss://fake.automatic-selection.com",
    WS_NODE_LIST: [
        {url: "wss://fake.automatic-selection.com", location: {translate: "settings.api_closest"}},
        {url: "ws://127.0.0.1:8090", location: "Locally hosted"},
        {url: "wss://bitshares.openledger.info/ws", location: "Nuremberg, Germany"},
        {url: "wss://eu.openledger.info/ws", location: "Berlin, Germany"},
        {url: "wss://bit.btsabc.org/ws", location: "Hong Kong"},
        {url: "wss://bts.ai.la/ws", location: "Hong Kong"},
        {url: "wss://bitshares.apasia.tech/ws", location: "Bangkok, Thailand"},
        {url: "wss://japan.bitshares.apasia.tech/ws", location: "Tokyo, Japan"},
        {url: "wss://bitshares.dacplay.org/ws", location:  "Hangzhou, China"},
        {url: "wss://bitshares-api.wancloud.io/ws", location:  "China"},
        {url: "wss://openledger.hk/ws", location: "Hong Kong"},
        {url: "wss://bitshares.crypto.fans/ws", location: "Munich, Germany"},
        {url: "wss://node.testnet.bitshares.eu", location: "Public Testnet Server (Frankfurt, Germany)"},
        {url: "wss://ws.gdex.top", location: "China"},
        {url: "wss://dex.rnglab.org", location: "Netherlands"},
        {url: "wss://dexnode.net/ws", location: "Dallas, USA"},
        {url: "wss://kc-us-dex.xeldal.com/ws", location: "Kansas City, USA"},
        {url: "wss://la.dexnode.net/ws", location: "Los Angeles, USA"},
        {url: "wss://btsza.co.za:8091/ws", location: "Cape Town, South Africa"},
        {url: "wss://api.bts.blckchnd.com", location: "Falkenstein, Germany"},
        {url: "wss://eu.nodes.bitshares.works", location: "Central Europe - BitShares Infrastructure Program"},
        {url: "wss://us.nodes.bitshares.works", location: "U.S. West Coast - BitShares Infrastructure Program"},
        {url: "wss://sg.nodes.bitshares.works", location: "Singapore - BitShares Infrastructure Program"},
    ],
    DEFAULT_FAUCET: "https://faucet.bitshares.eu/onboarding",  // 2017-12-infrastructure worker proposal
    TESTNET_FAUCET: "https://faucet.testnet.bitshares.eu",
    RPC_URL: "https://openledger.info/api/"
};

export const  gdexAPIs = {
    BASE: "https://api.gdex.io",
    ASSET_LIST: "/gateway/asset/assetList",
    ASSET_DETAIL: "/gateway/asset/assetDetail",
    GET_DEPOSIT_ADDRESS: "/gateway/address/getAddress",
    CHECK_WITHDRAY_ADDRESS: "/gateway/address/checkAddress",
    DEPOSIT_RECORD_LIST: "/gateway/deposit/recordList",
    DEPOSIT_RECORD_DETAIL: "/gateway/deposit/recordDetail",
    WITHDRAW_RECORD_LIST: "/gateway/withdraw/recordList",
    WITHDRAW_RECORD_DETAIL: "/gateway/withdraw/recordDetail",
    GET_USER_INFO: "/gateway/user/getUserInfo",
    USER_AGREEMENT: "/gateway/user/isAgree",
    WITHDRAW_RULE: "/gateway/withdraw/rule"
}
<|endoftext|>


<commit_before>(function() {
  // Your AngularJS application's name
  var APP_NAME = 'myApplication';
  // Your templates AngularJS module
  var TEMPLATES_NAME = 'appTemplates';
  // Where the built files would eventually live. If it's on its own domain,
  // this could be blank
  var ROOT = '';

  // Load the Pixbi embed
  var runLoader = function() {
    var vendor, app, templates, checkerId;

    // The vendor script first
    vendor = document.createElement('script');
    vendor.type = 'text/javascript';
    vendor.src = ROOT + '/vendor.js';

    // The templates then
    templates= document.createElement('script');
    templates.type = 'text/javascript';
    templates.src = ROOT + '/templates.js';

    // Finally the application script
    app = document.createElement('script');
    app.type = 'text/javascript';
    app.src = ROOT + '/app.js';

    // Add to vendor script, app stylesheet, and the Pixbi box
    document.body.appendChild(vendor);

    // Prepare controller declaration
    document.body.setAttribute('ng-controller', 'ApplicationController');

    checkerId = window.setInterval(function() {
      // Only when AngularJS is available
      if (window.angular !== void 0) {
        // Do we load our templates
        document.body.appendChild(templates);
        // And stop checking of course
        window.clearInterval(checkerId);

        checkerId = window.setInterval(function() {
          try {
            // Only when the templates are loaded
            angular.module(TEMPLATES_NAME);
            // Do we load our application code
            document.body.appendChild(app);
            // And stop checking already!
            window.clearInterval(checkerId);

            checkerId = window.setInterval(function() {
              try {
                // Only when the application is ready
                angular.module(APP_NAME);
                // Do we make this page AngularJS-enabled
                angular.bootstrap(document.body, [APP_NAME]);

                // Stop checking once again
                window.clearInterval(checkerId);
              } catch (error) {}
            }, 50);
          } catch (error) {}
        }, 50);
      }
    }, 50);
  };

  // Handle this loader being dynamically loaded into the page
  if (document.readyState === 'complete') {
    runLoader();

  // Handle this loader being loaded with the rest of the page
  } else {
    // Standard
    if (window.addEventListener != null) {
      window.addEventListener('load', runLoader, false);
    // IE
    } else if (window.attachEvent != null) {
      window.attachEvent('onload', runLoader);
    // Old school
    } else {
      window.onload = runLoader;
    }
  }
})();
<commit_msg>fix (loader): re-throw errors unless it's not finding the templates or the app<commit_after>(function() {
  // Your AngularJS application's name
  var APP_NAME = 'myApplication';
  // Your templates AngularJS module
  var TEMPLATES_NAME = 'appTemplates';
  // Where the built files would eventually live. If it's on its own domain,
  // this could be blank
  var ROOT = '';

  // Load the Pixbi embed
  var runLoader = function() {
    var vendor, app, templates, checkerId;

    // The vendor script first
    vendor = document.createElement('script');
    vendor.type = 'text/javascript';
    vendor.src = ROOT + '/vendor.js';

    // The templates then
    templates= document.createElement('script');
    templates.type = 'text/javascript';
    templates.src = ROOT + '/templates.js';

    // Finally the application script
    app = document.createElement('script');
    app.type = 'text/javascript';
    app.src = ROOT + '/app.js';

    // Add to vendor script, app stylesheet, and the Pixbi box
    document.body.appendChild(vendor);

    // Prepare controller declaration
    document.body.setAttribute('ng-controller', 'ApplicationController');

    checkerId = window.setInterval(function() {
      // Only when AngularJS is available
      if (window.angular !== void 0) {
        // Do we load our templates
        document.body.appendChild(templates);
        // And stop checking of course
        window.clearInterval(checkerId);

        checkerId = window.setInterval(function() {
          try {
            // Only when the templates are loaded
            angular.module(TEMPLATES_NAME);
            // Do we load our application code
            document.body.appendChild(app);
            // And stop checking already!
            window.clearInterval(checkerId);

            checkerId = window.setInterval(function() {
              try {
                // Only when the application is ready
                angular.module(APP_NAME);
                // Do we make this page AngularJS-enabled
                angular.bootstrap(document.body, [APP_NAME]);

                // Stop checking once again
                window.clearInterval(checkerId);
              } catch (error) {
                // Look for this error message for not finding the application module
                var appNotFound = new RegExp("[$injector:nomod] Module '" + APP_NAME);

                // Throw error if it's not missing the module
                if (error.message.match(appNotFound) === null) {
                  throw error;
                }
              }
            }, 50);
          } catch (error) {
            // Look for this error message for not finding the templates module
            var templatesNotFound = new RegExp("[$injector:nomod] Module '" + TEMPLATES_NAME);

            // Throw error if it's not missing the module
            if (error.message.match(templatesNotFound) === null) {
              throw error;
            }
          }
        }, 50);
      }
    }, 50);
  };

  // Handle this loader being dynamically loaded into the page
  if (document.readyState === 'complete') {
    runLoader();

  // Handle this loader being loaded with the rest of the page
  } else {
    // Standard
    if (window.addEventListener != null) {
      window.addEventListener('load', runLoader, false);
    // IE
    } else if (window.attachEvent != null) {
      window.attachEvent('onload', runLoader);
    // Old school
    } else {
      window.onload = runLoader;
    }
  }
})();
<|endoftext|>


<commit_before>exports.port 				= process.env.PORT || 8000;
//exports.defaultStoryPath 	= './stories/Zork1.z5';
//exports.defaultStoryPath 	= './stories/cryptographer.z5';
//exports.defaultStoryPath 	= './stories/Legend of the Missing Hat.z8';
exports.defaultStoryPath 	= './stories/quake.z5';
//exports.defaultStoryPath 	= './stories/shade.z5';
//exports.defaultStoryPath 	= './stories/vespers.z8';
exports.defaultStory 		= 'Quake';
exports.storiesPath 		= './stories';
exports.SMS 				= {};
exports.SMS.apiKey 			= 'dd5260de';
exports.SMS.apiSecret 		= 'ca411db6';
exports.SMS.sender 			= '19282388797';
<commit_msg>Delete config.js<commit_after><|endoftext|>


<commit_before>var Issue = require('../issue');

module.exports = {
    name: 'table-req-header',
    on: ['tag'],
    filter: ['table'],
    desc: 'If set, each `table` tag must contain a `header` tag.' // TODO
};

module.exports.lint = function (ele, opts) {
    var children = ele.children;
    var childIndex = 0;
    var child = children[childIndex];

    //ffwd to first relevant table child
    while (child && child.name &&
           child.name.match(/(caption|colgroup|tfoot)/i)) {
        childIndex++;
        child = children[childIndex];
    }

    if (child && child.name &&
        ((child.name.match(/thead/i)) ||
         (child.name.match(/tr/i) && child.children[0].name.match(/th/i)))
       ) {
        return [];
    }

    return new Issue('E035', ele.openLineCol);
};
<commit_msg>Minor simplification in table-req-header<commit_after>var Issue = require('../issue');

module.exports = {
    name: 'table-req-header',
    on: ['tag'],
    filter: ['table'],
    desc: 'If set, each `table` tag must contain a header: a `thead` tag or a `tr` tag with a `th` child.'
};

module.exports.lint = function (ele, opts) {
    var children = ele.children,
        childIndex = 0,
        child;

    //ffwd to first relevant table child
    while ((child = children[childIndex]) && child.name &&
           child.name.match(/(caption|colgroup|tfoot)/i)) {
        childIndex++;
    }

    if (child && child.name &&
        ((child.name.match(/thead/i)) ||
         (child.name.match(/tr/i) && child.children[0].name.match(/th/i)))
       ) {
        return [];
    }

    return new Issue('E035', ele.openLineCol);
};
<|endoftext|>


<commit_before>var
	fs = require("fs"),
	path = require("path"),
	walker = require("walker"),
	jsp = require("uglify-js").parser,
	pro = require("uglify-js").uglify
	;

options = function(args) {
	var opts = {};
	for (var i=2; i<args.length; i++) {
		var arg = args[i];
		if (arg[0] == "-") {
			var o = arg.slice(1);
			opts[o] = {enyo: 1, output: 1, alias: 1}[o] ? args[++i] : true;
		} else {
			opts.source = arg;
		}
	}
	w(opts);
	w("");
	return opts;
};

function printUsage() {
	w("Enyo 2.0 Minifier");
	w("Flags:")
	w("-no-alias:", "Don't use path macros");
	w("-alias ALIAS:", "Give paths a macroized alias");
	w("-enyo ENYOPATH:", "Path to enyo loader (enyo/enyo.js)");
	w("-output PATH/NAME:", "name of output file, prepend folder paths to change output directory");
	w("-h, -?, -help:", "Show this message");
}

// make a relative path from source to target
function makeRelPath(inSource, inTarget) {
	// node 0.5 has this nice thing, 0.4 does not
	if (path.relative) {
		return path.relative(inSource, inTarget);
	}
	var s,t;
	s = pathSplit(path.resolve(inSource));
	t = pathSplit(path.resolve(inTarget));
	while (s.length && s[0] === t[0]){
		s.shift();
		t.shift();
	}
	for(var i = 0, l = s.length; i < l; i++) {
		t.unshift("..");
	}
	return path.join.apply(null, t);
}

// properly split path based on platform
function pathSplit(inPath) {
	var sep = process.platform == "win32" ? "\\" : "/";
	return inPath.split(sep);
}

buildPathBlock = function(loader) {
	var p$ = [];
	for (var i=0, p; p=loader.packages[i]; i++) {
		if (p.name.indexOf("-") == -1) {
			p$.push(p.name + ': "' + p.folder + '"');
		}
	}
	var p = p$.join(', ');
	return !p ? "" : "\n// minifier: path aliases\n\nenyo.path.addPaths({" + p + "});\n";
};

concatCss = function(loader) {
	w("");
	var blob = "";
	for (var i=0, s; s=loader.sheets[i]; i++) {
		w(s);
		var code = fs.readFileSync(s, "utf8");
		// fix url paths
		code = code.replace(/url\([^)]*\)/g, function(inMatch) {
			// find the url path, ignore quotes in url string
			var urlPath = inMatch.replace(/["']/g, "").slice(4, -1);
			// skip data urls
			if (/^data:/.test(urlPath)) {
				return "url(" + urlPath + ")";
			}
			// get absolute path to referenced asset
			var normalizedUrlPath = path.join(s, "..", urlPath);
			// Make relative asset path to built css
			var relPath = makeRelPath(path.dirname(opt.output || "build"), normalizedUrlPath);
			if (process.platform == "win32") {
				relPath = pathSplit(relPath).join("/");
			}
			return "url(" + relPath + ")";
		});
		blob += "\n/* " + s + " */\n\n" + code + "\n";
	}
	return blob;
};

concatJs = function(loader) {
	w("");
	var blob = "";
	for (var i=0, m; m=loader.modules[i]; i++) {
		if (!opt["no-alias"] && !opt.alias) {
			w("* inserting path aliases");
			blob += buildPathBlock(loader);
			opt["no-alias"] = true;
		}
		w(m.path);
		blob += "\n// " + m.rawPath + "\n\n" + compressJsFile(m.path) + "\n";
		if (opt.alias == m.rawPath) {
			w("* inserting path aliases");
			blob += buildPathBlock(loader);
		}
	}
	return blob;
};

compress = function(inCode) {
	var ast = jsp.parse(inCode); // parse code and get the initial AST
	ast = pro.ast_mangle(ast); // get a new AST with mangled names
	ast = pro.ast_squeeze(ast); // get an AST with compression optimizations
	return pro.gen_code(ast, {indent_level:0, beautify: !opt.aggro, ascii_only:true}); // compressed code here
};

compressJsFile = function(inPath) {
	var code = fs.readFileSync(inPath, "utf8");
	return compress(code);
};

finish = function(loader) {
	//w(loader.packages);
	//w('');
	//
	var output = opt.output || "build";
	var outfolder = path.dirname(output);
	var exists = fs.existsSync || path.existsSync;
	if (outfolder != "." && !exists(outfolder)) {
		fs.mkdirSync(outfolder);
	}
	//
	var css = concatCss(loader);
	if (css.length) {
		w("");
		fs.writeFileSync(output + ".css", css, "utf8");
	}
	//
	var js = concatJs(loader);
	/*
	if (css.length) {
		js += "\n// " + "minifier: load css" + "\n\n";
		js += 'enyo.machine.sheet("' + output + '.css");\n';
	}
	*/
	if (js.length) {
		w("");
		fs.writeFileSync(output + ".js", js, "utf8");
	}
	//
	w("");
	w("done.");
	w("");
};

w = console.log;

opt = options(process.argv);
w("");

if (opt.help || opt.h || opt["?"]) {
	printUsage();
	process.exit();
}

walker.init(opt.enyo);
walker.walk(opt.source, finish);
<commit_msg>ENYO-894: switch to more advanced regular expression to find the URL part of a CSS url() expression Minor jshint-related code cleanups.<commit_after>var
	fs = require("fs"),
	path = require("path"),
	walker = require("walker"),
	jsp = require("uglify-js").parser,
	pro = require("uglify-js").uglify
	;

options = function(args) {
	var opts = {};
	for (var i=2; i<args.length; i++) {
		var arg = args[i];
		if (arg[0] == "-") {
			var o = arg.slice(1);
			opts[o] = {enyo: 1, output: 1, alias: 1}[o] ? args[++i] : true;
		} else {
			opts.source = arg;
		}
	}
	w(opts);
	w("");
	return opts;
};

function printUsage() {
	w("Enyo 2.0 Minifier");
	w("Flags:");
	w("-no-alias:", "Don't use path macros");
	w("-alias ALIAS:", "Give paths a macroized alias");
	w("-enyo ENYOPATH:", "Path to enyo loader (enyo/enyo.js)");
	w("-output PATH/NAME:", "name of output file, prepend folder paths to change output directory");
	w("-h, -?, -help:", "Show this message");
}

// make a relative path from source to target
function makeRelPath(inSource, inTarget) {
	// node 0.5 has this nice thing, 0.4 does not
	if (path.relative) {
		return path.relative(inSource, inTarget);
	}
	var s,t;
	s = pathSplit(path.resolve(inSource));
	t = pathSplit(path.resolve(inTarget));
	while (s.length && s[0] === t[0]){
		s.shift();
		t.shift();
	}
	for(var i = 0, l = s.length; i < l; i++) {
		t.unshift("..");
	}
	return path.join.apply(null, t);
}

// properly split path based on platform
function pathSplit(inPath) {
	var sep = process.platform == "win32" ? "\\" : "/";
	return inPath.split(sep);
}

buildPathBlock = function(loader) {
	var p$ = [];
	for (var i=0, p; (p=loader.packages[i]); i++) {
		if (p.name.indexOf("-") == -1) {
			p$.push(p.name + ': "' + p.folder + '"');
		}
	}
	p = p$.join(', ');
	return !p ? "" : "\n// minifier: path aliases\n\nenyo.path.addPaths({" + p + "});\n";
};

concatCss = function(loader) {
	w("");
	var blob = "";
	var repl = function(inMatch) {
		// find the url path, ignore quotes in url string
		var matches = /url\s*\(\s*(('([^']*)')|("([^"]*)")|([^'"]*))\s*\)/.exec(inMatch);
		var urlPath = matches[3] || matches[5] || matches[6];
		// skip data urls
		if (/^data:/.test(urlPath)) {
			return "url(" + urlPath + ")";
		}
		// get absolute path to referenced asset
		var normalizedUrlPath = path.join(s, "..", urlPath);
		// Make relative asset path to built css
		var relPath = makeRelPath(path.dirname(opt.output || "build"), normalizedUrlPath);
		if (process.platform == "win32") {
			relPath = pathSplit(relPath).join("/");
		}
		return "url(" + relPath + ")";
	};
	for (var i=0, s; (s=loader.sheets[i]); i++) {
		w(s);
		var code = fs.readFileSync(s, "utf8");
		// fix url paths
		code = code.replace(/url\([^)]*\)/g, repl);
		blob += "\n/* " + s + " */\n\n" + code + "\n";
	}
	return blob;
};

concatJs = function(loader) {
	w("");
	var blob = "";
	for (var i=0, m; (m=loader.modules[i]); i++) {
		if (!opt["no-alias"] && !opt.alias) {
			w("* inserting path aliases");
			blob += buildPathBlock(loader);
			opt["no-alias"] = true;
		}
		w(m.path);
		blob += "\n// " + m.rawPath + "\n\n" + compressJsFile(m.path) + "\n";
		if (opt.alias == m.rawPath) {
			w("* inserting path aliases");
			blob += buildPathBlock(loader);
		}
	}
	return blob;
};

compress = function(inCode) {
	var ast = jsp.parse(inCode); // parse code and get the initial AST
	ast = pro.ast_mangle(ast); // get a new AST with mangled names
	ast = pro.ast_squeeze(ast); // get an AST with compression optimizations
	return pro.gen_code(ast, {indent_level:0, beautify: !opt.aggro, ascii_only:true}); // compressed code here
};

compressJsFile = function(inPath) {
	var code = fs.readFileSync(inPath, "utf8");
	return compress(code);
};

finish = function(loader) {
	//w(loader.packages);
	//w('');
	//
	var output = opt.output || "build";
	var outfolder = path.dirname(output);
	var exists = fs.existsSync || path.existsSync;
	if (outfolder != "." && !exists(outfolder)) {
		fs.mkdirSync(outfolder);
	}
	//
	var css = concatCss(loader);
	if (css.length) {
		w("");
		fs.writeFileSync(output + ".css", css, "utf8");
	}
	//
	var js = concatJs(loader);
	/*
	if (css.length) {
		js += "\n// " + "minifier: load css" + "\n\n";
		js += 'enyo.machine.sheet("' + output + '.css");\n';
	}
	*/
	if (js.length) {
		w("");
		fs.writeFileSync(output + ".js", js, "utf8");
	}
	//
	w("");
	w("done.");
	w("");
};

w = console.log;

opt = options(process.argv);
w("");

if (opt.help || opt.h || opt["?"]) {
	printUsage();
	process.exit();
}

walker.init(opt.enyo);
walker.walk(opt.source, finish);
<|endoftext|>


<commit_before>'use strict';

let getSessionCache = require('./getSessionCache').getSessionCache;
let getObjectTemplate = require('../utils/getObjectTemplate');
let decompressSessionData = require('./decompressSessionData').decompressSessionData;

/**
 * Purpose unknown
 *
 * @param {String} path - The app name.
 * @param {unknown} session unknown
 * @param {unknown} controller unknown
 * @param {unknown} sessions unknown
 *
 * @returns {unknown} unknown
 */
function restoreSession(path, session, controller, sessions) {
    let ourObjectTemplate = getObjectTemplate(controller);

    ourObjectTemplate.withoutChangeTracking(function callBack() {
        let sessionData = getSessionCache(path, ourObjectTemplate.controller.__sessionId, true, sessions);
        // Will return in exising controller object because createEmptyObject does so
        let unserialized = session.semotus.controllers[path];

        controller = ourObjectTemplate.fromJSON(
            decompressSessionData(unserialized.controller),
            controller.__template__
        );

        if (unserialized.serializationTimeStamp !== sessionData.serializationTimeStamp) {
            ourObjectTemplate.logger.error({
                component: 'amorphic',
                module: 'getController',
                activity: 'restore',
                savedAs: sessionData.serializationTimeStamp,
                foundToBe: unserialized.serializationTimeStamp
            }, 'Session data not as saved');
        }

        if (session.semotus.objectMap && session.semotus.objectMap[path]) {
            ourObjectTemplate.objectMap = session.semotus.objectMap[path];
        }

        ourObjectTemplate.logger.info({component: 'amorphic', module: 'restoreSession', activity: 'restoring'});
        ourObjectTemplate.syncSession();  // Clean tracking of changes
    });

    return controller;
}

module.exports = {
    restoreSession: restoreSession
};
<commit_msg>updated module part of logging to log out the correct module<commit_after>'use strict';

let getSessionCache = require('./getSessionCache').getSessionCache;
let getObjectTemplate = require('../utils/getObjectTemplate');
let decompressSessionData = require('./decompressSessionData').decompressSessionData;

/**
 * Purpose unknown
 *
 * @param {String} path - The app name.
 * @param {unknown} session unknown
 * @param {unknown} controller unknown
 * @param {unknown} sessions unknown
 *
 * @returns {unknown} unknown
 */
function restoreSession(path, session, controller, sessions) {
    let ourObjectTemplate = getObjectTemplate(controller);

    ourObjectTemplate.withoutChangeTracking(function callBack() {
        let sessionData = getSessionCache(path, ourObjectTemplate.controller.__sessionId, true, sessions);
        // Will return in exising controller object because createEmptyObject does so
        let unserialized = session.semotus.controllers[path];

        controller = ourObjectTemplate.fromJSON(
            decompressSessionData(unserialized.controller),
            controller.__template__
        );

        if (unserialized.serializationTimeStamp !== sessionData.serializationTimeStamp) {
            ourObjectTemplate.logger.error({
                component: 'amorphic',
                module: 'restoreSession',
                activity: 'restore',
                savedAs: sessionData.serializationTimeStamp,
                foundToBe: unserialized.serializationTimeStamp
            }, 'Session data not as saved');
        }

        if (session.semotus.objectMap && session.semotus.objectMap[path]) {
            ourObjectTemplate.objectMap = session.semotus.objectMap[path];
        }

        ourObjectTemplate.logger.info({component: 'amorphic', module: 'restoreSession', activity: 'restoring'});
        ourObjectTemplate.syncSession();  // Clean tracking of changes
    });

    return controller;
}

module.exports = {
    restoreSession: restoreSession
};
<|endoftext|>