<commit_before>'use strict';

var mongoose = require('mongoose'),
    hat = require('hat');

//TODO: add required to the fields
var userSchema = new mongoose.Schema({
    facebookId: String,
    accessToken: String,
    name: String,
    photo: String,
    categories: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Category' }],
    notepads: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Notepad' }]
});

//TODO: fix it with static calls only, no new User, etc.
userSchema.static('create', function (data, cb) {
    console.log('new user data', {
        facebookId: data.facebookId,
        accessToken: hat(),
        name: data.name,
        photo: data.photo
    });
    var user = new User({
        facebookId: data.facebookId,
        accessToken: hat(),
        name: data.name,
        photo: data.photo
    });
    return user.save(function (err, user) {
        cb(err, user);
    });
});

//returns only _id
userSchema.static('getByAccessToken', function (accessToken, cb) {
    return this.findOne({ accessToken: accessToken }, null, null, cb);
});

//return only the _id and accessToken for now,
//all that we need to keep a logged in user and make checks on it
userSchema.static('fb', function (fbId, cb) {
    return this.findOne({ facebookId: fbId }, 'facebookId accessToken', null, cb);
});

userSchema.static('getCategories', function (uid, cb) {
    return this.findOne({ _id: uid }, 'categories', null, cb);
});

userSchema.static('getNotepads', function (uid, cb) {
    return this.findOne({ _id: uid }, 'notepads', null, cb);
});

userSchema.static('addCategory', function (userId, categoryId, cb) {
    return this.findOneAndUpdate({ _id: userId }, {
        $addToSet: { categories: categoryId }
    }, cb);
});

userSchema.static('addNotepad', function (userId, notepadId, cb) {
    return this.findOneAndUpdate({ _id: userId }, {
        $addToSet: { notepads: notepadId }
    }, cb);
});

userSchema.static('removeCategory', function (userId, categoryId, cb) {
    return this.findOneAndUpdate({ _id: userId }, {
        $pull: { categories: categoryId }
    }, cb);
});

userSchema.static('removeNotepad', function (userId, notepadId, cb) {
    return this.findOneAndUpdate({ _id: userId }, {
        $pull: { notepads: notepadId }
    }, cb);
});

var User = mongoose.model('User', userSchema);

module.exports = exports = User;
<commit_msg>User.fb set to give a little more information of the user as is needed on the site<commit_after>'use strict';

var mongoose = require('mongoose'),
    hat = require('hat');

//TODO: add required to the fields
var userSchema = new mongoose.Schema({
    facebookId: String,
    accessToken: String,
    name: String,
    photo: String,
    categories: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Category' }],
    notepads: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Notepad' }]
});

//TODO: fix it with static calls only, no new User, etc.
userSchema.static('create', function (data, cb) {
    console.log('new user data', {
        facebookId: data.facebookId,
        accessToken: hat(),
        name: data.name,
        photo: data.photo
    });
    var user = new User({
        facebookId: data.facebookId,
        accessToken: hat(),
        name: data.name,
        photo: data.photo
    });
    return user.save(function (err, user) {
        cb(err, user);
    });
});

//returns only _id
userSchema.static('getByAccessToken', function (accessToken, cb) {
    return this.findOne({ accessToken: accessToken }, null, null, cb);
});

//return only the _id and accessToken for now,
//all that we need to keep a logged in user and make checks on it
userSchema.static('fb', function (fbId, cb) {
    return this.findOne({ facebookId: fbId }, 'facebookId accessToken name photo', null, cb);
});

userSchema.static('getCategories', function (uid, cb) {
    return this.findOne({ _id: uid }, 'categories', null, cb);
});

userSchema.static('getNotepads', function (uid, cb) {
    return this.findOne({ _id: uid }, 'notepads', null, cb);
});

userSchema.static('addCategory', function (userId, categoryId, cb) {
    return this.findOneAndUpdate({ _id: userId }, {
        $addToSet: { categories: categoryId }
    }, cb);
});

userSchema.static('addNotepad', function (userId, notepadId, cb) {
    return this.findOneAndUpdate({ _id: userId }, {
        $addToSet: { notepads: notepadId }
    }, cb);
});

userSchema.static('removeCategory', function (userId, categoryId, cb) {
    return this.findOneAndUpdate({ _id: userId }, {
        $pull: { categories: categoryId }
    }, cb);
});

userSchema.static('removeNotepad', function (userId, notepadId, cb) {
    return this.findOneAndUpdate({ _id: userId }, {
        $pull: { notepads: notepadId }
    }, cb);
});

var User = mongoose.model('User', userSchema);

module.exports = exports = User;
<|endoftext|>


<commit_before>//-------------------------------------------------------------------------------
// Requires
//-------------------------------------------------------------------------------

var buildbug            = require('buildbug');

//-------------------------------------------------------------------------------
// Simplify References
//-------------------------------------------------------------------------------

var buildProject        = buildbug.buildProject;
var buildProperties     = buildbug.buildProperties;
var buildTarget         = buildbug.buildTarget;
var enableModule        = buildbug.enableModule;
var parallel            = buildbug.parallel;
var series              = buildbug.series;
var targetTask          = buildbug.targetTask;

//-------------------------------------------------------------------------------
// Enable Modules
//-------------------------------------------------------------------------------

var aws                 = enableModule("aws");
var bugpack             = enableModule('bugpack');
var bugunit             = enableModule('bugunit');
var core                = enableModule('core');
var nodejs              = enableModule('nodejs');

//-------------------------------------------------------------------------------
// Values
//-------------------------------------------------------------------------------

var version             = "0.1.2";
var dependencies        = {
    bugpack: "0.1.5"
};

//-------------------------------------------------------------------------------
// BuildProperties
//-------------------------------------------------------------------------------

buildProperties({
    node: {
        packageJson: {
            name: "buganno",
            version: version,
            description: "Library for loading and parsing annotations from JavaScript files.",
            main: "./scripts/buganno-node-module.js",
            dependencies: dependencies,
            author: "Brian Neisler <brian@airbug.com>",
            repository: {
                type: "git",
                url: "https://github.com/airbug/buganno.git"
            },
            bugs: {
                url: "https://github.com/airbug/buganno/issues"
            },
            licenses: [
                {
                    type : "MIT",
                    url : "https://raw.githubusercontent.com/airbug/buganno/master/LICENSE"
                }
            ]
        },
        sourcePaths: [
            "../bugcore/projects/bugcore/js/src",
            "../bugflow/projects/bugflow/js/src",
            "../bugfs/projects/bugfs/js/src",
            "../bugtrace/projects/bugtrace/js/src",
            "./projects/buganno/js/src"
        ],
        scriptPaths: [
            "./projects/buganno/js/scripts",
            "./projects/buganno-node/js/scripts"
        ],
        readmePath: "./README.md",
        unitTest: {
            packageJson: {
                name: "buganno-test",
                version: version,
                main: "./scripts/buganno-node-module.js",
                dependencies: dependencies,
                scripts: {
                    test: "./scripts/bugunit-run.js"
                }
            },
            sourcePaths: [
                "../buganno/projects/buganno/js/src",
                "../bugjs/projects/bugyarn/js/src",
                "../bugmeta/projects/bugmeta/js/src",
                "../bugunit/projects/bugdouble/js/src",
                "../bugunit/projects/bugunit/js/src"
            ],
            scriptPaths: [
                "../buganno/projects/buganno/js/scripts",
                "../bugunit/projects/bugunit/js/scripts"
            ],
            testPaths: [
                "../bugcore/projects/bugcore/js/test",
                "../bugflow/projects/bugflow/js/test",
                "../bugfs/projects/bugfs/js/test",
                "../bugtrace/projects/bugtrace/js/test",
                "./projects/buganno/js/test"
            ]
        }
    }
});

//-------------------------------------------------------------------------------
// BuildTargets
//-------------------------------------------------------------------------------

// Clean BuildTarget
//-------------------------------------------------------------------------------

buildTarget('clean').buildFlow(
    targetTask('clean')
);

// Local BuildTarget
//-------------------------------------------------------------------------------

buildTarget('local').buildFlow(
    series([
        targetTask('clean'),
        series([
            targetTask('createNodePackage', {
                properties: {
                    packageJson: buildProject.getProperty("node.packageJson"),
                    readmePath: buildProject.getProperty("node.readmePath"),
                    sourcePaths: buildProject.getProperty("node.sourcePaths").concat(
                        buildProject.getProperty("node.unitTest.sourcePaths")
                    ),
                    scriptPaths: buildProject.getProperty("node.scriptPaths").concat(
                        buildProject.getProperty("node.unitTest.scriptPaths")
                    ),
                    testPaths: buildProject.getProperty("node.unitTest.testPaths")
                }
            }),
            targetTask('generateBugPackRegistry', {
                init: function(task, buildProject, properties) {
                    var nodePackage = nodejs.findNodePackage(
                        buildProject.getProperty("node.packageJson.name"),
                        buildProject.getProperty("node.packageJson.version")
                    );
                    task.updateProperties({
                        sourceRoot: nodePackage.getBuildPath()
                    });
                }
            }),
            targetTask('packNodePackage', {
                properties: {
                    packageName: "{{node.packageJson.name}}",
                    packageVersion: "{{node.packageJson.version}}"
                }
            }),
            targetTask('startNodeModuleTests', {
                init: function(task, buildProject, properties) {
                    var packedNodePackage = nodejs.findPackedNodePackage(
                        buildProject.getProperty("node.packageJson.name"),
                        buildProject.getProperty("node.packageJson.version")
                    );
                    task.updateProperties({
                        modulePath: packedNodePackage.getFilePath()
                        //checkCoverage: true
                    });
                }
            }),
            targetTask("s3PutFile", {
                init: function(task, buildProject, properties) {
                    var packedNodePackage = nodejs.findPackedNodePackage(buildProject.getProperty("node.packageJson.name"),
                        buildProject.getProperty("node.packageJson.version"));
                    task.updateProperties({
                        file: packedNodePackage.getFilePath(),
                        options: {
                            acl: 'public-read',
                            encrypt: true
                        }
                    });
                },
                properties: {
                    bucket: "{{local-bucket}}"
                }
            })
        ])
    ])
).makeDefault();

// Prod BuildTarget
//-------------------------------------------------------------------------------

