<commit_before>'use strict';
var domv = require('domv');
var hrtime = require('../../swissarmyknife/hrtime');

require('static-reference')('./style/EditableBooleanText.less');

function EditableBooleanText(node, value, falseContent, trueContent)
{
        domv.Component.call(this, node, 'span');

        this.lastChangeByUser = null;

        if (this.isCreationConstructor(node))
        {
                //var div = this.shorthand('div');

                this.cls('EditableBooleanText');
                this.attr({
                        'data-false': falseContent || 'No',
                        'data-true': trueContent || 'Yes'
                });

                this.value = value;
        }
        else
        {
                this.assertHasClass('EditableBooleanText');
        }

        this.on('click', this._onClick);
        this.on('keydown', this._onKeydown);
}

module.exports = EditableBooleanText;
require('inherits')(EditableBooleanText, domv.Component);

EditableBooleanText.prototype.isChangedByUserSince = function(since)
{
        if (since === undefined ||
            since === null)
        {
                return true;
        }

        if (this.lastChangeByUser === null)
        {
                return false;
        }

        return this.lastChangeByUser > since;
};

Object.defineProperty(EditableBooleanText.prototype, 'falseContent', {
        configurable: true,
        get: function()
        {
                return this.getAttr('data-false');
        },
        set: function(value)
        {
                this.attr('data-false', value);
                this.value = this.value;
        }
});

Object.defineProperty(EditableBooleanText.prototype, 'trueContent', {
        configurable: true,
        get: function()
        {
                return this.getAttr('data-true');
        },
        set: function(value)
        {
                this.attr('data-true', value);
                this.value = this.value;
        }
});

Object.defineProperty(EditableBooleanText.prototype, 'value', {
        configurable: true,
        get: function()
        {
                return !!this.getAttr('data-value');
        },
        set: function(value)
        {
                value = !!value;
                this.attr('data-value', value);
                this.removeChildren();
                this.appendChild(value ? this.trueContent : this.falseContent);
        }
});

Object.defineProperty(EditableBooleanText.prototype, 'editing', {
        configurable: true,
        get: function()
        {
                return this.hasClass('editing');
        },
        set: function(value)
        {
                value = !!value;
                this.toggleClass('editing', value);
                this.attr('tabindex', value ? '0' : false);
        }
});

EditableBooleanText.prototype._onClick = function(e)
{
        e.preventDefault();

        var eventData = {
                targetComponent: this,
                newValue: !this.value
        };

        if (this.emit('domv-editable-change', eventData))
        {
                this.value = eventData.newValue;
                this.lastChangeByUser = hrtime();
        }
};

EditableBooleanText.prototype._onKeydown = function(e)
{
        if (e.keyCode === 13 || // enter key
            e.keyCode === 32    // space
        )
        {
                e.preventDefault();

                var eventData = {
                        targetComponent: this,
                        newValue: !this.value
                };

                if (this.emit('domv-editable-change', eventData))
                {
                        this.value = eventData.newValue;
                        this.lastChangeByUser = hrtime();
                }
        }
};
<commit_msg>Bug fix, only edit booleans when actually in edit mode<commit_after>'use strict';
var domv = require('domv');
var hrtime = require('../../swissarmyknife/hrtime');

require('static-reference')('./style/EditableBooleanText.less');

function EditableBooleanText(node, value, falseContent, trueContent)
{
        domv.Component.call(this, node, 'span');

        this.lastChangeByUser = null;

        if (this.isCreationConstructor(node))
        {
                //var div = this.shorthand('div');

                this.cls('EditableBooleanText');
                this.attr({
                        'data-false': falseContent || 'No',
                        'data-true': trueContent || 'Yes'
                });

                this.value = value;
        }
        else
        {
                this.assertHasClass('EditableBooleanText');
        }

        this.on('click', this._onClick);
        this.on('keydown', this._onKeydown);
}

module.exports = EditableBooleanText;
require('inherits')(EditableBooleanText, domv.Component);

EditableBooleanText.prototype.isChangedByUserSince = function(since)
{
        if (since === undefined ||
            since === null)
        {
                return true;
        }

        if (this.lastChangeByUser === null)
        {
                return false;
        }

        return this.lastChangeByUser > since;
};

Object.defineProperty(EditableBooleanText.prototype, 'falseContent', {
        configurable: true,
        get: function()
        {
                return this.getAttr('data-false');
        },
        set: function(value)
        {
                this.attr('data-false', value);
                this.value = this.value;
        }
});

Object.defineProperty(EditableBooleanText.prototype, 'trueContent', {
        configurable: true,
        get: function()
        {
                return this.getAttr('data-true');
        },
        set: function(value)
        {
                this.attr('data-true', value);
                this.value = this.value;
        }
});

Object.defineProperty(EditableBooleanText.prototype, 'value', {
        configurable: true,
        get: function()
        {
                return !!this.getAttr('data-value');
        },
        set: function(value)
        {
                value = !!value;
                this.attr('data-value', value);
                this.removeChildren();
                this.appendChild(value ? this.trueContent : this.falseContent);
        }
});

Object.defineProperty(EditableBooleanText.prototype, 'editing', {
        configurable: true,
        get: function()
        {
                return this.hasClass('editing');
        },
        set: function(value)
        {
                value = !!value;
                this.toggleClass('editing', value);
                this.attr('tabindex', value ? '0' : false);
        }
});

EditableBooleanText.prototype._onClick = function(e)
{
        if (!this.editing)
        {
                return;
        }

        e.preventDefault();

        var eventData = {
                targetComponent: this,
                newValue: !this.value
        };

        if (this.emit('domv-editable-change', eventData))
        {
                this.value = eventData.newValue;
                this.lastChangeByUser = hrtime();
        }
};

EditableBooleanText.prototype._onKeydown = function(e)
{
        if (!this.editing)
        {
                return;
        }

        if (e.keyCode === 13 || // enter key
            e.keyCode === 32    // space
        )
        {
                e.preventDefault();

                var eventData = {
                        targetComponent: this,
                        newValue: !this.value
                };

                if (this.emit('domv-editable-change', eventData))
                {
                        this.value = eventData.newValue;
                        this.lastChangeByUser = hrtime();
                }
        }
};
<|endoftext|>


