<commit_before>(function (clique, _, Backbone, $) {
    "use strict";

    clique.adapter = {};

    clique.Adapter = function (options) {
        var accessors;

        // Keep track of accessors.
        this.accessors = accessors = {};
        this.onNewAccessor = this.onNewAccessor || _.noop;
        this.addAccessor = function (blob) {
            var mut;

            if (!_.has(accessors, blob.key)) {
                accessors[blob.key] = new clique.util.Accessor(blob);
                this.onNewAccessor(mut);
            }

            mut = accessors[blob.key];

            return mut;
        };

        // Define methods.
        this.getAccessor = _.propertyOf(accessors);

        this.findNodes = function (spec) {
            return $.when(this.findNodesImpl(spec)).then(_.partial(_.map, _, this.addAccessor, this));
        };

        this.findNode = function (spec) {
            return $.when(this.findNodesImpl(spec)).then(_.bind(function (results) {
                if (_.isEmpty(results)) {
                    return undefined;
                }

                return this.addAccessor(results[0]);
            }, this));
        };

        this.findNodeByKey = function (key) {
            return this.findNode({
                key: key
            });
        };

        this.findLinks = function (_spec) {
            var spec = clique.util.deepCopy(_spec),
                undirected = _.isUndefined(spec.undirected) ? true : spec.undirected,
                directed = _.isUndefined(spec.directed) ? true : spec.directed,
                source = spec.source,
                target = spec.target;

            delete spec.undirected;
            delete spec.directed;
            delete spec.source;
            delete spec.target;

            return $.when(this.findLinksImpl(spec, source, target, undirected, directed)).then(_.partial(_.map, _, this.addAccessor, this));
        };

        this.findLink = function (spec) {
            return $.when(this.findLinksImpl(spec)).then(_.bind(function (results) {
                if (_.isEmpty(results)) {
                    return undefined;
                }

                return this.addAccessor(results[0]);
            }, this));
        };

        this.findLinkByKey = function (key) {
            return this.findLink({
                key: key
            });
        };

        this.getNeighborLinks = function (node, opts) {
            var reqs = [];

            opts = opts || {};
            _.each(["outgoing", "incoming", "undirected"], function (mode) {
                opts[mode] = _.isUndefined(opts[mode]) ? true : opts[mode];
            });

            if (opts.outgoing) {
                reqs.push(this.findLinks({
                    source: node.key(),
                    undirected: false
                }));
            }

            if (opts.incoming) {
                reqs.push(this.findLinks({
                    target: node.key(),
                    undirected: false
                }));
            }

            if (opts.undirected) {
                reqs.push(this.findLinks({
                    source: node.key(),
                    undirected: true
                }));

                reqs.push(this.findLinks({
                    target: node.key(),
                    undirected: true
                }));
            }

            return $.when.apply($, reqs).then(function () {
                return _.reduce(_.toArray(arguments), function (memo, item) {
                    return memo.concat(item);
                }, []);
            });
        };

        this.getOutgoingLinks = function (node) {
            return this.getNeighborLinks(node, {
                outgoing: true,
                incoming: false,
                undirected: false
            });
        };

        this.getOutflowingLinks = function (node) {
            return this.getNeighborLinks(node, {
                outgoing: true,
                incoming: false,
                undirected: true
            });
        };

        this.getIncomingLinks = function (node) {
            return this.getNeighborLinks(node, {
                outgoing: false,
                incoming: true,
                undirected: false
            });
        };

        this.getInflowingLinks = function (node) {
            return this.getNeighborLinks(node, {
                outgoing: false,
                incoming: true,
                undirected: true
            });
        };

        this.getUndirectedLinks = function (node) {
            return this.getNeighborLinks(node, {
                outgoing: false,
                incoming: false,
                undirected: true
            });
        };

        this.getDirectedLinks = function (node) {
            return this.getNeighborLinks(node, {
                outgoing: true,
                incoming: true,
                undirected: false
            });
        };

        this.getNeighbors = function (node, opts) {
            var key = node.key();
            return this.getNeighborLinks(node, opts).then(_.bind(function (links) {
                var neighborKeys,
                    muts;

                neighborKeys = _.map(links, function (link) {
                    return key === link.source() ? link.target() : link.source();
                });

                // Attempt to retrieve the accessors.  The ones we don't have
                // yet will show up as undefined in this array.
                muts = _.map(neighborKeys, this.getAccessor, this);

                _.each(muts, function (mut, i) {
                    if (_.isUndefined(mut)) {
                        muts[i] = this.findNodeByKey(neighborKeys[i]);
                    } else {
                        muts[i] = $.when(muts[i]);
                    }
                }, this);

                return $.when.apply($, muts);
            }, this)).then(function () {
                return _.toArray(arguments);
            });
        };

        this.getOutgoingNeighbors = function (node) {
            return this.getNeighbors(node, {
                outgoing: true,
                incoming: false,
                undirected: false
            });
        };

        this.getOutflowingNeighbors = function (node) {
            return this.getNeighbors(node, {
                outgoing: true,
                incoming: false,
                undirected: true
            });
        };

        this.getIncomingNeighbors = function (node) {
            return this.getNeighbors(node, {
                outgoing: false,
                incoming: true,
                undirected: false
            });
        };

        this.getInflowingNeighbors = function (node) {
            return this.getNeighbors(node, {
                outgoing: false,
                incoming: true,
                undirected: true
            });
        };

        this.getUndirectedNeighbors = function (node) {
            return this.getNeighbors(node, {
                outgoing: false,
                incoming: false,
                undirected: true
            });
        };

        this.getDirectedNeighbors = function (node) {
            return this.getNeighbors(node, {
                outgoing: true,
                incoming: true,
                undirected: false
            });
        };

        this.createNode = function (data) {
            return $.when(this.createNodeImpl(data || {}))
                .then(_.bind(this.addAccessor, this));
        };

        this.createLink = function (source, target, _data, undirected) {
            var data;

            // If source/target is a accessor, call its key method to get the
            // key; otherwise, assume it is a string describing the key already.
            source = _.result(source, "key", source);
            target = _.result(target, "key", target);

            data = _data || {};
            undirected = _.isUndefined(undirected) ? false : undirected;

            return $.when(this.createLinkImpl(source, target, data, undirected))
                .then(_.bind(this.addAccessor, this));
        };

        this.destroyNode = function (node) {
            var key = node.key();
            return this.destroyNodeImpl(key).then(function (response) {
                return {
                    key: key,
                    response: response
                };
            });
        };

        this.destroyLink = function (link) {
            var key = link.key();
            return this.destroyLinkImpl(key).then(function (response) {
                return {
                    key: key,
                    response: response
                };
            });
        };

        options = options || {};
        this.initialize.apply(this, arguments);
    };

    clique.Adapter.extend = Backbone.Model.extend;

    clique.adapter.NodeLinkList = clique.Adapter.extend({
        initialize: function (options) {
            var table = {};

            this.nodes = clique.util.deepCopy(options.nodes);
            this.links = clique.util.deepCopy(options.links);

            _.each(this.nodes, function (node, i) {
                var tmpNs = "datax",
                    ns;

                // Promote the data elements into a dedicated namespace.
                //
                // First figure out a suitable temporary name to use for the
                // namespace.
                while (_.has(node, tmpNs)) {
                    tmpNs += "x";
                }

                // Create the namespace.
                ns = node[tmpNs] = {};

                // Move all top-level properties into the namespace.
                _.each(node, function (v, k) {
                    if (k !== tmpNs) {
                        ns[k] = v;
                        delete node[k];
                    }
                });

                // Rename the temporary namespace as "data".
                if (tmpNs !== "data") {
                    node.data = ns;
                    delete node[tmpNs];
                }

                table[i] = node;

                // Assign a unique key to this node.
                node.key = _.uniqueId("node_");
            });

            _.each(this.links, function (link) {
                link.key = _.uniqueId("link_");

                link.source = table[link.source];
                link.target = table[link.target];
            }, this);
        },

        findNodesImpl: function (_spec) {
            var spec = clique.util.deepCopy(_spec),
                searchspace = this.nodes,
                result;

            if (spec.key) {
                searchspace = _.filter(searchspace, function (node) {
                    return node.key === spec.key;
                });

                delete spec.key;
            }

            result = _.filter(searchspace, function (node) {
                return _.isMatch(node.data, spec);
            });

            return result;
        },

        findLinksImpl: function (spec, source, target, undirected, directed) {
            return _.filter(this.links, function (link) {
                var undirectedMatch = (link.undirected || false) === undirected,
                    directedMatch = (_.isUndefined(link.undirected) || !link.undirected) === directed,
                    sourceMatch = _.isUndefined(source) || (link.source.key === source),
                    targetMatch = _.isUndefined(target) || (link.target.key === target),
                    dataMatch = _.isMatch(spec, link.data);

                return _.every([sourceMatch, targetMatch, dataMatch, undirectedMatch || directedMatch]);
            });
        },

        newNode: _.noop,
        newLink: _.noop,
        destroyNode: _.noop,
        destroyLink: _.noop
    });
}(window.clique, window._, window.Backbone, window.jQuery));
<commit_msg>Extend Adapter.getNeighbors() to return both neighbors and links<commit_after>(function (clique, _, Backbone, $) {
    "use strict";

    clique.adapter = {};

    clique.Adapter = function (options) {
        var accessors;

        // Keep track of accessors.
        this.accessors = accessors = {};
        this.onNewAccessor = this.onNewAccessor || _.noop;
        this.addAccessor = function (blob) {
            var mut;

            if (!_.has(accessors, blob.key)) {
                accessors[blob.key] = new clique.util.Accessor(blob);
                this.onNewAccessor(mut);
            }

            mut = accessors[blob.key];

            return mut;
        };

        // Define methods.
        this.getAccessor = _.propertyOf(accessors);

        this.findNodes = function (spec) {
            return $.when(this.findNodesImpl(spec)).then(_.partial(_.map, _, this.addAccessor, this));
        };

        this.findNode = function (spec) {
            return $.when(this.findNodesImpl(spec)).then(_.bind(function (results) {
                if (_.isEmpty(results)) {
                    return undefined;
                }

                return this.addAccessor(results[0]);
            }, this));
        };

        this.findNodeByKey = function (key) {
            return this.findNode({
                key: key
            });
        };

        this.findLinks = function (_spec) {
            var spec = clique.util.deepCopy(_spec),
                undirected = _.isUndefined(spec.undirected) ? true : spec.undirected,
                directed = _.isUndefined(spec.directed) ? true : spec.directed,
                source = spec.source,
                target = spec.target;

            delete spec.undirected;
            delete spec.directed;
            delete spec.source;
            delete spec.target;

            return $.when(this.findLinksImpl(spec, source, target, undirected, directed)).then(_.partial(_.map, _, this.addAccessor, this));
        };

        this.findLink = function (spec) {
            return $.when(this.findLinksImpl(spec)).then(_.bind(function (results) {
                if (_.isEmpty(results)) {
                    return undefined;
                }

                return this.addAccessor(results[0]);
            }, this));
        };

        this.findLinkByKey = function (key) {
            return this.findLink({
                key: key
            });
        };

        this.getNeighborLinks = function (node, opts) {
            var reqs = [];

            opts = opts || {};
            _.each(["outgoing", "incoming", "undirected"], function (mode) {
                opts[mode] = _.isUndefined(opts[mode]) ? true : opts[mode];
            });

            if (opts.outgoing) {
                reqs.push(this.findLinks({
                    source: node.key(),
                    undirected: false
                }));
            }

            if (opts.incoming) {
                reqs.push(this.findLinks({
                    target: node.key(),
                    undirected: false
                }));
            }

            if (opts.undirected) {
                reqs.push(this.findLinks({
                    source: node.key(),
                    undirected: true
                }));

                reqs.push(this.findLinks({
                    target: node.key(),
                    undirected: true
                }));
            }

            return $.when.apply($, reqs).then(function () {
                return _.reduce(_.toArray(arguments), function (memo, item) {
                    return memo.concat(item);
                }, []);
            });
        };

        this.getOutgoingLinks = function (node) {
            return this.getNeighborLinks(node, {
                outgoing: true,
                incoming: false,
                undirected: false
            });
        };

        this.getOutflowingLinks = function (node) {
            return this.getNeighborLinks(node, {
                outgoing: true,
                incoming: false,
                undirected: true
            });
        };

        this.getIncomingLinks = function (node) {
            return this.getNeighborLinks(node, {
                outgoing: false,
                incoming: true,
                undirected: false
            });
        };

        this.getInflowingLinks = function (node) {
            return this.getNeighborLinks(node, {
                outgoing: false,
                incoming: true,
                undirected: true
            });
        };

        this.getUndirectedLinks = function (node) {
            return this.getNeighborLinks(node, {
                outgoing: false,
                incoming: false,
                undirected: true
            });
        };

        this.getDirectedLinks = function (node) {
            return this.getNeighborLinks(node, {
                outgoing: true,
                incoming: true,
                undirected: false
            });
        };

        this.getNeighbors = function (node, opts) {
            var key = node.key(),
                links;

            return this.getNeighborLinks(node, opts).then(_.bind(function (links_) {
                var neighborKeys,
                    muts;

                links = links_;

                neighborKeys = _.map(links, function (link) {
                    return key === link.source() ? link.target() : link.source();
                });

                // Attempt to retrieve the accessors.  The ones we don't have
                // yet will show up as undefined in this array.
                muts = _.map(neighborKeys, this.getAccessor, this);

                _.each(muts, function (mut, i) {
                    if (_.isUndefined(mut)) {
                        muts[i] = this.findNodeByKey(neighborKeys[i]);
                    } else {
                        muts[i] = $.when(muts[i]);
                    }
                }, this);

                return $.when.apply($, muts);
            }, this)).then(function () {
                return {
                    nodes: _.toArray(arguments),
                    links: links
                };
            });
        };

        this.getOutgoingNeighbors = function (node) {
            return this.getNeighbors(node, {
                outgoing: true,
                incoming: false,
                undirected: false
            });
        };

        this.getOutflowingNeighbors = function (node) {
            return this.getNeighbors(node, {
                outgoing: true,
                incoming: false,
                undirected: true
            });
        };

        this.getIncomingNeighbors = function (node) {
            return this.getNeighbors(node, {
                outgoing: false,
                incoming: true,
                undirected: false
            });
        };

        this.getInflowingNeighbors = function (node) {
            return this.getNeighbors(node, {
                outgoing: false,
                incoming: true,
                undirected: true
            });
        };

        this.getUndirectedNeighbors = function (node) {
            return this.getNeighbors(node, {
                outgoing: false,
                incoming: false,
                undirected: true
            });
        };

        this.getDirectedNeighbors = function (node) {
            return this.getNeighbors(node, {
                outgoing: true,
                incoming: true,
                undirected: false
            });
        };

        this.createNode = function (data) {
            return $.when(this.createNodeImpl(data || {}))
                .then(_.bind(this.addAccessor, this));
        };

        this.createLink = function (source, target, _data, undirected) {
            var data;

            // If source/target is a accessor, call its key method to get the
            // key; otherwise, assume it is a string describing the key already.
            source = _.result(source, "key", source);
            target = _.result(target, "key", target);

            data = _data || {};
            undirected = _.isUndefined(undirected) ? false : undirected;

            return $.when(this.createLinkImpl(source, target, data, undirected))
                .then(_.bind(this.addAccessor, this));
        };

        this.destroyNode = function (node) {
            var key = node.key();
            return this.destroyNodeImpl(key).then(function (response) {
                return {
                    key: key,
                    response: response
                };
            });
        };

        this.destroyLink = function (link) {
            var key = link.key();
            return this.destroyLinkImpl(key).then(function (response) {
                return {
                    key: key,
                    response: response
                };
            });
        };

        options = options || {};
        this.initialize.apply(this, arguments);
    };

    clique.Adapter.extend = Backbone.Model.extend;

    clique.adapter.NodeLinkList = clique.Adapter.extend({
        initialize: function (options) {
            var table = {};

            this.nodes = clique.util.deepCopy(options.nodes);
            this.links = clique.util.deepCopy(options.links);

            _.each(this.nodes, function (node, i) {
                var tmpNs = "datax",
                    ns;

                // Promote the data elements into a dedicated namespace.
                //
                // First figure out a suitable temporary name to use for the
                // namespace.
                while (_.has(node, tmpNs)) {
                    tmpNs += "x";
                }

                // Create the namespace.
                ns = node[tmpNs] = {};

                // Move all top-level properties into the namespace.
                _.each(node, function (v, k) {
                    if (k !== tmpNs) {
                        ns[k] = v;
                        delete node[k];
                    }
                });

                // Rename the temporary namespace as "data".
                if (tmpNs !== "data") {
                    node.data = ns;
                    delete node[tmpNs];
                }

                table[i] = node;

                // Assign a unique key to this node.
                node.key = _.uniqueId("node_");
            });

            _.each(this.links, function (link) {
                link.key = _.uniqueId("link_");

                link.source = table[link.source];
                link.target = table[link.target];
            }, this);
        },

        findNodesImpl: function (_spec) {
            var spec = clique.util.deepCopy(_spec),
                searchspace = this.nodes,
                result;

            if (spec.key) {
                searchspace = _.filter(searchspace, function (node) {
                    return node.key === spec.key;
                });

                delete spec.key;
            }

            result = _.filter(searchspace, function (node) {
                return _.isMatch(node.data, spec);
            });

            return result;
        },

        findLinksImpl: function (spec, source, target, undirected, directed) {
            return _.filter(this.links, function (link) {
                var undirectedMatch = (link.undirected || false) === undirected,
                    directedMatch = (_.isUndefined(link.undirected) || !link.undirected) === directed,
                    sourceMatch = _.isUndefined(source) || (link.source.key === source),
                    targetMatch = _.isUndefined(target) || (link.target.key === target),
                    dataMatch = _.isMatch(spec, link.data);

                return _.every([sourceMatch, targetMatch, dataMatch, undirectedMatch || directedMatch]);
            });
        },

        newNode: _.noop,
        newLink: _.noop,
        destroyNode: _.noop,
        destroyLink: _.noop
    });
}(window.clique, window._, window.Backbone, window.jQuery));
<|endoftext|>