buildTarget('prod').buildFlow(
    series([
        targetTask('clean'),
        parallel([

            //Create test node buganno package

            series([
                targetTask('createNodePackage', {
                    properties: {
                        packageJson: buildProject.getProperty("node.unitTest.packageJson"),
                        sourcePaths: buildProject.getProperty("node.sourcePaths").concat(
                            buildProject.getProperty("node.unitTest.sourcePaths")
                        ),
                        scriptPaths: buildProject.getProperty("node.scriptPaths").concat(
                            buildProject.getProperty("node.unitTest.scriptPaths")
                        ),
                        testPaths: buildProject.getProperty("node.unitTest.testPaths")
                    }
                }),
                targetTask('generateBugPackRegistry', {
                    init: function(task, buildProject, properties) {
                        var nodePackage = nodejs.findNodePackage(
                            buildProject.getProperty("node.unitTest.packageJson.name"),
                            buildProject.getProperty("node.unitTest.packageJson.version")
                        );
                        task.updateProperties({
                            sourceRoot: nodePackage.getBuildPath()
                        });
                    }
                }),
                targetTask('packNodePackage', {
                    properties: {
                        packageName: "{{node.unitTest.packageJson.name}}",
                        packageVersion: "{{node.unitTest.packageJson.version}}"
                    }
                }),
                targetTask('startNodeModuleTests', {
                    init: function(task, buildProject, properties) {
                        var packedNodePackage = nodejs.findPackedNodePackage(
                            buildProject.getProperty("node.unitTest.packageJson.name"),
                            buildProject.getProperty("node.unitTest.packageJson.version")
                        );
                        task.updateProperties({
                            modulePath: packedNodePackage.getFilePath(),
                            checkCoverage: true
                        });
                    }
                })
            ]),

            // Create production node buganno package

            series([
                targetTask('createNodePackage', {
                    properties: {
                        packageJson: buildProject.getProperty("node.packageJson"),
                        readmePath: buildProject.getProperty("node.readmePath"),
                        sourcePaths: buildProject.getProperty("node.sourcePaths"),
                        scriptPaths: buildProject.getProperty("node.scriptPaths")
                    }
                }),
                targetTask('generateBugPackRegistry', {
                    init: function(task, buildProject, properties) {
                        var nodePackage = nodejs.findNodePackage(
                            buildProject.getProperty("node.packageJson.name"),
                            buildProject.getProperty("node.packageJson.version")
                        );
                        task.updateProperties({
                            sourceRoot: nodePackage.getBuildPath()
                        });
                    }
                }),
                targetTask('packNodePackage', {
                    properties: {
                        packageName: "{{node.packageJson.name}}",
                        packageVersion: "{{node.packageJson.version}}"
                    }
                }),
                targetTask("s3PutFile", {
                    init: function(task, buildProject, properties) {
                        var packedNodePackage = nodejs.findPackedNodePackage(buildProject.getProperty("node.packageJson.name"),
                            buildProject.getProperty("node.packageJson.version"));
                        task.updateProperties({
                            file: packedNodePackage.getFilePath(),
                            options: {
                                acl: 'public-read',
                                encrypt: true
                            }
                        });
                    },
                    properties: {
                        bucket: "{{prod-deploy-bucket}}"
                    }
                }),
                targetTask('npmConfigSet', {
                    properties: {
                        config: buildProject.getProperty("npmConfig")
                    }
                }),
                targetTask('npmAddUser'),
                targetTask('publishNodePackage', {
                    properties: {
                        packageName: "{{node.packageJson.name}}",
                        packageVersion: "{{node.packageJson.version}}"
                    }
                })
            ])
        ])
    ])
);
<commit_msg>Update to bugpack 0.1.6<commit_after>//-------------------------------------------------------------------------------
// Requires
//-------------------------------------------------------------------------------

var buildbug            = require('buildbug');

//-------------------------------------------------------------------------------
// Simplify References
//-------------------------------------------------------------------------------

var buildProject        = buildbug.buildProject;
var buildProperties     = buildbug.buildProperties;
var buildTarget         = buildbug.buildTarget;
var enableModule        = buildbug.enableModule;
var parallel            = buildbug.parallel;
var series              = buildbug.series;
var targetTask          = buildbug.targetTask;

//-------------------------------------------------------------------------------
// Enable Modules
//-------------------------------------------------------------------------------

var aws                 = enableModule("aws");
var bugpack             = enableModule('bugpack');
var bugunit             = enableModule('bugunit');
var core                = enableModule('core');
var nodejs              = enableModule('nodejs');

//-------------------------------------------------------------------------------
// Values
//-------------------------------------------------------------------------------

var version             = "0.1.2";
var dependencies        = {
    bugpack: "0.1.6"
};

//-------------------------------------------------------------------------------
// BuildProperties
//-------------------------------------------------------------------------------

buildProperties({
    node: {
        packageJson: {
            name: "buganno",
            version: version,
            description: "Library for loading and parsing annotations from JavaScript files.",
            main: "./scripts/buganno-node-module.js",
            dependencies: dependencies,
            author: "Brian Neisler <brian@airbug.com>",
            repository: {
                type: "git",
                url: "https://github.com/airbug/buganno.git"
            },
            bugs: {
                url: "https://github.com/airbug/buganno/issues"
            },
            licenses: [
                {
                    type : "MIT",
                    url : "https://raw.githubusercontent.com/airbug/buganno/master/LICENSE"
                }
            ]
        },
        sourcePaths: [
            "../bugcore/projects/bugcore/js/src",
            "../bugflow/projects/bugflow/js/src",
            "../bugfs/projects/bugfs/js/src",
            "../bugtrace/projects/bugtrace/js/src",
            "./projects/buganno/js/src"
        ],
        scriptPaths: [
            "./projects/buganno/js/scripts",
            "./projects/buganno-node/js/scripts"
        ],
        readmePath: "./README.md",
        unitTest: {
            packageJson: {
                name: "buganno-test",
                version: version,
                main: "./scripts/buganno-node-module.js",
                dependencies: dependencies,
                scripts: {
                    test: "./scripts/bugunit-run.js"
                }
            },
            sourcePaths: [
                "../buganno/projects/buganno/js/src",
                "../bugjs/projects/bugyarn/js/src",
                "../bugmeta/projects/bugmeta/js/src",
                "../bugunit/projects/bugdouble/js/src",
                "../bugunit/projects/bugunit/js/src"
            ],
            scriptPaths: [
                "../buganno/projects/buganno/js/scripts",
                "../bugunit/projects/bugunit/js/scripts"
            ],
            testPaths: [
                "../bugcore/projects/bugcore/js/test",
                "../bugflow/projects/bugflow/js/test",
                "../bugfs/projects/bugfs/js/test",
                "../bugtrace/projects/bugtrace/js/test",
                "./projects/buganno/js/test"
            ]
        }
    }
});

//-------------------------------------------------------------------------------
// BuildTargets
//-------------------------------------------------------------------------------

// Clean BuildTarget
//-------------------------------------------------------------------------------

buildTarget('clean').buildFlow(
    targetTask('clean')
);

// Local BuildTarget
//-------------------------------------------------------------------------------

buildTarget('local').buildFlow(
    series([
        targetTask('clean'),
        series([
            targetTask('createNodePackage', {
                properties: {
                    packageJson: buildProject.getProperty("node.packageJson"),
                    readmePath: buildProject.getProperty("node.readmePath"),
                    sourcePaths: buildProject.getProperty("node.sourcePaths").concat(
                        buildProject.getProperty("node.unitTest.sourcePaths")
                    ),
                    scriptPaths: buildProject.getProperty("node.scriptPaths").concat(
                        buildProject.getProperty("node.unitTest.scriptPaths")
                    ),
                    testPaths: buildProject.getProperty("node.unitTest.testPaths")
                }
            }),
            targetTask('generateBugPackRegistry', {
                init: function(task, buildProject, properties) {
                    var nodePackage = nodejs.findNodePackage(
                        buildProject.getProperty("node.packageJson.name"),
                        buildProject.getProperty("node.packageJson.version")
                    );
                    task.updateProperties({
                        sourceRoot: nodePackage.getBuildPath()
                    });
                }
            }),
            targetTask('packNodePackage', {
                properties: {
                    packageName: "{{node.packageJson.name}}",
                    packageVersion: "{{node.packageJson.version}}"
                }
            }),
            targetTask('startNodeModuleTests', {
                init: function(task, buildProject, properties) {
                    var packedNodePackage = nodejs.findPackedNodePackage(
                        buildProject.getProperty("node.packageJson.name"),
                        buildProject.getProperty("node.packageJson.version")
                    );
                    task.updateProperties({
                        modulePath: packedNodePackage.getFilePath()
                        //checkCoverage: true
                    });
                }
            }),
            targetTask("s3PutFile", {
                init: function(task, buildProject, properties) {
                    var packedNodePackage = nodejs.findPackedNodePackage(buildProject.getProperty("node.packageJson.name"),
                        buildProject.getProperty("node.packageJson.version"));
                    task.updateProperties({
                        file: packedNodePackage.getFilePath(),
                        options: {
                            acl: 'public-read',
                            encrypt: true
                        }
                    });
                },
                properties: {
                    bucket: "{{local-bucket}}"
                }
            })
        ])
    ])
).makeDefault();

// Prod BuildTarget
//-------------------------------------------------------------------------------