<commit_before>(function () {
    'use strict';

    var BSTNode = function (value) {
        this.key = value;
        this.right = null;
        this.left = null;
    };

    function basicCompare(a, b) {
        return a - b;
    }

    var BST = function (compareFn) {
        this.root = null;
        this.cmp = compareFn || basicCompare;
    };

    BST.prototype.add = function (value) {
        var newNode = new BSTNode(value);

        if (this.root === null) {
            this.root = newNode;
        } else {
            addNode(this.root, newNode, this.cmp);
        }
    };

    BST.prototype.contains = function (value) {
        return containsNode(this.root, value, this.cmp);
    };

    BST.prototype.inOrderTraversal = function (cb) {
        inOrderTraverseNode(this.root, cb);
    };

    BST.prototype.preOrderTraversal = function (cb) {
        preOrderTraverseNode(this.root, cb);
    };

    BST.prototype.postOrderTraversal = function (cb) {
        postOrderTraverseNode(this.root, cb);
    };

    BST.prototype.min = function () {
        return minNode(this.root);
    };

    BST.prototype.max = function () {
        return maxNode(this.root);
    };

    BST.prototype.remove = function (key) {
        var removeNode = this.root;
        var parent = this.root;
        var isLeftChild = true;

        while (removeNode.key !== key) {
            parent = removeNode;

            if (this.cmp(removeNode.key, key) > 0) {
                isLeftChild = true;
                removeNode = removeNode.left;
            } else {
                isLeftChild = false;
                removeNode = removeNode.right;
            }

            if (removeNode === null) {
                return false;
            }
        }

        // case 1: leaf node
        if (removeNode.left === null && removeNode.right === null) {

            if (removeNode === this.root) {
                this.root = null;
            }

            if (isLeftChild) {
                parent.left = null;

            } else {
                parent.right = null;
            }

        // case 2: one child node
        // case 2a: left child but no right child
        } else if (removeNode.right === null) {

            if (removeNode === this.root) {
                this.root = removeNode.left;

            } else if (isLeftChild) {
                parent.left = removeNode.left;

            } else {
                parent.right = removeNode.left;
            }

        // case 2b: right child but no left child
        } else if (removeNode.left === null) {

            if (removeNode === this.root) {
                this.root = removeNode.right;

            } else if (isLeftChild) {
                parent.left = removeNode.right;

            } else {
                parent.right = removeNode.right;
            }

        // case 3: both left and right nodes
        // this is where it gets a bit harder...need to determine the replacement
        // node.
        } else {

            var replacement = getReplacementNode(removeNode);

            if (removeNode === this.root) {
                this.root = replacement;

            } else if (isLeftChild) {
                parent.left = replacement;

            } else {
                parent.right = replacement;
            }

            replacement.left = removeNode.left;
        }

        return true;
    };

    module.exports = BST;

    if (module.parent === null) {
        main();
    }

    function main() {
    }

    /********** helper functions **********/
    function addNode(node, newNode, cmp) {
        if (cmp(node.key, newNode.key) > 0) {
            if (node.left === null) {
                node.left = newNode;
            } else {
                addNode(node.left, newNode, cmp);
            }

        } else {
            if (node.right === null) {
                node.right = newNode;
            } else {
                addNode(node.right, newNode, cmp);
            }

        }
    }

    function containsNode(node, value, cmp) {
        if (node === null) {
            return false;
        }

        if (cmp(node.key, value) > 0) {
            return containsNode(node.left, value, cmp);
        } else if (cmp(value, node.key) > 0) {
            return containsNode(node.right, value, cmp);
        } else {
            return true;
        }
    }

    function inOrderTraverseNode(node, cb) {
        if (node !== null) {
            inOrderTraverseNode(node.left, cb);
            cb(node.key);
            inOrderTraverseNode(node.right, cb);
        }
    }

    function preOrderTraverseNode(node, cb) {
        if (node !== null) {
            cb(node.key);
            preOrderTraverseNode(node.left, cb);
            preOrderTraverseNode(node.right, cb);
        }
    }

    function postOrderTraverseNode(node, cb) {
        if (node !== null) {
            postOrderTraverseNode(node.left, cb);
            postOrderTraverseNode(node.right, cb);
            cb(node.key);
        }
    }

    function minNode(node) {
        if (node) {
            while (node && node.left !== null) {
                node = node.left;
            }
            return node.key;
        }
        return null;
    }

    function maxNode(node) {
        if (node) {
            while (node && node.right !== null) {
                node = node.right;
            }
            return node.key;
        }
        return null;
    }

    function getReplacementNode(nodeToRemove) {
        var replacementParent = nodeToRemove;
        var replacementNode = nodeToRemove;

        var focusNode = nodeToRemove.right;

        while (focusNode !== null) {
            replacementParent = replacementNode;
            replacementNode = focusNode;

            focusNode = focusNode.left;
        }

        if (replacementNode !== nodeToRemove.right) {
            replacementParent.left = replacementNode.right;
            replacementNode.right = nodeToRemove.right;
        }

        return replacementNode;
    }

}());
<commit_msg>Fix remove method to work w/ user-defined comparator<commit_after>(function () {
    'use strict';

    var BSTNode = function (value) {
        this.key = value;
        this.right = null;
        this.left = null;
    };

    function basicCompare(a, b) {
        return a - b;
    }

    var BST = function (compareFn) {
        this.root = null;
        this.cmp = compareFn || basicCompare;
    };

    BST.prototype.add = function (value) {
        var newNode = new BSTNode(value);

        if (this.root === null) {
            this.root = newNode;
        } else {
            addNode(this.root, newNode, this.cmp);
        }
    };

    BST.prototype.contains = function (value) {
        return containsNode(this.root, value, this.cmp);
    };

    BST.prototype.inOrderTraversal = function (cb) {
        inOrderTraverseNode(this.root, cb);
    };

    BST.prototype.preOrderTraversal = function (cb) {
        preOrderTraverseNode(this.root, cb);
    };

    BST.prototype.postOrderTraversal = function (cb) {
        postOrderTraverseNode(this.root, cb);
    };

    BST.prototype.min = function () {
        return minNode(this.root);
    };

    BST.prototype.max = function () {
        return maxNode(this.root);
    };

    BST.prototype.remove = function (key) {
        var removeNode = this.root;
        var parent = this.root;
        var isLeftChild = true;

        while (this.cmp(removeNode.key, key) !== 0) {
            parent = removeNode;

            if (this.cmp(removeNode.key, key) > 0) {
                isLeftChild = true;
                removeNode = removeNode.left;
            } else {
                isLeftChild = false;
                removeNode = removeNode.right;
            }

            if (removeNode === null) {
                return false;
            }
        }

        // case 1: leaf node
        if (removeNode.left === null && removeNode.right === null) {

            if (removeNode === this.root) {
                this.root = null;
            }

            if (isLeftChild) {
                parent.left = null;

            } else {
                parent.right = null;
            }

        // case 2: one child node
        // case 2a: left child but no right child
        } else if (removeNode.right === null) {

            if (removeNode === this.root) {
                this.root = removeNode.left;

            } else if (isLeftChild) {
                parent.left = removeNode.left;

            } else {
                parent.right = removeNode.left;
            }

        // case 2b: right child but no left child
        } else if (removeNode.left === null) {

            if (removeNode === this.root) {
                this.root = removeNode.right;

            } else if (isLeftChild) {
                parent.left = removeNode.right;

            } else {
                parent.right = removeNode.right;
            }

        // case 3: both left and right nodes
        // this is where it gets a bit harder...need to determine the replacement
        // node.
        } else {

            var replacement = getReplacementNode(removeNode);

            if (removeNode === this.root) {
                this.root = replacement;

            } else if (isLeftChild) {
                parent.left = replacement;

            } else {
                parent.right = replacement;
            }

            replacement.left = removeNode.left;
        }

        return true;
    };

    module.exports = BST;

    if (module.parent === null) {
        main();
    }

    function main() {
    }

    /********** helper functions **********/
    function addNode(node, newNode, cmp) {
        if (cmp(node.key, newNode.key) > 0) {
            if (node.left === null) {
                node.left = newNode;
            } else {
                addNode(node.left, newNode, cmp);
            }

        } else {
            if (node.right === null) {
                node.right = newNode;
            } else {
                addNode(node.right, newNode, cmp);
            }

        }
    }

    function containsNode(node, value, cmp) {
        if (node === null) {
            return false;
        }

        if (cmp(node.key, value) > 0) {
            return containsNode(node.left, value, cmp);
        } else if (cmp(value, node.key) > 0) {
            return containsNode(node.right, value, cmp);
        } else {
            return true;
        }
    }

    function inOrderTraverseNode(node, cb) {
        if (node !== null) {
            inOrderTraverseNode(node.left, cb);
            cb(node.key);
            inOrderTraverseNode(node.right, cb);
        }
    }

    function preOrderTraverseNode(node, cb) {
        if (node !== null) {
            cb(node.key);
            preOrderTraverseNode(node.left, cb);
            preOrderTraverseNode(node.right, cb);
        }
    }

    function postOrderTraverseNode(node, cb) {
        if (node !== null) {
            postOrderTraverseNode(node.left, cb);
            postOrderTraverseNode(node.right, cb);
            cb(node.key);
        }
    }

    function minNode(node) {
        if (node) {
            while (node && node.left !== null) {
                node = node.left;
            }
            return node.key;
        }
        return null;
    }

    function maxNode(node) {
        if (node) {
            while (node && node.right !== null) {
                node = node.right;
            }
            return node.key;
        }
        return null;
    }

    function getReplacementNode(nodeToRemove) {
        var replacementParent = nodeToRemove;
        var replacementNode = nodeToRemove;

        var focusNode = nodeToRemove.right;

        while (focusNode !== null) {
            replacementParent = replacementNode;
            replacementNode = focusNode;

            focusNode = focusNode.left;
        }

        if (replacementNode !== nodeToRemove.right) {
            replacementParent.left = replacementNode.right;
            replacementNode.right = nodeToRemove.right;
        }

        return replacementNode;
    }

}());
<|endoftext|>


<commit_before>"use strict";

// dependencies
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const PORT = process.env.PORT || 3000;

// init app
const app = express();

//configure body parser
app.use(bodyParser.urlencoded(
	{
		extended: false
	}));

// use jade as view engine
app.set("view engine", "jade");