<commit_before>module.exports = function(grunt) {

  grunt.initConfig({

    pkg: grunt.file.readJSON('package.json'),
    banner: '/*!\n' +
            ' * <%= pkg.name %> v<%= pkg.version %> (<%= pkg.homepage %>)\n' +
            ' * Copyright 2014-<%= grunt.template.today("yyyy") %> <%= pkg.author %>\n' +
            ' * Licensed under <%= pkg.license.type %> (<%= pkg.license.url %>)\n' +
            ' */\n\n',

  // Clean Distribution folder
    clean: {
      dist: 'dist',
      distDemo: 'demo/dist'
    },

    jshint: {

      ignore_warning:{
        options: {
        '-W099': true,
        },
        src: 'js/*.js'
      },

      options: {

          globals: {
              "curly": true,
              "eqnull": true,
              "eqeqeq": true,
              "undef": true,
              "globals": {
                    "jQuery": true
                }
          }
        }
    },

    concat: {
      aria: {
        src: [
          'js/aria.js',
          'js/**/*.js',
          'js/config.js' // this needs to be the last item in this list
        ],
        dest: 'dist/js/<%= pkg.name %>.js'
      }
    },

    uglify: {
      options: {
        banner: '<%= banner %>',
        mangle: true
      },
      dist: {
        src: 'dist/js/<%= pkg.name %>.js',
        dest: 'dist/js/<%= pkg.name %>.min.js'
      },
    },

    less: {
      compileCore: {
        options: {
          strictMath: true,
          sourceMap: true,
          outputSourceFiles: true,
          sourceMapURL: '<%= pkg.name %>.css.map',
          sourceMapFilename: 'demo/dist/css/<%= pkg.name %>.css.map'
        },
        src: 'demo/less/base.less',
        dest: 'demo/dist/css/<%= pkg.name %>.css'
      }
    },

    csslint: {
      options: {
        csslintrc: 'demo/.csslintrc'
      },
      dist: [
        'demo/dist/css/<%= pkg.name %>.css'
      ]
    },

    cssmin: {
      options: {
        compatibility: 'ie8',
        keepSpecialComments: '*',
        advanced: false
      },
      minifyCore: {
        src: 'demo/dist/css/<%= pkg.name %>.css',
        dest: 'demo/dist/css/<%= pkg.name %>.min.css'
      }
    },

    watch: {
        grunt: { files: ['Gruntfile.js'] },
        js: {
            files: 'js/*.js',
            tasks: ['default']
        },
        less: {
            files: 'demo/less/**/*.less',
            tasks: ['default']
        },
        demo: { files: 'demo/*' },
        options: {
            livereload: true
        }
    },

    connect: {
      server: {
        options: {
            hostname: 'localhost',
            port: 8083,
            base: '.',
            keepalive: true,
            open: true
        }
      }
    }

  });

grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-uglify');

grunt.loadNpmTasks('grunt-contrib-csslint');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-less');

grunt.registerTask('default', ['clean', 'jshint', 'less', 'csslint', 'cssmin', 'concat', 'uglify']);

grunt.registerTask('dev',['connect:server']);

};
<commit_msg>updating watch to include subfolder wildcard for *.js<commit_after>module.exports = function(grunt) {

  grunt.initConfig({

    pkg: grunt.file.readJSON('package.json'),
    banner: '/*!\n' +
            ' * <%= pkg.name %> v<%= pkg.version %> (<%= pkg.homepage %>)\n' +
            ' * Copyright 2014-<%= grunt.template.today("yyyy") %> <%= pkg.author %>\n' +
            ' * Licensed under <%= pkg.license.type %> (<%= pkg.license.url %>)\n' +
            ' */\n\n',

  // Clean Distribution folder
    clean: {
      dist: 'dist',
      distDemo: 'demo/dist'
    },

    jshint: {

      ignore_warning:{
        options: {
        '-W099': true,
        },
        src: 'js/**/*.js'
      },

      options: {

          globals: {
              "curly": true,
              "eqnull": true,
              "eqeqeq": true,
              "undef": true,
              "globals": {
                    "jQuery": true
                }
          }
        }
    },

    concat: {
      aria: {
        src: [
          'js/aria.js',
          'js/**/*.js',
          'js/config.js' // this needs to be the last item in this list
        ],
        dest: 'dist/js/<%= pkg.name %>.js'
      }
    },

    uglify: {
      options: {
        banner: '<%= banner %>',
        mangle: true
      },
      dist: {
        src: 'dist/js/<%= pkg.name %>.js',
        dest: 'dist/js/<%= pkg.name %>.min.js'
      },
    },

    less: {
      compileCore: {
        options: {
          strictMath: true,
          sourceMap: true,
          outputSourceFiles: true,
          sourceMapURL: '<%= pkg.name %>.css.map',
          sourceMapFilename: 'demo/dist/css/<%= pkg.name %>.css.map'
        },
        src: 'demo/less/base.less',
        dest: 'demo/dist/css/<%= pkg.name %>.css'
      }
    },

    csslint: {
      options: {
        csslintrc: 'demo/.csslintrc'
      },
      dist: [
        'demo/dist/css/<%= pkg.name %>.css'
      ]
    },

    cssmin: {
      options: {
        compatibility: 'ie8',
        keepSpecialComments: '*',
        advanced: false
      },
      minifyCore: {
        src: 'demo/dist/css/<%= pkg.name %>.css',
        dest: 'demo/dist/css/<%= pkg.name %>.min.css'
      }
    },

    watch: {
        grunt: { files: ['Gruntfile.js'] },
        js: {
            files: 'js/**/*.js',
            tasks: ['default']
        },
        less: {
            files: 'demo/less/**/*.less',
            tasks: ['default']
        },
        demo: { files: 'demo/*' },
        options: {
            livereload: true
        }
    },

    connect: {
      server: {
        options: {
            hostname: 'localhost',
            port: 8083,
            base: '.',
            keepalive: true,
            open: true
        }
      }
    }

  });

grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-uglify');

grunt.loadNpmTasks('grunt-contrib-csslint');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-less');

grunt.registerTask('default', ['clean', 'jshint', 'less', 'csslint', 'cssmin', 'concat', 'uglify']);

grunt.registerTask('dev',['connect:server']);

};
<|endoftext|>