buildTarget('prod').buildFlow(
    series([
        targetTask('clean'),
        parallel([

            //Create test node buganno package

            series([
                targetTask('createNodePackage', {
                    properties: {
                        packageJson: buildProject.getProperty("node.unitTest.packageJson"),
                        sourcePaths: buildProject.getProperty("node.sourcePaths").concat(
                            buildProject.getProperty("node.unitTest.sourcePaths")
                        ),
                        scriptPaths: buildProject.getProperty("node.scriptPaths").concat(
                            buildProject.getProperty("node.unitTest.scriptPaths")
                        ),
                        testPaths: buildProject.getProperty("node.unitTest.testPaths")
                    }
                }),
                targetTask('generateBugPackRegistry', {
                    init: function(task, buildProject, properties) {
                        var nodePackage = nodejs.findNodePackage(
                            buildProject.getProperty("node.unitTest.packageJson.name"),
                            buildProject.getProperty("node.unitTest.packageJson.version")
                        );
                        task.updateProperties({
                            sourceRoot: nodePackage.getBuildPath()
                        });
                    }
                }),
                targetTask('packNodePackage', {
                    properties: {
                        packageName: "{{node.unitTest.packageJson.name}}",
                        packageVersion: "{{node.unitTest.packageJson.version}}"
                    }
                }),
                targetTask('startNodeModuleTests', {
                    init: function(task, buildProject, properties) {
                        var packedNodePackage = nodejs.findPackedNodePackage(
                            buildProject.getProperty("node.unitTest.packageJson.name"),
                            buildProject.getProperty("node.unitTest.packageJson.version")
                        );
                        task.updateProperties({
                            modulePath: packedNodePackage.getFilePath(),
                            checkCoverage: true
                        });
                    }
                })
            ]),

            // Create production node buganno package

            series([
                targetTask('createNodePackage', {
                    properties: {
                        packageJson: buildProject.getProperty("node.packageJson"),
                        readmePath: buildProject.getProperty("node.readmePath"),
                        sourcePaths: buildProject.getProperty("node.sourcePaths"),
                        scriptPaths: buildProject.getProperty("node.scriptPaths")
                    }
                }),
                targetTask('generateBugPackRegistry', {
                    init: function(task, buildProject, properties) {
                        var nodePackage = nodejs.findNodePackage(
                            buildProject.getProperty("node.packageJson.name"),
                            buildProject.getProperty("node.packageJson.version")
                        );
                        task.updateProperties({
                            sourceRoot: nodePackage.getBuildPath()
                        });
                    }
                }),
                targetTask('packNodePackage', {
                    properties: {
                        packageName: "{{node.packageJson.name}}",
                        packageVersion: "{{node.packageJson.version}}"
                    }
                }),
                targetTask("s3PutFile", {
                    init: function(task, buildProject, properties) {
                        var packedNodePackage = nodejs.findPackedNodePackage(buildProject.getProperty("node.packageJson.name"),
                            buildProject.getProperty("node.packageJson.version"));
                        task.updateProperties({
                            file: packedNodePackage.getFilePath(),
                            options: {
                                acl: 'public-read',
                                encrypt: true
                            }
                        });
                    },
                    properties: {
                        bucket: "{{prod-deploy-bucket}}"
                    }
                }),
                targetTask('npmConfigSet', {
                    properties: {
                        config: buildProject.getProperty("npmConfig")
                    }
                }),
                targetTask('npmAddUser'),
                targetTask('publishNodePackage', {
                    properties: {
                        packageName: "{{node.packageJson.name}}",
                        packageVersion: "{{node.packageJson.version}}"
                    }
                })
            ])
        ])
    ])
);
<|endoftext|>


<commit_before>var _          = require('_'),
    overload   = require('overload'),
    O          = overload.O,

    _SUPPORTS  = require('../supports'),
    _NODE_TYPE = require('../nodeType'),

    _utils     = require('../utils'),
    _div       = require('../div');

var _outerHtml = function() {
    return this.length ? this[0].outerHTML : null;
};

var _text = {
    get: (_div.textContent !== undefined) ?
        function(elem) { return elem.textContent; } :
            function(elem) { return elem.innerText; } ,
    set: (_div.textContent !== undefined) ?
        function(elem, str) { elem.textContent = str; } :
            function(elem, str) { elem.innerText = str; }
};

var _valHooks = {
    option: {
        get: function(elem) {
            var val = elem.getAttribute('value');
            return _.exists(val) ? val : _text.get(elem);
        }
    },

    select: {
        get: function(elem) {
            var value, option,
                options = elem.options,
                index   = elem.selectedIndex,
                one     = elem.type === 'select-one' || index < 0,
                values  = one ? null : [],
                max     = one ? index + 1 : options.length,
                idx     = index < 0 ? max : (one ? index : 0);

            // Loop through all the selected options
            for (; idx < max; idx++) {
                option = options[idx];

                // oldIE doesn't update selected after form reset (#2551)
                if ((option.selected || idx === index) &&
                        // Don't return options that are disabled or in a disabled optgroup
                        (_SUPPORTS.optDisabled ? !option.disabled : option.getAttribute('disabled') === null) &&
                        (!option.parentNode.disabled || !_utils.isNodeName(option.parentNode, 'optgroup'))) {

                    // Get the specific value for the option
                    value = _valHooks.option.get(option);

                    // We don't need an array for one selects
                    if (one) {
                        return value;
                    }

                    // Multi-Selects return an array
                    values.push(value);
                }
            }

            return values;
        },

        set: function(elem, value) {
            var optionSet, option,
                options = elem.options,
                values  = jQuery.makeArray(value),
                idx     = options.length;

            while (idx--) {
                option = options[idx];

                if (jQuery.inArray(jQuery.valHooks.option.get(option), values) >= 0) {
                    option.selected = optionSet = true;
                } else {
                    option.selected = false;
                }
            }

            // Force browsers to behave consistently when non-matching value is set
            if (!optionSet) {
                elem.selectedIndex = -1;
            }
        }
    }

};

// Radios and checkboxes getter/setter
_.each(['radio', 'checkbox'], function(type) {
    _valHooks[type] = {
        set: function(elem, value) {
            if (_.isArray(value)) {
                return (elem.checked = jQuery.inArray(jQuery(elem).val(), value) >= 0);
            }
        }
    };

    if (!_SUPPORTS.checkOn) {
        _valHooks[type].get = function(elem) {
            // Support: Webkit - '' is returned instead of 'on' if a value isn't specified
            return elem.getAttribute('value') === null ? 'on' : elem.value;
        };
    }
});

var _getVal = function(elem) {
    if (!elem || (elem.nodeType !== _NODE_TYPE.ELEMENT)) { return; }

    var hook = _valHooks[elem.type] || _valHooks[_utils.normalNodeName(elem)];
    if (hook && hook.get) {
        return hook.get(elem);
    }

    return _utils.normalizeNewlines(elem.value);
};

var _setVal = function(elem, value) {
    if (elem.nodeType !== _NODE_TYPE.ELEMENT) { return; }

    var hook = _valHooks[elem.type] || _valHooks[_utils.normalNodeName(elem)];
    if (hook && hook.set) {
        hook.set(elem, value);
    } else {
        elem.setAttribute('value', value);
    }
};

module.exports = {
    fn: {
        // TODO: Overload and determine api
        // TODO: unit tests
        outerHtml: _outerHtml,
        outerHTML: _outerHtml,

        html: overload()
            .args(String)
            .use(function(html) {
                return _.each(this, function(elem) {
                    elem.innerHTML = html;
                });
            })

            .args(Function)
            .use(function(iterator) {
                return _.each(this, function(elem, idx) {
                    elem.innerHTML = iterator.call(elem, idx, elem.innerHTML);
                });
            })

            .fallback(function() {
                var first = this[0];
                return (!first) ? undefined : first.innerHTML;
            })
            .expose(),

        // TODO: Add handling of (and unit tests for) \r\n in IE
        val: overload()
            .args(O.any(String, Number))
            .use(function(value) {
                value = '' + value;
                return _.each(this, function(elem) {
                    _setVal(elem, value);
                });
            })

            .args(Function)
            .use(function(iterator) {
                return _.each(this, function(elem, idx) {
                    if (elem.nodeType !== _NODE_TYPE.ELEMENT) { return; }

                    var value = iterator.call(elem, idx, _getVal(elem));
                    var hook = _valHooks[elem.type] || _valHooks[_utils.normalNodeName(elem)];

                    if (hook && hook.set) {
                        hook.set(elem, value);
                    } else {
                        elem.setAttribute('value', value);
                    }
                });
            })

            .args(Array)
            .use(function(arr) {
                var dom = this,
                    len = this.length;
                _.each(arr, function(val, idx) {
                    if (idx >= len) { return false; }
                    _setVal(dom[idx], '' + val);
                });
                return this;
            })

            .fallback(function() {
                return _getVal(this[0]);
            })

            .expose(),

        text: overload()
            .args(String)
            .use(function(str) {
                return _.each(this, function(elem) {
                    _text.set(elem, str);
                });
            })

            .args(Function)
            .use(function(iterator) {
                return _.each(this, function(elem, idx) {
                    _text.set(elem, iterator.call(elem, idx, _text.get(elem)));
                });
            })

            .fallback(function() {
                var str = '';
                _.each(this, function(elem) {
                    str += _text.get(elem);
                });

                return str;
            })
            .expose()
    }
};
<commit_msg>Fixed failing test<commit_after>var _          = require('_'),
    overload   = require('overload'),
    O          = overload.O,

    _SUPPORTS  = require('../supports'),
    _NODE_TYPE = require('../nodeType'),

    _utils     = require('../utils'),
    _div       = require('../div');

var _outerHtml = function() {
    return this.length ? this[0].outerHTML : null;
};

var _text = {
    get: (_div.textContent !== undefined) ?
        function(elem) { return elem.textContent; } :
            function(elem) { return elem.innerText; } ,
    set: (_div.textContent !== undefined) ?
        function(elem, str) { elem.textContent = str; } :
            function(elem, str) { elem.innerText = str; }
};

var _valHooks = {
    option: {
        get: function(elem) {
            var val = elem.getAttribute('value');
            return _.exists(val) ? val : _text.get(elem);
        }
    },

    select: {
        get: function(elem) {
            var value, option,
                options = elem.options,
                index   = elem.selectedIndex,
                one     = elem.type === 'select-one' || index < 0,
                values  = one ? null : [],
                max     = one ? index + 1 : options.length,
                idx     = index < 0 ? max : (one ? index : 0);

            // Loop through all the selected options
            for (; idx < max; idx++) {
                option = options[idx];

                // oldIE doesn't update selected after form reset (#2551)
                if ((option.selected || idx === index) &&
                        // Don't return options that are disabled or in a disabled optgroup
                        (_SUPPORTS.optDisabled ? !option.disabled : option.getAttribute('disabled') === null) &&
                        (!option.parentNode.disabled || !_utils.isNodeName(option.parentNode, 'optgroup'))) {

                    // Get the specific value for the option
                    value = _valHooks.option.get(option);

                    // We don't need an array for one selects
                    if (one) {
                        return value;
                    }

                    // Multi-Selects return an array
                    values.push(value);
                }
            }

            return values;
        },

        set: function(elem, value) {
            var optionSet, option,
                options = elem.options,
                values  = jQuery.makeArray(value),
                idx     = options.length;

            while (idx--) {
                option = options[idx];

                if (jQuery.inArray(jQuery.valHooks.option.get(option), values) >= 0) {
                    option.selected = optionSet = true;
                } else {
                    option.selected = false;
                }
            }

            // Force browsers to behave consistently when non-matching value is set
            if (!optionSet) {
                elem.selectedIndex = -1;
            }
        }
    }

};

// Radios and checkboxes getter/setter
_.each(['radio', 'checkbox'], function(type) {
    _valHooks[type] = {
        set: function(elem, value) {
            if (_.isArray(value)) {
                return (elem.checked = jQuery.inArray(jQuery(elem).val(), value) >= 0);
            }
        }
    };

    if (!_SUPPORTS.checkOn) {
        _valHooks[type].get = function(elem) {
            // Support: Webkit - '' is returned instead of 'on' if a value isn't specified
            return elem.getAttribute('value') === null ? 'on' : elem.value;
        };
    }
});