app.get("/", (req, res) =>
{
	res.send("
Welcome to mah pagggggeeee
");
})

//route for getting create note form
app.get("/notes/new", (req, res) =>
{
	res.render("new-note");
})

//route for making new notes
app.post("/notes", (req, res) =>
{
	console.log(req.body);
	res.redirect("/")
})

app.listen(PORT, () =>
{
	console.log(`app listening on port: ${PORT}`);
})<commit_msg>finished feature: connected to mongodb and added ability to save a new note<commit_after>"use strict";

// dependencies
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const PORT = process.env.PORT || 3000;
const MONGODB_URL = "mongodb://localhost:27017/evernode"

// init app
const app = express();

const Note = mongoose.model('Notes', mongoose.Schema({
	title : String,
	text : String
}));

//configure body parser
app.use(bodyParser.urlencoded(
	{
		extended: false
	}));

// use jade as view engine
app.set("view engine", "jade");

app.get("/", (req, res) =>
{
	res.send("
Welcome to mah pagggggeeee
");
})

//route for getting create note form
app.get("/notes/new", (req, res) =>
{
	res.render("new-note");
})

//route for making new notes
app.post("/notes", (req, res) =>
{
	Note.create(req.body, (err, note) =>
	{
		if (err) throw err
		console.log(note);
		res.redirect("/")
	})
})

//connect to mongo
mongoose.connect(MONGODB_URL);

//when mongo is connected
mongoose.connection.on("open", () =>
{
	//Start app on specified port
	app.listen(PORT, () =>
	{
		console.log(`port running on port ${PORT}`);
		console.log(`Connected to mongodb`);
	})

})<|endoftext|>


<commit_before>/*global $, app, me, client*/
"use strict";

var HumanView = require('human-view');
var templates = require('../templates');
var ContactListItem = require('../views/contactListItem');
var MUCListItem = require('../views/mucListItem');

module.exports = HumanView.extend({
    template: templates.body,
    initialize: function () {
        this.listenTo(app.state, 'change:title', this.handleTitle);
        if (window.macgap) {
            window.macgap.dock.badge = '';
        }
    },
    events: {
        'click a[href]': 'handleLinkClick',
        'click .reconnect': 'handleReconnect'
    },
    classBindings: {
        connected: '#connectionOverlay'
    },
    render: function () {
        $('head').append(templates.head());
        $('body').removeClass('aux');
        this.renderAndBind();
        this.renderCollection(me.contacts, ContactListItem, this.$('#roster nav'));
        this.renderCollection(me.mucs, MUCListItem, this.$('#bookmarks nav'));
        return this;
    },
    handleReconnect: function (e) {
        client.connect();
    },
    handleLinkClick: function (e) {
        var t = $(e.target);
        var aEl = t.is('a') ? t[0] : t.closest('a')[0];
        var local = window.location.host === aEl.host;
        var path = aEl.pathname.slice(1);

        if (local) {
            e.preventDefault();
            app.navigate(path);
            return false;
        }
    },
    handleTitle: function (e) {
        document.title = app.state.title;
        if (window.macgap) {
            window.macgap.dock.badge = app.state.badge;
        }
    }
});
<commit_msg>Update badge handling.<commit_after>/*global $, app, me, client*/
"use strict";

var HumanView = require('human-view');
var templates = require('../templates');
var ContactListItem = require('../views/contactListItem');
var MUCListItem = require('../views/mucListItem');

module.exports = HumanView.extend({
    template: templates.body,
    initialize: function () {
        this.listenTo(app.state, 'change:title', this.handleTitle);
        app.desktop.updateBadge('');
    },
    events: {
        'click a[href]': 'handleLinkClick',
        'click .reconnect': 'handleReconnect'
    },
    classBindings: {
        connected: '#connectionOverlay'
    },
    render: function () {
        $('head').append(templates.head());
        $('body').removeClass('aux');
        this.renderAndBind();
        this.renderCollection(me.contacts, ContactListItem, this.$('#roster nav'));
        this.renderCollection(me.mucs, MUCListItem, this.$('#bookmarks nav'));
        return this;
    },
    handleReconnect: function (e) {
        client.connect();
    },
    handleLinkClick: function (e) {
        var t = $(e.target);
        var aEl = t.is('a') ? t[0] : t.closest('a')[0];
        var local = window.location.host === aEl.host;
        var path = aEl.pathname.slice(1);

        if (local) {
            e.preventDefault();
            app.navigate(path);
            return false;
        }
    },
    handleTitle: function (e) {
        document.title = app.state.title;
        app.desktop.updateBadge(app.state.badge);
    }
});
<|endoftext|>


<commit_before>'use strict';

angular.module('myApp.controllers.private', [])

// Homepage controller
.controller('PrivateCtrl', function($scope, $rootScope, firebaseData, $location, $http, $timeout, $firebaseObject) {
    $scope.isCollapsed = true;
    $scope.messages = [];
    $scope.groups = [];
    $scope.groupInfo = "";
    $scope.messageText = "";
    $scope.chats = [];
    $scope.selected = null;
    $scope.name = '';
    $scope.userData;

    $scope.groupId = $location.search().groupId;

    var firepadRef = firebaseData.database().ref('/docs/' + $scope.groupId + '/');

    // Get Group Data
    $http.get('https://groupgenius-5953b.firebaseio.com/groups.json')
    .success(function (response) {
        var key;
        for (key in response)
        {
            if (response[key].groupId == $scope.groupId)
            {
                $scope.groupInfo = response[key];
                return;
            }
        }
    });

    firebaseData.provider().onAuthStateChanged(function(user) {
        var email = firebaseData.provider().currentUser.email;
        //console.log(email);
        var userRef = firebaseData.database().ref('/users/');
        $scope.userData = $firebaseObject(userRef);
        //userRefObject.$bindTo($scope, 'userData');
        $scope.userData.$loaded()
          .then(function() {
            console.log('user data');
            console.log($scope.userData);
            for(var user in $scope.userData) {
                if($scope.userData[user]) {
                    if(email == $scope.userData[user].email) {
                        console.log(user);
                        $scope.name = $scope.userData[user].firstName + ' ' + $scope.userData[user].lastName;
                        console.log('name found: ' + $scope.name);
                        break;
                    }
                }
            }
          })
          .catch(function(err) {
            console.error(err);
          });
    });
/*
    firebaseData.database().ref('/users/').on('value', function(snapshot) {
        var users = snapshot.val();
        for(var user in users) {
            if(email == user.email) {
                console.log(user);
                $scope.name = user.firstName + ' ' + user.lastName;
                console.log('name found: ' + $scope.name);
                break;
            }
        }
    });
*/
    // Initialize chats
    console.log($scope.groupId);
    $scope.chatRef = firebaseData.database().ref('/chat/' + $scope.groupId + '/');

    $timeout(function() {
        $scope.chatRef.on('value', function(snapshot) {
            $timeout(function() {
                if($scope.chats.length == 0) {
                    $scope.chatObjects = snapshot.val();
                    if($scope.chatObjects) {
                        for(var key in $scope.chatObjects) {
                            $scope.chatObjects[key].chatName = key;
                            $scope.chatObjects[key].selected = false;
                            console.log($scope.chatObjects[key]);
                            $scope.chats.push($scope.chatObjects[key]);
                        }
                    }
                }
                // Initialize the first variable
                $scope.chats[0].selected = true;

                $scope.$apply();
            }, 1000);
        });
    }, 1000);

    firebaseData.provider().onAuthStateChanged(function(user) {
        var userId = user.uid;
        //firepad stuff
        var codeMirror = CodeMirror(document.getElementById('wrapper-document'), { lineWrapping: true });
        var firepad = Firepad.fromCodeMirror(firepadRef, codeMirror, {
            richTextShortcuts: true,
            richTextToolbar: true,
            userId: userId,
            defaultText: 'Hello, World!'
        });
        var firepadUserList = FirepadUserList.fromDiv(firepadRef.child('users'),
        document.getElementById('group-activeStatus'), userId, getUniqname(user.email));

        $scope.chatRef.off();
        var setMessage = function(data){
            $scope.messages.push(data.val());
            $scope.$apply();
        }

        $scope.chatRef.limitToLast(12).on('child_added', setMessage);
        $scope.chatRef.limitToLast(12).on('child_changed', setMessage);
    });

    $scope.saveMessage = function() {
        if(!$scope.messageText) {
            return;
        }
    $scope.chatRef.push({
        name: $scope.name,
        text: $scope.messageText
    }).then(function() {
        $scope.messageText = "";
            $('#chat-area').scrollTop($('#chat-area').height());
            //This apply seems to be okay. Comment out if we're still getting errors.
            $scope.$apply();
        });
    }

$scope.location = $location;
    // Gets groupId from the url
    $scope.$watch('location.search()', function() {
        $scope.groupId = ($location.search()).groupId;
        // Get group data from groupId

    }, true);
    // Changes groupId in the url
    $scope.changeTarget = function(name) {
        $location.search('groupId', name);
    }
    $scope.groupInfo = {};
});

//Taken from github
var FirepadUserList = (function() {
  function FirepadUserList(ref, place, userId, displayName) {
    if (!(this instanceof FirepadUserList)) {
      return new FirepadUserList(ref, place, userId, displayName);
  }

  this.ref_ = ref;
  this.userId_ = userId;
  this.place_ = place;
  this.firebaseCallbacks_ = [];

  var self = this;
  this.hasName_ = !!displayName;
  this.displayName_ = displayName || 'Guest ' + Math.floor(Math.random() * 1000);
  this.firebaseOn_(ref.root.child('.info/connected'), 'value', function(s) {
      if (s.val() === true && self.displayName_) {
        var nameRef = ref.child(self.userId_).child('name');
        nameRef.onDisconnect().remove();
        nameRef.set(self.displayName_);
    }
});

  this.userList_ = this.makeUserList_()
  place.appendChild(this.userList_);
}

  // This is the primary "constructor" for symmetry with Firepad.
  FirepadUserList.fromDiv = FirepadUserList;

  FirepadUserList.prototype.dispose = function() {
    this.removeFirebaseCallbacks_();
    this.ref_.child(this.userId_).child('name').remove();

    this.place_.removeChild(this.userList_);
};

FirepadUserList.prototype.makeUserList_ = function() {
    return elt('div', [
      this.makeHeading_(),
      elt('div', [
        this.makeUserEntryForSelf_(),
        this.makeUserEntriesForOthers_()
        ], {'class': 'firepad-userlist-users' })
      ], {'class': 'firepad-userlist' });
};

FirepadUserList.prototype.makeHeading_ = function() {
    var counterSpan = elt('span', '0');
    this.firebaseOn_(this.ref_, 'value', function(usersSnapshot) {
      setTextContent(counterSpan, "" + usersSnapshot.numChildren());
  });

    return elt('div', [
      elt('span', 'ONLINE ('),
          counterSpan,
          elt('span', ')')
          ], { 'class': 'firepad-userlist-heading' });
};

FirepadUserList.prototype.makeUserEntryForSelf_ = function() {
    var myUserRef = this.ref_.child(this.userId_);

    var colorDiv = elt('div', null, { 'class': 'firepad-userlist-color-indicator' });
    this.firebaseOn_(myUserRef.child('color'), 'value', function(colorSnapshot) {
      var color = colorSnapshot.val();
      if (isValidColor(color)) {
        colorDiv.style.backgroundColor = color;
    }
});

    var nameInput = elt('p', null, { type: 'text', 'class': 'firepad-userlist-name-input'} );
    nameInput.innerHTML = this.displayName_;

    var nameHint = elt('div', 'ENTER YOUR NAME', { 'class': 'firepad-userlist-name-hint'} );
    /*if (this.hasName_)*/ nameHint.style.display = 'none';

    // Update Firebase when name changes.
    var self = this;
    on(nameInput, 'change', function(e) {
      var name = nameInput.value || "Guest " + Math.floor(Math.random() * 1000);
      myUserRef.child('name').onDisconnect().remove();
      myUserRef.child('name').set(name);
      nameHint.style.display = 'none';
      nameInput.blur();
      self.displayName_ = name;
      stopEvent(e);
  });

    var nameDiv = elt('div', [nameInput, nameHint]);

    return elt('div', [ colorDiv, nameDiv ], {
      'class': 'firepad-userlist-user ' + 'firepad-user-' + this.userId_
  });
};

FirepadUserList.prototype.makeUserEntriesForOthers_ = function() {
    var self = this;
    var userList = elt('div');
    var userId2Element = { };

    function updateChild(userSnapshot, prevChildName) {
      var userId = userSnapshot.key;
      var div = userId2Element[userId];
      if (div) {
        userList.removeChild(div);
        delete userId2Element[userId];
    }
    var name = userSnapshot.child('name').val();
    if (typeof name !== 'string') { name = 'Guest'; }
    name = name.substring(0, 20);

    var color = userSnapshot.child('color').val();
    if (!isValidColor(color)) {
        color = "#ffb"
    }

    var colorDiv = elt('div', null, { 'class': 'firepad-userlist-color-indicator' });
    colorDiv.style.backgroundColor = color;

    var nameDiv = elt('div', name || 'Guest', { 'class': 'firepad-userlist-name' });

    var userDiv = elt('div', [ colorDiv, nameDiv ], {
        'class': 'firepad-userlist-user ' + 'firepad-user-' + userId
    });
    userId2Element[userId] = userDiv;

    if (userId === self.userId_) {
        // HACK: We go ahead and insert ourself in the DOM, so we can easily order other users against it.
        // But don't show it.
        userDiv.style.display = 'none';
    }

    var nextElement =  prevChildName ? userId2Element[prevChildName].nextSibling : userList.firstChild;
    userList.insertBefore(userDiv, nextElement);
}

this.firebaseOn_(this.ref_, 'child_added', updateChild);
this.firebaseOn_(this.ref_, 'child_changed', updateChild);
this.firebaseOn_(this.ref_, 'child_moved', updateChild);
this.firebaseOn_(this.ref_, 'child_removed', function(removedSnapshot) {
  var userId = removedSnapshot.key;
  var div = userId2Element[userId];
  if (div) {
    userList.removeChild(div);
    delete userId2Element[userId];
}
});

return userList;
};

FirepadUserList.prototype.firebaseOn_ = function(ref, eventType, callback, context) {
    this.firebaseCallbacks_.push({ref: ref, eventType: eventType, callback: callback, context: context });
    ref.on(eventType, callback, context);
    return callback;
};

FirepadUserList.prototype.firebaseOff_ = function(ref, eventType, callback, context) {
    ref.off(eventType, callback, context);
    for(var i = 0; i < this.firebaseCallbacks_.length; i++) {
      var l = this.firebaseCallbacks_[i];
      if (l.ref === ref && l.eventType === eventType && l.callback === callback && l.context === context) {
        this.firebaseCallbacks_.splice(i, 1);
        break;
    }
}
};

FirepadUserList.prototype.removeFirebaseCallbacks_ = function() {
    for(var i = 0; i < this.firebaseCallbacks_.length; i++) {
      var l = this.firebaseCallbacks_[i];
      l.ref.off(l.eventType, l.callback, l.context);
  }
  this.firebaseCallbacks_ = [];
};

/** Assorted helpers */

function isValidColor(color) {
    return typeof color === 'string' &&
    (color.match(/^#[a-fA-F0-9]{3,6}$/) || color == 'transparent');
}

/** DOM helpers */
function elt(tag, content, attrs) {
    var e = document.createElement(tag);
    if (typeof content === "string") {
      setTextContent(e, content);
  } else if (content) {
      for (var i = 0; i < content.length; ++i) { e.appendChild(content[i]); }
  }
for(var attr in (attrs || { })) {
  e.setAttribute(attr, attrs[attr]);
}
return e;
}

function setTextContent(e, str) {
    e.innerHTML = "";
    e.appendChild(document.createTextNode(str));
}

function on(emitter, type, f) {
    if (emitter.addEventListener) {
      emitter.addEventListener(type, f, false);
  } else if (emitter.attachEvent) {
      emitter.attachEvent("on" + type, f);
  }
}

function off(emitter, type, f) {
    if (emitter.removeEventListener) {
      emitter.removeEventListener(type, f, false);
  } else if (emitter.detachEvent) {
      emitter.detachEvent("on" + type, f);
  }
}

function preventDefault(e) {
    if (e.preventDefault) {
      e.preventDefault();
  } else {
      e.returnValue = false;
  }
}

function stopPropagation(e) {
    if (e.stopPropagation) {
      e.stopPropagation();
  } else {
      e.cancelBubble = true;
  }
}

function stopEvent(e) {
    preventDefault(e);
    stopPropagation(e);
}

return FirepadUserList;
})();

function getUniqname(email){
    console.log(email);
    return email.substring(0,email.indexOf('@'));
}
<commit_msg>Scroll to bottom of chat onload<commit_after>'use strict';

angular.module('myApp.controllers.private', [])

// Homepage controller
.controller('PrivateCtrl', function($scope, $rootScope, firebaseData, $location, $http, $timeout, $firebaseObject) {
    $scope.isCollapsed = true;
    $scope.messages = [];
    $scope.groups = [];
    $scope.groupInfo = "";
    $scope.messageText = "";
    $scope.chats = [];
    $scope.selected = null;
    $scope.name = '';
    $scope.userData;

    $scope.groupId = $location.search().groupId;

    var firepadRef = firebaseData.database().ref('/docs/' + $scope.groupId + '/');

    // Get Group Data
    $http.get('https://groupgenius-5953b.firebaseio.com/groups.json')
    .success(function (response) {
        var key;
        for (key in response)
        {
            if (response[key].groupId == $scope.groupId)
            {
                $scope.groupInfo = response[key];
                return;
            }
        }
    });

    firebaseData.provider().onAuthStateChanged(function(user) {
        var email = firebaseData.provider().currentUser.email;
        //console.log(email);
        var userRef = firebaseData.database().ref('/users/');
        $scope.userData = $firebaseObject(userRef);
        //userRefObject.$bindTo($scope, 'userData');
        $scope.userData.$loaded()
          .then(function() {
            console.log('user data');
            console.log($scope.userData);
            for(var user in $scope.userData) {
                if($scope.userData[user]) {
                    if(email == $scope.userData[user].email) {
                        console.log(user);
                        $scope.name = $scope.userData[user].firstName + ' ' + $scope.userData[user].lastName;
                        console.log('name found: ' + $scope.name);
                        break;
                    }
                }
            }
          })
          .catch(function(err) {
            console.error(err);
          });
    });
/*
    firebaseData.database().ref('/users/').on('value', function(snapshot) {
        var users = snapshot.val();
        for(var user in users) {
            if(email == user.email) {
                console.log(user);
                $scope.name = user.firstName + ' ' + user.lastName;
                console.log('name found: ' + $scope.name);
                break;
            }
        }
    });
*/
    // Initialize chats
    console.log($scope.groupId);
    $scope.chatRef = firebaseData.database().ref('/chat/' + $scope.groupId + '/');

    $timeout(function() {
        $scope.chatRef.on('value', function(snapshot) {
            $timeout(function() {
                if($scope.chats.length == 0) {
                    $scope.chatObjects = snapshot.val();
                    if($scope.chatObjects) {
                        for(var key in $scope.chatObjects) {
                            $scope.chatObjects[key].chatName = key;
                            $scope.chatObjects[key].selected = false;
                            console.log($scope.chatObjects[key]);
                            $scope.chats.push($scope.chatObjects[key]);
                            $('#chat-area').scrollTop($('#chat-area').height());
                        }
                    }
                }
                // Initialize the first variable
                $scope.chats[0].selected = true;

                $scope.$apply();
            }, 1000);
        });
    }, 1000);

    firebaseData.provider().onAuthStateChanged(function(user) {
        var userId = user.uid;
        //firepad stuff
        var codeMirror = CodeMirror(document.getElementById('wrapper-document'), { lineWrapping: true });
        var firepad = Firepad.fromCodeMirror(firepadRef, codeMirror, {
            richTextShortcuts: true,
            richTextToolbar: true,
            userId: userId,
            defaultText: 'Hello, World!'
        });
        var firepadUserList = FirepadUserList.fromDiv(firepadRef.child('users'),
        document.getElementById('group-activeStatus'), userId, getUniqname(user.email));

        $scope.chatRef.off();
        var setMessage = function(data){
            $scope.messages.push(data.val());
            $scope.$apply();
        }

        $scope.chatRef.limitToLast(12).on('child_added', setMessage);
        $scope.chatRef.limitToLast(12).on('child_changed', setMessage);
    });

    $scope.saveMessage = function() {
        if(!$scope.messageText) {
            return;
        }
    $scope.chatRef.push({
        name: $scope.name,
        text: $scope.messageText
    }).then(function() {
        $scope.messageText = "";
            $('#chat-area').scrollTop($('#chat-area').height());
            //This apply seems to be okay. Comment out if we're still getting errors.
            $scope.$apply();
        });
    }

$scope.location = $location;
    // Gets groupId from the url
    $scope.$watch('location.search()', function() {
        $scope.groupId = ($location.search()).groupId;
        // Get group data from groupId

    }, true);
    // Changes groupId in the url
    $scope.changeTarget = function(name) {
        $location.search('groupId', name);
    }
    $scope.groupInfo = {};
});

//Taken from github
var FirepadUserList = (function() {
  function FirepadUserList(ref, place, userId, displayName) {
    if (!(this instanceof FirepadUserList)) {
      return new FirepadUserList(ref, place, userId, displayName);
  }

  this.ref_ = ref;
  this.userId_ = userId;
  this.place_ = place;
  this.firebaseCallbacks_ = [];

  var self = this;
  this.hasName_ = !!displayName;
  this.displayName_ = displayName || 'Guest ' + Math.floor(Math.random() * 1000);
  this.firebaseOn_(ref.root.child('.info/connected'), 'value', function(s) {
      if (s.val() === true && self.displayName_) {
        var nameRef = ref.child(self.userId_).child('name');
        nameRef.onDisconnect().remove();
        nameRef.set(self.displayName_);
    }
});

  this.userList_ = this.makeUserList_()
  place.appendChild(this.userList_);
}

  // This is the primary "constructor" for symmetry with Firepad.
  FirepadUserList.fromDiv = FirepadUserList;

  FirepadUserList.prototype.dispose = function() {
    this.removeFirebaseCallbacks_();
    this.ref_.child(this.userId_).child('name').remove();

    this.place_.removeChild(this.userList_);
};

FirepadUserList.prototype.makeUserList_ = function() {
    return elt('div', [
      this.makeHeading_(),
      elt('div', [
        this.makeUserEntryForSelf_(),
        this.makeUserEntriesForOthers_()
        ], {'class': 'firepad-userlist-users' })
      ], {'class': 'firepad-userlist' });
};

FirepadUserList.prototype.makeHeading_ = function() {
    var counterSpan = elt('span', '0');
    this.firebaseOn_(this.ref_, 'value', function(usersSnapshot) {
      setTextContent(counterSpan, "" + usersSnapshot.numChildren());
  });

    return elt('div', [
      elt('span', 'ONLINE ('),
          counterSpan,
          elt('span', ')')
          ], { 'class': 'firepad-userlist-heading' });
};

FirepadUserList.prototype.makeUserEntryForSelf_ = function() {
    var myUserRef = this.ref_.child(this.userId_);

    var colorDiv = elt('div', null, { 'class': 'firepad-userlist-color-indicator' });
    this.firebaseOn_(myUserRef.child('color'), 'value', function(colorSnapshot) {
      var color = colorSnapshot.val();
      if (isValidColor(color)) {
        colorDiv.style.backgroundColor = color;
    }
});

    var nameInput = elt('p', null, { type: 'text', 'class': 'firepad-userlist-name-input'} );
    nameInput.innerHTML = this.displayName_;

    var nameHint = elt('div', 'ENTER YOUR NAME', { 'class': 'firepad-userlist-name-hint'} );
    /*if (this.hasName_)*/ nameHint.style.display = 'none';

    // Update Firebase when name changes.
    var self = this;
    on(nameInput, 'change', function(e) {
      var name = nameInput.value || "Guest " + Math.floor(Math.random() * 1000);
      myUserRef.child('name').onDisconnect().remove();
      myUserRef.child('name').set(name);
      nameHint.style.display = 'none';
      nameInput.blur();
      self.displayName_ = name;
      stopEvent(e);
  });

    var nameDiv = elt('div', [nameInput, nameHint]);

    return elt('div', [ colorDiv, nameDiv ], {
      'class': 'firepad-userlist-user ' + 'firepad-user-' + this.userId_
  });
};

FirepadUserList.prototype.makeUserEntriesForOthers_ = function() {
    var self = this;
    var userList = elt('div');
    var userId2Element = { };

    function updateChild(userSnapshot, prevChildName) {
      var userId = userSnapshot.key;
      var div = userId2Element[userId];
      if (div) {
        userList.removeChild(div);
        delete userId2Element[userId];
    }
    var name = userSnapshot.child('name').val();
    if (typeof name !== 'string') { name = 'Guest'; }
    name = name.substring(0, 20);

    var color = userSnapshot.child('color').val();
    if (!isValidColor(color)) {
        color = "#ffb"
    }

    var colorDiv = elt('div', null, { 'class': 'firepad-userlist-color-indicator' });
    colorDiv.style.backgroundColor = color;

    var nameDiv = elt('div', name || 'Guest', { 'class': 'firepad-userlist-name' });

    var userDiv = elt('div', [ colorDiv, nameDiv ], {
        'class': 'firepad-userlist-user ' + 'firepad-user-' + userId
    });
    userId2Element[userId] = userDiv;

    if (userId === self.userId_) {
        // HACK: We go ahead and insert ourself in the DOM, so we can easily order other users against it.
        // But don't show it.
        userDiv.style.display = 'none';
    }

    var nextElement =  prevChildName ? userId2Element[prevChildName].nextSibling : userList.firstChild;
    userList.insertBefore(userDiv, nextElement);
}

this.firebaseOn_(this.ref_, 'child_added', updateChild);
this.firebaseOn_(this.ref_, 'child_changed', updateChild);
this.firebaseOn_(this.ref_, 'child_moved', updateChild);
this.firebaseOn_(this.ref_, 'child_removed', function(removedSnapshot) {
  var userId = removedSnapshot.key;
  var div = userId2Element[userId];
  if (div) {
    userList.removeChild(div);
    delete userId2Element[userId];
}
});

return userList;
};

FirepadUserList.prototype.firebaseOn_ = function(ref, eventType, callback, context) {
    this.firebaseCallbacks_.push({ref: ref, eventType: eventType, callback: callback, context: context });
    ref.on(eventType, callback, context);
    return callback;
};

FirepadUserList.prototype.firebaseOff_ = function(ref, eventType, callback, context) {
    ref.off(eventType, callback, context);
    for(var i = 0; i < this.firebaseCallbacks_.length; i++) {
      var l = this.firebaseCallbacks_[i];
      if (l.ref === ref && l.eventType === eventType && l.callback === callback && l.context === context) {
        this.firebaseCallbacks_.splice(i, 1);
        break;
    }
}
};

FirepadUserList.prototype.removeFirebaseCallbacks_ = function() {
    for(var i = 0; i < this.firebaseCallbacks_.length; i++) {
      var l = this.firebaseCallbacks_[i];
      l.ref.off(l.eventType, l.callback, l.context);
  }
  this.firebaseCallbacks_ = [];
};

/** Assorted helpers */

function isValidColor(color) {
    return typeof color === 'string' &&
    (color.match(/^#[a-fA-F0-9]{3,6}$/) || color == 'transparent');
}

/** DOM helpers */
function elt(tag, content, attrs) {
    var e = document.createElement(tag);
    if (typeof content === "string") {
      setTextContent(e, content);
  } else if (content) {
      for (var i = 0; i < content.length; ++i) { e.appendChild(content[i]); }
  }
for(var attr in (attrs || { })) {
  e.setAttribute(attr, attrs[attr]);
}
return e;
}

function setTextContent(e, str) {
    e.innerHTML = "";
    e.appendChild(document.createTextNode(str));
}

function on(emitter, type, f) {
    if (emitter.addEventListener) {
      emitter.addEventListener(type, f, false);
  } else if (emitter.attachEvent) {
      emitter.attachEvent("on" + type, f);
  }
}

function off(emitter, type, f) {
    if (emitter.removeEventListener) {
      emitter.removeEventListener(type, f, false);
  } else if (emitter.detachEvent) {
      emitter.detachEvent("on" + type, f);
  }
}

function preventDefault(e) {
    if (e.preventDefault) {
      e.preventDefault();
  } else {
      e.returnValue = false;
  }
}

function stopPropagation(e) {
    if (e.stopPropagation) {
      e.stopPropagation();
  } else {
      e.cancelBubble = true;
  }
}

function stopEvent(e) {
    preventDefault(e);
    stopPropagation(e);
}

return FirepadUserList;
})();

function getUniqname(email){
    console.log(email);
    return email.substring(0,email.indexOf('@'));
}
<|endoftext|>


<commit_before>import "./";

orb.vector.rotationMatrix = function(α, e) {
  var cosα = Math.cos(α),
      sinα = Math.sin(α);

  switch(e) {
    case 1:
      return [
        1,     0,    0,
        0,  cosα, sinα,
        0, -sinα, cosα
      ];
      break;
    case 2:
      return [
        cosα, 0, -sinα,
           0, 1,     0,
        sinα, 0,  cosα
      ];
      break;
    case 3:
      return [
         cosα, sinα, 0,
        -sinα, cosα, 0,
            0,    0, 1
      ];
      break;
  }
};

orb.vector.r = orb.vector.rotationMatrix;
<commit_msg>[FIX] remove unreachable break statements<commit_after>import "./";

orb.vector.rotationMatrix = function(α, e) {
  var cosα = Math.cos(α),
      sinα = Math.sin(α);

  switch(e) {
    case 1:
      return [
        1,     0,    0,
        0,  cosα, sinα,
        0, -sinα, cosα
      ];

    case 2:
      return [
        cosα, 0, -sinα,
           0, 1,     0,
        sinα, 0,  cosα
      ];

    case 3:
      return [
         cosα, sinα, 0,
        -sinα, cosα, 0,
            0,    0, 1
      ];

  }
};

orb.vector.r = orb.vector.rotationMatrix;
<|endoftext|>


<commit_before>/*!
Waypoints - 4.0.1
Copyright © 2011-2016 Caleb Troughton
Licensed under the MIT license.
https://github.com/imakewebthings/waypoints/blob/master/licenses.txt
*/
(function() {
  'use strict'

  var keyCounter = 0
  var allWaypoints = {}

  /* http://imakewebthings.com/waypoints/api/waypoint */
  function Waypoint(options) {
    if (!options) {
      throw new Error('No options passed to Waypoint constructor')
    }
    if (!options.element) {
      throw new Error('No element option passed to Waypoint constructor')
    }
    if (!options.handler) {
      throw new Error('No handler option passed to Waypoint constructor')
    }

    this.key = 'waypoint-' + keyCounter
    this.options = Waypoint.Adapter.extend({}, Waypoint.defaults, options)
    this.element = this.options.element
    this.adapter = new Waypoint.Adapter(this.element)
    this.callback = options.handler
    this.axis = this.options.horizontal ? 'horizontal' : 'vertical'
    this.enabled = this.options.enabled
    this.triggerPoint = null
    this.group = Waypoint.Group.findOrCreate({
      name: this.options.group,
      axis: this.axis
    })
    this.context = Waypoint.Context.findOrCreateByElement(this.options.context)

    if (Waypoint.offsetAliases[this.options.offset]) {
      this.options.offset = Waypoint.offsetAliases[this.options.offset]
    }
    this.group.add(this)
    this.context.add(this)
    allWaypoints[this.key] = this
    keyCounter += 1
  }

  /* Private */
  Waypoint.prototype.queueTrigger = function(direction) {
    this.group.queueTrigger(this, direction)
  }

  /* Private */
  Waypoint.prototype.trigger = function(args) {
    if (!this.enabled) {
      return
    }
    if (this.callback) {
      this.callback.apply(this, args)
    }
  }

  /* Public */
  /* http://imakewebthings.com/waypoints/api/destroy */
  Waypoint.prototype.destroy = function() {
    this.context.remove(this)
    this.group.remove(this)
    delete allWaypoints[this.key]
  }

  /* Public */
  /* http://imakewebthings.com/waypoints/api/disable */
  Waypoint.prototype.disable = function() {
    this.enabled = false
    return this
  }

  /* Public */
  /* http://imakewebthings.com/waypoints/api/enable */
  Waypoint.prototype.enable = function() {
    this.context.refresh()
    this.enabled = true
    return this
  }

  /* Public */
  /* http://imakewebthings.com/waypoints/api/next */
  Waypoint.prototype.next = function() {
    return this.group.next(this)
  }

  /* Public */
  /* http://imakewebthings.com/waypoints/api/previous */
  Waypoint.prototype.previous = function() {
    return this.group.previous(this)
  }

  /* Private */
  Waypoint.invokeAll = function(method) {
    var allWaypointsArray = []
    for (var waypointKey in allWaypoints) {
      allWaypointsArray.push(allWaypoints[waypointKey])
    }
    for (var i = 0, end = allWaypointsArray.length; i < end; i++) {
      allWaypointsArray[i][method]()
    }
  }

  /* Public */
  /* http://imakewebthings.com/waypoints/api/destroy-all */
  Waypoint.destroyAll = function() {
    Waypoint.invokeAll('destroy')
  }

  /* Public */
  /* http://imakewebthings.com/waypoints/api/disable-all */
  Waypoint.disableAll = function() {
    Waypoint.invokeAll('disable')
  }

  /* Public */
  /* http://imakewebthings.com/waypoints/api/enable-all */
  Waypoint.enableAll = function() {
    Waypoint.Context.refreshAll()
    for (var waypointKey in allWaypoints) {
      allWaypoints[waypointKey].enabled = true
    }
    return this
  }

  /* Public */
  /* http://imakewebthings.com/waypoints/api/refresh-all */
  Waypoint.refreshAll = function() {
    Waypoint.Context.refreshAll()
  }

  /* Public */
  /* http://imakewebthings.com/waypoints/api/viewport-height */
  Waypoint.viewportHeight = function() {
    return window.innerHeight || document.documentElement.clientHeight
  }

  /* Public */
  /* http://imakewebthings.com/waypoints/api/viewport-width */
  Waypoint.viewportWidth = function() {
    return document.documentElement.clientWidth
  }

  Waypoint.adapters = []

  Waypoint.defaults = {
    context: window,
    continuous: true,
    enabled: true,
    group: 'default',
    horizontal: false,
    offset: 0
  }

  Waypoint.offsetAliases = {
    'bottom-in-view': function() {
      return this.context.innerHeight() - this.adapter.outerHeight()
    },
    'right-in-view': function() {
      return this.context.innerWidth() - this.adapter.outerWidth()
    }
  }

  window.Waypoint = Waypoint
}())
;(function() {
  'use strict'

  function requestAnimationFrameShim(callback) {
    window.setTimeout(callback, 1000 / 60)
  }

  var keyCounter = 0
  var contexts = {}
  var Waypoint = window.Waypoint
  var oldWindowLoad = window.onload

  /* http://imakewebthings.com/waypoints/api/context */
  function Context(element) {
    this.element = element
    this.Adapter = Waypoint.Adapter
    this.adapter = new this.Adapter(element)
    this.key = 'waypoint-context-' + keyCounter
    this.didScroll = false
    this.didResize = false
    this.oldScroll = {
      x: this.adapter.scrollLeft(),
      y: this.adapter.scrollTop()
    }
    this.waypoints = {
      vertical: {},
      horizontal: {}
    }

    element.waypointContextKey = this.key
    contexts[element.waypointContextKey] = this
    keyCounter += 1
    if (!Waypoint.windowContext) {
      Waypoint.windowContext = true
      Waypoint.windowContext = new Context(window)
    }

    this.createThrottledScrollHandler()
    this.createThrottledResizeHandler()
  }

  /* Private */
  Context.prototype.add = function(waypoint) {
    var axis = waypoint.options.horizontal ? 'horizontal' : 'vertical'
    this.waypoints[axis][waypoint.key] = waypoint
    this.refresh()
  }

  /* Private */
  Context.prototype.checkEmpty = function() {
    var horizontalEmpty = this.Adapter.isEmptyObject(this.waypoints.horizontal)
    var verticalEmpty = this.Adapter.isEmptyObject(this.waypoints.vertical)
    var isWindow = this.element == this.element.window
    if (horizontalEmpty && verticalEmpty && !isWindow) {
      this.adapter.off('.waypoints')
      delete contexts[this.key]
    }
  }

  /* Private */
  Context.prototype.createThrottledResizeHandler = function() {
    var self = this

    function resizeHandler() {
      self.handleResize()
      self.didResize = false
    }

    this.adapter.on('resize.waypoints', function() {
      if (!self.didResize) {
        self.didResize = true
        Waypoint.requestAnimationFrame(resizeHandler)
      }
    })
  }

  /* Private */
  Context.prototype.createThrottledScrollHandler = function() {
    var self = this
    function scrollHandler() {
      self.handleScroll()
      self.didScroll = false
    }

    this.adapter.on('scroll.waypoints', function() {
      if (!self.didScroll || Waypoint.isTouch) {
        self.didScroll = true
        Waypoint.requestAnimationFrame(scrollHandler)
      }
    })
  }

  /* Private */
  Context.prototype.handleResize = function() {
    Waypoint.Context.refreshAll()
  }

  /* Private */
  Context.prototype.handleScroll = function() {
    var triggeredGroups = {}
    var axes = {
      horizontal: {
        newScroll: this.adapter.scrollLeft(),
        oldScroll: this.oldScroll.x,
        forward: 'right',
        backward: 'left'
      },
      vertical: {
        newScroll: this.adapter.scrollTop(),
        oldScroll: this.oldScroll.y,
        forward: 'down',
        backward: 'up'
      }
    }

    for (var axisKey in axes) {
      var axis = axes[axisKey]
      var isForward = axis.newScroll > axis.oldScroll
      var direction = isForward ? axis.forward : axis.backward

      for (var waypointKey in this.waypoints[axisKey]) {
        var waypoint = this.waypoints[axisKey][waypointKey]
        if (waypoint.triggerPoint === null) {
          continue
        }
        var wasBeforeTriggerPoint = axis.oldScroll < waypoint.triggerPoint
        var nowAfterTriggerPoint = axis.newScroll >= waypoint.triggerPoint
        var crossedForward = wasBeforeTriggerPoint && nowAfterTriggerPoint
        var crossedBackward = !wasBeforeTriggerPoint && !nowAfterTriggerPoint
        if (crossedForward || crossedBackward) {
          waypoint.queueTrigger(direction)
          triggeredGroups[waypoint.group.id] = waypoint.group
        }
      }
    }

    for (var groupKey in triggeredGroups) {
      triggeredGroups[groupKey].flushTriggers()
    }

    this.oldScroll = {
      x: axes.horizontal.newScroll,
      y: axes.vertical.newScroll
    }
  }

  /* Private */
  Context.prototype.innerHeight = function() {
    /*eslint-disable eqeqeq */
    if (this.element == this.element.window) {
      return Waypoint.viewportHeight()
    }
    /*eslint-enable eqeqeq */
    return this.adapter.innerHeight()
  }

  /* Private */
  Context.prototype.remove = function(waypoint) {
    delete this.waypoints[waypoint.axis][waypoint.key]
    this.checkEmpty()
  }

  /* Private */
  Context.prototype.innerWidth = function() {
    /*eslint-disable eqeqeq */
    if (this.element == this.element.window) {
      return Waypoint.viewportWidth()
    }
    /*eslint-enable eqeqeq */
    return this.adapter.innerWidth()
  }

  /* Public */
  /* http://imakewebthings.com/waypoints/api/context-destroy */
  Context.prototype.destroy = function() {
    var allWaypoints = []
    for (var axis in this.waypoints) {
      for (var waypointKey in this.waypoints[axis]) {
        allWaypoints.push(this.waypoints[axis][waypointKey])
      }
    }
    for (var i = 0, end = allWaypoints.length; i < end; i++) {
      allWaypoints[i].destroy()
    }
  }

  /* Public */
  /* http://imakewebthings.com/waypoints/api/context-refresh */
  Context.prototype.refresh = function() {
    /*eslint-disable eqeqeq */
    var isWindow = this.element == this.element.window
    /*eslint-enable eqeqeq */
    var contextOffset = isWindow ? undefined : this.adapter.offset()
    var triggeredGroups = {}
    var axes

    this.handleScroll()
    axes = {
      horizontal: {
        contextOffset: isWindow ? 0 : contextOffset.left,
        contextScroll: isWindow ? 0 : this.oldScroll.x,
        contextDimension: this.innerWidth(),
        oldScroll: this.oldScroll.x,
        forward: 'right',
        backward: 'left',
        offsetProp: 'left'
      },
      vertical: {
        contextOffset: isWindow ? 0 : contextOffset.top,
        contextScroll: isWindow ? 0 : this.oldScroll.y,
        contextDimension: this.innerHeight(),
        oldScroll: this.oldScroll.y,
        forward: 'down',
        backward: 'up',
        offsetProp: 'top'
      }
    }

    for (var axisKey in axes) {
      var axis = axes[axisKey]
      for (var waypointKey in this.waypoints[axisKey]) {
        var waypoint = this.waypoints[axisKey][waypointKey]
        var adjustment = waypoint.options.offset
        var oldTriggerPoint = waypoint.triggerPoint
        var elementOffset = 0
        var freshWaypoint = oldTriggerPoint == null
        var contextModifier, wasBeforeScroll, nowAfterScroll
        var triggeredBackward, triggeredForward

        if (waypoint.element !== waypoint.element.window) {
          elementOffset = waypoint.adapter.offset()[axis.offsetProp]
        }

        if (typeof adjustment === 'function') {
          adjustment = adjustment.apply(waypoint)
        }
        else if (typeof adjustment === 'string') {
          adjustment = parseFloat(adjustment)
          if (waypoint.options.offset.indexOf('%') > - 1) {
            adjustment = Math.ceil(axis.contextDimension * adjustment / 100)
          }
        }

        contextModifier = axis.contextScroll - axis.contextOffset
        waypoint.triggerPoint = Math.floor(elementOffset + contextModifier - adjustment)
        wasBeforeScroll = oldTriggerPoint < axis.oldScroll
        nowAfterScroll = waypoint.triggerPoint >= axis.oldScroll
        triggeredBackward = wasBeforeScroll && nowAfterScroll
        triggeredForward = !wasBeforeScroll && !nowAfterScroll

        if (!freshWaypoint && triggeredBackward) {
          waypoint.queueTrigger(axis.backward)
          triggeredGroups[waypoint.group.id] = waypoint.group
        }
        else if (!freshWaypoint && triggeredForward) {
          waypoint.queueTrigger(axis.forward)
          triggeredGroups[waypoint.group.id] = waypoint.group
        }
        else if (freshWaypoint && axis.oldScroll >= waypoint.triggerPoint) {
          waypoint.queueTrigger(axis.forward)
          triggeredGroups[waypoint.group.id] = waypoint.group
        }
      }
    }

    Waypoint.requestAnimationFrame(function() {
      for (var groupKey in triggeredGroups) {
        triggeredGroups[groupKey].flushTriggers()
      }
    })

    return this
  }

  /* Private */
  Context.findOrCreateByElement = function(element) {
    return Context.findByElement(element) || new Context(element)
  }

  /* Private */
  Context.refreshAll = function() {
    for (var contextId in contexts) {
      contexts[contextId].refresh()
    }
  }

  /* Public */
  /* http://imakewebthings.com/waypoints/api/context-find-by-element */
  Context.findByElement = function(element) {
    return contexts[element.waypointContextKey]
  }

  window.onload = function() {
    if (oldWindowLoad) {
      oldWindowLoad()
    }
    Context.refreshAll()
  }

  Waypoint.requestAnimationFrame = function(callback) {
    var requestFn = window.requestAnimationFrame ||
      window.mozRequestAnimationFrame ||
      window.webkitRequestAnimationFrame ||
      requestAnimationFrameShim
    requestFn.call(window, callback)
  }
  Waypoint.Context = Context
}())
;(function() {
  'use strict'

  function byTriggerPoint(a, b) {
    return a.triggerPoint - b.triggerPoint
  }

  function byReverseTriggerPoint(a, b) {
    return b.triggerPoint - a.triggerPoint
  }

  var groups = {
    vertical: {},
    horizontal: {}
  }
  var Waypoint = window.Waypoint

  /* http://imakewebthings.com/waypoints/api/group */
  function Group(options) {
    this.name = options.name
    this.axis = options.axis
    this.id = this.name + '-' + this.axis
    this.waypoints = []
    this.clearTriggerQueues()
    groups[this.axis][this.name] = this
  }

  /* Private */
  Group.prototype.add = function(waypoint) {
    this.waypoints.push(waypoint)
  }

  /* Private */
  Group.prototype.clearTriggerQueues = function() {
    this.triggerQueues = {
      up: [],
      down: [],
      left: [],
      right: []
    }
  }

  /* Private */
  Group.prototype.flushTriggers = function() {
    for (var direction in this.triggerQueues) {
      var waypoints = this.triggerQueues[direction]
      var reverse = direction === 'up' || direction === 'left'
      waypoints.sort(reverse ? byReverseTriggerPoint : byTriggerPoint)
      for (var i = 0, end = waypoints.length; i < end; i += 1) {
        var waypoint = waypoints[i]
        if (waypoint.options.continuous || i === waypoints.length - 1) {
          waypoint.trigger([direction])
        }
      }
    }
    this.clearTriggerQueues()
  }

  /* Private */
  Group.prototype.next = function(waypoint) {
    this.waypoints.sort(byTriggerPoint)
    var index = Waypoint.Adapter.inArray(waypoint, this.waypoints)
    var isLast = index === this.waypoints.length - 1
    return isLast ? null : this.waypoints[index + 1]
  }

  /* Private */
  Group.prototype.previous = function(waypoint) {
    this.waypoints.sort(byTriggerPoint)
    var index = Waypoint.Adapter.inArray(waypoint, this.waypoints)
    return index ? this.waypoints[index - 1] : null
  }

  /* Private */
  Group.prototype.queueTrigger = function(waypoint, direction) {
    this.triggerQueues[direction].push(waypoint)
  }

  /* Private */
  Group.prototype.remove = function(waypoint) {
    var index = Waypoint.Adapter.inArray(waypoint, this.waypoints)
    if (index > -1) {
      this.waypoints.splice(index, 1)
    }
  }

  /* Public */
  /* http://imakewebthings.com/waypoints/api/first */
  Group.prototype.first = function() {
    return this.waypoints[0]
  }

  /* Public */
  /* http://imakewebthings.com/waypoints/api/last */
  Group.prototype.last = function() {
    return this.waypoints[this.waypoints.length - 1]
  }

  /* Private */
  Group.findOrCreate = function(options) {
    return groups[options.axis][options.name] || new Group(options)
  }

  Waypoint.Group = Group
}())
;(function() {
  'use strict'

  var $ = window.jQuery
  var Waypoint = window.Waypoint

  function JQueryAdapter(element) {
    this.$element = $(element)
  }

  $.each([
    'innerHeight',
    'innerWidth',
    'off',
    'offset',
    'on',
    'outerHeight',
    'outerWidth',
    'scrollLeft',
    'scrollTop'
  ], function(i, method) {
    JQueryAdapter.prototype[method] = function() {
      var args = Array.prototype.slice.call(arguments)
      return this.$element[method].apply(this.$element, args)
    }
  })

  $.each([
    'extend',
    'inArray',
    'isEmptyObject'
  ], function(i, method) {
    JQueryAdapter[method] = $[method]
  })

  Waypoint.adapters.push({
    name: 'jquery',
    Adapter: JQueryAdapter
  })
  Waypoint.Adapter = JQueryAdapter
}())
;(function() {
  'use strict'

  var Waypoint = window.Waypoint

  function createExtension(framework) {
    return function() {
      var waypoints = []
      var overrides = arguments[0]

      if (framework.isFunction(arguments[0])) {
        overrides = framework.extend({}, arguments[1])
        overrides.handler = arguments[0]
      }

      this.each(function() {
        var options = framework.extend({}, overrides, {
          element: this
        })
        if (typeof options.context === 'string') {
          options.context = framework(this).closest(options.context)[0]
        }
        waypoints.push(new Waypoint(options))
      })

      return waypoints
    }
  }

  if (window.jQuery) {
    window.jQuery.fn.waypoint = createExtension(window.jQuery)
  }
  if (window.Zepto) {
    window.Zepto.fn.waypoint = createExtension(window.Zepto)
  }
}())
;<commit_msg>Delete jquery.waypoints.js<commit_after><|endoftext|>


<commit_before>import _ from 'lodash';
import { Observable } from 'rxjs';
import { of } from 'rxjs/observable/of';
import { from } from 'rxjs/observable/from';

class ExampleObservable extends Observable {
    constructor(source) {
        super();
        this.source = source;
    }

    lift(operator) {
        const observable = new ExampleObservable();
        observable.source = this;
        observable.operator = operator;
        return observable;
    }

    static given(params, description) {
        return (new this(of(params)))
            .map(given => ({ given }))
            .extend(ex => ({ description: _.template(description)(ex) }));
    }

    static givenEach(params, description) {
        if (_.isArray(params)) {
            return (new this(from(params)))
                .map(given => ({ given }))
                .attachId()
                .extend(ex => ({ description: _.template(description)(ex) }));
        }
        return (new this(of(params)))
            .map(given => ({ given }))
            .extend(ex => ({ description: _.template(description)(ex) }));
    }

    when(doSomething) {
        return this.extend(ex => ({ actual: doSomething(ex.given) }));
    }

    whenObserving(doSomething) {
        return this.mergeMap(ex => doSomething(ex.given)
            .map(actual => _.extend(ex, { actual }))
        );
    }

    then(check) {
        return this.do((example) => {
            try {
                return check(example.actual);
            } catch (e) {
                _.extend(e, { example });
                throw (e);
            }
        });
    }

    thenEach(check, expecteds) {
        return this.do((example) => {
            try {
                check(example.actual, expecteds[example.id]);
            } catch (e) {
                _.extend(e, { example });
                throw (e);
            }
            return example;
        });
    }

    extend(extension) {
        if (_.isFunction(extension)) return this.map(ex => _.extend(ex, extension(ex)));
        return this.map(ex => _.extend(ex, extension));
    }

    attachId() {
        return this.pairwise()
            .mergeMap((pair) => {
                if (!pair[0].id) {
                    return [
                        _.extend(pair[0], { id: 0 }),
                        _.extend(pair[1], { id: 1 }),
                    ];
                }
                return [_.extend(pair[1], { id: pair[0].id + 1 })];
            });
    }
}

export default module.exports = description => ({
    given: stuff => ExampleObservable.given(stuff, description),
    givenEach: stuff => ExampleObservable.givenEach(stuff, description),
});
<commit_msg>Renamed the array items in attach ID to extracted variables for readability.<commit_after>import _ from 'lodash';
import { Observable } from 'rxjs';
import { of } from 'rxjs/observable/of';
import { from } from 'rxjs/observable/from';

class ExampleObservable extends Observable {
    constructor(source) {
        super();
        this.source = source;
    }

    lift(operator) {
        const observable = new ExampleObservable();
        observable.source = this;
        observable.operator = operator;
        return observable;
    }

    static given(params, description) {
        return (new this(of(params)))
            .map(given => ({ given }))
            .extend(ex => ({ description: _.template(description)(ex) }));
    }

    static givenEach(params, description) {
        if (_.isArray(params)) {
            return (new this(from(params)))
                .map(given => ({ given }))
                .attachId()
                .extend(ex => ({ description: _.template(description)(ex) }));
        }
        return (new this(of(params)))
            .map(given => ({ given }))
            .extend(ex => ({ description: _.template(description)(ex) }));
    }

    when(doSomething) {
        return this.extend(ex => ({ actual: doSomething(ex.given) }));
    }

    whenObserving(doSomething) {
        return this.mergeMap(ex => doSomething(ex.given)
            .map(actual => _.extend(ex, { actual }))
        );
    }

    then(check) {
        return this.do((example) => {
            try {
                return check(example.actual);
            } catch (e) {
                _.extend(e, { example });
                throw (e);
            }
        });
    }

    thenEach(check, expecteds) {
        return this.do((example) => {
            try {
                check(example.actual, expecteds[example.id]);
            } catch (e) {
                _.extend(e, { example });
                throw (e);
            }
            return example;
        });
    }

    extend(extension) {
        if (_.isFunction(extension)) return this.map(ex => _.extend(ex, extension(ex)));
        return this.map(ex => _.extend(ex, extension));
    }

    attachId() {
        return this.pairwise()
            .mergeMap(([previous, current]) => {
                if (!previous.id) {
                    return [
                        _.extend(previous, { id: 0 }),
                        _.extend(current, { id: 1 }),
                    ];
                }
                return [_.extend(current, { id: previous.id + 1 })];
            });
    }
}

export default module.exports = description => ({
    given: stuff => ExampleObservable.given(stuff, description),
    givenEach: stuff => ExampleObservable.givenEach(stuff, description),
});
<|endoftext|>


<commit_before>module.exports = {
	package: {
		files: [
			{
				cwd: '<%= paths.source %>',
				src: [
					'**',
					'!<%= paths.js %>/source/**',
					'!includes/wpcom.php'
				],
				dest: '<%= paths.tmp %>',
				expand: true
			}
		]
	},
	wpcom: {
		files: [
			{
				cwd: 'src',
				src: [
					'**',
					'!<%= paths.js %>/source/**',
					'!includes/back-compat.php',
					'!includes/plugins/**',
					'!includes/vendor/class-audiotheme-themenotice.php',
					'!includes/wporg.php',
					'!languages/**'
				],
				dest: '<%= paths.wpcom %>',
				expand: true
			}
		]
	}
};
<commit_msg>Don't package WPCOM-only templates.<commit_after>module.exports = {
	package: {
		files: [
			{
				cwd: '<%= paths.source %>',
				src: [
					'**',
					'!<%= paths.js %>/source/**',
					'!includes/wpcom.php',
					'!templates/wpcom-*'
				],
				dest: '<%= paths.tmp %>',
				expand: true
			}
		]
	},
	wpcom: {
		files: [
			{
				cwd: 'src',
				src: [
					'**',
					'!<%= paths.js %>/source/**',
					'!includes/back-compat.php',
					'!includes/plugins/**',
					'!includes/vendor/class-audiotheme-themenotice.php',
					'!includes/wporg.php',
					'!languages/**'
				],
				dest: '<%= paths.wpcom %>',
				expand: true
			}
		]
	}
};
<|endoftext|>


<commit_before>goog.require('ol.Map');
goog.require('ol.RendererHint');
goog.require('ol.View2D');
goog.require('ol.layer.Tile');
goog.require('ol.layer.Vector');
goog.require('ol.source.GeoJSON');
goog.require('ol.source.MapQuestOpenAerial');
goog.require('ol.style.Fill');
goog.require('ol.style.Stroke');
goog.require('ol.style.Style');

var styleArray = [new ol.style.Style({
  fill: new ol.style.Fill({
    color: 'rgba(255, 255, 255, 0.6)'
  }),
  stroke: new ol.style.Stroke({
    color: '#319FD3',
    width: 1
  })
})];

var vectorLayer = new ol.layer.Vector({
  source: new ol.source.GeoJSON({
    url: 'data/countries.geojson'
  }),
  styleFunction: function(feature, resolution) {
    return styleArray;
  }
});

var map = new ol.Map({
  layers: [
    new ol.layer.Tile({
      source: new ol.source.MapQuestOpenAerial()
    }),
    vectorLayer
  ],
  renderer: ol.RendererHint.CANVAS,
  target: 'map',
  view: new ol.View2D({
    center: [0, 0],
    zoom: 2
  })
});

var highlight;
var displayFeatureInfo = function(pixel) {
  var oldHighlight = highlight;

  var feature = map.forEachFeatureAtPixel(pixel, function(feature, layer) {
    return feature;
  });

  var info = document.getElementById('info');
  if (feature) {
    info.innerHTML = feature.getId() + ': ' + feature.get('name');
  } else {
    info.innerHTML = ' ';
  }

  highlight = feature;

  if (highlight !== oldHighlight) {
    map.requestRenderFrame();
  }
};

$(map.getViewport()).on('mousemove', function(evt) {
  var pixel = map.getEventPixel(evt.originalEvent);
  displayFeatureInfo(pixel);
});

map.on('singleclick', function(evt) {
  var pixel = evt.getPixel();
  displayFeatureInfo(pixel);
});

var highlightStyle = new ol.style.Style({
  stroke: new ol.style.Stroke({
    color: '#f00',
    width: 1
  }),
  fill: new ol.style.Fill({
    color: 'rgba(255,0,0,0.1)'
  })
});

map.on('postcompose', function(evt) {
  if (highlight) {
    var render = evt.getRender();
    render.drawFeature(highlight, highlightStyle);
  }
});
<commit_msg>Set zoom in vector-layer example to match master<commit_after>goog.require('ol.Map');
goog.require('ol.RendererHint');
goog.require('ol.View2D');
goog.require('ol.layer.Tile');
goog.require('ol.layer.Vector');
goog.require('ol.source.GeoJSON');
goog.require('ol.source.MapQuestOpenAerial');
goog.require('ol.style.Fill');
goog.require('ol.style.Stroke');
goog.require('ol.style.Style');

var styleArray = [new ol.style.Style({
  fill: new ol.style.Fill({
    color: 'rgba(255, 255, 255, 0.6)'
  }),
  stroke: new ol.style.Stroke({
    color: '#319FD3',
    width: 1
  })
})];

var vectorLayer = new ol.layer.Vector({
  source: new ol.source.GeoJSON({
    url: 'data/countries.geojson'
  }),
  styleFunction: function(feature, resolution) {
    return styleArray;
  }
});

var map = new ol.Map({
  layers: [
    new ol.layer.Tile({
      source: new ol.source.MapQuestOpenAerial()
    }),
    vectorLayer
  ],
  renderer: ol.RendererHint.CANVAS,
  target: 'map',
  view: new ol.View2D({
    center: [0, 0],
    zoom: 1
  })
});

var highlight;
var displayFeatureInfo = function(pixel) {
  var oldHighlight = highlight;

  var feature = map.forEachFeatureAtPixel(pixel, function(feature, layer) {
    return feature;
  });

  var info = document.getElementById('info');
  if (feature) {
    info.innerHTML = feature.getId() + ': ' + feature.get('name');
  } else {
    info.innerHTML = ' ';
  }

  highlight = feature;

  if (highlight !== oldHighlight) {
    map.requestRenderFrame();
  }
};

$(map.getViewport()).on('mousemove', function(evt) {
  var pixel = map.getEventPixel(evt.originalEvent);
  displayFeatureInfo(pixel);
});

map.on('singleclick', function(evt) {
  var pixel = evt.getPixel();
  displayFeatureInfo(pixel);
});

var highlightStyle = new ol.style.Style({
  stroke: new ol.style.Stroke({
    color: '#f00',
    width: 1
  }),
  fill: new ol.style.Fill({
    color: 'rgba(255,0,0,0.1)'
  })
});

map.on('postcompose', function(evt) {
  if (highlight) {
    var render = evt.getRender();
    render.drawFeature(highlight, highlightStyle);
  }
});
<|endoftext|>