<commit_before>// 20: spread - with-arrays
// To do: make all tests pass, leave the assert lines unchanged!
// Follow the hints of the failure messages!

describe('spread with arrays', () => {

  it('extracts each array item', function() {
    const [b, a] = [...[1, 2]];
    assert.equal(a, 1);
    assert.equal(b, 2);
  });

  it('in combination with rest', function() {
    const [a, b, ...rest] = [...[0, 1, 2, 3, 4, 5]];
    assert.equal(a, 1);
    assert.equal(b, 2);
    assert.deepEqual(rest, [3, 4, 5]);
  });

  it('spreading into the rest', function() {
    const [...rest] = [...[,1, 2, 3, 4, 5]];
    assert.deepEqual(rest, [1, 2, 3, 4, 5]);
  });

  describe('used as function parameter', () => {
    it('prefix with `...` to spread as function params', function() {
      const magicNumbers = [1, 2];
      const fn = (magicA, magicB) => {
        assert.deepEqual(magicNumbers[0], magicA);
        assert.deepEqual(magicNumbers[1], magicB);
      };
      fn(magicNumbers);
    });

    it('pass an array of numbers to Math.max()', function() {
      const max = Math.max(...[23, 0, 42, 43]);
      assert.equal(max, 42);
    });
  });
});
<commit_msg>Adhere ADR#1.<commit_after>// 20: spread - with-arrays
// To do: make all tests pass, leave the assert lines unchanged!
// Follow the hints of the failure messages!

describe('Spread with arrays', () => {
  it('extracts each array item', function() {
    const [b, a] = [...[1, 2]];
    assert.equal(a, 1);
    assert.equal(b, 2);
  });
  it('in combination with rest', function() {
    const [a, b, ...rest] = [...[0, 1, 2, 3, 4, 5]];
    assert.equal(a, 1);
    assert.equal(b, 2);
    assert.deepEqual(rest, [3, 4, 5]);
  });
  it('spreading into the rest', function() {
    const [...rest] = [...[,1, 2, 3, 4, 5]];
    assert.deepEqual(rest, [1, 2, 3, 4, 5]);
  });
  describe('used as function parameter', () => {
    it('prefix with `...` to spread as function params', function() {
      const magicNumbers = [1, 2];
      const fn = (magicA, magicB) => {
        assert.deepEqual(magicNumbers[0], magicA);
        assert.deepEqual(magicNumbers[1], magicB);
      };
      fn(magicNumbers);
    });
    it('pass an array of numbers to Math.max()', function() {
      const max = Math.max(...[23, 0, 42, 43]);
      assert.equal(max, 42);
    });
  });
});
<|endoftext|>


<commit_before>/**
 * The Image map layer module.
 *
 * @return WMSLayer class (extends Class).
 */
define([
  'underscore',
  'amplify',
  'uri',
  'abstract/layer/OverlayLayerClass',
  'map/views/layers/CustomInfowindow',

], function(_, amplify, UriTemplate, OverlayLayerClass, CustomInfowindow) {

  'use strict';

  function bound(value, opt_min, opt_max) {
      if (opt_min != null) value = Math.max(value, opt_min);
      if (opt_max != null) value = Math.min(value, opt_max);
      return value;
  }

  function degreesToRadians(deg) {
      return deg * (Math.PI / 180);
  }

  function radiansToDegrees(rad) {
      return rad / (Math.PI / 180);
  }

  function MercatorProjection() {
      var MERCATOR_RANGE = 256;
      this.pixelOrigin_ = new google.maps.Point(
          MERCATOR_RANGE / 2, MERCATOR_RANGE / 2);
      this.pixelsPerLonDegree_ = MERCATOR_RANGE / 360;
      this.pixelsPerLonRadian_ = MERCATOR_RANGE / (2 * Math.PI);
  };

  MercatorProjection.prototype.fromLatLngToPoint = function(latLng, opt_point) {
      var me = this;

      var point = opt_point || new google.maps.Point(0, 0);

      var origin = me.pixelOrigin_;
      point.x = origin.x + latLng.lng() * me.pixelsPerLonDegree_;
      // NOTE(appleton): Truncating to 0.9999 effectively limits latitude to
      // 89.189.  This is about a third of a tile past the edge of the world tile.
      var siny = bound(Math.sin(degreesToRadians(latLng.lat())), -0.9999, 0.9999);
      point.y = origin.y + 0.5 * Math.log((1 + siny) / (1 - siny)) * -me.pixelsPerLonRadian_;
      return point;
  };

  MercatorProjection.prototype.fromDivPixelToLatLng = function(pixel, zoom) {
      var me = this;

      var origin = me.pixelOrigin_;
      var scale = Math.pow(2, zoom);
      var lng = (pixel.x / scale - origin.x) / me.pixelsPerLonDegree_;
      var latRadians = (pixel.y / scale - origin.y) / -me.pixelsPerLonRadian_;
      var lat = radiansToDegrees(2 * Math.atan(Math.exp(latRadians)) - Math.PI / 2);
      return new google.maps.LatLng(lat, lng);
  };

  MercatorProjection.prototype.fromDivPixelToSphericalMercator = function(pixel, zoom) {
      var me = this;
      var coord = me.fromDivPixelToLatLng(pixel, zoom);

      var r= 6378137.0;
      var x = r* degreesToRadians(coord.lng());
      var latRad = degreesToRadians(coord.lat());
      var y = (r/2) * Math.log((1+Math.sin(latRad))/ (1-Math.sin(latRad)));

      return new google.maps.Point(x,y);
  };

  var WMSLayerClass = OverlayLayerClass.extend({

    init: function(layer, options, map) {
      this.map = map;
      this.url = this.options.url;
      this.tiles = layer.tileurl;
      this._super(layer, options, map);
      this._setImageMapType(layer);
    },

    _getLayer: function() {
      var deferred = new $.Deferred();
      deferred.resolve(this._imageMaptype);
      return deferred.promise();
    },

    _setImageMapType: function(layer) {
      this._imageMaptype = new google.maps.ImageMapType({
        getTileUrl: _.bind(this._getTileUrl,this),
        tileSize: this.tileSize,
        name: this.name,
        url: this.tiles
      });
      this.addClick();
    },

    _getTileUrl: function(coord, zoom) {
      var lULP = new google.maps.Point(coord.x*256,(coord.y+1)*256);
      var lLRP = new google.maps.Point((coord.x+1)*256,coord.y*256);
      var projectionMap = new MercatorProjection();

      var lULg = projectionMap.fromDivPixelToSphericalMercator(lULP, zoom);
      var lLRg  = projectionMap.fromDivPixelToSphericalMercator(lLRP, zoom);

      var lUL_Latitude = lULg.y;
      var lUL_Longitude = lULg.x;
      var lLR_Latitude = lLRg.y;
      var lLR_Longitude = lLRg.x;
      //GJ: there is a bug when crossing the -180 longitude border (tile does not render) - this check seems to fix it
      if (lLR_Longitude < lUL_Longitude) {
        lLR_Longitude = Math.abs(lLR_Longitude);
      }
      var url = this.url;
      url += "&BBOX=" + lUL_Longitude + "," + lUL_Latitude + "," + lLR_Longitude + "," + lLR_Latitude; // set bounding box
      return url;
    },

    addClick: function() {
      google.maps.event.addListener(this.map, "click", _.bind(function(event) {
        var projectionMap = new MercatorProjection();
        this.location = {
          zoom: this.map.getZoom(),
          latlng: event.latLng,
          point: projectionMap.fromLatLngToPoint(event.latLng),
          setBounds: function() {
            this.boundL = new google.maps.LatLng(this.latlng.lat()-0.1, this.latlng.lng()-0.1);
            this.boundR = new google.maps.LatLng(this.latlng.lat()+0.1, this.latlng.lng()+0.1);
          },
          setBBox: function() {
            this.bbox = this.boundL.lng() + "," + this.boundL.lat() + "," + this.boundR.lng() + "," + this.boundR.lat();
          },
        }
        this.location.setBounds();
        this.location.setBBox();
        this.location.infowindowUrl = this.getQuery(this.location.latlng.K,this.location.latlng.G);

        $.get(this.location.infowindowUrl).done(_.bind(function(data) {
          if(this.infowindow) {
            this.infowindow.remove();
          }
          var data = JSON.parse(data);
          if (!!data.features[0]) {
            var infoWindowOptions = {
              offset: [0, 100],
              infowindowData: {
                name: data.features[0].attributes['tis.nombre']|| data.features[0].attributes['nombre'],
                country: data.features[0].attributes['tis.pais']|| data.features[0].attributes['pais'],
                status: data.features[0].attributes['tis.leyenda']|| data.features[0].attributes['situacion'],
                date_create: data.features[0].attributes['tis.fecha_norma'],
                area_ha: data.features[0].attributes['tis.area_oficial_ha']|| data.features[0].attributes['area_oficial_ha'],
                category:data.features[0].attributes['tis.categoria'],
                source: data.features[0].attributes['tis.fuente'],
                company: data.features[0].attributes['cia'],
                substance: data.features[0].attributes['tipo_minerio'],
              }
            }
            this.infowindow = new CustomInfowindow(this.location.latlng, this.map, infoWindowOptions);
          }
        }, this ));

      }, this ));

    },

  });
  return WMSLayerClass;
});
<commit_msg>Infowindows bulletproof.<commit_after>/**
 * The Image map layer module.
 *
 * @return WMSLayer class (extends Class).
 */