var _getVal = function(elem) {
    if (!elem || (elem.nodeType !== _NODE_TYPE.ELEMENT)) { return; }

    var hook = _valHooks[elem.type] || _valHooks[_utils.normalNodeName(elem)];
    if (hook && hook.get) {
        return hook.get(elem);
    }

    var val = elem.value;
    return _.isString(val) ? _utils.normalizeNewlines() : val;

};

var _setVal = function(elem, value) {
    if (elem.nodeType !== _NODE_TYPE.ELEMENT) { return; }

    var hook = _valHooks[elem.type] || _valHooks[_utils.normalNodeName(elem)];
    if (hook && hook.set) {
        hook.set(elem, value);
    } else {
        elem.setAttribute('value', value);
    }
};

module.exports = {
    fn: {
        // TODO: Overload and determine api
        // TODO: unit tests
        outerHtml: _outerHtml,
        outerHTML: _outerHtml,

        html: overload()
            .args(String)
            .use(function(html) {
                return _.each(this, function(elem) {
                    elem.innerHTML = html;
                });
            })

            .args(Function)
            .use(function(iterator) {
                return _.each(this, function(elem, idx) {
                    elem.innerHTML = iterator.call(elem, idx, elem.innerHTML);
                });
            })

            .fallback(function() {
                var first = this[0];
                return (!first) ? undefined : first.innerHTML;
            })
            .expose(),

        // TODO: Add handling of (and unit tests for) \r\n in IE
        val: overload()
            .args(O.any(String, Number))
            .use(function(value) {
                value = '' + value;
                return _.each(this, function(elem) {
                    _setVal(elem, value);
                });
            })

            .args(Function)
            .use(function(iterator) {
                return _.each(this, function(elem, idx) {
                    if (elem.nodeType !== _NODE_TYPE.ELEMENT) { return; }

                    var value = iterator.call(elem, idx, _getVal(elem));
                    var hook = _valHooks[elem.type] || _valHooks[_utils.normalNodeName(elem)];

                    if (hook && hook.set) {
                        hook.set(elem, value);
                    } else {
                        elem.setAttribute('value', value);
                    }
                });
            })

            .args(Array)
            .use(function(arr) {
                var dom = this,
                    len = this.length;
                _.each(arr, function(val, idx) {
                    if (idx >= len) { return false; }
                    _setVal(dom[idx], '' + val);
                });
                return this;
            })

            .fallback(function() {
                return _getVal(this[0]);
            })

            .expose(),

        text: overload()
            .args(String)
            .use(function(str) {
                return _.each(this, function(elem) {
                    _text.set(elem, str);
                });
            })

            .args(Function)
            .use(function(iterator) {
                return _.each(this, function(elem, idx) {
                    _text.set(elem, iterator.call(elem, idx, _text.get(elem)));
                });
            })

            .fallback(function() {
                var str = '';
                _.each(this, function(elem) {
                    str += _text.get(elem);
                });

                return str;
            })
            .expose()
    }
};
<|endoftext|>


<commit_before>define(['root', 'gemabord/log'], function(root, Log) {
  'use strict';

  // Map shorthand functions to Log.i
  root.log = root.out = Log.i;

  return Log;
});<commit_msg>Fixes log reference<commit_after>define(['root', 'gameboard/log'], function(root, Log) {
  'use strict';

  // Map shorthand functions to Log.i
  root.log = root.out = Log.i;

  return Log;
});<|endoftext|>


<commit_before>'use strict';

// look up how to connect to folder of images. //
var option = [];

// ref. https://stackoverflow.com/questions/24029767/returning-a-random-new-initialized-object-in-javascript //
function A() {
  this.option = "A";
}

function B() {
  this.option = "B";
}

function C() {
  this.option = "C";
}

var allOptions = [A, B, C];

function render([A, B, C];) {
  for(var i = 0; i < allOptions.length; i++) {
    allOptions[i].render(3);
  }

new option('img/bathroom.jpg', 'img/boots.jpg', 'img/breakfast-1.jpg');
new option('img/breakfast.jpg', 'img/bubblegum.jpg', 'img/chair.jpg');
new option('img/cthulhu.jpg', 'img/dog-duck.jpg', 'img/dragon.jpg');
new option('img/pen.jpg', 'img/pet-sweep.jpg', 'img/scissors.jpg');
new option('img/shark.jpg', 'img/sweep.png', 'img/tauntaun.jpg');
new option('img/unicorn.jpg', 'img/usb.gif', 'img/water-can.jpg');
new option('img/wine-glass.jpg');

};

function getRandomOptions() {
  var rand = Math.floor(Math.random() * allOptions.length);
  return new option[rand]();
}

log(getRandomOptions());
log(getRandomOptions());
log(getRandomOptions());
log(getRandomOptions());
<commit_msg>Corrections<commit_after>'use strict';

// ref. 'Returning a random new initialized object in JavaScript'
// https://stackoverflow.com/
// https://stackoverflow.com/questions/24029767/returning-a-random-new-initialized-object-in-javascript
var option = function renderOption() {

  for(var i = 0; i < allOptions.length; i++) {
    allOptions[i].render(3);

// need to look up how to connect to folder of images. //
  if option = function A() {
    this.option = "A";
    }

    else if (false) {
      option = function B() {
      this.option = "B";
      }
    }

    else if (false) {
    option = function C() {
    this.option = "C";
      }
    }

  new option('img/bathroom.jpg', 'img/boots.jpg', 'img/breakfast-1.jpg');
  new option('img/breakfast.jpg', 'img/bubblegum.jpg', 'img/chair.jpg');
  new option('img/cthulhu.jpg', 'img/dog-duck.jpg', 'img/dragon.jpg');
  new option('img/pen.jpg', 'img/pet-sweep.jpg', 'img/scissors.jpg');
  new option('img/shark.jpg', 'img/sweep.png', 'img/tauntaun.jpg');
  new option('img/unicorn.jpg', 'img/usb.gif', 'img/water-can.jpg');
  new option('img/wine-glass.jpg');

}

  tdEl = document.createElement('td');
  tdEl.textContent = allOptions;
  trEl.appendChild(tdEl);
  theTable.appendChild(trEl);

  function getRandomOptions() {
    var rand = Math.floor(Math.random() * allOptions.length);
    return new option[rand]();
  }
}

renderOption(getRandomOptions());
log(getRandomOptions());
log(getRandomOptions());
log(getRandomOptions());
<|endoftext|>


<commit_before>/**
 * Custom prototype metods
 * @author zhurbitsky@gmail.com
 */

HTMLElement.prototype.show = function(){
    try{
        this.style.display = 'block';
    }catch(e){
        _debug(e);
    }
}

HTMLElement.prototype.hide = function(){
    try{
        this.style.display = 'none';
    }catch(e){
        _debug(e);
    }
}

HTMLElement.prototype.moveX = function(to_x){
    try{
        this.style.left = parseInt(to_x)+'px';
    }catch(e){
        _debug(e);
    }
}

HTMLElement.prototype.moveY = function(to_y){
    try{
        this.style.top = parseInt(to_y)+'px';
    }catch(e){
        _debug(e);
    }
}

HTMLElement.prototype.offsetX = function(offset_x){
    if (!this.style.left){
        this.style.left = 0+'px';
    };

    try{
        this.style.left = parseInt(this.style.left)+offset_x+'px';
    }catch(e){
        _debug(e);
    }
}

HTMLElement.prototype.offsetY = function(offset_y){
    if (!this.style.top){
        this.style.top = 0+'px';
    };

    try{
        this.style.top = parseInt(this.style.top)+offset_y+'px';
    }catch(e){
        _debug(e);
    }
}

HTMLElement.prototype.setClass = function(class_name){
    try{
        this.className = class_name;
    }catch(e){
        _debug(e);
    }
}

HTMLElement.prototype.addClass = function(class_name){
    try{
        if (!this.className){
            this.setClass(class_name);
        }else{
            var new_class_name = this.className;
            new_class_name += " ";
            new_class_name += class_name;
            this.setClass(new_class_name);
        }
    }catch(e){
        _debug(e);
    }
}

String.prototype.clearnl = function(){
    return this.replace(/(\n(\r)?)/g, '');
}

if (typeof Object.prototype.toSource != 'function'){

    /*Array.prototype.toSource = function(){
        return '[' + this.join( ', ' ) + ']';
    }

    Object.prototype.toSource = function(){
        return 'This browser not support Object toSource method';
    }*/

    Object.prototype.toSource = function() {
        var con = this.constructor;
        if(con == String) {
            //return '"' + this + '"';
            return this;
        } else if(con == Number) {
            return this;
        } else if(con == Array) {
            var res = '[';
            for(var i=0,len=this.length;i<len;i++) {
                if(i == len-1)
                    res += this[i].toSource() + ']';
                else
                    res += this[i].toSource() + ', ';
            }
            return res;
        } else if(con == RegExp) {
            return this;
        } else if(con == Object) {
            var res = '{';
            var i=0;
            for(var j in this) {
                if(j != 'toSource') {
                    if(i == 0) {
                        res += j + ':' + this[j].toSource(1);
                    } else {
                        res += ', ' + j + ':' + this[j].toSource(1);
                    }
                    i++;
                }
            }
            res += '}';
            if(arguments.length) {
                return res;
            } else {
                return '(' + res + ')';
            }
        }
    }

}

Array.prototype.getIdxById = function(id){
    for (var i=0; i<this.length; i++){
        if (this[i].hasOwnProperty('id')){
            if (this[i].id == id){
                return i;
            }
        }
    }
    return null;
}

Array.prototype.getIdxByVal = function(what, eq){
    for (var i=0; i<this.length; i++){
        if (this[i].hasOwnProperty(what)){
            if (this[i][what] == eq){
                return i;
            }
        }
    }
    return null;
}

Array.prototype.getIdxByNumber = function(number){
    for (var i=0; i<this.length; i++){
        if (this[i].hasOwnProperty('number')){
            if (this[i].number == number){
                return i;
            }
        }
    }
    return null;
}

Array.prototype.inArray = function (value){
    for (var i=0; i < this.length; i++){
        if (this[i] === value){
            return true;
        }
    }
    return false;
};<commit_msg>"Add _debug, $ functions"<commit_after>/**
 * Alias for document.getElementById.
 * @param {Number} id
 * @return {*} DOMElement
 */
var $ = function(id){
    return document.getElementById(id);
}

/**
 * Debug function.
 */