define([
  'underscore',
  'amplify',
  'uri',
  'abstract/layer/OverlayLayerClass',
  'map/views/layers/CustomInfowindow',

], function(_, amplify, UriTemplate, OverlayLayerClass, CustomInfowindow) {

  'use strict';

  function bound(value, opt_min, opt_max) {
      if (opt_min != null) value = Math.max(value, opt_min);
      if (opt_max != null) value = Math.min(value, opt_max);
      return value;
  }

  function degreesToRadians(deg) {
      return deg * (Math.PI / 180);
  }

  function radiansToDegrees(rad) {
      return rad / (Math.PI / 180);
  }

  function MercatorProjection() {
      var MERCATOR_RANGE = 256;
      this.pixelOrigin_ = new google.maps.Point(
          MERCATOR_RANGE / 2, MERCATOR_RANGE / 2);
      this.pixelsPerLonDegree_ = MERCATOR_RANGE / 360;
      this.pixelsPerLonRadian_ = MERCATOR_RANGE / (2 * Math.PI);
  };

  MercatorProjection.prototype.fromLatLngToPoint = function(latLng, opt_point) {
      var me = this;

      var point = opt_point || new google.maps.Point(0, 0);

      var origin = me.pixelOrigin_;
      point.x = origin.x + latLng.lng() * me.pixelsPerLonDegree_;
      // NOTE(appleton): Truncating to 0.9999 effectively limits latitude to
      // 89.189.  This is about a third of a tile past the edge of the world tile.
      var siny = bound(Math.sin(degreesToRadians(latLng.lat())), -0.9999, 0.9999);
      point.y = origin.y + 0.5 * Math.log((1 + siny) / (1 - siny)) * -me.pixelsPerLonRadian_;
      return point;
  };

  MercatorProjection.prototype.fromDivPixelToLatLng = function(pixel, zoom) {
      var me = this;

      var origin = me.pixelOrigin_;
      var scale = Math.pow(2, zoom);
      var lng = (pixel.x / scale - origin.x) / me.pixelsPerLonDegree_;
      var latRadians = (pixel.y / scale - origin.y) / -me.pixelsPerLonRadian_;
      var lat = radiansToDegrees(2 * Math.atan(Math.exp(latRadians)) - Math.PI / 2);
      return new google.maps.LatLng(lat, lng);
  };

  MercatorProjection.prototype.fromDivPixelToSphericalMercator = function(pixel, zoom) {
      var me = this;
      var coord = me.fromDivPixelToLatLng(pixel, zoom);

      var r= 6378137.0;
      var x = r* degreesToRadians(coord.lng());
      var latRad = degreesToRadians(coord.lat());
      var y = (r/2) * Math.log((1+Math.sin(latRad))/ (1-Math.sin(latRad)));

      return new google.maps.Point(x,y);
  };

  var WMSLayerClass = OverlayLayerClass.extend({

    init: function(layer, options, map) {
      this.map = map;
      this.url = this.options.url;
      this.tiles = layer.tileurl;
      this._super(layer, options, map);
      this._setImageMapType(layer);
    },

    _getLayer: function() {
      var deferred = new $.Deferred();
      deferred.resolve(this._imageMaptype);
      return deferred.promise();
    },

    _setImageMapType: function(layer) {
      this._imageMaptype = new google.maps.ImageMapType({
        getTileUrl: _.bind(this._getTileUrl,this),
        tileSize: this.tileSize,
        name: this.name,
        url: this.tiles
      });
      this.addClick();
    },

    _getTileUrl: function(coord, zoom) {
      var lULP = new google.maps.Point(coord.x*256,(coord.y+1)*256);
      var lLRP = new google.maps.Point((coord.x+1)*256,coord.y*256);
      var projectionMap = new MercatorProjection();

      var lULg = projectionMap.fromDivPixelToSphericalMercator(lULP, zoom);
      var lLRg  = projectionMap.fromDivPixelToSphericalMercator(lLRP, zoom);

      var lUL_Latitude = lULg.y;
      var lUL_Longitude = lULg.x;
      var lLR_Latitude = lLRg.y;
      var lLR_Longitude = lLRg.x;
      //GJ: there is a bug when crossing the -180 longitude border (tile does not render) - this check seems to fix it
      if (lLR_Longitude < lUL_Longitude) {
        lLR_Longitude = Math.abs(lLR_Longitude);
      }
      var url = this.url;
      url += "&BBOX=" + lUL_Longitude + "," + lUL_Latitude + "," + lLR_Longitude + "," + lLR_Latitude; // set bounding box
      return url;
    },

    addClick: function() {
      google.maps.event.addListener(this.map, "click", _.bind(function(event) {
        var projectionMap = new MercatorProjection();
        this.location = {
          zoom: this.map.getZoom(),
          latlng: event.latLng,
          point: projectionMap.fromLatLngToPoint(event.latLng),
          setBounds: function() {
            this.boundL = new google.maps.LatLng(this.latlng.lat()-0.1, this.latlng.lng()-0.1);
            this.boundR = new google.maps.LatLng(this.latlng.lat()+0.1, this.latlng.lng()+0.1);
          },
          setBBox: function() {
            this.bbox = this.boundL.lng() + "," + this.boundL.lat() + "," + this.boundR.lng() + "," + this.boundR.lat();
          },
        }
        this.location.setBounds();
        this.location.setBBox();
        this.location.infowindowUrl = this.getQuery(this.location.latlng.lng(),this.location.latlng.lat());

        $.get(this.location.infowindowUrl).done(_.bind(function(data) {
          if(this.infowindow) {
            this.infowindow.remove();
          }
          var data = JSON.parse(data);
          if (!!data && !!data.features && !!data.features[0]) {
            var infoWindowOptions = {
              offset: [0, 100],
              infowindowData: {
                name: data.features[0].attributes['tis.nombre']|| data.features[0].attributes['nombre'],
                country: data.features[0].attributes['tis.pais']|| data.features[0].attributes['pais'],
                status: data.features[0].attributes['tis.leyenda']|| data.features[0].attributes['situacion'],
                date_create: data.features[0].attributes['tis.fecha_norma'],
                area_ha: data.features[0].attributes['tis.area_oficial_ha']|| data.features[0].attributes['area_oficial_ha'],
                category:data.features[0].attributes['tis.categoria'],
                source: data.features[0].attributes['tis.fuente'],
                company: data.features[0].attributes['cia'],
                substance: data.features[0].attributes['tipo_minerio'],
              }
            }
            this.infowindow = new CustomInfowindow(this.location.latlng, this.map, infoWindowOptions);
          }
        }, this ));

      }, this ));

    },

  });
  return WMSLayerClass;
});
<|endoftext|>


<commit_before>/**
 * The Image map layer module.
 *
 * @return WMSLayer class (extends Class).
 */
define([
  'underscore',
  'amplify',
  'uri',
  'abstract/layer/OverlayLayerClass',
  'map/views/layers/CustomInfowindow',

], function(_, amplify, UriTemplate, OverlayLayerClass, CustomInfowindow) {

  'use strict';

  function bound(value, opt_min, opt_max) {
      if (opt_min != null) value = Math.max(value, opt_min);
      if (opt_max != null) value = Math.min(value, opt_max);
      return value;
  }

  function degreesToRadians(deg) {
      return deg * (Math.PI / 180);
  }

  function radiansToDegrees(rad) {
      return rad / (Math.PI / 180);
  }

  function MercatorProjection() {
      var MERCATOR_RANGE = 256;
      this.pixelOrigin_ = new google.maps.Point(
          MERCATOR_RANGE / 2, MERCATOR_RANGE / 2);
      this.pixelsPerLonDegree_ = MERCATOR_RANGE / 360;
      this.pixelsPerLonRadian_ = MERCATOR_RANGE / (2 * Math.PI);
  };

  MercatorProjection.prototype.fromLatLngToPoint = function(latLng, opt_point) {
      var me = this;

      var point = opt_point || new google.maps.Point(0, 0);

      var origin = me.pixelOrigin_;
      point.x = origin.x + latLng.lng() * me.pixelsPerLonDegree_;
      // NOTE(appleton): Truncating to 0.9999 effectively limits latitude to
      // 89.189.  This is about a third of a tile past the edge of the world tile.
      var siny = bound(Math.sin(degreesToRadians(latLng.lat())), -0.9999, 0.9999);
      point.y = origin.y + 0.5 * Math.log((1 + siny) / (1 - siny)) * -me.pixelsPerLonRadian_;
      return point;
  };

  MercatorProjection.prototype.fromDivPixelToLatLng = function(pixel, zoom) {
      var me = this;

      var origin = me.pixelOrigin_;
      var scale = Math.pow(2, zoom);
      var lng = (pixel.x / scale - origin.x) / me.pixelsPerLonDegree_;
      var latRadians = (pixel.y / scale - origin.y) / -me.pixelsPerLonRadian_;
      var lat = radiansToDegrees(2 * Math.atan(Math.exp(latRadians)) - Math.PI / 2);
      return new google.maps.LatLng(lat, lng);
  };

  MercatorProjection.prototype.fromDivPixelToSphericalMercator = function(pixel, zoom) {
      var me = this;
      var coord = me.fromDivPixelToLatLng(pixel, zoom);

      var r= 6378137.0;
      var x = r* degreesToRadians(coord.lng());
      var latRad = degreesToRadians(coord.lat());
      var y = (r/2) * Math.log((1+Math.sin(latRad))/ (1-Math.sin(latRad)));

      return new google.maps.Point(x,y);
  };

  var WMSLayerClass = OverlayLayerClass.extend({

    init: function(layer, options, map) {
      this.map = map;
      this.url = this.options.url;
      this.infowindowUrl = this.options.url;
      this.tiles = layer.tileurl;
      this._super(layer, options, map);
      this._setImageMapType(layer);
    },

    _getLayer: function() {
      var deferred = new $.Deferred();
      deferred.resolve(this._imageMaptype);
      return deferred.promise();
    },

    _setImageMapType: function(layer) {
      this._imageMaptype = new google.maps.ImageMapType({
        getTileUrl: _.bind(this._getTileUrl,this),
        tileSize: this.tileSize,
        name: this.name,
        url: this.tiles
      });
      this.addClick();
    },

    _getTileUrl: function(coord, zoom) {
      var lULP = new google.maps.Point(coord.x*256,(coord.y+1)*256);
      var lLRP = new google.maps.Point((coord.x+1)*256,coord.y*256);
      var projectionMap = new MercatorProjection();

      var lULg = projectionMap.fromDivPixelToSphericalMercator(lULP, zoom);
      var lLRg  = projectionMap.fromDivPixelToSphericalMercator(lLRP, zoom);

      var lUL_Latitude = lULg.y;
      var lUL_Longitude = lULg.x;
      var lLR_Latitude = lLRg.y;
      var lLR_Longitude = lLRg.x;
      //GJ: there is a bug when crossing the -180 longitude border (tile does not render) - this check seems to fix it
      if (lLR_Longitude < lUL_Longitude) {
        lLR_Longitude = Math.abs(lLR_Longitude);
      }
      var url = this.url;
      url += "&BBOX=" + lUL_Longitude + "," + lUL_Latitude + "," + lLR_Longitude + "," + lLR_Latitude; // set bounding box
      return url;
    },

    addClick: function() {
      google.maps.event.addListener(this.map, "click", _.bind(function(event) {
        var projectionMap = new MercatorProjection();
        this.location = {
          zoom: this.map.getZoom(),
          latlng: event.latLng,
          point: projectionMap.fromLatLngToPoint(event.latLng),
          setBounds: function() {
            this.boundL = new google.maps.LatLng(this.latlng.lat()-0.1, this.latlng.lng()-0.1);
            this.boundR = new google.maps.LatLng(this.latlng.lat()+0.1, this.latlng.lng()+0.1);
          },
          setBBox: function() {
            this.bbox = this.boundL.lng() + "," + this.boundL.lat() + "," + this.boundR.lng() + "," + this.boundR.lat();
          },
        }
        this.location.setBounds();
        this.location.setBBox();
        this.location.url = this.getQuery(this.location.point.x,this.location.point.y,this.location.bbox);

        $.get(this.infowindowUrl).done(_.bind(function(xml){
          if(this.infowindow) {
            this.infowindow.remove();
          }
          var data = this.xmlToJson(xml);
          var info = data['FeatureInfoResponse']['FIELDS'].attrs;
          var infoWindowOptions = {
            offset: [0, 100],
            infowindowData: {
              name: info['Nombre'],
              country: info['País'],
              area_ha: info['ÁreaOficialha'],
            }
          }
          this.infowindow = new CustomInfowindow(this.location.latlng, this.map, infoWindowOptions);
        }, this ));

        $.ajax({
          type:"GET",
          headers: { 'origin': 'localhost' },
          url: this.infowindowUrl,
          success: function(data) {
            console.log(data)
          }
        });

      }, this ));

    },

    xmlToJson: function(xml) {
      // Create the return object
      var obj = {};

      if (xml.nodeType == 1) { // element
        // do attributes
        if (xml.attributes.length > 0) {
        obj["attrs"] = {};
          for (var j = 0; j < xml.attributes.length; j++) {
            var attribute = xml.attributes.item(j);
            obj["attrs"][attribute.nodeName] = attribute.nodeValue;
          }
        }
      } else if (xml.nodeType == 3) { // text
        obj = xml.nodeValue;
      }

      // do children
      if (xml.hasChildNodes()) {
        for(var i = 0; i < xml.childNodes.length; i++) {
          var item = xml.childNodes.item(i);
          var nodeName = item.nodeName;
          if (typeof(obj[nodeName]) == "undefined") {
            obj[nodeName] = this.xmlToJson(item);
          } else {
            if (typeof(obj[nodeName].push) == "undefined") {
              var old = obj[nodeName];
              obj[nodeName] = [];
              obj[nodeName].push(old);
            }
            obj[nodeName].push(this.xmlToJson(item));
          }
        }
      }
      return obj;
    },

  });
  return WMSLayerClass;
});
<commit_msg>raisg layer format and show infowindow<commit_after>/**
 * The Image map layer module.
 *
 * @return WMSLayer class (extends Class).
 */
define([
  'underscore',
  'amplify',
  'uri',
  'abstract/layer/OverlayLayerClass',
  'map/views/layers/CustomInfowindow',

], function(_, amplify, UriTemplate, OverlayLayerClass, CustomInfowindow) {

  'use strict';

  function bound(value, opt_min, opt_max) {
      if (opt_min != null) value = Math.max(value, opt_min);
      if (opt_max != null) value = Math.min(value, opt_max);
      return value;
  }

  function degreesToRadians(deg) {
      return deg * (Math.PI / 180);
  }

  function radiansToDegrees(rad) {
      return rad / (Math.PI / 180);
  }

  function MercatorProjection() {
      var MERCATOR_RANGE = 256;
      this.pixelOrigin_ = new google.maps.Point(
          MERCATOR_RANGE / 2, MERCATOR_RANGE / 2);
      this.pixelsPerLonDegree_ = MERCATOR_RANGE / 360;
      this.pixelsPerLonRadian_ = MERCATOR_RANGE / (2 * Math.PI);
  };

  MercatorProjection.prototype.fromLatLngToPoint = function(latLng, opt_point) {
      var me = this;

      var point = opt_point || new google.maps.Point(0, 0);

      var origin = me.pixelOrigin_;
      point.x = origin.x + latLng.lng() * me.pixelsPerLonDegree_;
      // NOTE(appleton): Truncating to 0.9999 effectively limits latitude to
      // 89.189.  This is about a third of a tile past the edge of the world tile.
      var siny = bound(Math.sin(degreesToRadians(latLng.lat())), -0.9999, 0.9999);
      point.y = origin.y + 0.5 * Math.log((1 + siny) / (1 - siny)) * -me.pixelsPerLonRadian_;
      return point;
  };

  MercatorProjection.prototype.fromDivPixelToLatLng = function(pixel, zoom) {
      var me = this;

      var origin = me.pixelOrigin_;
      var scale = Math.pow(2, zoom);
      var lng = (pixel.x / scale - origin.x) / me.pixelsPerLonDegree_;
      var latRadians = (pixel.y / scale - origin.y) / -me.pixelsPerLonRadian_;
      var lat = radiansToDegrees(2 * Math.atan(Math.exp(latRadians)) - Math.PI / 2);
      return new google.maps.LatLng(lat, lng);
  };

  MercatorProjection.prototype.fromDivPixelToSphericalMercator = function(pixel, zoom) {
      var me = this;
      var coord = me.fromDivPixelToLatLng(pixel, zoom);

      var r= 6378137.0;
      var x = r* degreesToRadians(coord.lng());
      var latRad = degreesToRadians(coord.lat());
      var y = (r/2) * Math.log((1+Math.sin(latRad))/ (1-Math.sin(latRad)));

      return new google.maps.Point(x,y);
  };

  var WMSLayerClass = OverlayLayerClass.extend({

    init: function(layer, options, map) {
      this.map = map;
      this.url = this.options.url;
      this.tiles = layer.tileurl;
      this._super(layer, options, map);
      this._setImageMapType(layer);
    },

    _getLayer: function() {
      var deferred = new $.Deferred();
      deferred.resolve(this._imageMaptype);
      return deferred.promise();
    },

    _setImageMapType: function(layer) {
      this._imageMaptype = new google.maps.ImageMapType({
        getTileUrl: _.bind(this._getTileUrl,this),
        tileSize: this.tileSize,
        name: this.name,
        url: this.tiles
      });
      this.addClick();
    },

    _getTileUrl: function(coord, zoom) {
      var lULP = new google.maps.Point(coord.x*256,(coord.y+1)*256);
      var lLRP = new google.maps.Point((coord.x+1)*256,coord.y*256);
      var projectionMap = new MercatorProjection();

      var lULg = projectionMap.fromDivPixelToSphericalMercator(lULP, zoom);
      var lLRg  = projectionMap.fromDivPixelToSphericalMercator(lLRP, zoom);

      var lUL_Latitude = lULg.y;
      var lUL_Longitude = lULg.x;
      var lLR_Latitude = lLRg.y;
      var lLR_Longitude = lLRg.x;
      //GJ: there is a bug when crossing the -180 longitude border (tile does not render) - this check seems to fix it
      if (lLR_Longitude < lUL_Longitude) {
        lLR_Longitude = Math.abs(lLR_Longitude);
      }
      var url = this.url;
      url += "&BBOX=" + lUL_Longitude + "," + lUL_Latitude + "," + lLR_Longitude + "," + lLR_Latitude; // set bounding box
      return url;
    },

    addClick: function() {
      google.maps.event.addListener(this.map, "click", _.bind(function(event) {
        var projectionMap = new MercatorProjection();
        this.location = {
          zoom: this.map.getZoom(),
          latlng: event.latLng,
          point: projectionMap.fromLatLngToPoint(event.latLng),
          setBounds: function() {
            this.boundL = new google.maps.LatLng(this.latlng.lat()-0.1, this.latlng.lng()-0.1);
            this.boundR = new google.maps.LatLng(this.latlng.lat()+0.1, this.latlng.lng()+0.1);
          },
          setBBox: function() {
            this.bbox = this.boundL.lng() + "," + this.boundL.lat() + "," + this.boundR.lng() + "," + this.boundR.lat();
          },
        }
        this.location.setBounds();
        this.location.setBBox();
        this.location.infowindowUrl = this.getQuery(this.location.latlng.F,this.location.latlng.A);

        $.get(this.location.infowindowUrl).done(_.bind(function(data) {
          if(this.infowindow) {
            this.infowindow.remove();
          }
          var data = JSON.parse(data);
          var infoWindowOptions = {
            offset: [0, 100],
            infowindowData: {
              name: data.features[0].attributes['tis.nombre'],
              country: data.features[0].attributes['tis.pais'],
              area_ha: data.features[0].attributes['tis.area_oficial_ha'].toLocaleString(),
            }
          }
          this.infowindow = new CustomInfowindow(this.location.latlng, this.map, infoWindowOptions);
        }, this ));

      }, this ));

    },

  });
  return WMSLayerClass;
});
<|endoftext|>


<commit_before>/*
 * This is a referenceable object that can be required by other modules,
 * which has urls written into it at runtime by the Kolibri server.
 */

import setWebpackPublicPath from '../utils/setWebpackPublicPath';
import plugin_data from 'plugin_data';

function generateUrl(baseUrl, url) {
  const base = new URL(baseUrl, window.location.origin);
  const urlObject = new URL(url, base);
  return urlObject.href;
}

const urls = {
  setUp() {
    // Set urls onto this object for export
    // This will add functions for every reversible URL
    // and strings for __staticURL, __mediaURL, and __contentURL
    // this behaviour is defined in kolibri/core/kolibri_plugin.py
    // in the url_tag method of the FrontEndCoreAppAssetHook.
    Object.assign(this, plugin_data.urls);
    setWebpackPublicPath(this);
  },
  static(url) {
    if (!this.__staticURL) {
      throw new ReferenceError('Static URL is not defined');
    }
    const base = new URL(this.__staticURL, window.location.origin);
    const urlObject = new URL(url, base);
    return urlObject.href;
  },
  media(url) {
    if (!this.__mediaURL) {
      throw new ReferenceError('Media URL is not defined');
    }
    const base = new URL(this.__mediaURL, window.location.origin);
    const urlObject = new URL(url, base);
    return urlObject.href;
  },
  storageUrl(fileId, extension, embeddedFilePath = '') {
    const filename = `${fileId}.${extension}`;
    if (['perseus', 'zip', 'h5p'].includes(extension)) {
      return this['kolibri:core:zipcontent'](filename, embeddedFilePath);
    }
    return generateUrl(this.__contentURL, `${filename[0]}/${filename[1]}/${filename}`);
  },
};

export default urls;
<commit_msg>Correct Url value typos.<commit_after>/*
 * This is a referenceable object that can be required by other modules,
 * which has urls written into it at runtime by the Kolibri server.
 */

import setWebpackPublicPath from '../utils/setWebpackPublicPath';
import plugin_data from 'plugin_data';

function generateUrl(baseUrl, url) {
  const base = new URL(baseUrl, window.location.origin);
  const urlObject = new URL(url, base);
  return urlObject.href;
}