function _debug(){
    if (debug){

        var text = '';
        for (var i = 0; i < arguments.length; i++){
            if (arguments[i].message && arguments[i].name){
                text += ' '+arguments[i];
            }else{
                text += ' '+arguments[i].toSource();
            }
        }

        try{
            gSTB.Debug(text);
        }catch(e){
            console&&console.log&&console.log(t);
        }
    }
}

/**
 * Custom prototype metods
 * @author zhurbitsky@gmail.com
 */

HTMLElement.prototype.show = function(){
    try{
        this.style.display = 'block';
    }catch(e){
        _debug(e);
    }
}

HTMLElement.prototype.hide = function(){
    try{
        this.style.display = 'none';
    }catch(e){
        _debug(e);
    }
}

HTMLElement.prototype.moveX = function(to_x){
    try{
        this.style.left = parseInt(to_x)+'px';
    }catch(e){
        _debug(e);
    }
}

HTMLElement.prototype.moveY = function(to_y){
    try{
        this.style.top = parseInt(to_y)+'px';
    }catch(e){
        _debug(e);
    }
}

HTMLElement.prototype.offsetX = function(offset_x){
    if (!this.style.left){
        this.style.left = 0+'px';
    };

    try{
        this.style.left = parseInt(this.style.left)+offset_x+'px';
    }catch(e){
        _debug(e);
    }
}

HTMLElement.prototype.offsetY = function(offset_y){
    if (!this.style.top){
        this.style.top = 0+'px';
    };

    try{
        this.style.top = parseInt(this.style.top)+offset_y+'px';
    }catch(e){
        _debug(e);
    }
}

HTMLElement.prototype.setClass = function(class_name){
    try{
        this.className = class_name;
    }catch(e){
        _debug(e);
    }
}

HTMLElement.prototype.addClass = function(class_name){
    try{
        if (!this.className){
            this.setClass(class_name);
        }else{
            var new_class_name = this.className;
            new_class_name += " ";
            new_class_name += class_name;
            this.setClass(new_class_name);
        }
    }catch(e){
        _debug(e);
    }
}

String.prototype.clearnl = function(){
    return this.replace(/(\n(\r)?)/g, '');
}

if (typeof Object.prototype.toSource != 'function'){

    /*Array.prototype.toSource = function(){
        return '[' + this.join( ', ' ) + ']';
    }

    Object.prototype.toSource = function(){
        return 'This browser not support Object toSource method';
    }*/

    Object.prototype.toSource = function() {
        var con = this.constructor;
        if(con == String) {
            //return '"' + this + '"';
            return this;
        } else if(con == Number) {
            return this;
        } else if(con == Array) {
            var res = '[';
            for(var i=0,len=this.length;i<len;i++) {
                if(i == len-1)
                    res += this[i].toSource() + ']';
                else
                    res += this[i].toSource() + ', ';
            }
            return res;
        } else if(con == RegExp) {
            return this;
        } else if(con == Object) {
            var res = '{';
            var i=0;
            for(var j in this) {
                if(j != 'toSource') {
                    if(i == 0) {
                        res += j + ':' + this[j].toSource(1);
                    } else {
                        res += ', ' + j + ':' + this[j].toSource(1);
                    }
                    i++;
                }
            }
            res += '}';
            if(arguments.length) {
                return res;
            } else {
                return '(' + res + ')';
            }
        }
    }

}

Array.prototype.getIdxById = function(id){
    for (var i=0; i<this.length; i++){
        if (this[i].hasOwnProperty('id')){
            if (this[i].id == id){
                return i;
            }
        }
    }
    return null;
}

Array.prototype.getIdxByVal = function(what, eq){
    for (var i=0; i<this.length; i++){
        if (this[i].hasOwnProperty(what)){
            if (this[i][what] == eq){
                return i;
            }
        }
    }
    return null;
}

Array.prototype.getIdxByNumber = function(number){
    for (var i=0; i<this.length; i++){
        if (this[i].hasOwnProperty('number')){
            if (this[i].number == number){
                return i;
            }
        }
    }
    return null;
}

Array.prototype.inArray = function (value){
    for (var i=0; i < this.length; i++){
        if (this[i] === value){
            return true;
        }
    }
    return false;
};<|endoftext|>


<commit_before>/*!
 * @license  Neuron Framwork
 * author    i@kael.me
 */

/**
 * corek
 * seed.js -> enhance/ -> loader.js -> selector/ -> core/ -> dom/
 */

/**
 * module seed
 */

/**
 * @param {undefined=} undef
 */
;(function(host, K, undef){

// exactly, K must be an object, or override it
K = host[K] = host && host[K] || {};

/**
 * isXXX method - basic javascript method detecting

 * NEVER use KM._type to test for a certain type in your javascript for business,
 * since the returned string may be subject to change in a future version
 * use KM.isXXX instead
 * ------------------------------------------------------------------------------------ */
K._type = function(){

	function _type(obj){
		return type_map[ toString.call(obj) ];
	};

	var toString = Object.prototype.toString,
		_K = K,
		type_list = 'Boolean Number String Function Array Date RegExp Object'.split(' '),
		i = type_list.length,

		type_map = {},
		name,
		name_lower;

	while( i -- ){
		name = type_list[i];
		name_lower = name.toLowerCase();

		type_map[ '[object ' + name + ']' ] = name_lower;

		_K['is' + name] = function(nl){
			return function(o){
				_type(o) === nl;
			}
		}(name_lower);
	}

	_K.isPlainObject = function(obj){
		return obj && _K.isObject(obj) && 'isPrototypeOf' in obj;
	};

	return _type;
}();

K.__HOST = K.__HOST || host;

K.build = '%buildtime%';

})(this, 'KM');

/**

 milestone 2.0 ------------------------------------

 2011-09-02  Kael:
 - rename core.js as seed.js
 - remove everything unnecessary out of seed.js
 - seed.js will only manage the KM namespace and provide support for type detection

 milestone 1.0 ------------------------------------

 2010-08-27  Kael:
 - add global configuration: KM.__PARSER as DOM selector and parser

 2010-08-16  Kael:
 TODO:
 √ GLOBAL: remove all native implements of non-ECMAScript5 standards

 * change log:
 * 2011-04-19  Kael: move KM.type to lang.js
 * 2011-04-01  Kael Zhang: add adapter for typeOf of mootools
 * 2010-12-13  Kael Zhang: fix the getter of KM.data
 * 2010-10-09  Kael Zhang: 创建文件
 */<commit_msg>add global support for CommonJS(NodeJS); fix a bug about isXXXX method<commit_after>/*!
 * @license  Neuron Framwork
 * author    i@kael.me
 */

/**
 * corek
 * seed.js -> enhance/ -> loader.js -> selector/ -> core/ -> dom/
 */

/**
 * module seed
 */

/**
 * @param {undefined=} undef
 */
;(function(host, K, undef){

// exactly, K must be an object, or override it
K = host[K] = host && host[K] || {};

/**
 * isXXX method - basic javascript method detecting

 * NEVER use KM._type to test for a certain type in your javascript for business,
 * since the returned string may be subject to change in a future version
 * use KM.isXXX instead
 * ------------------------------------------------------------------------------------ */
K._type = function(){

	function _type(obj){
		return type_map[ toString.call(obj) ];
	};

	var toString = Object.prototype.toString,
		_K = K,
		type_list = 'Boolean Number String Function Array Date RegExp Object'.split(' '),
		i = type_list.length,

		type_map = {},
		name,
		name_lower;

	while( i -- ){
		name = type_list[i];
		name_lower = name.toLowerCase();

		type_map[ '[object ' + name + ']' ] = name_lower;

		_K['is' + name] = function(nl){
			return function(o){
				return _type(o) === nl;
			}
		}(name_lower);
	}

	_K.isPlainObject = function(obj){
		return obj && _K.isObject(obj) && 'isPrototypeOf' in obj;
	};

	return _type;
}();

K.__HOST = K.__HOST || host;

K.build = '%buildtime%';

// NodeJS
})( typeof exports != 'undefined' ? exports : this, 'KM');

/**

 milestone 2.0 ------------------------------------

 2011-09-04  Kael:
 - add global support for CommonJS(NodeJS)

 TODO:
 A. make Slick Selector Engine slim

 2011-09-02  Kael:
 - rename core.js as seed.js
 - remove everything unnecessary out of seed.js
 - seed.js will only manage the KM namespace and provide support for type detection

 milestone 1.0 ------------------------------------

 2010-08-27  Kael:
 - add global configuration: KM.__PARSER as DOM selector and parser

 2010-08-16  Kael:
 TODO:
 √ GLOBAL: remove all native implements of non-ECMAScript5 standards

 * change log:
 * 2011-04-19  Kael: move KM.type to lang.js
 * 2011-04-01  Kael Zhang: add adapter for typeOf of mootools
 * 2010-12-13  Kael Zhang: fix the getter of KM.data
 * 2010-10-09  Kael Zhang: 创建文件
 */<|endoftext|>


<commit_before>angular.module('ngCloudMine', [])