const urls = {
  setUp() {
    // Set urls onto this object for export
    // This will add functions for every reversible URL
    // and strings for __staticURL, __mediaURL, and __contentURL
    // this behaviour is defined in kolibri/core/kolibri_plugin.py
    // in the url_tag method of the FrontEndCoreAppAssetHook.
    Object.assign(this, plugin_data.urls);
    setWebpackPublicPath(this);
  },
  static(url) {
    if (!this.__staticUrl) {
      throw new ReferenceError('Static Url is not defined');
    }
    const base = new URL(this.__staticUrl, window.location.origin);
    const urlObject = new URL(url, base);
    return urlObject.href;
  },
  media(url) {
    if (!this.__mediaUrl) {
      throw new ReferenceError('Media Url is not defined');
    }
    const base = new URL(this.__mediaUrl, window.location.origin);
    const urlObject = new URL(url, base);
    return urlObject.href;
  },
  storageUrl(fileId, extension, embeddedFilePath = '') {
    const filename = `${fileId}.${extension}`;
    if (['perseus', 'zip', 'h5p'].includes(extension)) {
      return this['kolibri:core:zipcontent'](filename, embeddedFilePath);
    }
    return generateUrl(this.__contentUrl, `${filename[0]}/${filename[1]}/${filename}`);
  },
};

export default urls;
<|endoftext|>


<commit_before>//===========================================================================
//    Copyright 2014 Delving B.V.
//
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
//===========================================================================

define(["angular"], function (angular) {
    "use strict";

    var mod = angular.module("common.directives.scrollable", []);

    mod.directive("scrollable", ["$window", "$timeout", function($window, $timeout) {
        return {
            restrict: 'E,A',
            replace: false,
            scope: true,
            link: function($scope, $element, $attrs){
                $timeout(function(){
                    var offset = $attrs.offset,
                        height = $attrs.fixedHeight;
                    $scope.elHeight = null;
                    function initialize () {
                        if(!height){
                            $scope.elHeight = $window.innerHeight - offset;
                        }
                        else {
                            $scope.elHeight = height;
                        }
                    }
                    initialize();
                    return angular.element($window).bind('resize', function() {
                        initialize();
                        return $scope.$apply();
                    });
                },500,true);
            }
        }
    }]);

    return mod;
});

<commit_msg>remove timeout and set element height css directly in link function instead of passing to scope which no longer seems to work<commit_after>//===========================================================================
//    Copyright 2014 Delving B.V.
//
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
//===========================================================================

define(["angular"], function (angular) {
    "use strict";

    var mod = angular.module("common.directives.scrollable", []);

    mod.directive("scrollable", ["$window", "$timeout", function($window, $timeout) {
        return {
            restrict: 'E,A',
            replace: false,
            scope: false,
            link: function($scope, $element, $attrs){
                    var offset = $attrs.offset,
                        attr_fixed_height = $attrs.fixedHeight,
                        container_height = null;
                    function initialize () {
                        if(!attr_fixed_height){
                          container_height = $window.innerHeight - offset;
                        }
                        else {
                          container_height = attr_fixed_height;
                        }
                        // set element height
                        $element.css({
                          height: container_height + "px"
                        });
                    }
                    initialize();
                    return angular.element($window).bind('resize', function() {
                        initialize();
                        return $scope.$apply();
                    });
            }
        }
    }]);

    return mod;
});

<|endoftext|>


<commit_before>function Window(parameters) {

	// @if NODE_ENV='development'
	c.log('[Window] ✔');
	// @endif

	this.id = parameters.id;

	app.commandLine.appendSwitch('enable-webvr');
	app.commandLine.appendSwitch('enable-web-bluetooth');

	if(parameters.url != null) {
		// @if NODE_ENV='development'
		c.log('[Window] Creating with URL: ' + parameters.url);
		// @endif
		this.url = parameters.url;
	}

	this.onFocusCallback = parameters.onFocus;
	this.onCloseCallback = parameters.onClose;

	this.handle = UserManager.getPreferenceByName('show_title_bar');
	this.omnibox = true;
	this.console = false;
	this.windowHelper = false;
	this.isAlwaysOnTop = false;
	this.isFirstLoad = true;

	this.browser = new BrowserWindow({
	  width: UserManager.getPreferenceByName('default_window_width'),
	  height: UserManager.getPreferenceByName('default_window_height'),
	  frame: false,
	  backgroundColor: '#141414',
	  show: false,
	  x: parameters.x ? parameters.x : 890,
	  y: parameters.y ? parameters.y : 660,
	  minWidth: 600,
	  minHeight: 350,
	  darkTheme: true,
	  webPreferences: {
	  	"experimentalFeatures": true,
	  	"experimentalCanvasFeatures": true
	  }
	});

	this.camera = new Camera({
		id: this.id,
		browser: this.browser,
		onRecordingBegin: this.lockDimensions.bind(this),
		onRecordingEnd: this.unlockDimensions.bind(this)
	});

	// @if NODE_ENV='development'
	c.log('[Window] file://' + __dirname + '/src/html/index.html');
	// @endif

	this.attachEvents();
	this.browser.loadURL('file://' + __dirname + '/src/html/index.html' + '#' + this.id);

	// @if NODE_ENV='development'
	this.browser.webContents.openDevTools();
	// @endif
}

Window.prototype.attachEvents = function() {

	this.browser.webContents.on('dom-ready', this.onReady.bind(this));
	this.browser.on('focus', this.onFocus.bind(this));
	this.browser.on('closed', this.onClosed.bind(this));

	ipcMain.on('setOmniboxShow', this.setOmniboxShow.bind(this));
	ipcMain.on('setOmniboxHide', this.setOmniboxHide.bind(this));

	ipcMain.on('onDidFinishFirstLoad', function(e, windowId) {
		if(windowId == this.id) {
			if(this.isFirstLoad) this.isFirstLoad = false;
			this.updateMenus();
		}
	}.bind(this));

	ipcMain.on('is-fullscreen', function(event, id) {
		if(this.id == id) {
			event.returnValue = this.browser.isFullScreen();
		}
	}.bind(this));

	ipcMain.on('setWindowSize', function(e, width, height, windowId) {
		if(this.id == windowId) this.setSize(width, height);
	}.bind(this));

}

Window.prototype.setSize = function(width, height) {

	var currentScreen = electronScreen.getDisplayMatching(this.browser.getBounds());
	var currentPosition = this.browser.getBounds();

	var x = this.browser.getBounds().x;
	var y = this.browser.getBounds().y;

	// If requested dimensions are supperior to current screen,
	// default to work area size
	if(width > currentScreen.workArea.width) {
		width = currentScreen.workArea.width;
		x = currentScreen.workArea.x;
	}
	if(height > currentScreen.workArea.height) {
		height = currentScreen.workArea.height;
		y = currentScreen.workArea.y;
	}

	this.browser.setBounds({
		x: x,
		y: y,
		width: width,
		height: height
	}, true);

	// Ask WindowHelper to update the UI on we're done
	this.browser.webContents.send('update_window_dimensions', this.id);

}

Window.prototype.onReady = function() {

	this.browser.webContents.send('ready');
	if(this.url) this.load(this.url);
	this.browser.show();

}

Window.prototype.onFocus = function() {

	this.onFocusCallback(this);
	this.updateMenus();

}

Window.prototype.close = function() {

	this.browser.close();

}

Window.prototype.onClosed = function() {

	// @if NODE_ENV='development'
	c.log('[Window] Closed');
	// @endif
	// this.camera.abortProcesses();
	CommandManager.unregisterAll(this.browser);
	this.browser = null;
	this.onCloseCallback();

}

Window.prototype.toggleDevTools = function() {

	this.browser.webContents.send('toggleDevTools');

}

Window.prototype.updateMenus = function() {

	CommandManager.setCheckbox('Window', 'Float on Top', this.isAlwaysOnTop);
	CommandManager.setCheckbox('View', 'Title Bar', this.handle);
	CommandManager.setCheckbox('Tools', 'Mini Console', this.console);
	CommandManager.setCheckbox('Tools', 'Window Helper', this.windowHelper && !this.browser.isFullScreen());
	CommandManager.setEnabled('View', 'Toggle Omnibox', !this.isFirstLoad);
	CommandManager.setEnabled('Tools', 'Mini Console', !this.isFirstLoad);
	CommandManager.setEnabled('Tools', 'Toggle Devtools', !this.isFirstLoad);

	if(this.browser) {
		CommandManager.setCheckbox('View', 'Fullscreen', this.browser.isFullScreen());
	}

}

Window.prototype.setOmniboxShow = function() {

	this.omnibox = true;

}

Window.prototype.setOmniboxHide = function() {

	this.omnibox = false;

}

Window.prototype.showOmnibox = function() {

	// @if NODE_ENV='development'
	c.log('[Window] Showing Omnibox');
	// @endif

	this.omnibox = true;
	this.browser.webContents.send('showOmnibox');

}

Window.prototype.hideOmnibox = function() {

	// @if NODE_ENV='development'
	c.log('[Window] Hiding Omnibox');
	// @endif

	this.omnibox = false;
	this.browser.webContents.send('hideOmnibox');

}

Window.prototype.toggleHandle = function() {

	if(this.handle) {
		// @if NODE_ENV='development'
		c.log('[Window] Hiding handle!');
		// @endif
		this.handle = false;
		this.browser.webContents.send('hideHandle');

		if(this.browser.isFullScreen()) {
			var currentScreen = electronScreen.getDisplayMatching(this.browser.getBounds());
			this.browser.setBounds({
				x: 0,
				y: 0,
				width: currentScreen.workArea.width,
				height: currentScreen.workArea.height
			}, false);
		}
		else {
			this.browser.setSize(
				this.browser.getSize()[0],
				this.browser.getSize()[1] - 22 // 22 being the handle's height :(
			);
		}
	}
	else {
		// @if NODE_ENV='development'
		c.log('[Window] Showing handle');
		// @endif
		this.handle = true;
		this.browser.webContents.send('showHandle');

		if(this.browser.isFullScreen()) {
			var currentScreen = electronScreen.getDisplayMatching(this.browser.getBounds());
			this.browser.setBounds({
				x: 0,
				y: 0,
				width: currentScreen.workArea.width,
				height: currentScreen.workArea.height
			}, false);
		}
		else {
			this.browser.setSize(
				this.browser.getSize()[0],
				this.browser.getSize()[1] + 22
			);
		}
	}

	CommandManager.toggleChecked('View', 'Title Bar');

}

Window.prototype.toggleWindowHelper = function() {

		this.windowHelper != this.windowHelper;
		this.browser.webContents.send('toggle_window_helper', this.id);
		CommandManager.toggleChecked('Tools', 'Window Helper');

}

Window.prototype.toggleConsole = function() {

	this.console != this.console;
	this.browser.webContents.send('toggle_mini_console', this.id);
	CommandManager.toggleChecked('Tools', 'Mini Console');

}

Window.prototype.toggleOmnibox = function() {

	// @if NODE_ENV='development'
	c.log('[Window] Toggling Omnibox');
	// @endif
	if(this.omnibox) {
		this.hideOmnibox();
	}
	else {
		this.showOmnibox();
	}

}

Window.prototype.reload = function() {

	this.browser.webContents.send('reload');
}

Window.prototype.reloadIgnoringCache = function() {

	this.browser.webContents.send('reloadIgnoringCache');

}