.service('cmWS', ['$q', function($q) {
  var service = {};

  var distanceRE = /#{distance}/,
      latRE = /#{lat}/,
      longRE = /#{long}/;

  function arrayify(data) {
    var ary = [];

    for (var key in data) {
      var obj = data[key];

      ary.push(obj);
      ary[key] = obj;
    }

    return ary;
  };

  function checkDistanceParams(query, options, distance, lat, long) {
    var errorString = null;

    if (!query) {
      errorString = 'Missing query';
    } else if (!options) {
      errorString = 'Missing options';
    } else if (!distance) {
      errorString = 'Missing distance';
    } else if (!lat) {
      errorString = 'Missing latitude';
    } else if (!long) {
      errorString = 'Missing longitude';
    } else if (!query.match(distanceRE)) {
      errorString = 'Missing distance variable in query';
    } else if (!query.match(latRE)) {
      errorString = 'Missing latitude variable in query';
    } else if (!query.match(longRE)) {
      errorString = 'Missing longitude variable in query';
    }

    return errorString;
  }

  function distanceQuery(query, distance, lat, long) {
    query = query.replace(distanceRE, distance);
    query = query.replace(latRE, lat);
    query = query.replace(longRE, long);

    return query;
  };

  function calculateCount(pager) {
    return service.getSearchCount(pager.query, angular.copy(pager.options))
    .then(function(total) {
      pager.total = total;
      calcTotalPages(pager);

      return pager;
    });
  };

  function calcTotalPages(pager) {
    pager.totalPages = Math.ceil(pager.total / pager.countPerPage);
  };

  function deferSuccessAndError(method, args) {
    return deferSuccessAndErrorWithHandlers(method, args);
  };

  function deferSuccessAndErrorWithHandlers(method, args, successHandler, errorHandler) {
    var deferred = $q.defer();

    if (!successHandler) successHandler = function(data, meta, deferred) {
      deferred.resolve(data);
    };

    if (!errorHandler) errorHandler = function(err, deferred) {
      deferred.reject(err);
    };

    window.ws[method].apply(window.ws, args)
    .on('success', function(data, meta) {
      successHandler(arrayify(data), meta, deferred);
    }).on('error', function(err) {
      errorHandler(err, deferred);
    });

    return deferred.promise;
  };

  function deferResult(method, args) {
    var deferred = $q.defer();

    window.ws[method].apply(window.ws, args)
    .on('result', function(data) {
      deferred.resolve(data);
    });

    return deferred.promise;
  };

  service.search = function(query, options) {
    return deferSuccessAndError('search', [query, options]);
  };

  service.logout = function(email, password, options) {
    return deferSuccessAndError('logout', []);
  };

  service.set = function(id, object, options) {
    return deferSuccessAndError('set', [id, object, options]);
  };

  service.update = function(id, object, options) {
    return deferSuccessAndError('update', [id, object, options]);
  };

  service.login = function(email, password, options) {
    return deferSuccessAndError('login', [email, password, options]);
  };

  service.run = function(snippet, params, options) {
    return deferResult('run', [snippet, params, options]);
  };

  service.getACL = function(acl_id, options) {
    return deferSuccessAndError('getACL', [acl_id, options]);
  };

  service.getACLs = function(options) {
    return deferSuccessAndError('getACLs', [options]);
  };

  service.updateACL = function(acl, options) {
    return deferSuccessAndError('updateACL', [acl, options]);
  };

  service.getSearchCount = function(query, options) {
    if (!options) {
      options = {applevel: true};
    }

    options.limit = 0;
    options.count = true;

    return deferSuccessAndErrorWithHandlers('search', [query, options], function(data, meta, deferred) {
      deferred.resolve(meta.count);
    });
  };

  service.getDistanceCount = function(query, options, distance, lat, long) {
    var errorMessage = checkDistanceParams(query, options, distance, lat, long);
    if (errorMessage) {
      return $q.reject(errorMessage);
    }

    return service.getSearchCount(
      distanceQuery(query, distance, lat, long), options
    );
  };

  service.getDistance = function(query, options, distance, lat, long) {
    var errorMessage = checkDistanceParams(query, options, distance, lat, long);
    if (errorMessage) {
      return $q.reject(errorMessage);
    }

    options.distance = true;
    query = distanceQuery(query, distance, lat, long);

    return deferSuccessAndErrorWithHandlers('search', [query, options], function(data, meta, deferred) {
      for (metaKey in meta) {
        var metaData = meta[metaKey];

        if (data[metaKey] && meta[metaKey].geo && meta[metaKey].geo.distance) {
          data[metaKey].distance = meta[metaKey].geo.distance;
        }
      }

      deferred.resolve(data);
    });
  };

  service.getPager = function(countPerPage, query, options, updater) {
    if (!options) {
      options = {applevel: true};
    }

    if (!updater) {
      updater = function(data) {
        return data;
      };
    }

    var pager = {
      query: query,
      options: options,
      total: 0,
      countPerPage: countPerPage,
      totalPages: 0,
      page: 0,

      setPerPage: function(perPage) {
        pager.countPerPage = perPage;
        calcTotalPages(pager);

        //TODO: Calculate new page to keep first item on page
        this.page = 0;

        var deferred = $q.defer();
        deferred.resolve();
        return deferred.promise;
      },

      setQuery: function(query) {
        pager.query = query;
        return calculateCount(pager);
      },

      getPage: function(page) {
        var opts = angular.copy(options);
        this.page = page;

        if (page < 0 || page >= this.totalPages) {
          return $q.reject('Page doesn\'t exist');
        }

        opts.limit = this.countPerPage;
        opts.skip = page * this.countPerPage;

        return deferSuccessAndError('search', [this.query, opts]).then(updater);
      }
    };

    return calculateCount(pager);
  };

  service.getDistancePager = function(countPerPage, query, distance, lat, long, options, updater) {
    if (!options) {
      options = {};
    }

    var errorMessage = checkDistanceParams(query, options, distance, lat, long);
    if (errorMessage) {
      return $q.reject(errorMessage);
    }

    return this.getPager(
      countPerPage,
      distanceQuery(query, distance, lat, long),
      options, updater
    ).then(function(pager) {
      pager.originalQuery = query;
      pager.setDistanceLatAndLong = function(distance, lat, long) {
        var newDistanceQuery = distanceQuery(
          angular.copy(pager.originalQuery),
          distance, lat, long
        );

        pager.query = newDistanceQuery;

        return calculateCount(pager);
      };

      return pager;
    });
  };

  return service;
}]);
<commit_msg>Very helpful<commit_after>angular.module('ngCloudMine', [])

.service('cmWS', ['$q', function($q) {
  var service = {};

  var distanceRE = /#{distance}/,
      latRE = /#{lat}/,
      longRE = /#{long}/;

  function arrayify(data) {
    var ary = [];

    for (var key in data) {
      var obj = data[key];
      obj.id = key;

      ary.push(obj);
      ary[key] = obj;
    }

    return ary;
  };

  function checkDistanceParams(query, options, distance, lat, long) {
    var errorString = null;

    if (!query) {
      errorString = 'Missing query';
    } else if (!options) {
      errorString = 'Missing options';
    } else if (!distance) {
      errorString = 'Missing distance';
    } else if (!lat) {
      errorString = 'Missing latitude';
    } else if (!long) {
      errorString = 'Missing longitude';
    } else if (!query.match(distanceRE)) {
      errorString = 'Missing distance variable in query';
    } else if (!query.match(latRE)) {
      errorString = 'Missing latitude variable in query';
    } else if (!query.match(longRE)) {
      errorString = 'Missing longitude variable in query';
    }

    return errorString;
  }

  function distanceQuery(query, distance, lat, long) {
    query = query.replace(distanceRE, distance);
    query = query.replace(latRE, lat);
    query = query.replace(longRE, long);

    return query;
  };

  function calculateCount(pager) {
    return service.getSearchCount(pager.query, angular.copy(pager.options))
    .then(function(total) {
      pager.total = total;
      calcTotalPages(pager);

      return pager;
    });
  };

  function calcTotalPages(pager) {
    pager.totalPages = Math.ceil(pager.total / pager.countPerPage);
  };

  function deferSuccessAndError(method, args) {
    return deferSuccessAndErrorWithHandlers(method, args);
  };

  function deferSuccessAndErrorWithHandlers(method, args, successHandler, errorHandler) {
    var deferred = $q.defer();

    if (!successHandler) successHandler = function(data, meta, deferred) {
      deferred.resolve(data);
    };

    if (!errorHandler) errorHandler = function(err, deferred) {
      deferred.reject(err);
    };

    window.ws[method].apply(window.ws, args)
    .on('success', function(data, meta) {
      successHandler(arrayify(data), meta, deferred);
    }).on('error', function(err) {
      errorHandler(err, deferred);
    });

    return deferred.promise;
  };

  function deferResult(method, args) {
    var deferred = $q.defer();

    window.ws[method].apply(window.ws, args)
    .on('result', function(data) {
      deferred.resolve(data);
    });

    return deferred.promise;
  };

  service.search = function(query, options) {
    return deferSuccessAndError('search', [query, options]);
  };

  service.logout = function(email, password, options) {
    return deferSuccessAndError('logout', []);
  };

  service.set = function(id, object, options) {
    return deferSuccessAndError('set', [id, object, options]);
  };

  service.update = function(id, object, options) {
    return deferSuccessAndError('update', [id, object, options]);
  };

  service.login = function(email, password, options) {
    return deferSuccessAndError('login', [email, password, options]);
  };

  service.run = function(snippet, params, options) {
    return deferResult('run', [snippet, params, options]);
  };

  service.getACL = function(acl_id, options) {
    return deferSuccessAndError('getACL', [acl_id, options]);
  };

  service.getACLs = function(options) {
    return deferSuccessAndError('getACLs', [options]);
  };

  service.updateACL = function(acl, options) {
    return deferSuccessAndError('updateACL', [acl, options]);
  };

  service.getSearchCount = function(query, options) {
    if (!options) {
      options = {applevel: true};
    }

    options.limit = 0;
    options.count = true;

    return deferSuccessAndErrorWithHandlers('search', [query, options], function(data, meta, deferred) {
      deferred.resolve(meta.count);
    });
  };

  service.getDistanceCount = function(query, options, distance, lat, long) {
    var errorMessage = checkDistanceParams(query, options, distance, lat, long);
    if (errorMessage) {
      return $q.reject(errorMessage);
    }

    return service.getSearchCount(
      distanceQuery(query, distance, lat, long), options
    );
  };

  service.getDistance = function(query, options, distance, lat, long) {
    var errorMessage = checkDistanceParams(query, options, distance, lat, long);
    if (errorMessage) {
      return $q.reject(errorMessage);
    }

    options.distance = true;
    query = distanceQuery(query, distance, lat, long);

    return deferSuccessAndErrorWithHandlers('search', [query, options], function(data, meta, deferred) {
      for (metaKey in meta) {
        var metaData = meta[metaKey];

        if (data[metaKey] && meta[metaKey].geo && meta[metaKey].geo.distance) {
          data[metaKey].distance = meta[metaKey].geo.distance;
        }
      }

      deferred.resolve(data);
    });
  };

  service.getPager = function(countPerPage, query, options, updater) {
    if (!options) {
      options = {applevel: true};
    }

    if (!updater) {
      updater = function(data) {
        return data;
      };
    }

    var pager = {
      query: query,
      options: options,
      total: 0,
      countPerPage: countPerPage,
      totalPages: 0,
      page: 0,

      setPerPage: function(perPage) {
        pager.countPerPage = perPage;
        calcTotalPages(pager);

        //TODO: Calculate new page to keep first item on page
        this.page = 0;

        var deferred = $q.defer();
        deferred.resolve();
        return deferred.promise;
      },

      setQuery: function(query) {
        pager.query = query;
        return calculateCount(pager);
      },

      getPage: function(page) {
        var opts = angular.copy(options);
        this.page = page;

        if (page < 0 || page >= this.totalPages) {
          return $q.reject('Page doesn\'t exist');
        }

        opts.limit = this.countPerPage;
        opts.skip = page * this.countPerPage;

        return deferSuccessAndError('search', [this.query, opts]).then(updater);
      }
    };

    return calculateCount(pager);
  };

  service.getDistancePager = function(countPerPage, query, distance, lat, long, options, updater) {
    if (!options) {
      options = {};
    }

    var errorMessage = checkDistanceParams(query, options, distance, lat, long);
    if (errorMessage) {
      return $q.reject(errorMessage);
    }

    return this.getPager(
      countPerPage,
      distanceQuery(query, distance, lat, long),
      options, updater
    ).then(function(pager) {
      pager.originalQuery = query;
      pager.setDistanceLatAndLong = function(distance, lat, long) {
        var newDistanceQuery = distanceQuery(
          angular.copy(pager.originalQuery),
          distance, lat, long
        );

        pager.query = newDistanceQuery;

        return calculateCount(pager);
      };

      return pager;
    });
  };

  return service;
}]);
<|endoftext|>


<commit_before>angular.module('ngCloudMine', [])

.service('cmWS', ['$q', function($q) {
  function arrayify(data) {
    var ary = [];

    for (var key in data) {
      var obj = data[key];

      ary.push(obj);
      ary[key] = data[key];
    }

    return ary;
  };

  function deferSuccessAndError(method, args) {
    return deferSuccessAndErrorWithHandlers(method, args);
  };

  function deferSuccessAndErrorWithHandlers(method, args, successHandler, errorHander) {
    var deferred = $q.defer();

    window.ws[method].apply(window.ws, args)
    .on('success', function(data, meta) {
      if (successHandler) successHandler(data, meta);

      deferred.resolve(arrayify(data));
    }).on('error', function(err) {
      if (errorHandler) errorHandler(err);

      deferred.reject(err);
    });

    return deferred.promise;
  };

  return {
    search: function(query, options) {
      return deferSuccessAndError('search', [query, options]);
    },

    logout: function(email, password, options) {
      return deferSuccessAndError('logout', []);
    },

    set: function(id, object, options) {
      return deferSuccessAndError('set', [id, object, options]);
    },

    update: function(id, object, options) {
      return deferSuccessAndError('update', [id, object, options]);
    },

    login: function(email, password, options) {
      return deferSuccessAndError('login', [email, password, options]);
    },

    getSearchCount: function(query, options) {
      var deferred = $q.defer();
      if (!options) {
        options = {};
      }

      options.applevel = true;
      options.limit = 0;
      options.count = true;

      window.ws.search(query, options).on('success', function(data, meta) {
        deferred.resolve(meta.count);
      });

      return deferred.promise;
    },

    getPager: function(pageCount, query, options) {
      var pager = {
        query: query,
        count: null,
        pageCount: null,
        pages: null,
        getPage: function(page) {
          if (page < 0 || page >= this.pages) {
            return $q.reject('Page doesn\'t exist');
          }

          var options = {
            applevel: true,
            limit: pageCount,
            skip: page * pageCount
          };

          return deferSuccessAndError('search', [query, options]);
        }
      };

      return this.getSearchCount(query, options)
      .then(function(count) {
        pager.count = count
        pager.pages = Math.ceil(count / pageCount);

        return pager;
      });
    }
  };
}]);
<commit_msg>Refactor<commit_after>angular.module('ngCloudMine', [])

.service('cmWS', ['$q', function($q) {
  function arrayify(data) {
    var ary = [];

    for (var key in data) {
      var obj = data[key];

      ary.push(obj);
      ary[key] = data[key];
    }

    return ary;
  };

  function deferSuccessAndError(method, args) {
    return deferSuccessAndErrorWithHandlers(method, args);
  };

  function deferSuccessAndErrorWithHandlers(method, args, successHandler, errorHandler) {
    var deferred = $q.defer();

    if (!successHandler) successHandler = function(data, meta, deferred) {
      deferred.resolve(data);
    };

    if (!errorHandler) errorHandler = function(err, deferred) {
      deferred.reject(err);
    };

    window.ws[method].apply(window.ws, args)
    .on('success', function(data, meta) {
      successHandler(arrayify(data), meta, deferred);
    }).on('error', function(err) {
      errorHandler(err, deferred);
    });

    return deferred.promise;
  };

  return {
    search: function(query, options) {
      return deferSuccessAndError('search', [query, options]);
    },

    logout: function(email, password, options) {
      return deferSuccessAndError('logout', []);
    },

    set: function(id, object, options) {
      return deferSuccessAndError('set', [id, object, options]);
    },

    update: function(id, object, options) {
      return deferSuccessAndError('update', [id, object, options]);
    },

    login: function(email, password, options) {
      return deferSuccessAndError('login', [email, password, options]);
    },

    getSearchCount: function(query, options) {
      if (!options) {
        options = {};
      }

      options.applevel = true;
      options.limit = 0;
      options.count = true;

      return deferSuccessAndErrorWithHandlers('search', [query, options], function(data, meta, deferred) {
        deferred.resolve(meta.count);
      });
    },

    getPager: function(pageCount, query, options) {
      var pager = {
        query: query,
        count: null,
        pageCount: null,
        pages: null,
        getPage: function(page) {
          if (page < 0 || page >= this.pages) {
            return $q.reject('Page doesn\'t exist');
          }

          var options = {
            applevel: true,
            limit: pageCount,
            skip: page * pageCount
          };

          return deferSuccessAndError('search', [query, options]);
        }
      };

      return this.getSearchCount(query, options)
      .then(function(count) {
        pager.count = count
        pager.pages = Math.ceil(count / pageCount);

        return pager;
      });
    }
  };
}]);
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define */

define(function (require, exports, module) {

    "use strict";

    // Code that needs to display user strings should call require("strings") to load
    // src/strings.js. This file will dynamically load strings.js for the specified brackets.locale.
    //
    // See the README.md file in this folder for information on how to add a new translation for
    // another language or locale.
    //
    // TODO: dynamically populate the local prefix list below?
    module.exports = {
        root: true,
        "de": true,
        "fr": true,
        "nb": true,
        "es": true,
        "it": true,
        "pt-br": true,
        "pt-pt": true,
        "ja": true,
        "tr": true,
        "ru": true,
        "sv": true,
        "zh-cn":true
    };
});
<commit_msg>add space to nls/string.js<commit_after>/*
 * Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define */

define(function (require, exports, module) {

    "use strict";

    // Code that needs to display user strings should call require("strings") to load
    // src/strings.js. This file will dynamically load strings.js for the specified brackets.locale.
    //
    // See the README.md file in this folder for information on how to add a new translation for
    // another language or locale.
    //
    // TODO: dynamically populate the local prefix list below?
    module.exports = {
        root: true,
        "de": true,
        "fr": true,
        "nb": true,
        "es": true,
        "it": true,
        "pt-br": true,
        "pt-pt": true,
        "ja": true,
        "tr": true,
        "ru": true,
        "sv": true,
        "zh-cn": true
    };
});
<|endoftext|>


<commit_before>
// httpClient returns a Client instance for the given URL endpoint
//
// opts is an optional object that is passed to the Client --
// see the Client constructor for details
//
var httpClient = function(endpoint, opts) {
    var httpTransport = function(req, callback) {
        var reqJson = JSON_stringify(req);
        var options = {
            url: endpoint,
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            body: reqJson
        };
        request(options, function(error, response, body) {
            callback(parseResponse(req, error, body));
        });
    };

    return new Client(httpTransport, opts);
};

// Export blessed functions to the package
exports.httpClient = httpClient;
exports.inprocClient = inprocClient;
exports.Client = Client;
exports.Server = Server;
exports.JSON_stringify = JSON_stringify;
<commit_msg>exporting helper functions for use in custom transports<commit_after>
// httpClient returns a Client instance for the given URL endpoint
//
// opts is an optional object that is passed to the Client --
// see the Client constructor for details
//
var httpClient = function(endpoint, opts) {
    var httpTransport = function(req, callback) {
        var reqJson = JSON_stringify(req);
        var options = {
            url: endpoint,
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            body: reqJson
        };
        request(options, function(error, response, body) {
            callback(parseResponse(req, error, body));
        });
    };

    return new Client(httpTransport, opts);
};

// Export blessed functions to the package
exports.httpClient = httpClient;
exports.inprocClient = inprocClient;
exports.Client = Client;
exports.Server = Server;
exports.JSON_stringify = JSON_stringify;
exports.errResp = errResp;
exports.parseResponse = parseResponse;
<|endoftext|>


<commit_before>goog.provide('ngeo.Menu');
goog.provide('ngeo.MenuEvent');
goog.provide('ngeo.MenuEventType');

goog.require('ol.Overlay');
goog.require('ol.OverlayPositioning');
goog.require('ol.events.Event');

/**
 * @enum {string}
 */
ngeo.MenuEventType = {
  /**
   * Triggered upon clicking an action button
   * @event ngeo.MenuEvent#actionclick
   */
  ACTION_CLICK: 'actionclick'
};

/**
 * @classdesc
 * Events emitted by {@link ngeo.Menu} instances are instances of this type.
 *
 * @constructor
 * @extends {ol.events.Event}
 * @implements {ngeox.MenuEvent}
 * @param {ngeo.MenuEventType} type Type.
 * @param {string} action Action name that was clicked.
 */
ngeo.MenuEvent = function(type, action) {

  ol.events.Event.call(this, type);

  /**
   * The action name that was clicked.
   * @type {string}
   * @api stable
   */
  this.action = action;

};
ol.inherits(ngeo.MenuEvent, ol.events.Event);

/**
 * @classdesc
 * An OpenLayers overlay that shows a contextual menu with configurable actions
 * anchored from its top left to a specific location. An event is fired when
 * any of the action is clicked.
 *
 * @constructor
 * @extends {ol.Overlay}
 * @param {ngeox.MenuOptions=} menuOptions Menu options.
 * @param {olx.OverlayOptions=} opt_overlayOptions Overlay options.
 */