Window.prototype.load = function(url) {

	this.browser.webContents.send('display-notification', {
		'body' : 'Loading ' + url,
		'lifespan' : 3000,
	});

	this.browser.webContents.send('load', url);

}

Window.prototype.navigateBack = function() {

	this.browser.webContents.send('goBack');
}

Window.prototype.navigateForward = function() {

	this.browser.webContents.send('display-notification', {
		'body' : 'Navigating forward...',
		'lifespan' : 2000,
	});

	this.browser.webContents.send('goForward');
}

Window.prototype.setAlwaysOnTopToggle = function() {

	this.isAlwaysOnTop =! this.isAlwaysOnTop;
	this.browser.setAlwaysOnTop(this.isAlwaysOnTop);
	CommandManager.toggleChecked('Window', 'Float on Top');

}

Window.prototype.lockDimensions = function() {

	this.browser.setResizable(false);

}

Window.prototype.unlockDimensions = function() {

	this.browser.setResizable(true);

}<commit_msg>Use display bound for fullscreen dimensions<commit_after>function Window(parameters) {

	// @if NODE_ENV='development'
	c.log('[Window] ✔');
	// @endif

	this.id = parameters.id;

	app.commandLine.appendSwitch('enable-webvr');
	app.commandLine.appendSwitch('enable-web-bluetooth');

	if(parameters.url != null) {
		// @if NODE_ENV='development'
		c.log('[Window] Creating with URL: ' + parameters.url);
		// @endif
		this.url = parameters.url;
	}

	this.onFocusCallback = parameters.onFocus;
	this.onCloseCallback = parameters.onClose;

	this.handle = UserManager.getPreferenceByName('show_title_bar');
	this.omnibox = true;
	this.console = false;
	this.windowHelper = false;
	this.isAlwaysOnTop = false;
	this.isFirstLoad = true;

	this.browser = new BrowserWindow({
	  width: UserManager.getPreferenceByName('default_window_width'),
	  height: UserManager.getPreferenceByName('default_window_height'),
	  frame: false,
	  backgroundColor: '#141414',
	  show: false,
	  x: parameters.x ? parameters.x : 890,
	  y: parameters.y ? parameters.y : 660,
	  minWidth: 600,
	  minHeight: 350,
	  darkTheme: true,
	  webPreferences: {
	  	"experimentalFeatures": true,
	  	"experimentalCanvasFeatures": true
	  }
	});

	this.camera = new Camera({
		id: this.id,
		browser: this.browser,
		onRecordingBegin: this.lockDimensions.bind(this),
		onRecordingEnd: this.unlockDimensions.bind(this)
	});

	// @if NODE_ENV='development'
	c.log('[Window] file://' + __dirname + '/src/html/index.html');
	// @endif

	this.attachEvents();
	this.browser.loadURL('file://' + __dirname + '/src/html/index.html' + '#' + this.id);

	// @if NODE_ENV='development'
	this.browser.webContents.openDevTools();
	// @endif
}

Window.prototype.attachEvents = function() {

	this.browser.webContents.on('dom-ready', this.onReady.bind(this));
	this.browser.on('focus', this.onFocus.bind(this));
	this.browser.on('closed', this.onClosed.bind(this));

	ipcMain.on('setOmniboxShow', this.setOmniboxShow.bind(this));
	ipcMain.on('setOmniboxHide', this.setOmniboxHide.bind(this));

	ipcMain.on('onDidFinishFirstLoad', function(e, windowId) {
		if(windowId == this.id) {
			if(this.isFirstLoad) this.isFirstLoad = false;
			this.updateMenus();
		}
	}.bind(this));

	ipcMain.on('is-fullscreen', function(event, id) {
		if(this.id == id) {
			event.returnValue = this.browser.isFullScreen();
		}
	}.bind(this));

	ipcMain.on('setWindowSize', function(e, width, height, windowId) {
		if(this.id == windowId) this.setSize(width, height);
	}.bind(this));

}

Window.prototype.setSize = function(width, height) {

	var currentScreen = electronScreen.getDisplayMatching(this.browser.getBounds());
	var currentPosition = this.browser.getBounds();

	var x = this.browser.getBounds().x;
	var y = this.browser.getBounds().y;

	// If requested dimensions are supperior to current screen,
	// default to work area size
	if(width > currentScreen.workArea.width) {
		width = currentScreen.workArea.width;
		x = currentScreen.workArea.x;
	}
	if(height > currentScreen.workArea.height) {
		height = currentScreen.workArea.height;
		y = currentScreen.workArea.y;
	}

	this.browser.setBounds({
		x: x,
		y: y,
		width: width,
		height: height
	}, true);

	// Ask WindowHelper to update the UI on we're done
	this.browser.webContents.send('update_window_dimensions', this.id);

}

Window.prototype.onReady = function() {

	this.browser.webContents.send('ready');
	if(this.url) this.load(this.url);
	this.browser.show();

}

Window.prototype.onFocus = function() {

	this.onFocusCallback(this);
	this.updateMenus();

}

Window.prototype.close = function() {

	this.browser.close();

}

Window.prototype.onClosed = function() {

	// @if NODE_ENV='development'
	c.log('[Window] Closed');
	// @endif
	// this.camera.abortProcesses();
	CommandManager.unregisterAll(this.browser);
	this.browser = null;
	this.onCloseCallback();

}

Window.prototype.toggleDevTools = function() {

	this.browser.webContents.send('toggleDevTools');

}

Window.prototype.updateMenus = function() {

	CommandManager.setCheckbox('Window', 'Float on Top', this.isAlwaysOnTop);
	CommandManager.setCheckbox('View', 'Title Bar', this.handle);
	CommandManager.setCheckbox('Tools', 'Mini Console', this.console);
	CommandManager.setCheckbox('Tools', 'Window Helper', this.windowHelper && !this.browser.isFullScreen());
	CommandManager.setEnabled('View', 'Toggle Omnibox', !this.isFirstLoad);
	CommandManager.setEnabled('Tools', 'Mini Console', !this.isFirstLoad);
	CommandManager.setEnabled('Tools', 'Toggle Devtools', !this.isFirstLoad);

	if(this.browser) {
		CommandManager.setCheckbox('View', 'Fullscreen', this.browser.isFullScreen());
	}

}

Window.prototype.setOmniboxShow = function() {

	this.omnibox = true;

}

Window.prototype.setOmniboxHide = function() {

	this.omnibox = false;

}

Window.prototype.showOmnibox = function() {

	// @if NODE_ENV='development'
	c.log('[Window] Showing Omnibox');
	// @endif

	this.omnibox = true;
	this.browser.webContents.send('showOmnibox');

}

Window.prototype.hideOmnibox = function() {

	// @if NODE_ENV='development'
	c.log('[Window] Hiding Omnibox');
	// @endif

	this.omnibox = false;
	this.browser.webContents.send('hideOmnibox');

}

Window.prototype.toggleHandle = function() {

	if(this.handle) {
		// @if NODE_ENV='development'
		c.log('[Window] Hiding handle!');
		// @endif
		this.handle = false;
		this.browser.webContents.send('hideHandle');

		if(this.browser.isFullScreen()) {
			c.log('Setting window size for fullscreen!');
			var currentScreen = electronScreen.getDisplayMatching(this.browser.getBounds());
			this.browser.setBounds({
				x: 0,
				y: 0,
				width: currentScreen.size.width,
				height: currentScreen.size.height
			}, false);
		}
		else {
			this.browser.setSize(
				this.browser.getSize()[0],
				this.browser.getSize()[1] - 22 // 22 being the handle's height :(
			);
		}
	}
	else {
		// @if NODE_ENV='development'
		c.log('[Window] Showing handle');
		// @endif
		this.handle = true;
		this.browser.webContents.send('showHandle');

		if(this.browser.isFullScreen()) {
			var currentScreen = electronScreen.getDisplayMatching(this.browser.getBounds());
			this.browser.setBounds({
				x: 0,
				y: 0,
				width: currentScreen.bounds.width,
				height: currentScreen.bounds.height
			}, false);
		}
		else {
			this.browser.setSize(
				this.browser.getSize()[0],
				this.browser.getSize()[1] + 22
			);
		}
	}

	CommandManager.toggleChecked('View', 'Title Bar');

}

Window.prototype.toggleWindowHelper = function() {

		this.windowHelper != this.windowHelper;
		this.browser.webContents.send('toggle_window_helper', this.id);
		CommandManager.toggleChecked('Tools', 'Window Helper');

}

Window.prototype.toggleConsole = function() {

	this.console != this.console;
	this.browser.webContents.send('toggle_mini_console', this.id);
	CommandManager.toggleChecked('Tools', 'Mini Console');

}

Window.prototype.toggleOmnibox = function() {

	// @if NODE_ENV='development'
	c.log('[Window] Toggling Omnibox');
	// @endif
	if(this.omnibox) {
		this.hideOmnibox();
	}
	else {
		this.showOmnibox();
	}

}

Window.prototype.reload = function() {

	this.browser.webContents.send('reload');
}

Window.prototype.reloadIgnoringCache = function() {

	this.browser.webContents.send('reloadIgnoringCache');

}

Window.prototype.load = function(url) {

	this.browser.webContents.send('display-notification', {
		'body' : 'Loading ' + url,
		'lifespan' : 3000,
	});

	this.browser.webContents.send('load', url);

}

Window.prototype.navigateBack = function() {

	this.browser.webContents.send('goBack');
}

Window.prototype.navigateForward = function() {

	this.browser.webContents.send('display-notification', {
		'body' : 'Navigating forward...',
		'lifespan' : 2000,
	});

	this.browser.webContents.send('goForward');
}

Window.prototype.setAlwaysOnTopToggle = function() {

	this.isAlwaysOnTop =! this.isAlwaysOnTop;
	this.browser.setAlwaysOnTop(this.isAlwaysOnTop);
	CommandManager.toggleChecked('Window', 'Float on Top');

}

Window.prototype.lockDimensions = function() {

	this.browser.setResizable(false);

}

Window.prototype.unlockDimensions = function() {

	this.browser.setResizable(true);

}<|endoftext|>


<commit_before>/* globals strings */
/* jshint globalstrict: true */

"use strict";

function flashCopied() {
  var copiedElement = document.querySelector('#copiedNotification');
  copiedElement.style.display = 'flex';
  copiedElement.className = 'fadein';
  setTimeout(function() {
    window.close();
  }, 500);
}

function copyToClipboard(text) {
  var input = document.createElement('input');
  input.style.position = 'fixed';
  input.style.opacity = 0;
  input.value = text;

  document.body.appendChild(input);

  input.select();
  document.execCommand('Copy');

  document.body.removeChild(input);
  flashCopied();
}

function showString(string, id) {
  var containerli = document.createElement('li');
  containerli.className = 'list-group-item';
  containerli.id = 'stringID-' + id;

  var badge = document.createElement('span');
  badge.className = 'badge';
  if (string.demo === false) {
    string.demo = '(none)';
  }

  var demo = string.demo;
  // handle trimming
  if (demo.length > 10) {
    demo = demo.substr(0, 10) + ' [...]';
  }
  badge.innerText = demo;

  var classification = document.createElement('span');
  classification.className = 'classification';
  classification.innerHTML = string.classification;

  var label = document.createElement('span');
  label.className = 'name';
  label.innerHTML = string.name;

  containerli.appendChild(badge);
  containerli.appendChild(classification);
  containerli.appendChild(label);

  document.querySelector('#stringList').appendChild(containerli);
}