ngeo.Menu = function(menuOptions, opt_overlayOptions) {

  const options = opt_overlayOptions !== undefined ? opt_overlayOptions : {};

  options.positioning = ol.OverlayPositioning.TOP_LEFT;

  /**
   * @type {Array.<goog.events.Key>}
   * @private
   */
  this.listenerKeys_ = [];

  /**
   * @type {goog.events.Key}
   * @private
   */
  this.clickOutListenerKey_ = null;

  /**
   * @type {Array.<ol.EventsKey>}
   * @private
   */
  this.olListenerKeys_ = [];

  const contentEl = $('<div/>', {
    'class': 'panel panel-default'
  });

  /**
   * @type {boolean}
   * @private
   */
  this.autoClose_ = menuOptions.autoClose !== undefined ?
    menuOptions.autoClose : true;

  // titleEl
  if (menuOptions.title) {
    const headerEl = $('<div>', {
      'class': 'panel-heading'
    }).appendTo(contentEl);

    $('<span>', {
      text: menuOptions.title
    }).appendTo(headerEl);
  }

  // actionsEl
  const actionsEl = $('<div>', {
    'class': 'list-group'
  }).appendTo(contentEl);

  /**
   * @type {Array.<jQuery>}
   * @private
   */
  this.actions_ = [];

  menuOptions.actions.forEach((action) => {
    this.actions_.push(
      $('<button>', {
        'class': 'list-group-item',
        'data-name': action.name,
        'text': [
          ' ',
          (action.label) !== undefined ? action.label : action.name
        ].join('')
      })
        .appendTo(actionsEl)
        .prepend($('<span>', {
          'class': action.cls !== undefined ? action.cls : ''
        }))
    );
  });

  options.element = contentEl[0];

  ol.Overlay.call(this, options);

};
ol.inherits(ngeo.Menu, ol.Overlay);

/**
 * @param {ol.PluggableMap|undefined} map Map.
 * @export
 * @override
 */
ngeo.Menu.prototype.setMap = function(map) {

  const keys = this.listenerKeys_;
  const olKeys = this.olListenerKeys_;

  const currentMap = this.getMap();
  if (currentMap) {
    keys.forEach((key) => {
      goog.events.unlistenByKey(key);
    }, this);
    keys.length = 0;
    olKeys.forEach((key) => {
      ol.events.unlistenByKey(key);
    }, this);
    olKeys.length = 0;
  }

  ol.Overlay.prototype.setMap.call(this, map);

  if (map) {
    this.actions_.forEach((action) => {
      const data = action.data();
      keys.push(
        goog.events.listen(
          action[0],
          'click',
          this.handleActionClick_.bind(this, data.name),
          false,
          this
        )
      );
    });

    // Autoclose the menu when clicking anywhere else than the menu
    olKeys.push(
      ol.events.listen(
        map,
        'pointermove',
        this.handleMapPointerMove_,
        this
      )
    );
  }

};

/**
 * Opens the menu at the desited coordinate. Also starts listening for the
 * clickout if autoClose is enabled.
 * @param {ol.Coordinate} coordinate Where to open the menu.
 * @export
 */
ngeo.Menu.prototype.open = function(coordinate) {
  this.setPosition(coordinate);
  if (this.autoClose_) {
    this.clickOutListenerKey_ =  goog.events.listen(
      document.documentElement,
      'mousedown',
      this.handleClickOut_,
      false,
      this
    );
  }

};

/**
 * @export
 */
ngeo.Menu.prototype.close = function() {
  this.setPosition(undefined);

  if (this.clickOutListenerKey_ !== null) {
    goog.events.unlistenByKey(this.clickOutListenerKey_);
  }
};

/**
 * @param {string} action The action name that was clicked.
 * @param {Event} evt Event.
 * @private
 */
ngeo.Menu.prototype.handleActionClick_ = function(action, evt) {

  this.dispatchEvent(
    new ngeo.MenuEvent(ngeo.MenuEventType.ACTION_CLICK, action));

  if (this.autoClose_) {
    this.close();
  }

  evt.stopPropagation();
};

/**
 * Handles clicks out of the menu. If the menu is visible, close it.
 * @param {Event} evt Event.
 * @private
 */
ngeo.Menu.prototype.handleClickOut_ = function(evt) {
  const element = this.getElement();
  if (element && $(evt.target).closest(element).length === 0) {
    this.close();
  }
};

/**
 * When the mouse is hovering the menu, set the event coordinate and pixel
 * values to Infinity to do as if the mouse had been move out of range of the
 * map. This prevents behaviours such as vertex still appearing while mouse
 * hovering edges of features bound to an active modify control while the
 * cursor is on top of the menu.
 * @param {ol.MapBrowserEvent} evt Event.
 * @private
 */
ngeo.Menu.prototype.handleMapPointerMove_ = function(evt) {
  const target = evt.originalEvent.target;
  goog.asserts.assertInstanceof(target, Element);

  const element = this.getElement();
  goog.asserts.assertInstanceof(element, Element);

  if (element.contains(target)) {
    evt.coordinate = [Infinity, Infinity];
    evt.pixel = [Infinity, Infinity];
  }
};
<commit_msg>Remove goog.events usage from ngeo-menu<commit_after>goog.provide('ngeo.Menu');
goog.provide('ngeo.MenuEvent');
goog.provide('ngeo.MenuEventType');

goog.require('ol.Overlay');
goog.require('ol.OverlayPositioning');
goog.require('ol.events.Event');

/**
 * @enum {string}
 */
ngeo.MenuEventType = {
  /**
   * Triggered upon clicking an action button
   * @event ngeo.MenuEvent#actionclick
   */
  ACTION_CLICK: 'actionclick'
};

/**
 * @classdesc
 * Events emitted by {@link ngeo.Menu} instances are instances of this type.
 *
 * @constructor
 * @extends {ol.events.Event}
 * @implements {ngeox.MenuEvent}
 * @param {ngeo.MenuEventType} type Type.
 * @param {string} action Action name that was clicked.
 */
ngeo.MenuEvent = function(type, action) {

  ol.events.Event.call(this, type);

  /**
   * The action name that was clicked.
   * @type {string}
   * @api stable
   */
  this.action = action;

};
ol.inherits(ngeo.MenuEvent, ol.events.Event);

/**
 * @classdesc
 * An OpenLayers overlay that shows a contextual menu with configurable actions
 * anchored from its top left to a specific location. An event is fired when
 * any of the action is clicked.
 *
 * @constructor
 * @extends {ol.Overlay}
 * @param {ngeox.MenuOptions=} menuOptions Menu options.
 * @param {olx.OverlayOptions=} opt_overlayOptions Overlay options.
 */
ngeo.Menu = function(menuOptions, opt_overlayOptions) {

  const options = opt_overlayOptions !== undefined ? opt_overlayOptions : {};

  options.positioning = ol.OverlayPositioning.TOP_LEFT;

  /**
   * @type {Array.<ol.EventsKey>}
   * @private
   */
  this.listenerKeys_ = [];

  /**
   * @type {?ol.EventsKey}
   * @private
   */
  this.clickOutListenerKey_ = null;

  const contentEl = $('<div/>', {
    'class': 'panel panel-default'
  });

  /**
   * @type {boolean}
   * @private
   */
  this.autoClose_ = menuOptions.autoClose !== undefined ?
    menuOptions.autoClose : true;

  // titleEl
  if (menuOptions.title) {
    const headerEl = $('<div>', {
      'class': 'panel-heading'
    }).appendTo(contentEl);

    $('<span>', {
      text: menuOptions.title
    }).appendTo(headerEl);
  }

  // actionsEl
  const actionsEl = $('<div>', {
    'class': 'list-group'
  }).appendTo(contentEl);

  /**
   * @type {Array.<jQuery>}
   * @private
   */
  this.actions_ = [];

  menuOptions.actions.forEach((action) => {
    this.actions_.push(
      $('<button>', {
        'class': 'list-group-item',
        'data-name': action.name,
        'text': [
          ' ',
          (action.label) !== undefined ? action.label : action.name
        ].join('')
      })
        .appendTo(actionsEl)
        .prepend($('<span>', {
          'class': action.cls !== undefined ? action.cls : ''
        }))
    );
  });

  options.element = contentEl[0];

  ol.Overlay.call(this, options);

};
ol.inherits(ngeo.Menu, ol.Overlay);

/**
 * @param {ol.PluggableMap|undefined} map Map.
 * @export
 * @override
 */
ngeo.Menu.prototype.setMap = function(map) {

  const currentMap = this.getMap();
  if (currentMap) {
    this.listenerKeys_.forEach(ol.events.unlistenByKey);
    this.listenerKeys_.length = 0;
  }

  ol.Overlay.prototype.setMap.call(this, map);

  if (map) {
    this.actions_.forEach((action) => {
      const data = action.data();
      this.listenerKeys_.push(
        ol.events.listen(
          action[0],
          'click',
          this.handleActionClick_.bind(this, data.name)
        )
      );
    });

    // Autoclose the menu when clicking anywhere else than the menu
    this.listenerKeys_.push(
      ol.events.listen(
        map,
        'pointermove',
        this.handleMapPointerMove_,
        this
      )
    );
  }

};

/**
 * Opens the menu at the desited coordinate. Also starts listening for the
 * clickout if autoClose is enabled.
 * @param {ol.Coordinate} coordinate Where to open the menu.
 * @export
 */
ngeo.Menu.prototype.open = function(coordinate) {
  this.setPosition(coordinate);
  if (this.autoClose_) {
    this.clickOutListenerKey_ = ol.events.listen(
      document.documentElement,
      'mousedown',
      this.handleClickOut_,
      this
    );
  }

};

/**
 * @export
 */
ngeo.Menu.prototype.close = function() {
  this.setPosition(undefined);

  if (this.clickOutListenerKey_ !== null) {
    ol.events.unlistenByKey(this.clickOutListenerKey_);
  }
};

/**
 * @param {string} action The action name that was clicked.
 * @param {Event} evt Event.
 * @private
 */
ngeo.Menu.prototype.handleActionClick_ = function(action, evt) {

  this.dispatchEvent(
    new ngeo.MenuEvent(ngeo.MenuEventType.ACTION_CLICK, action));

  if (this.autoClose_) {
    this.close();
  }

  evt.stopPropagation();
};

/**
 * Handles clicks out of the menu. If the menu is visible, close it.
 * @param {Event} evt Event.
 * @private
 */
ngeo.Menu.prototype.handleClickOut_ = function(evt) {
  const element = this.getElement();
  if (element && $(evt.target).closest(element).length === 0) {
    this.close();
  }
};

/**
 * When the mouse is hovering the menu, set the event coordinate and pixel
 * values to Infinity to do as if the mouse had been move out of range of the
 * map. This prevents behaviours such as vertex still appearing while mouse
 * hovering edges of features bound to an active modify control while the
 * cursor is on top of the menu.
 * @param {ol.MapBrowserEvent} evt Event.
 * @private
 */
ngeo.Menu.prototype.handleMapPointerMove_ = function(evt) {
  const target = evt.originalEvent.target;
  goog.asserts.assertInstanceof(target, Element);

  const element = this.getElement();
  goog.asserts.assertInstanceof(element, Element);

  if (element.contains(target)) {
    evt.coordinate = [Infinity, Infinity];
    evt.pixel = [Infinity, Infinity];
  }
};
<|endoftext|>