function searchChangeHandler() {
  var query = document.querySelector('#searchBox').value.toLowerCase();
  var names = document.querySelectorAll('.list-group-item');

  // home rolled O(n) search... what could go wrong?
  var displayedStrings = 0;
  for (var i = 0; i < names.length; i += 1) {
    if (names[i].innerText.toLowerCase().indexOf(query) > -1) {
      names[i].style.display = 'block';
      displayedStrings += 1;
    } else {
      names[i].style.display = 'none';
    }

    if (displayedStrings === 0) {
      document.querySelector('#noResults').style.display = 'block';
    } else {
      document.querySelector('#noResults').style.display = 'none';
    }
  }
}

// load all strings into view
strings.forEach(function(string, index) {
  showString(string, index);
});

// set up click listeners
var copyableClass = document.getElementsByClassName('list-group-item');

function ClickHandler() {
  var id = this.id.split('-')[1];
  copyToClipboard(strings[id].value);
}

for (var i = 0; i < copyableClass.length; i += 1) {
  copyableClass[i].addEventListener('click', ClickHandler, false);
}

// attach the search listener
document.querySelector('#searchBox').addEventListener('input', searchChangeHandler);
<commit_msg>Replace input with textarea<commit_after>/* globals strings */
/* jshint globalstrict: true */

"use strict";

function flashCopied() {
  var copiedElement = document.querySelector('#copiedNotification');
  copiedElement.style.display = 'flex';
  copiedElement.className = 'fadein';
  setTimeout(function() {
    window.close();
  }, 500);
}

function copyToClipboard(text) {
  var input = document.createElement('textarea');
  input.style.position = 'fixed';
  input.style.opacity = 0;
  input.value = text;

  document.body.appendChild(input);

  input.select();
  document.execCommand('Copy');

  document.body.removeChild(input);
  flashCopied();
}

function showString(string, id) {
  var containerli = document.createElement('li');
  containerli.className = 'list-group-item';
  containerli.id = 'stringID-' + id;

  var badge = document.createElement('span');
  badge.className = 'badge';
  if (string.demo === false) {
    string.demo = '(none)';
  }

  var demo = string.demo;
  // handle trimming
  if (demo.length > 10) {
    demo = demo.substr(0, 10) + ' [...]';
  }
  badge.innerText = demo;

  var classification = document.createElement('span');
  classification.className = 'classification';
  classification.innerHTML = string.classification;

  var label = document.createElement('span');
  label.className = 'name';
  label.innerHTML = string.name;

  containerli.appendChild(badge);
  containerli.appendChild(classification);
  containerli.appendChild(label);

  document.querySelector('#stringList').appendChild(containerli);
}

function searchChangeHandler() {
  var query = document.querySelector('#searchBox').value.toLowerCase();
  var names = document.querySelectorAll('.list-group-item');

  // home rolled O(n) search... what could go wrong?
  var displayedStrings = 0;
  for (var i = 0; i < names.length; i += 1) {
    if (names[i].innerText.toLowerCase().indexOf(query) > -1) {
      names[i].style.display = 'block';
      displayedStrings += 1;
    } else {
      names[i].style.display = 'none';
    }

    if (displayedStrings === 0) {
      document.querySelector('#noResults').style.display = 'block';
    } else {
      document.querySelector('#noResults').style.display = 'none';
    }
  }
}

// load all strings into view
strings.forEach(function(string, index) {
  showString(string, index);
});

// set up click listeners
var copyableClass = document.getElementsByClassName('list-group-item');

function ClickHandler() {
  var id = this.id.split('-')[1];
  copyToClipboard(strings[id].value);
}

for (var i = 0; i < copyableClass.length; i += 1) {
  copyableClass[i].addEventListener('click', ClickHandler, false);
}

// attach the search listener
document.querySelector('#searchBox').addEventListener('input', searchChangeHandler);
<|endoftext|>


<commit_before>// Manages the utility links that appear on the details view.
define(
function () {
  'use strict';

  // The DOM element for the print button utility link.
  var _printButton;

  function init() {
    _printButton = document.querySelector('.utility-links .button-print');

    // Set event on print button and show the button.
    _printButton.addEventListener('click', _clickPrintButton, false);
    _printButton.classList.remove('hide');
  }

  // Issue print command when print button is clicked.
  // @param evt [Object] The click event object.
  function _clickPrintButton(evt) {
    evt.preventDefault();
    window.print();
  }

  return {
    init:init
  };
});<commit_msg>Adds trailing return to JS module<commit_after>// Manages the utility links that appear on the details view.
define(
function () {
  'use strict';

  // The DOM element for the print button utility link.
  var _printButton;

  function init() {
    _printButton = document.querySelector('.utility-links .button-print');

    // Set event on print button and show the button.
    _printButton.addEventListener('click', _clickPrintButton, false);
    _printButton.classList.remove('hide');
  }

  // Issue print command when print button is clicked.
  // @param evt [Object] The click event object.
  function _clickPrintButton(evt) {
    evt.preventDefault();
    window.print();
  }

  return {
    init:init
  };
});
<|endoftext|>


<commit_before>(function($){
   'use strict';
   var ndfDateID = 'sb-ndf-date';
   var ndfDateRegEx = new RegExp('^' + ndfDateID);
   var ndfDate = {unique_id:ndfDateID,text:{headline:'No Data Found'},start_date:{ year: new Date().getFullYear()}} ;
   var timeline$;
   var ndf$;
   var timeline;
   var isEmpty = false;
   var o;

   $.widget("sb.timeline", {
      options: {
         timelineID: null,
         ndfID: null,
         timenav_position: null,
         language : 'en',
         layout: 'landscape',
         width: null,
         height: null,
         ajaxIdentifier: null,
         pageItems:null
      },
      _create: function() {
         var that = this;
         o = that.options;
         timeline$ = $('#'+o.timelineID);
         ndf$ = $('#'+o.ndfID);

         this._getData().done(function(tlData){
            if(tlData.events.length === 0){
               isEmpty = true;
               tlData.events.push(ndfDate);
            }else{
               isEmpty = false;
            }
            timeline = new TL.Timeline(o.timelineID,tlData, {
               timenav_position : o.timenav_position,
               language: o.language,
               layout: o.layout,
               width: o.width,
               height: o.height
            });

            if(isEmpty){
               that._noDataFound();
            }
         });

         this.element.on('apexrefresh', function( event ){
            that._refresh();
         });
      },
      _getData: function(){
         return apex.server.plugin(
            this.options.ajaxIdentifier,
            {
               x10: "DATA",
               pageItems: this.options.pageItems
            }
         );
      },
      _refresh : function(){
         var that = this;
         var curEvent;
         var ndfEvents = [];
         this._getData().done(function(tlData){
            if(tlData && tlData.hasOwnProperty('events')){
               if(tlData.events.length === 0){
                  that._noDataFound();
                  return;
               }
               isEmpty = false;

               // the timeline breaks if it doesnt have an event
               // we add a temporary event so that all events can be deleted
               //then we remove the temporary event at the end
               timeline.add($.extend(true,{},ndfDate));
               for (var i = timeline.config.events.length - 1; i >= 0; i--) {
                  curEvent = timeline.config.events[i];
                  if(!ndfDateRegEx.test(curEvent.unique_id)){
                     timeline.removeId(curEvent.unique_id);
                  }else{
                     ndfEvents.push(curEvent);
                  }
               };

               for(var i = 0; i < tlData.events.length; i++){
                 timeline.add(tlData.events[i]);
               }
               while(ndfEvents.length > 0){
                 timeline.removeId(ndfEvents.pop().unique_id);
               }
               that._updateDisplay();
            }
         });
      },
      _noDataFound : function(){
         isEmpty = true;
         this._updateDisplay();
      },
      _updateDisplay : function(){
         if(isEmpty){
            timeline$.hide();
            ndf$.show();
         }else{
            timeline$.show();
            ndf$.hide();
         }
      }
   });
})(apex.jQuery);<commit_msg>moved update display to happen sooner<commit_after>(function($){
   'use strict';
   var ndfDateID = 'sb-ndf-date';
   var ndfDateRegEx = new RegExp('^' + ndfDateID);
   var ndfDate = {unique_id:ndfDateID,text:{headline:'No Data Found'},start_date:{ year: new Date().getFullYear()}} ;
   var timeline$;
   var ndf$;
   var timeline;
   var isEmpty = false;
   var o;

   $.widget("sb.timeline", {
      options: {
         timelineID: null,
         ndfID: null,
         timenav_position: null,
         language : 'en',
         layout: 'landscape',
         width: null,
         height: null,
         ajaxIdentifier: null,
         pageItems:null
      },
      _create: function() {
         var that = this;
         o = that.options;
         timeline$ = $('#'+o.timelineID);
         ndf$ = $('#'+o.ndfID);

         this._getData().done(function(tlData){
            if(tlData.events.length === 0){
               isEmpty = true;
               tlData.events.push(ndfDate);
            }else{
               isEmpty = false;
            }
            timeline = new TL.Timeline(o.timelineID,tlData, {
               timenav_position : o.timenav_position,
               language: o.language,
               layout: o.layout,
               width: o.width,
               height: o.height
            });

            if(isEmpty){
               that._noDataFound();
            }
         });

         this.element.on('apexrefresh', function( event ){
            that._refresh();
         });
      },
      _getData: function(){
         return apex.server.plugin(
            this.options.ajaxIdentifier,
            {
               x10: "DATA",
               pageItems: this.options.pageItems
            }
         );
      },
      _refresh : function(){
         var that = this;
         var curEvent;
         var ndfEvents = [];
         this._getData().done(function(tlData){
            if(tlData && tlData.hasOwnProperty('events')){
               if(tlData.events.length === 0){
                  that._noDataFound();
                  return;
               }
               isEmpty = false;

               // the timeline breaks if it doesnt have an event
               // we add a temporary event so that all events can be deleted
               // then we remove the temporary event at the end
               timeline.add($.extend(true,{},ndfDate));
               for (var i = timeline.config.events.length - 1; i >= 0; i--) {
                  curEvent = timeline.config.events[i];
                  if(!ndfDateRegEx.test(curEvent.unique_id)){
                     timeline.removeId(curEvent.unique_id);
                  }else{
                     ndfEvents.push(curEvent);
                  }
               };

               // we want the timline to be visible before manipulating events
               // in the case of removing all events it does not matter if the timeline is visible
               // the timeline scale cannot compute properly while the timeline is hidden
               that._updateDisplay();

               for(var i = 0; i < tlData.events.length; i++){
                 timeline.add(tlData.events[i]);
               }
               while(ndfEvents.length > 0){
                 timeline.removeId(ndfEvents.pop().unique_id);
               }

            }
         });
      },
      _noDataFound : function(){
         isEmpty = true;
         this._updateDisplay();
      },
      _updateDisplay : function(){
         if(isEmpty){
            timeline$.hide();
            ndf$.show();
         }else{
            timeline$.show();
            ndf$.hide();
         }
      }
   });
})(apex.jQuery);<|endoftext|>