<commit_before>'use strict';

import Botkit from 'botkit';
import requestify from 'requestify';
import _ from 'lodash';
import config from '../../config';
import botkit_mongo_storage from './botkit_storage_mongoose';
import logger from './logger';
import * as messages from './messages';
import * as actions from './actions';

export const controller = Botkit.slackbot({
    storage: botkit_mongo_storage(config)
});

function save_user(scope, { access_token, user_id, team_id, user }) {
    let approved_scopes = scope.split(/\,/);

    controller.storage.users.get(user_id, (err, user) => {
        if (!user) {
            user = {
                id: user_id,
                access_token: access_token,
                scopes: approved_scopes,
                team_id: team_id,
                user: user
            };
        }

        controller.storage.users.save(user, (err, id) => {
            if (err) {
                logger.error('An error occurred while saving a user: ', err);
                controller.trigger('error', [err]);
            }
        });
    });
}

export function connect(config) {
    let bot = controller.spawn(config);
    controller.trigger('create_bot', [ bot, config ]);
}

export function save_team({ access_token, bot, scope }) {
    let url = `https://slack.com/api/auth.test?token=${access_token}`;

    return new Promise((resolve, reject) => {
        resolve(requestify.get(url).then((res) => {
            console.log(res);
            let { team_id, user_id, url, team, user } = res.getBody();

            let slack_team = {
                    id: team_id,
                    bot:{
                    token: bot.bot_access_token,
                    user_id: bot.bot_user_id,
                    createdBy: user_id
                },
                createdBy: user_id,
                url: url,
                name: team
            };

            connect(slack_team);
            save_user(scope, { access_token, user_id, team_id, user });

            return slack_team;
        }));
    });
}

export function register_slack_team(incoming_webhook_url, team_id, callback) {
    controller.storage.teams.get(team_id, (err, team) => {
        team.webhooks = {
            incomingUrl: incoming_webhook_url
        };

        controller.storage.teams.save(team, (err, team) => {
            if (!err) {
                callback(messages.register_command_reply(incoming_webhook_url));
            }
        });
    });
}

export function share_channel(team_id, channel_id, channel_name, callback) {
    controller.storage.teams.get(team_id, (err, team) => {
        if (!err) {
            let shared_channel = {
                id: `${team_id}.${channel_id}`,
                team_id: team.id,
                team_name: team.name,
                channel_id: channel_id,
                channel_name: channel_name,
                joined_channels: []
            };

            controller.storage.shares.save(shared_channel, (err, shared_channel) => {
                callback(messages.share_command_reply(shared_channel.channel_name));
            });
        }
    });
}

export function get_available_channels(channel_id, filter, callback) {
    controller.storage.shares.all((err, shares) => {
        let channels = _.filter(shares, (share) => share.channel_id !== channel_id);
        if (filter !== '') {
            channels = _.filter(channels, (channel) => channel.team_name === filter);
        }

        let grouped_channels = _.groupBy(channels, 'team_name');
        let reply_message = {
            attachments: []
        };

        _.forEach(grouped_channels, (value, key) => {
            let attachment = messages.available_channels_reply(key);

            _.forEach(value, (channel) => {
                attachment.actions.push(actions.available_channel_action(channel.channel_name, channel.channel_id, channel.team_id));
            });

            reply_message.attachments.push(attachment);
        });

        callback(reply_message);
    });
}

export function join_shared_channel({ actions, team, channel }, callback) {
    controller.storage.shares.get(actions[0].value, (err, shared_channel) => {
        controller.storage.teams.get(team.id, (err, team) => {
            if (!_.isArray(shared_channel.joined_channels)) {
                shared_channel.joined_channels = [];
            }

            shared_channel.joined_channels.push({
                id: team.id,
                webhook_url: team.webhooks.incomingUrl,
                post_channel_id: channel.id
            });

            controller.storage.shares.save(shared_channel);

            callback({
                text: `:white_check_mark: You have joined the conversation in *${shared_channel.team_name}'s* *#${shared_channel.channel_name}*!`,
                replace_original: false
            });
        });
    });
}

export function process_event({ token, team_id, event }, callback) {
    let url = `https://slack.com/api/users.info?token=${token}&user=${event.user}`;
    let shared_channel_id = `${team_id}.${event.channel}`;

    console.log(shared_channel_id);

    requestify.get(url).then((res) => {
        let payload = res.getBody();

        console.log(payload);

        if (payload.ok) {
            controller.storage.shares.get(shared_channel_id, (err, shared_channel) => {
                if (!err && shared_channel !== null) {
                    _.forEach(shared_channel.joined_channels, (channel) => {
                        let post_message = {
                            username: payload.user.name,
                            channel: channel.post_channel_id,
                            icon_url: payload.user.profile.image_32,
                            text: event.text
                        };
                        let options = {
                            headers: {
                                'content-type': 'application/json'
                            }
                        };
                        requestify.post(channel.webhook_url, post_message, options);
                    });
                }
            });
        }
    });
}

const _bots = {};

function trackBot(bot) {
    _bots[bot.config.token] = bot;
}

controller.on('create_bot', (bot, team) => {
    if (_bots[bot.config.token]) {
        bot.api.channels.list({ token: bot.confi.token }, (err, result) => {
            if (!err) {
                team.channels = []; // reset channel listing.
                if (result.ok) {
                    for (var i = 0; i < result.channels.length; i++) {
                        team.channels.push({
                            id: result.channels[i].id,
                            name: result.channels[i].name
                        });
                    }
                }
            }
        });

        logger.info("already online! channel listing updated.");
    } else {
        bot.startRTM((err) => {
            if (!err) {
                trackBot(bot);

                bot.api.channels.list({ token: bot.config.token }, (err, result) => {
                    if(!err) {
                        team.channels = [];
                        if (result.ok) {
                            for (var i = 0; i < result.channels.length; i++) {
                                team.channels.push({
                                    id: result.channels[i].id,
                                    name: result.channels[i].name
                                });
                            }
                        }

                        controller.saveTeam(team, function(err, id) {
                            if (err) {
                                logger.info("Error saving team");
                            }
                            else {
                                logger.info("Team " + team.name + " saved");
                            }
                        });
                    }
                });
            }

            bot.say(messages.general_help_message(team.createdBy));
        });
    }
});<commit_msg>getting team to access the proper oauth token<commit_after>'use strict';

import Botkit from 'botkit';
import requestify from 'requestify';
import _ from 'lodash';
import config from '../../config';
import botkit_mongo_storage from './botkit_storage_mongoose';
import logger from './logger';
import * as messages from './messages';
import * as actions from './actions';

export const controller = Botkit.slackbot({
    storage: botkit_mongo_storage(config)
});

function save_user(scope, { access_token, user_id, team_id, user }) {
    let approved_scopes = scope.split(/\,/);

    controller.storage.users.get(user_id, (err, user) => {
        if (!user) {
            user = {
                id: user_id,
                access_token: access_token,
                scopes: approved_scopes,
                team_id: team_id,
                user: user
            };
        }

        controller.storage.users.save(user, (err, id) => {
            if (err) {
                logger.error('An error occurred while saving a user: ', err);
                controller.trigger('error', [err]);
            }
        });
    });
}

export function connect(config) {
    let bot = controller.spawn(config);
    controller.trigger('create_bot', [ bot, config ]);
}

export function save_team({ access_token, bot, scope }) {
    let url = `https://slack.com/api/auth.test?token=${access_token}`;

    return new Promise((resolve, reject) => {
        resolve(requestify.get(url).then((res) => {
            console.log(res);
            let { team_id, user_id, url, team, user } = res.getBody();

            let slack_team = {
                    id: team_id,
                    bot:{
                    token: bot.bot_access_token,
                    user_id: bot.bot_user_id,
                    createdBy: user_id
                },
                createdBy: user_id,
                url: url,
                name: team
            };

            connect(slack_team);
            save_user(scope, { access_token, user_id, team_id, user });

            return slack_team;
        }));
    });
}

export function register_slack_team(incoming_webhook_url, team_id, callback) {
    controller.storage.teams.get(team_id, (err, team) => {
        team.webhooks = {
            incomingUrl: incoming_webhook_url
        };

        controller.storage.teams.save(team, (err, team) => {
            if (!err) {
                callback(messages.register_command_reply(incoming_webhook_url));
            }
        });
    });
}

export function share_channel(team_id, channel_id, channel_name, callback) {
    controller.storage.teams.get(team_id, (err, team) => {
        if (!err) {
            let shared_channel = {
                id: `${team_id}.${channel_id}`,
                team_id: team.id,
                team_name: team.name,
                channel_id: channel_id,
                channel_name: channel_name,
                joined_channels: []
            };

            controller.storage.shares.save(shared_channel, (err, shared_channel) => {
                callback(messages.share_command_reply(shared_channel.channel_name));
            });
        }
    });
}

export function get_available_channels(channel_id, filter, callback) {
    controller.storage.shares.all((err, shares) => {
        let channels = _.filter(shares, (share) => share.channel_id !== channel_id);
        if (filter !== '') {
            channels = _.filter(channels, (channel) => channel.team_name === filter);
        }

        let grouped_channels = _.groupBy(channels, 'team_name');
        let reply_message = {
            attachments: []
        };

        _.forEach(grouped_channels, (value, key) => {
            let attachment = messages.available_channels_reply(key);

            _.forEach(value, (channel) => {
                attachment.actions.push(actions.available_channel_action(channel.channel_name, channel.channel_id, channel.team_id));
            });

            reply_message.attachments.push(attachment);
        });

        callback(reply_message);
    });
}

export function join_shared_channel({ actions, team, channel }, callback) {
    controller.storage.shares.get(actions[0].value, (err, shared_channel) => {
        controller.storage.teams.get(team.id, (err, team) => {
            if (!_.isArray(shared_channel.joined_channels)) {
                shared_channel.joined_channels = [];
            }

            shared_channel.joined_channels.push({
                id: team.id,
                webhook_url: team.webhooks.incomingUrl,
                post_channel_id: channel.id
            });

            controller.storage.shares.save(shared_channel);

            callback({
                text: `:white_check_mark: You have joined the conversation in *${shared_channel.team_name}'s* *#${shared_channel.channel_name}*!`,
                replace_original: false
            });
        });
    });
}

export function process_event({ token, team_id, event }, callback) {
    controller.storage.teams.get(team_id, (err, team_info) => {
        let url = `https://slack.com/api/users.info?token=${team_info.bot.bot_access_token}&user=${event.user}`;
        let shared_channel_id = `${team_id}.${event.channel}`;

        console.log(shared_channel_id);

        requestify.get(url).then((res) => {
            let payload = res.getBody();

            console.log(payload);

            if (payload.ok) {
                controller.storage.shares.get(shared_channel_id, (err, shared_channel) => {
                    if (!err && shared_channel !== null) {
                        _.forEach(shared_channel.joined_channels, (channel) => {
                            let post_message = {
                                username: payload.user.name,
                                channel: channel.post_channel_id,
                                icon_url: payload.user.profile.image_32,
                                text: event.text
                            };
                            let options = {
                                headers: {
                                    'content-type': 'application/json'
                                }
                            };
                            requestify.post(channel.webhook_url, post_message, options);
                        });
                    }
                });
            }
        });
    });
}

const _bots = {};

function trackBot(bot) {
    _bots[bot.config.token] = bot;
}

controller.on('create_bot', (bot, team) => {
    if (_bots[bot.config.token]) {
        bot.api.channels.list({ token: bot.confi.token }, (err, result) => {
            if (!err) {
                team.channels = []; // reset channel listing.
                if (result.ok) {
                    for (var i = 0; i < result.channels.length; i++) {
                        team.channels.push({
                            id: result.channels[i].id,
                            name: result.channels[i].name
                        });
                    }
                }
            }
        });

        logger.info("already online! channel listing updated.");
    } else {
        bot.startRTM((err) => {
            if (!err) {
                trackBot(bot);

                bot.api.channels.list({ token: bot.config.token }, (err, result) => {
                    if(!err) {
                        team.channels = [];
                        if (result.ok) {
                            for (var i = 0; i < result.channels.length; i++) {
                                team.channels.push({
                                    id: result.channels[i].id,
                                    name: result.channels[i].name
                                });
                            }
                        }

                        controller.saveTeam(team, function(err, id) {
                            if (err) {
                                logger.info("Error saving team");
                            }
                            else {
                                logger.info("Team " + team.name + " saved");
                            }
                        });
                    }
                });
            }

            bot.say(messages.general_help_message(team.createdBy));
        });
    }
});<|endoftext|>


<commit_before><commit_msg>Add the action kit page info to the project if it exists<commit_after><|endoftext|>


<commit_before>'use strict';

angular.module('examples', [
    'ngRoute',
    'ui.bootstrap',
    'lx.navigation',
    'lx.layout',
    'examples.home',
    'examples.about',
    'examples.lib'
])
    .constant('ACTIVE_APP', 'examples')
    .config(function ($routeProvider, $locationProvider, $lxNavigationProvider) {
        // routing
        $locationProvider.html5Mode(true);
        $routeProvider.otherwise({redirectTo: '/examples/home'});

        // navigation
        $lxNavigationProvider.set({
            navigation: {
                main: [
                    {
                        title: 'Home',
                        route: '/main/home',
                        app: 'main'
                    },
                    {
                        title: 'About',
                        roles: ['Guest'],
                        route: '/main/about',
                        app: 'main'
                    },
                    {
                        title: 'Contact',
                        route: '/main/contact',
                        resources: ['/awesomeThings'],
                        app: 'main'
                    },
                    {
                        title: 'Examples',
                        route: '/examples/home',
                        app: 'examples'
                    },
                    {
                        title: 'Admin',
                        roles: ['Admin'],
                        route: '/admin/home',
                        app: 'admin'
                    }
                ],
                tree: [
                    {
                        title: 'Main',
                        app: 'main',
                        children: [
                            {
                                title: 'Home',
                                route: '/main/home',
                                app: 'main'
                            },
                            {
                                title: 'About',
                                route: '/main/about',
                                roles: ['Guest'],
                                app: 'main'
                            },
                            {
                                title: 'Contact',
                                route: '/main/contact',
                                resources: ['/awesomeThings'],
                                app: 'main'
                            }
                        ]
                    },
                    {
                        title: 'Examples',
                        app: 'examples',
                        children: [
                            {
                                title: 'Home',
                                route: '/examples/home',
                                app: 'examples'
                            },
                            {
                                title: 'About',
                                route: '/examples/about',
                                app: 'examples'
                            },
                            {
                                title: 'Lib',
                                route: '/examples/lib',
                                app: 'examples'
                            }
                        ]
                    },
                    {
                        title: 'Admin with a very long Title and ellipsis',
                        roles: ['Guest'],
                        route: '/admin/home',
                        app: 'admin'
                    }
                ]
            }
        });
  })
    .run(function($rootScope, lxMessageBoxService, lxToastBoxService, $window) {

        if($window.sessionStorage.token){
            $rootScope.isLoggedIn = true;
        } else {
            $rootScope.isLoggedIn = false;
        }

        if($window.sessionStorage.acl){

            var aclTemp = JSON.parse($window.sessionStorage.acl);
            var acl,roles = [];

            if(aclTemp.hasOwnProperty('acl')){
                acl=aclTemp.acl;
            }
            if(aclTemp.hasOwnProperty('roles')){
                roles=aclTemp.roles;
            }
            $rootScope.testAclUser = {
                username: 'horschde',
                acl: acl,
                rolesAsObjects: roles
            };
        } else {
            $rootScope.testAclUser = {};
            $rootScope.testAclAdmin = {};
        }

        $rootScope.pathNav = 'assets/includes/nav_list.html';
        $rootScope.pathNavTree = 'assets/includes/nav_tree_outside.html';

        $rootScope.lxMessageBoxService = lxMessageBoxService;
        $rootScope.lxToastBoxService = lxToastBoxService;

        $rootScope.openToastAnimated = function(){
            $rootScope.lxToastBoxService.show('Hier steht eine kleine Nachricht mit dem was gerade passiert ist.','danger');
            $rootScope.lxToastBoxAnimated = true;
        };
        $rootScope.openToast = function(){
            $rootScope.lxToastBoxService.show('Hier steht eine kleine Nachricht mit dem was gerade passiert ist.','success');
            $rootScope.lxToastBoxAnimated = false;
        };

        $rootScope.openMsgAnimated = function(){
            $rootScope.lxMessageBoxAnimated = true;
            $rootScope.lxMessageBoxService.show('glyphicon glyphicon-trash','Delete Item','Soll das ausgewählte Item wirklich gelöscht werden?',[ 'ja','nein','vielleicht'],function(err,res){
                console.log('Error: ',err);
                console.log('Result: ',res);
                if(res==='ja'){
                    $rootScope.lxToastBoxAnimated = true;
                    $rootScope.lxToastBoxService.show('Item wurde erfolgreich gelöscht.','success');
                }
            });
        };
        $rootScope.openMsg = function(){
            $rootScope.lxMessageBoxAnimated = false;
            $rootScope.lxMessageBoxService.show('glyphicon glyphicon-trash','Delete Item','Soll das ausgewählte Item wirklich gelöscht werden?',[ 'ja','nein','vielleicht'],function(err,res){
                console.log('Error: ',err);
                console.log('Result: ',res);
            });
        };

    });

<commit_msg>chore: delete var<commit_after>'use strict';

angular.module('examples', [
    'ngRoute',
    'ui.bootstrap',
    'lx.navigation',
    'lx.layout',
    'examples.home',
    'examples.about',
    'examples.lib'
])
    .constant('ACTIVE_APP', 'examples')
    .config(function ($routeProvider, $locationProvider, $lxNavigationProvider) {
        // routing
        $locationProvider.html5Mode(true);
        $routeProvider.otherwise({redirectTo: '/examples/home'});

        // navigation
        $lxNavigationProvider.set({
            navigation: {
                main: [
                    {
                        title: 'Home',
                        route: '/main/home',
                        app: 'main'
                    },
                    {
                        title: 'About',
                        roles: ['Guest'],
                        route: '/main/about',
                        app: 'main'
                    },
                    {
                        title: 'Contact',
                        route: '/main/contact',
                        resources: ['/awesomeThings'],
                        app: 'main'
                    },
                    {
                        title: 'Examples',
                        route: '/examples/home',
                        app: 'examples'
                    },
                    {
                        title: 'Admin',
                        roles: ['Admin'],
                        route: '/admin/home',
                        app: 'admin'
                    }
                ],
                tree: [
                    {
                        title: 'Main',
                        app: 'main',
                        children: [
                            {
                                title: 'Home',
                                route: '/main/home',
                                app: 'main'
                            },
                            {
                                title: 'About',
                                route: '/main/about',
                                roles: ['Guest'],
                                app: 'main'
                            },
                            {
                                title: 'Contact',
                                route: '/main/contact',
                                resources: ['/awesomeThings'],
                                app: 'main'
                            }
                        ]
                    },
                    {
                        title: 'Examples',
                        app: 'examples',
                        children: [
                            {
                                title: 'Home',
                                route: '/examples/home',
                                app: 'examples'
                            },
                            {
                                title: 'About',
                                route: '/examples/about',
                                app: 'examples'
                            },
                            {
                                title: 'Lib',
                                route: '/examples/lib',
                                app: 'examples'
                            }
                        ]
                    },
                    {
                        title: 'Admin with a very long Title and ellipsis',
                        roles: ['Guest'],
                        route: '/admin/home',
                        app: 'admin'
                    }
                ]
            }
        });
  })
    .run(function($rootScope, lxMessageBoxService, lxToastBoxService, $window) {

        if($window.sessionStorage.token){
            $rootScope.isLoggedIn = true;
        } else {
            $rootScope.isLoggedIn = false;
        }

        if($window.sessionStorage.acl){

            var aclTemp = JSON.parse($window.sessionStorage.acl);
            var acl,roles = [];

            if(aclTemp.hasOwnProperty('acl')){
                acl=aclTemp.acl;
            }
            if(aclTemp.hasOwnProperty('roles')){
                roles=aclTemp.roles;
            }
            $rootScope.testAclUser = {
                username: 'horschde',
                acl: acl,
                rolesAsObjects: roles
            };
        } else {
            $rootScope.testAclUser = {};
        }

        $rootScope.pathNav = 'assets/includes/nav_list.html';
        $rootScope.pathNavTree = 'assets/includes/nav_tree_outside.html';

        $rootScope.lxMessageBoxService = lxMessageBoxService;
        $rootScope.lxToastBoxService = lxToastBoxService;

        $rootScope.openToastAnimated = function(){
            $rootScope.lxToastBoxService.show('Hier steht eine kleine Nachricht mit dem was gerade passiert ist.','danger');
            $rootScope.lxToastBoxAnimated = true;
        };
        $rootScope.openToast = function(){
            $rootScope.lxToastBoxService.show('Hier steht eine kleine Nachricht mit dem was gerade passiert ist.','success');
            $rootScope.lxToastBoxAnimated = false;
        };

        $rootScope.openMsgAnimated = function(){
            $rootScope.lxMessageBoxAnimated = true;
            $rootScope.lxMessageBoxService.show('glyphicon glyphicon-trash','Delete Item','Soll das ausgewählte Item wirklich gelöscht werden?',[ 'ja','nein','vielleicht'],function(err,res){
                console.log('Error: ',err);
                console.log('Result: ',res);
                if(res==='ja'){
                    $rootScope.lxToastBoxAnimated = true;
                    $rootScope.lxToastBoxService.show('Item wurde erfolgreich gelöscht.','success');
                }
            });
        };
        $rootScope.openMsg = function(){
            $rootScope.lxMessageBoxAnimated = false;
            $rootScope.lxMessageBoxService.show('glyphicon glyphicon-trash','Delete Item','Soll das ausgewählte Item wirklich gelöscht werden?',[ 'ja','nein','vielleicht'],function(err,res){
                console.log('Error: ',err);
                console.log('Result: ',res);
            });
        };

    });

<|endoftext|>


<commit_before>module.exports = {
    PRODUCTION: process.env.NODE_ENV === 'production',
    log4js: {
        "appenders": [{
                "type": "console",
                "category": "console",
                "layout": {
                    type: 'pattern',
                    'pattern': '%[[%d] [%-5p] %7c -%] %m'
                }
            },
            {
                "category": ["logFile"],
                "type": "dateFile",
                "layout": {
                    type: 'pattern',
                    'pattern': '%[[%d] [%-5p] %7c -%] %m'
                },
                "filename": "logs/date",
                "alwaysIncludePattern": true,
                "pattern": "-yyyy-MM-dd-hh.log"
            },
            {
                "type": "console",
                "category": "db",
                "layout": {
                    type: 'pattern',
                    'pattern': '%[[%d] [%-5p] %7c -%] %m'
                }
            },
        ],
        "replaceConsole": true,
        "levels": {
            "logFile": "AUTO",
            "console": "ALL",
            "db": "debug"
        }
    },
    mysql: {
        host: 'localhost',
        user: 'root',
        password: '',
        database: 'test',
        connectionLimit: 2,
        outputSQL: true
    },
    auth: {
        loginSuccess:'/users',
        loginFailure:'/',
        jwt : {
            PRIVATE_KEY:'alskdjfhqoiweuryamsdvalksjfh',
            timeout: 5, //by seconds
            issuer: 'Neusoft'
        }
    }
}<commit_msg>修改配置错误<commit_after>module.exports = {
    PRODUCTION: process.env.NODE_ENV === 'production',
    log4js: {
        "appenders": [{
                "type": "console",
                "category": "console",
                "layout": {
                    type: 'pattern',
                    'pattern': '%[[%d] [%-5p] %7c -%] %m'
                }
            },
            {
                "category": ["logFile"],
                "type": "dateFile",
                "layout": {
                    type: 'pattern',
                    'pattern': '%[[%d] [%-5p] %7c -%] %m'
                },
                "filename": "logs/date",
                "alwaysIncludePattern": true,
                "pattern": "-yyyy-MM-dd-hh.log"
            },
            {
                "type": "console",
                "category": "db",
                "layout": {
                    type: 'pattern',
                    'pattern': '%[[%d] [%-5p] %7c -%] %m'
                }
            },
        ],
        "replaceConsole": true,
        "levels": {
            "logFile": "AUTO",
            "console": "ALL",
            "db": "debug"
        }
    },
    mysql: {
        host: 'localhost',
        user: 'root',
        password: '',
        database: 'test',
        connectionLimit: 2,
        outputSQL: true
    },
    auth: {
        loginSuccess:'/users',
        loginFailure:'/',
        jwt : {
            PRIVATE_KEY:'alskdjfhqoiweuryamsdvalksjfh',
            timeout: 30*60, //by seconds
            issuer: 'Neusoft'
        }
    }
}<|endoftext|>


<commit_before>import {Observable as O} from 'rx';
import Cycle from '@cycle/core';
import {makeDOMDriver} from '@cycle/dom';
import {div, button, svg} from '@cycle/dom';

import {preventDefaultDriver} from '../../drivers/prevent-default';
import {keyboardDriver} from '../../drivers/keyboard';
import {globalEventDriver} from '../../drivers/global-events';

const renderDots = (dots) =>
  svg('svg', {
    attributes: {
      width: 200,
      height: 200,
      class: 'graphics-root',
      viewBox: `0 0 500 500`,
      preserveAspectRatio: 'xMidYMid meet',
    },
  }, dots.map((dot) => [
    svg('circle', {
      cx: 250 + Math.sin(dot.angle) * 200,
      cy: 250 - Math.cos(dot.angle) * 200,
      r: 50,
      fill: '#444',
    }),
    svg('text', {
      x: 250 + Math.sin(dot.angle) * 200,
      y: 250 - Math.cos(dot.angle) * 200,
      fill: '#fff',
      'font-size': '50px',
      'text-anchor': 'middle',
      'dominant-baseline': 'central',
    }, dot.value.toString()),
  ]))
;

const renderButtons = (state) => div([
  button({
    attributes: {
      'data-action': 'add-bit',
    },
  }, 'Add Bit'),

  button({
    attributes: {
      'data-action': 'remove-bit',
    },
  }, 'Remove Bit'),
]);

// convert array of angles into svg
const render = (state) =>
  div([
    div(['Number of bits:', state.bitCount]),
    renderButtons(state),
    renderDots(state.dots),
  ])
;

// generate array of angles for a number circle of
// given bitCount.
const dotArray = (bitCount) =>
  Array
  // init array of length 2^bits.
  .apply(Array, {length: Math.pow(2, bitCount)})
  // map array to angles
  .map((_, index, all) => ({
    angle: 2 * Math.PI * index / all.length,
    value: index,
  }))
;

const model = (initialBitCount) =>
  // number of bits to generate the number circle for
  O.just(initialBitCount)
  // convert number of bit's into array of angles
  .map((bitCount) => ({
    bitCount,
    dots: dotArray(bitCount),
  }))
;

const view = (state$) =>
  state$.map(render)
;

const numberCircleApp = (sources) => {
  const state$ = model(3);
  const vtree$ = view(state$);

  return {
    DOM: vtree$,
  };
};

const drivers = {
  DOM: makeDOMDriver('#app'),
  preventDefault: preventDefaultDriver,
  keydown: keyboardDriver,
  globalEvents: globalEventDriver,
};

Cycle.run(numberCircleApp, drivers);
<commit_msg>make add and remove buttons work<commit_after>import {Observable as O} from 'rx';
import Cycle from '@cycle/core';
import {makeDOMDriver} from '@cycle/dom';
import {div, button, svg} from '@cycle/dom';

import {preventDefaultDriver} from '../../drivers/prevent-default';
import {keyboardDriver} from '../../drivers/keyboard';
import {globalEventDriver} from '../../drivers/global-events';

const renderDots = (dots) =>
  svg('svg', {
    attributes: {
      width: 200,
      height: 200,
      class: 'graphics-root',
      viewBox: `0 0 500 500`,
      preserveAspectRatio: 'xMidYMid meet',
    },
  }, dots.map((dot) => [
    svg('circle', {
      cx: 250 + Math.sin(dot.angle) * 200,
      cy: 250 - Math.cos(dot.angle) * 200,
      r: 50,
      fill: '#444',
    }),
    svg('text', {
      x: 250 + Math.sin(dot.angle) * 200,
      y: 250 - Math.cos(dot.angle) * 200,
      fill: '#fff',
      'font-size': '50px',
      'text-anchor': 'middle',
      'dominant-baseline': 'central',
    }, dot.value.toString()),
  ]))
;

const renderButtons = (state) => div([
  button({
    attributes: {
      'data-action': 'add-bit',
    },
  }, 'Add Bit'),

  button({
    attributes: {
      'data-action': 'remove-bit',
    },
  }, 'Remove Bit'),
]);

// convert array of angles into svg
const render = (state) =>
  div([
    div(['Number of bits:', state.bitCount]),
    renderButtons(state),
    renderDots(state.dots),
  ])
;

// generate array of angles for a number circle of
// given bitCount.
const dotArray = (bitCount) =>
  Array
  // init array of length 2^bits.
  .apply(Array, {length: Math.pow(2, bitCount)})
  // map array to angles
  .map((_, index, all) => ({
    angle: 2 * Math.PI * index / all.length,
    value: index,
  }))
;

const intent = (DOM) => {
  return {
    addBit$: DOM.select('[data-action="add-bit"]').events('click'),
    removeBit$: DOM.select('[data-action="remove-bit"]').events('click'),
  };
};

const model = (initialBitCount, actions) => {
  const modifierFunction$ = O.merge([
    actions.addBit$.map(() => (state) =>
      ({bitCount: state.bitCount + 1})
    ),
    actions.removeBit$.map(() => (state) =>
      ({bitCount: state.bitCount - 1})
    ),
  ]);

  return modifierFunction$
  // number of bits to generate the number circle for
  .startWith({bitCount: initialBitCount})
  // apply the function
  .scan((state, modifierFunction) => modifierFunction(state))
  // convert number of bit's into array of angles
  .map(({bitCount}) => ({
    bitCount,
    dots: dotArray(bitCount),
  }));
};

const view = (state$) =>
  state$.map(render)
;

const numberCircleApp = (sources) => {
  const actions = intent(sources.DOM);
  const state$ = model(3, actions);
  const vtree$ = view(state$);

  return {
    DOM: vtree$,
  };
};

const drivers = {
  DOM: makeDOMDriver('#app'),
  preventDefault: preventDefaultDriver,
  keydown: keyboardDriver,
  globalEvents: globalEventDriver,
};

Cycle.run(numberCircleApp, drivers);
<|endoftext|>


<commit_before>/*global window, document, jQuery, Handsontable, NVMetadata */
(function ($) {
  'use strict';

  /*jslint unparam: true */
  var boldRenderer = function (instance, td, row, col, prop,
    value, cellProperties) {
    //jshint unused:false

    Handsontable.renderers.TextRenderer.apply(this, arguments);
    td.style.fontWeight = 'bold';
  };

  $(document).ready(function () {
    var container = document.getElementById('hot'),
      hot = new Handsontable(container, {
        data: window.NVMetadata.data,
        stretchH: 'all',
        colHeaders: true,
        rowHeaders: true,
        contextMenu: true,
        height: 400,
        cells: function (r) {
          if (r === 0) {
            this.renderer = boldRenderer;
          }
        }
      });

    $('.btn-save-metadata').click(function () {
      $.ajax({
        type: 'POST',
        data: JSON.stringify(hot.getData()),
        contentType: 'application/json; charset=utf-8'
      })
        .done(function () {
          var collectionId = NVMetadata.getCollectionIdFromURL(
            window.location.href
          );
          window.location.replace('/collections/' + collectionId);
        })
        .fail(function (jqXHR, textStatus, errorThrown) {
          NVMetadata.displayErrors($('.errors'),
            NVMetadata.getErrors(jqXHR, textStatus, errorThrown));
        });
    });

    window.onbeforeunload = function () {
      if (window.sheetModified) {
        return 'You have pending unsaved changes. ' +
          'Do you really want to discard them ?';
      }
    };
  });

}(jQuery));
<commit_msg>made the "File Name" column readOnly in the metadata grid (locked for edits)<commit_after>/*global window, document, jQuery, Handsontable, NVMetadata */
(function ($) {
  'use strict';

  /*jslint unparam: true */
  var boldRenderer = function (instance, td, row, col, prop,
    value, cellProperties) {
    //jshint unused:false

    Handsontable.renderers.TextRenderer.apply(this, arguments);
    td.style.fontWeight = 'bold';
  };

  $(document).ready(function () {
    var container = document.getElementById('hot'),
      hot = new Handsontable(container, {
        data: window.NVMetadata.data,
        stretchH: 'all',
        colHeaders: true,
        rowHeaders: true,
        contextMenu: true,
        height: 400,
        cells: function (r, c) {
          if (r === 0) {
            this.renderer = boldRenderer;
          }
          if (c === 0) {
            return {readOnly: true};
          }
        }
      });

    $('.btn-save-metadata').click(function () {
      $.ajax({
        type: 'POST',
        data: JSON.stringify(hot.getData()),
        contentType: 'application/json; charset=utf-8'
      })
        .done(function () {
          var collectionId = NVMetadata.getCollectionIdFromURL(
            window.location.href
          );
          window.location.replace('/collections/' + collectionId);
        })
        .fail(function (jqXHR, textStatus, errorThrown) {
          NVMetadata.displayErrors($('.errors'),
            NVMetadata.getErrors(jqXHR, textStatus, errorThrown));
        });
    });

    window.onbeforeunload = function () {
      if (window.sheetModified) {
        return 'You have pending unsaved changes. ' +
          'Do you really want to discard them ?';
      }
    };
  });

}(jQuery));
<|endoftext|>


<commit_before>/*global window, document, jQuery, Handsontable, NVMetadata */
(function ($) {
  'use strict';

  function isString(val) {
    return (typeof val === 'string' || val instanceof String);
  }

  function cache() {
    var storage = {};
    return {
      get: function (key) {
        return storage[key];
      },
      set: function (key, value) {
        storage[key] = value;
      }
    }
  }

  var cache = cache();

  function cachedAjaxSource(source) {
    return function (query, process) {
      var data = cache.get(source);
      if (data) {
        process(data);
      } else {
        $.ajax({
          url: source,
          dataType: 'json',
          success: function (response) {
            cache.set(source, response.data);
            process(response.data);
          }
        });
      }
    }
  }

  function headerNames(headers) {
    return headers.map(function (x) {
      if (x.required) {
        return x.name + '*';
      }
      return x.name;
    });
  }

  function guessFieldType(field) {
    if (field.datasource) {
      return 'autocomplete';
    } else {
      return 'text';
    }
  }

  function getDataSource(field) {
    var datasource = field.datasource;

    if (datasource) {
      if (datasource.choices) {
        return NVMetadata.datasources[datasource.choices];
      } else if (datasource.url) {
        return cachedAjaxSource(datasource.url);
      }
    } else {
      return undefined;
    }
  }

  function emptyOrSpaced(value) {
    return !(value && /\S/.test(value))
  }

  function stringRequiredValidator(value, callback) {
    if (emptyOrSpaced(value)) {
      return callback(false);
    } else {
      return callback(true);
    }
  }

  function getFieldValidator(field) {
    if (field.required && !field.datasource) {
      return stringRequiredValidator;
    } else {
      return undefined;
    }
  }

  function columnSettings(headers) {
    return headers.map(function (x) {
      return {
        type: guessFieldType(x),
        source: getDataSource(x),
        strict: x.required,
        validator: getFieldValidator(x)
      }
    });
  }

  function getDefaultHeight(data) {
    var minHeight = 400,
      rowHeight = 24;

    if ((data.length + 1) * rowHeight < minHeight) {
      return minHeight;
    } else {
      return undefined;
    }
  }

  function columnExist(columnName) {
    var value = columnName.trim(),
      elems = NVMetadata.headers.filter(function (x) {
        return x.name === value;
      });

    return elems.length !== 0;
  }

  function serializeTable(hotInstance) {
    return [window.NVMetadata.headers.map(function (x) {
      return x.name
    })].concat(hotInstance.getData());
  }

  function validateInput(value, success, failure) {
    if (emptyOrSpaced(value)) {
      failure();
    } else if (columnExist(value)) {
      failure("Column already exists");
    } else {
      success();
    }
  }

  function showError($el, msg) {
    $el.addClass('has-error');
    if (msg) {
      $('.help-block', $el).text(msg);
    }
  }

  function clearError($el) {
    $('.help-block', $el).empty();
    $el.removeClass('has-error');
  }

  function getNewColumnName(callback) {
    var $modalEl = $('#columnNameModal'),
      $submit = $('button[type="submit"]', $modalEl),
      $columnNameEl = $('#column-name'),
      $inputWrapper = $('.js-input-wrapper', $modalEl);

    $modalEl.on('shown.bs.modal', function () {
      $columnNameEl.focus().attr("autocomplete", "off");

      $columnNameEl.keyup(function (e) {
        validateInput($columnNameEl.val(), function () {
          $submit.prop('disabled', false);
          clearError($inputWrapper);
        }, function (msg) {
          $submit.prop('disabled', true);
          if (msg) {
            showError($inputWrapper, msg);
          }
        });
      });

      $('.js-name-form', $modalEl).submit(function () {
        var name = $columnNameEl.val().trim();
        callback(name);
        $modalEl.modal('hide');
        $columnNameEl.val('');
        return false;
      });
    });

    $modalEl.on('hide.bs.modal', function () {
      $columnNameEl.val('');
      clearError($inputWrapper);
    });

    $modalEl.modal();
  }

  function insertColumn(hotInstance, selection) {
    hotInstance.deselectCell();
    getNewColumnName(function (name) {
      NVMetadata.headers.push({
        name: name
      });
      hotInstance.updateSettings({
        data: window.NVMetadata.data,
        colHeaders: headerNames(window.NVMetadata.headers),
        columns: columnSettings(NVMetadata.headers)
      });
      hotInstance.render();
    });
  }

  $(document).ready(function () {

    var container = document.getElementById('hot'),
      hot = new Handsontable(container, {
        data: window.NVMetadata.data,
        colHeaders: headerNames(window.NVMetadata.headers),
        columns: columnSettings(window.NVMetadata.headers),
        rowHeaders: true,
        height: getDefaultHeight(window.NVMetadata.data),
        contextMenu: {
          callback: function (key) {
            if (key === 'insert_column_left' ||
              key === 'insert_column_right') {
              insertColumn(hot, hot.getSelected());
            }
          },
          items: {
            'row_above': {},
            'row_below': {},
            'hsep1': '---------',
            'insert_column_left': {
              name: 'Insert column on the left'
            },
            'insert_column_right': {
              name: 'Insert column on the right'
            },
            'hsep2': '---------',
            'remove_row': {},
            'hsep3': '---------',
            'undo': {},
            'redo': {}
          }
        },
        cells: function (r, c, prop) {
          if (c === 0) {
            return {
              readOnly: true
            };
          }
        }
      });

    $('.btn-save-metadata').click(function () {
      $.ajax({
          type: 'POST',
          data: JSON.stringify(serializeTable(hot)),
          contentType: 'application/json; charset=utf-8'
        })
        .done(function () {
          var collectionId = NVMetadata.getCollectionIdFromURL(
            window.location.href
          );
          window.location.replace('/collections/' + collectionId);
        })
        .fail(function (jqXHR, textStatus, errorThrown) {
          NVMetadata.displayErrors($('.errors'),
            NVMetadata.getErrors(jqXHR, textStatus, errorThrown));
        });
    });

    window.onbeforeunload = function () {
      if (hot.isUndoAvailable()) {
        return 'You have pending unsaved changes. ' +
          'Do you really want to discard them ?';
      }
    };
  });

}(jQuery));
<commit_msg>insert column; debounced ajax<commit_after>/*global window, document, jQuery, Handsontable, NVMetadata */
(function ($) {
  'use strict';

  function isString(val) {
    return (typeof val === 'string' || val instanceof String);
  }

  function cache() {
    var storage = {};
    return {
      get: function (key) {
        return storage[key];
      },
      set: function (key, value) {
        storage[key] = value;
      }
    }
  }

  function debounce(func, wait, immediate) {
    var timeout;
    return function () {
      var context = this,
        args = arguments;
      var later = function () {
        timeout = null;
        if (!immediate) func.apply(context, args);
      };
      var callNow = immediate && !timeout;
      clearTimeout(timeout);
      timeout = setTimeout(later, wait);
      if (callNow) func.apply(context, args);
    };
  }

  var requestData = debounce(function (source, success) {
    console.log('call');
    $.ajax({
      url: source,
      dataType: 'json',
      success: success
    });
  }, 250, true);

  var cache = cache();

  function cachedAjaxSource(source) {
    return function (query, process) {
      var data = cache.get(source);
      if (data) {
        process(data);
      } else {
        requestData(source, function (response) {
          cache.set(source, response.data);
          process(response.data);
        });
      }
    }
  }

  function headerNames(headers) {
    return headers.map(function (x) {
      if (x.required) {
        return x.name + '*';
      }
      return x.name;
    });
  }

  function guessFieldType(field) {
    if (field.datasource) {
      return 'autocomplete';
    } else {
      return 'text';
    }
  }

  function getDataSource(field) {
    var datasource = field.datasource;

    if (datasource) {
      if (datasource.choices) {
        return NVMetadata.datasources[datasource.choices];
      } else if (datasource.url) {
        return cachedAjaxSource(datasource.url);
      }
    } else {
      return undefined;
    }
  }

  function emptyOrSpaced(value) {
    return !(value && /\S/.test(value))
  }

  function stringRequiredValidator(value, callback) {
    if (emptyOrSpaced(value)) {
      return callback(false);
    } else {
      return callback(true);
    }
  }

  function getFieldValidator(field) {
    if (field.required && !field.datasource) {
      return stringRequiredValidator;
    } else {
      return undefined;
    }
  }

  function columnSettings(headers) {
    return headers.map(function (x) {
      return {
        type: guessFieldType(x),
        source: getDataSource(x),
        strict: x.required,
        validator: getFieldValidator(x)
      }
    });
  }

  function getDefaultHeight(data) {
    var minHeight = 400,
      rowHeight = 24;

    if ((data.length + 1) * rowHeight < minHeight) {
      return minHeight;
    } else {
      return undefined;
    }
  }

  function columnExist(columnName) {
    var value = columnName.trim(),
      elems = NVMetadata.headers.filter(function (x) {
        return x.name === value;
      });

    return elems.length !== 0;
  }

  function serializeTable(hotInstance) {
    return [window.NVMetadata.headers.map(function (x) {
      return x.name
    })].concat(hotInstance.getData());
  }

  function validateInput(value, success, failure) {
    if (emptyOrSpaced(value)) {
      failure();
    } else if (columnExist(value)) {
      failure("Column already exists");
    } else {
      success();
    }
  }

  function showError($el, msg) {
    $el.addClass('has-error');
    if (msg) {
      $('.help-block', $el).text(msg);
    }
  }

  function clearError($el) {
    $('.help-block', $el).empty();
    $el.removeClass('has-error');
  }

  function getNewColumnName(callback) {
    var $modalEl = $('#columnNameModal'),
      $submit = $('button[type="submit"]', $modalEl),
      $columnNameEl = $('#column-name'),
      $inputWrapper = $('.js-input-wrapper', $modalEl);

    $modalEl.on('shown.bs.modal', function () {
      $columnNameEl.focus().attr("autocomplete", "off");

      $columnNameEl.keyup(function (e) {
        validateInput($columnNameEl.val(), function () {
          $submit.prop('disabled', false);
          clearError($inputWrapper);
        }, function (msg) {
          $submit.prop('disabled', true);
          if (msg) {
            showError($inputWrapper, msg);
          }
        });
      });

      $('.js-name-form', $modalEl)
        .off('submit.modal')
        .on('submit.modal', function () {
          var name = $columnNameEl.val().trim();
          callback(name);
          $modalEl.modal('hide');
          $columnNameEl.val('');
          return false;
        });
    });

    $modalEl.on('hide.bs.modal', function () {
      $columnNameEl.val('');
      clearError($inputWrapper);
    });

    $modalEl.modal();
  }

  function insertDataColumn(index, name) {
    NVMetadata.headers.splice(index, 0, {
      name: name
    });
    NVMetadata.data.map(function (x) {
      x.splice(index, 0, '');
    });
  }

  function insertLocation(selection, key) {
    if (key === 'insert_column_left') {
      return selection[1];
    } else {
      return selection[3] + 1;
    }
  }

  function handleInsertColumn(hotInstance, selection, key) {
    hotInstance.deselectCell();

    getNewColumnName(function (name) {
      var index = insertLocation(selection, key);

      insertDataColumn(index, name);

      hotInstance.updateSettings({
        data: window.NVMetadata.data,
        colHeaders: headerNames(window.NVMetadata.headers),
        columns: columnSettings(window.NVMetadata.headers)
      });
      hotInstance.render();
    });
  }

  $(document).ready(function () {

    var container = document.getElementById('hot'),
      hot = new Handsontable(container, {
        data: window.NVMetadata.data,
        colHeaders: headerNames(window.NVMetadata.headers),
        columns: columnSettings(window.NVMetadata.headers),
        rowHeaders: true,
        height: getDefaultHeight(window.NVMetadata.data),
        contextMenu: {
          callback: function (key) {
            if (key === 'insert_column_left' ||
              key === 'insert_column_right') {
              handleInsertColumn(hot, hot.getSelected(), key);
            }
          },
          items: {
            'row_above': {},
            'row_below': {},
            'hsep1': '---------',
            'insert_column_left': {
              name: 'Insert column on the left',
              disabled: function () {
                return hot.getSelected()[1] === 0
              }
            },
            'insert_column_right': {
              name: 'Insert column on the right'
            },
            'hsep2': '---------',
            'remove_row': {},
            'hsep3': '---------',
            'undo': {},
            'redo': {}
          }
        },
        cells: function (r, c, prop) {
          if (c === 0) {
            return {
              readOnly: true
            };
          }
        }
      });

    $('.btn-save-metadata').click(function () {
      $.ajax({
          type: 'POST',
          data: JSON.stringify(serializeTable(hot)),
          contentType: 'application/json; charset=utf-8'
        })
        .done(function () {
          var collectionId = NVMetadata.getCollectionIdFromURL(
            window.location.href
          );
          window.onbeforeunload = undefined;
          window.location.replace('/collections/' + collectionId);
        })
        .fail(function (jqXHR, textStatus, errorThrown) {
          NVMetadata.displayErrors($('.errors'),
            NVMetadata.getErrors(jqXHR, textStatus, errorThrown));
        });
    });

    window.onbeforeunload = function () {
      if (hot.isUndoAvailable()) {
        return 'You have pending unsaved changes. ' +
          'Do you really want to discard them ?';
      }
    };
  });

}(jQuery));
<|endoftext|>


<commit_before>window.addEventListener('DOMContentLoaded', (event) => {
  const cards = document.getElementsByClassName('card');
  for (const card of cards) {
    const up = card.getElementsByClassName('upvote')[0];
    up.addEventListener('click', function() {
      renderVote(card, 'upvote');
    });
    const down = card.getElementsByClassName('downvote')[0];
    down.addEventListener('click', function() {
      renderVote(card, 'downvote');
    });
  }
});

async function renderVote(card, action) {
  const total = card.getElementsByClassName('total-votes')[0];
  total.innerHTML = await updateVote(card.value, action);
}

async function updateVote(url, action) {
  const response = await fetch('/vote', {
    method: 'POST',
    body: 'url=' + url + '&' + action,
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
  });
  return response.text();
}
<commit_msg>Clean up script, add helper functions<commit_after>window.addEventListener('DOMContentLoaded', (event) => {
  const cards = document.getElementsByClassName('card');
  initVote(cards);
  for (const card of cards) {
    const up = card.getElementsByClassName('upvote')[0];
    const down = card.getElementsByClassName('downvote')[0];
    up.addEventListener('click', function() {
      renderVote(card, 'upvote');
    });
    down.addEventListener('click', function() {
      renderVote(card, 'downvote');
    });
  }
});

function initVote(cards) {
  for (const card of cards) {
    fetch('/vote?url=' + card.value).then((res) => res.json()).then((json) => {
      toggleButtons(card, json);
    });
  }
}

async function renderVote(card, action) {
  const json = await updateVote(card.value, action);
  toggleButtons(card, json);
}

function toggleButtons(card, json) {
  const total = card.getElementsByClassName('total-votes')[0];
  if (Object.keys(json).length !== 0) {
    total.innerHTML = json.totalvotes;
    const up = card.getElementsByClassName('upvote')[0];
    const down = card.getElementsByClassName('downvote')[0];
    if (json.toggleUpvote === 'active') {
      up.style.color = 'green';
    } else {
      up.style.color = 'black';
    }
    if (json.toggleDownvote === 'active') {
      down.style.color = 'red';
    } else {
      down.style.color = 'black';
    }
  }
}

async function updateVote(url, action) {
  const response = await fetch('/vote', {
    method: 'POST',
    body: 'url=' + url + '&' + action,
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
  });
  return response.json();
}
<|endoftext|>


<commit_before>function SeleniumIDEGenericAutoCompleteSearch() {
	this.candidates = {};
}

SeleniumIDEGenericAutoCompleteSearch.prototype = {
	startSearch: function(searchString, searchParam, prevResult, listener) {
		var result = new AutoCompleteResult(searchString, this.candidates[searchParam] || []);
		listener.onSearchResult(this, result);
	},

	stopSearch: function() {
	},

    setCandidates: function(key, values) {
        this.setCandidatesWithComments(key, values, null);
	},

    setCandidatesWithComments: function(key, values, comments) {
		var count = values.Count();
        var candidates = this.candidates[key] = new Array(count);
		for (var i = 0; i < count; i++) {
            candidates[i] = [values.GetElementAt(i).QueryInterface(Components.interfaces.nsISupportsString).data,
                             comments ? comments.GetElementAt(i).QueryInterface(Components.interfaces.nsISupportsString).data : null];
		}
	},

    clearCandidates: function(key) {
        if (this.candidates[key]) {
            delete this.candidates[key];
        }
    },

    QueryInterface: function(uuid) {
		if (uuid.equals(Components.interfaces.nsISeleniumIDEGenericAutoCompleteSearch) ||
			uuid.equals(Components.interfaces.nsIAutoCompleteSearch) ||
			uuid.equals(Components.interfaces.nsISupports)) {
			return this;
		}
        Components.returnCode = Components.results.NS_ERROR_NO_INTERFACE;
        return null;
    }
};

function AutoCompleteResult(search, candidates) {
	this.search = search;
	this.result = [];
	var lsearch = search.toLowerCase();
	for (var i = 0; i < candidates.length; i++) {
		if (candidates[i][0].toLowerCase().indexOf(lsearch) == 0) {
            this.result.push(candidates[i]);
		}
	}
}

AutoCompleteResult.prototype = {
	get defaultIndex() {
		return 0;
	},
	get errorDescription() {
		return '';
	},
	get matchCount() {
		return this.result.length;
	},
	get searchResult() {
		return Components.interfaces.nsIAutoCompleteResult.RESULT_SUCCESS;
	},
	get searchString() {
		return this.search;
	},
	getCommentAt: function(index) {
		return this.result[index][1] || '';
	},
	getStyleAt: function(index) {
		return '';
	},
	getValueAt: function(index) {
		return this.result[index][0];
	},
	getImageAt: function (index) {
		return '';
	},
	getLabelAt: function getLabelAt(index) {
		return this.getValueAt(index);
  },
	removeValueAt: function(rowIndex, removeFromDb) {
	},
    QueryInterface: function (uuid) {
		if (uuid.equals(Components.interfaces.nsIAutoCompleteResult) ||
			uuid.equals(Components.interfaces.nsISupports)) {
			return this;
		}
        Components.returnCode = Components.results.NS_ERROR_NO_INTERFACE;
        return null;
    }
};

//const COMPONENT_ID = Components.ID("{4791AF5F-AFBA-45A1-8204-47A135DF9591}");
const COMPONENT_ID = Components.ID("{E5226A0D-4698-4E15-9D6D-86771AE172C9}");

var SeleniumIDEGenericAutoCompleteModule = {
    registerSelf: function (compMgr, fileSpec, location, type) {
        compMgr = compMgr.QueryInterface(Components.interfaces.nsIComponentRegistrar);
        compMgr.registerFactoryLocation(COMPONENT_ID,
                                        "Selenium IDE Generic Autocomplete",
                                        "@mozilla.org/autocomplete/search;1?name=selenium-ide-generic",
                                        fileSpec,
                                        location,
                                        type);
    },

    getClassObject: function (compMgr, cid, iid) {
        if (!cid.equals(COMPONENT_ID)) throw Components.results.NS_ERROR_NO_INTERFACE;
        if (!iid.equals(Components.interfaces.nsIFactory))
            throw Components.results.NS_ERROR_NOT_IMPLEMENTED;

		return SeleniumIDEGenericAutoCompleteFactory;
    },

    canUnload: function(compMgr) {
        return true;
    }
};

var SeleniumIDEGenericAutoCompleteFactory = {
	createInstance: function (outer, iid) {
		if (outer != null)
			throw Components.results.NS_ERROR_NO_AGGREGATION;
		return new SeleniumIDEGenericAutoCompleteSearch().QueryInterface(iid);
	}
};

function NSGetModule(compMgr, fileSpec) {
    return SeleniumIDEGenericAutoCompleteModule;
}

function NSGetFactory(cid) {
    if (cid.toString().toUpperCase() != COMPONENT_ID.toString().toUpperCase()) throw Components.results.NS_ERROR_FACTORY_NOT_REGISTERED;
    return SeleniumIDEGenericAutoCompleteFactory;
}
<commit_msg>AdamGoucher - issue 992 - camel case autocomplete search<commit_after>function SeleniumIDEGenericAutoCompleteSearch() {
	this.candidates = {};
}

SeleniumIDEGenericAutoCompleteSearch.prototype = {
	startSearch: function(searchString, searchParam, prevResult, listener) {
		var result = new AutoCompleteResult(searchString, this.candidates[searchParam] || []);
		listener.onSearchResult(this, result);
	},

	stopSearch: function() {
	},

    setCandidates: function(key, values) {
        this.setCandidatesWithComments(key, values, null);
	},

    setCandidatesWithComments: function(key, values, comments) {
		var count = values.Count();
        var candidates = this.candidates[key] = new Array(count);
		for (var i = 0; i < count; i++) {
            candidates[i] = [values.GetElementAt(i).QueryInterface(Components.interfaces.nsISupportsString).data,
                             comments ? comments.GetElementAt(i).QueryInterface(Components.interfaces.nsISupportsString).data : null];
		}
	},

    clearCandidates: function(key) {
        if (this.candidates[key]) {
            delete this.candidates[key];
        }
    },

    QueryInterface: function(uuid) {
		if (uuid.equals(Components.interfaces.nsISeleniumIDEGenericAutoCompleteSearch) ||
			uuid.equals(Components.interfaces.nsIAutoCompleteSearch) ||
			uuid.equals(Components.interfaces.nsISupports)) {
			return this;
		}
        Components.returnCode = Components.results.NS_ERROR_NO_INTERFACE;
        return null;
    }
};

function AutoCompleteResult(search, candidates) {
	this.search = search;
	this.result = [];
	var lsearch = search.toLowerCase();
    //Samit: Enh: add support for camel case autocompletion
    if (lsearch != search && search.match(/^[A-Za-z]+$/)) {
        var searchregexp = new RegExp(search.replace(/([A-Z]|$)/g,".*$1"));
        for (var i = 0; i < candidates.length; i++) {
            if (searchregexp.test(candidates[i][0])) {
                this.result.push(candidates[i]);
            }
        }
    }else {
        for (var i = 0; i < candidates.length; i++) {
            if (candidates[i][0].toLowerCase().indexOf(lsearch) == 0) {
                this.result.push(candidates[i]);
            }
        }
    }
}

AutoCompleteResult.prototype = {
	get defaultIndex() {
		return 0;
	},
	get errorDescription() {
		return '';
	},
	get matchCount() {
		return this.result.length;
	},
	get searchResult() {
		return Components.interfaces.nsIAutoCompleteResult.RESULT_SUCCESS;
	},
	get searchString() {
		return this.search;
	},
	getCommentAt: function(index) {
		return this.result[index][1] || '';
	},
	getStyleAt: function(index) {
		return '';
	},
	getValueAt: function(index) {
		return this.result[index][0];
	},
	getImageAt: function (index) {
		return '';
	},
	getLabelAt: function getLabelAt(index) {
		return this.getValueAt(index);
  },
	removeValueAt: function(rowIndex, removeFromDb) {
	},
    QueryInterface: function (uuid) {
		if (uuid.equals(Components.interfaces.nsIAutoCompleteResult) ||
			uuid.equals(Components.interfaces.nsISupports)) {
			return this;
		}
        Components.returnCode = Components.results.NS_ERROR_NO_INTERFACE;
        return null;
    }
};

//const COMPONENT_ID = Components.ID("{4791AF5F-AFBA-45A1-8204-47A135DF9591}");
const COMPONENT_ID = Components.ID("{E5226A0D-4698-4E15-9D6D-86771AE172C9}");

var SeleniumIDEGenericAutoCompleteModule = {
    registerSelf: function (compMgr, fileSpec, location, type) {
        compMgr = compMgr.QueryInterface(Components.interfaces.nsIComponentRegistrar);
        compMgr.registerFactoryLocation(COMPONENT_ID,
                                        "Selenium IDE Generic Autocomplete",
                                        "@mozilla.org/autocomplete/search;1?name=selenium-ide-generic",
                                        fileSpec,
                                        location,
                                        type);
    },

    getClassObject: function (compMgr, cid, iid) {
        if (!cid.equals(COMPONENT_ID)) throw Components.results.NS_ERROR_NO_INTERFACE;
        if (!iid.equals(Components.interfaces.nsIFactory))
            throw Components.results.NS_ERROR_NOT_IMPLEMENTED;

		return SeleniumIDEGenericAutoCompleteFactory;
    },

    canUnload: function(compMgr) {
        return true;
    }
};

var SeleniumIDEGenericAutoCompleteFactory = {
	createInstance: function (outer, iid) {
		if (outer != null)
			throw Components.results.NS_ERROR_NO_AGGREGATION;
		return new SeleniumIDEGenericAutoCompleteSearch().QueryInterface(iid);
	}
};

function NSGetModule(compMgr, fileSpec) {
    return SeleniumIDEGenericAutoCompleteModule;
}

function NSGetFactory(cid) {
    if (cid.toString().toUpperCase() != COMPONENT_ID.toString().toUpperCase()) throw Components.results.NS_ERROR_FACTORY_NOT_REGISTERED;
    return SeleniumIDEGenericAutoCompleteFactory;
}
<|endoftext|>


<commit_before>'use strict'
// external deps
var ObjectId = require('mongodb').ObjectId;
require("mongodb-toolkit");

module.exports = class BaseManager {
    constructor(db, user, locale) {
        this.db = db;
        this.user = user;
        this.locale = locale;

        this.collection = null;
    }

    _validate(data) {
        throw new Error('_validate(data) not implemented');
    }

    _getQuery(paging) {
        throw new Error('_getQuery(paging) not implemented');
    }
    _createIndexes() {
        return Promise.resolve(true);
    }

    read(paging) {
        var _paging = Object.assign({
            page: 1,
            size: 20,
            order: {},
            filter: {},
            asc: true
        }, paging);
        // var start = process.hrtime();

        return new Promise((resolve, reject) => {
            this._createIndexes()
                .then((createIndexResults) => {
                    var query = this._getQuery(_paging);
                    this.collection
                        .where(query)
                        .select(_paging.select)
                        .page(_paging.page, _paging.size)
                        .order(_paging.order)
                        .execute()
                        .then(result => {
                            // var elapsed = process.hrtime(start);
                            // console.log(elapsed);
                            resolve(result);
                        })
                        .catch(e => {
                            reject(e);
                        });
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    create(data) {
        return new Promise((resolve, reject) => {
            this._createIndexes()
                .then((createIndexResults) => {
                    this._validate(data)
                        .then(validData => {
                            this.collection.insert(validData)
                                .then(id => {
                                    resolve(id);
                                })
                                .catch(e => {
                                    reject(e);
                                });
                        })
                        .catch(e => {
                            reject(e);
                        });
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    update(data) {
        return new Promise((resolve, reject) => {
            this._createIndexes()
                .then((createIndexResults) => {
                    this._validate(data)
                        .then(validData => {
                            this.collection.update(validData)
                                .then(id => {
                                    resolve(id);
                                })
                                .catch(e => {
                                    reject(e);
                                });
                        })
                        .catch(e => {
                            reject(e);
                        });
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    delete(data) {
        return new Promise((resolve, reject) => {
            this._createIndexes()
                .then((createIndexResults) => {
                    this._validate(data)
                        .then(validData => {
                            validData._deleted = true;
                            this.collection.update(validData)
                                .then(id => {
                                    resolve(id);
                                })
                                .catch(e => {
                                    reject(e);
                                });
                        })
                        .catch(e => {
                            reject(e);
                        });
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

     _delete(id) {

        if (id === '')
            return Promise.resolve(null);
        else {
            return this.collection.deleteOne({
                    _id: id
                })
                .then(result => {
                    return result.n == 1;
                })
                .catch(e => {

                    throw e;
                });
        }
    }

    getSingleById(id) {
        return new Promise((resolve, reject) => {
            if (id === '')
                resolve(null);
            var query = {
                _id: new ObjectId(id),
                _deleted: false
            };
            this.getSingleByQuery(query)
                .then(data => {
                    resolve(data);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    getSingleByIdOrDefault(id) {
        return new Promise((resolve, reject) => {
            if (id === '')
                resolve(null);
            var query = {
                _id: new ObjectId(id),
                _deleted: false
            };
            this.getSingleByQueryOrDefault(query)
                .then(data => {
                    resolve(data);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    getSingleByQuery(query) {
        return new Promise((resolve, reject) => {
            this.collection
                .single(query)
                .then(data => {
                    resolve(data);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    getSingleByQueryOrDefault(query) {
        return new Promise((resolve, reject) => {
            this.collection
                .singleOrDefault(query)
                .then(data => {
                    resolve(data);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }
};
<commit_msg>delete base manager<commit_after><|endoftext|>


<commit_before>export default {
    description: `
    A roc plugin to enable the typed-css-modules, which generates typescript definition
    files for your css files.

    ## How to use?
    Install the plugin as a dev dependency in your roc project:
    \`\`\`
    npm install --save-dev roc-plugin-typed-css-modules
    \`\`\`

    The plugin will now automatically scan any css imports you have in your .ts and
    .tsx files and generate d.ts-files for them. **Be aware though that no type
    definition files are generated until you reference a style in your css file:**
    \`\`\`javascript
    import * as React from 'react';
    // It's not enough to just import the style...
    import * as styles from './style.scss';

    export const MyReactComponent = () => (
    // ...you need to reference it as well before the plugin will kick in and generate type definitions!

Hello CSS Modules world!

    );
    \`\`\`

    Once a reference has been made, the plugin will automatically refresh the type
    definitions when you add new styles into your CSS-file.

    ## Caveats
    Currently, the webpack build with roc isn't automatically rerunning after the type
    definitions have been generated, which means that the typescript compiler will fail
    when trying to compile the file that is referencing the CSS file. Right now, the
    solution is unfortunately to rerun the build (or, in development, restart the dev
    server). For more on these issues, see [this discussion.](https://github.com/Quramy/typed-css-modules/issues/2)

    ### Could not find required extension. Needs roc-plugin-typescript@^*version*
    You'll get this warning if the typescript plugin isn't loaded before this plugin
    is. Per default, [roc will look](https://github.com/rocjs/roc/blob/master/docs/LoadingExtensions.md)
    for any roc-plugin-* packages in your package.json and load them in alphabetic
    order. To get rid of the warning, you'll need to specify the load order explicitly
    in your package.json file:
    \`\`\`
        ...
        "devDependencies": {
            ...
            // Alphabetic order
            "roc-plugin-typed-css-modules": "^2.0.0",
            "roc-plugin-typescript": "^2.0.0-alpha",
            ...
        },
        "roc": {
            // Needed to specify load order correctly to fullfill plugin dependencies
            "plugins": [
                ...
                // Reverse order from above
                "roc-plugin-typescript",
                "roc-plugin-typed-css-modules",
                ...
            ]
        }
    \`\`\`
    `,
    actions: [{
        hook: 'add-style',
        description: 'generates typescript definition files for your css files.',
        action: () => () => () => ({
            extensions: ['css'],
            loaders: require.resolve('typed-css-modules-loader'),
        }),
    }],
    required: {
        'roc-plugin-typescript': '^2.0.0-alpha',
        'roc-plugin-style-css': '^1.0.0-beta.2',
    },
};
<commit_msg>Added plugin name to roc config.<commit_after>export default {
    name: 'roc-plugin-typed-css-modules',
    description: `
    A roc plugin to enable the typed-css-modules, which generates typescript definition
    files for your css files.

    ## How to use?
    Install the plugin as a dev dependency in your roc project:
    \`\`\`
    npm install --save-dev roc-plugin-typed-css-modules
    \`\`\`

    The plugin will now automatically scan any css imports you have in your .ts and
    .tsx files and generate d.ts-files for them. **Be aware though that no type
    definition files are generated until you reference a style in your css file:**
    \`\`\`javascript
    import * as React from 'react';
    // It's not enough to just import the style...
    import * as styles from './style.scss';

    export const MyReactComponent = () => (
    // ...you need to reference it as well before the plugin will kick in and generate type definitions!

Hello CSS Modules world!

    );
    \`\`\`

    Once a reference has been made, the plugin will automatically refresh the type
    definitions when you add new styles into your CSS-file.

    ## Caveats
    Currently, the webpack build with roc isn't automatically rerunning after the type
    definitions have been generated, which means that the typescript compiler will fail
    when trying to compile the file that is referencing the CSS file. Right now, the
    solution is unfortunately to rerun the build (or, in development, restart the dev
    server). For more on these issues, see [this discussion.](https://github.com/Quramy/typed-css-modules/issues/2)

    ### Could not find required extension. Needs roc-plugin-typescript@^*version*
    You'll get this warning if the typescript plugin isn't loaded before this plugin
    is. Per default, [roc will look](https://github.com/rocjs/roc/blob/master/docs/LoadingExtensions.md)
    for any roc-plugin-* packages in your package.json and load them in alphabetic
    order. To get rid of the warning, you'll need to specify the load order explicitly
    in your package.json file:
    \`\`\`
        ...
        "devDependencies": {
            ...
            // Alphabetic order
            "roc-plugin-typed-css-modules": "^2.0.0",
            "roc-plugin-typescript": "^2.0.0-alpha",
            ...
        },
        "roc": {
            // Needed to specify load order correctly to fullfill plugin dependencies
            "plugins": [
                ...
                // Reverse order from above
                "roc-plugin-typescript",
                "roc-plugin-typed-css-modules",
                ...
            ]
        }
    \`\`\`
    `,
    actions: [{
        hook: 'add-style',
        description: 'generates typescript definition files for your css files.',
        action: () => () => () => ({
            extensions: ['css'],
            loaders: require.resolve('typed-css-modules-loader'),
        }),
    }],
    required: {
        'roc-plugin-typescript': '^2.0.0-alpha',
        'roc-plugin-style-css': '^1.0.0-beta.2',
    },
};
<|endoftext|>


<commit_before><commit_msg>Backport TransformControls.js changes<commit_after><|endoftext|>


<commit_before>/*
 * Copyright (c) 2013-2014 Chukong Technologies Inc.
 *
 * 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.
 */

//
// cocos2d ui constants
//
// This helper file should be required after jsb_cocos2d.js
//

var ccui = ccui || {};

// =====================Constants=====================

/*
 * UILayout
 */
//layoutBackGround color type
ccui.Layout.BG_COLOR_NONE = 0;
ccui.Layout.BG_COLOR_SOLID = 1;
ccui.Layout.BG_COLOR_GRADIENT = 2;

//Layout type
ccui.Layout.ABSOLUTE = 0;
ccui.Layout.LINEAR_VERTICAL = 1;
ccui.Layout.LINEAR_HORIZONTAL = 2;
ccui.Layout.RELATIVE = 3;

//Layout clipping type
ccui.Layout.CLIPPING_STENCIL = 0;
ccui.Layout.CLIPPING_SCISSOR = 1;

ccui.Layout.BACKGROUND_IMAGE_ZORDER = -2;
ccui.Layout.BACKGROUND_RENDERER_ZORDER = -2;

/*
 * UILayoutDefine
 */
//LinearGravity
ccui.LINEAR_GRAVITY_NONE = 0;
ccui.LINEAR_GRAVITY_LEFT = 1;
ccui.LINEAR_GRAVITY_TOP = 2;
ccui.LINEAR_GRAVITY_RIGHT = 3;
ccui.LINEAR_GRAVITY_BOTTOM = 4;
ccui.LINEAR_GRAVITY_CENTER_VERTICAL = 5;
ccui.LINEAR_GRAVITY_CENTER_HORIZONTAL = 6;

//RelativeAlign
ccui.RELATIVE_ALIGN_NONE = 0;
ccui.RELATIVE_ALIGN_PARENT_TOP_LEFT = 1;
ccui.RELATIVE_ALIGN_PARENT_TOP_CENTER_HORIZONTAL = 2;
ccui.RELATIVE_ALIGN_PARENT_TOP_RIGHT = 3;
ccui.RELATIVE_ALIGN_PARENT_LEFT_CENTER_VERTICAL = 4;
ccui.RELATIVE_ALIGN_PARENT_CENTER = 5;
ccui.RELATIVE_ALIGN_PARENT_RIGHT_CENTER_VERTICAL = 6;
ccui.RELATIVE_ALIGN_PARENT_LEFT_BOTTOM = 7;
ccui.RELATIVE_ALIGN_PARENT_BOTTOM_CENTER_HORIZONTAL = 8;
ccui.RELATIVE_ALIGN_PARENT_RIGHT_BOTTOM = 9;

ccui.RELATIVE_ALIGN_LOCATION_ABOVE_LEFT = 10;
ccui.RELATIVE_ALIGN_LOCATION_ABOVE_CENTER = 11;
ccui.RELATIVE_ALIGN_LOCATION_ABOVE_RIGHT = 12;

ccui.RELATIVE_ALIGN_LOCATION_LEFT_TOP = 13;
ccui.RELATIVE_ALIGN_LOCATION_LEFT_CENTER = 14;
ccui.RELATIVE_ALIGN_LOCATION_LEFT_BOTTOM = 15;

ccui.RELATIVE_ALIGN_LOCATION_RIGHT_TOP = 16;
ccui.RELATIVE_ALIGN_LOCATION_RIGHT_CENTER = 17;
ccui.RELATIVE_ALIGN_LOCATION_RIGHT_BOTTOM = 18;

ccui.RELATIVE_ALIGN_LOCATION_BELOW_TOP = 19;
ccui.RELATIVE_ALIGN_LOCATION_BELOW_CENTER = 20;
ccui.RELATIVE_ALIGN_LOCATION_BELOW_BOTTOM = 21;

/*
 * LayoutParameter
 */
//layout parameter type
ccui.LayoutParameter.NONE = 0;
ccui.LayoutParameter.LINEAR = 1;
ccui.LayoutParameter.RELATIVE = 2;

/*
 * UIWidget
 */
//bright style
ccui.Widget.BRIGHT_STYLE_NONE = -1;
ccui.Widget.BRIGHT_STYLE_NORMAL = 0;
ccui.Widget.BRIGHT_STYLE_HIGH_LIGHT = 1;

//widget type
ccui.Widget.TYPE_WIDGET = 0;
ccui.Widget.TYPE_CONTAINER = 1;

//texture resource type
ccui.Widget.LOCAL_TEXTURE = 0;
ccui.Widget.PLIST_TEXTURE = 1;

//touch event type
ccui.Widget.TOUCH_BEGAN = 0;
ccui.Widget.TOUCH_MOVED = 1;
ccui.Widget.TOUCH_ENDED = 2;
ccui.Widget.TOUCH_CANCELED = 3;

//size type
ccui.Widget.SIZE_ABSOLUTE = 0;
ccui.Widget.SIZE_PERCENT = 1;

//position type
ccui.Widget.POSITION_ABSOLUTE = 0;
ccui.Widget.POSITION_PERCENT = 1;

/*
 * UIListView
 */
//listView event type
ccui.ListView.EVENT_SELECTED_ITEM = 0;

//listView gravity
ccui.ListView.GRAVITY_LEFT = 0;
ccui.ListView.GRAVITY_RIGHT = 1;
ccui.ListView.GRAVITY_CENTER_HORIZONTAL = 2;
ccui.ListView.GRAVITY_TOP = 3;
ccui.ListView.GRAVITY_BOTTOM = 4;
ccui.ListView.GRAVITY_CENTER_VERTICAL = 5;

/*
 * UIScrollView
 */
//ScrollView direction
ccui.ScrollView.DIR_NONE = 0;
ccui.ScrollView.DIR_VERTICAL = 1;
ccui.ScrollView.DIR_HORIZONTAL = 2;
ccui.ScrollView.DIR_BOTH = 3;

//ScrollView event
ccui.ScrollView.EVENT_SCROLL_TO_TOP = 0;
ccui.ScrollView.EVENT_SCROLL_TO_BOTTOM = 1;
ccui.ScrollView.EVENT_SCROLL_TO_LEFT = 2;
ccui.ScrollView.EVENT_SCROLL_TO_RIGHT = 3;
ccui.ScrollView.EVENT_SCROLLING = 4;
ccui.ScrollView.EVENT_BOUNCE_TOP = 5;
ccui.ScrollView.EVENT_BOUNCE_BOTTOM = 6;
ccui.ScrollView.EVENT_BOUNCE_LEFT = 7;
ccui.ScrollView.EVENT_BOUNCE_RIGHT = 8;

ccui.ScrollView.AUTO_SCROLL_MAX_SPEED = 1000;
ccui.ScrollView.SCROLLDIR_UP = cc.p(0, 1);
ccui.ScrollView.SCROLLDIR_DOWN = cc.p(0, -1);
ccui.ScrollView.SCROLLDIR_LEFT = cc.p(-1, 0);
ccui.ScrollView.SCROLLDIR_RIGHT = cc.p(1, 0);

/*
 * UIPageView
 */
//PageView event
ccui.PageView.EVENT_TURNING = 0;

//PageView touch direction
ccui.PageView.TOUCH_DIR_LEFT = 0;
ccui.PageView.TOUCH_DIR_RIGHT = 1;

/*
 * UIButton
 */
ccui.NORMAL_RENDERER_ZORDER = -2;
ccui.PRESSED_RENDERER_ZORDER = -2;
ccui.DISABLED_RENDERER_ZORDER = -2;
ccui.TITLE_RENDERER_ZORDER = -1;

/*
 * UICheckBox
 */
//CheckBoxEvent type
ccui.CheckBox.EVENT_SELECTED = 0;
ccui.CheckBox.EVENT_UNSELECTED = 1;

//Render zorder
ccui.CheckBox.BOX_RENDERER_ZORDER = -1;
ccui.CheckBox.BOX_SELECTED_RENDERER_ZORDER = -1;
ccui.CheckBox.BOX_DISABLED_RENDERER_ZORDER = -1;
ccui.CheckBox.FRONT_CROSS_RENDERER_ZORDER = -1;
ccui.CheckBox.FRONT_CROSS_DISABLED_RENDERER_ZORDER = -1;

/*
 * UIImageView
 */
ccui.ImageView.RENDERER_ZORDER = -1;

/*
 * UILoadingBar
 */
//loadingBar Type
ccui.LoadingBar.TYPE_LEFT = 0;
ccui.LoadingBar.TYPE_RIGHT = 1;

ccui.LoadingBar.RENDERER_ZORDER = -1;

/*
 * UIRichElement
 */
//Rich element type
//ccui.RichElement.TYPE_TEXT = 0;
//ccui.RichElement.TYPE_IMAGE = 1;
//ccui.RichElement.TYPE_CUSTOM = 2;

/*
 * UISlider
 */
//Slider event type
ccui.Slider.EVENT_PERCENT_CHANGED = 0;

//Render zorder
ccui.Slider.BASEBAR_RENDERER_ZORDER = -3;
ccui.Slider.PROGRESSBAR_RENDERER_ZORDER = -2;
ccui.Slider.BALL_RENDERER_ZORDER = -1;

/*
 * UIText
 */
ccui.Text.RENDERER_ZORDER = -1;

/*
 * UITextAtlas
 */
ccui.TextAtlas.RENDERER_ZORDER = -1;

/*
 * UITextBMFont
 */
ccui.TextBMFont.RENDERER_ZORDER = -1;

/*
 * UITextField
 */
//TextField event
ccui.TextField.EVENT_ATTACH_WITH_ME = 0;
ccui.TextField.EVENT_DETACH_WITH_ME = 1;
ccui.TextField.EVENT_INSERT_TEXT = 2;
ccui.TextField.EVENT_DELETE_BACKWARD = 3;

ccui.TextField.RENDERER_ZORDER = -1;

/*
 * UIMargin
 */
ccui.Margin = cc.Class.extend({
    left: 0,
    top: 0,
    right: 0,
    bottom: 0,
    ctor: function () {
        if (arguments.length == 1) {
            var uiMargin = arguments[0];
            this.left = uiMargin.left;
            this.top = uiMargin.top;
            this.right = uiMargin.right;
            this.bottom = uiMargin.bottom;
        }
        if (arguments.length == 4) {
            this.left = arguments[0];
            this.top = arguments[1];
            this.right = arguments[2];
            this.bottom = arguments[3];
        }
    },
    setMargin: function (l, t, r, b) {
        this.left = l;
        this.top = t;
        this.right = r;
        this.bottom = b;
    },
    equals: function (target) {
        return (this.left == target.left && this.top == target.top && this.right == target.right && this.bottom == target.bottom);
    }
});

ccui.MarginZero = function(){
    return new ccui.Margin(0,0,0,0);
};

/*
 * UIWidget temporary solution to addChild
 * addNode and addChild function should be merged in ccui.Widget
 */
ccui.Widget.prototype.addNode = ccui.Widget.prototype.addChild;

/*
 * UITextField temporary solution to getString, wait for -x patch
 */
ccui.TextField.prototype.getString = ccui.TextField.prototype.getStringValue;<commit_msg>Issue #5618: add (g|s)etSize in ccui.Widget.prototype<commit_after>/*
 * Copyright (c) 2013-2014 Chukong Technologies Inc.
 *
 * 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.
 */

//
// cocos2d ui constants
//
// This helper file should be required after jsb_cocos2d.js
//

var ccui = ccui || {};

// =====================Constants=====================

/*
 * UILayout
 */
//layoutBackGround color type
ccui.Layout.BG_COLOR_NONE = 0;
ccui.Layout.BG_COLOR_SOLID = 1;
ccui.Layout.BG_COLOR_GRADIENT = 2;

//Layout type
ccui.Layout.ABSOLUTE = 0;
ccui.Layout.LINEAR_VERTICAL = 1;
ccui.Layout.LINEAR_HORIZONTAL = 2;
ccui.Layout.RELATIVE = 3;

//Layout clipping type
ccui.Layout.CLIPPING_STENCIL = 0;
ccui.Layout.CLIPPING_SCISSOR = 1;

ccui.Layout.BACKGROUND_IMAGE_ZORDER = -2;
ccui.Layout.BACKGROUND_RENDERER_ZORDER = -2;

/*
 * UILayoutDefine
 */
//LinearGravity
ccui.LINEAR_GRAVITY_NONE = 0;
ccui.LINEAR_GRAVITY_LEFT = 1;
ccui.LINEAR_GRAVITY_TOP = 2;
ccui.LINEAR_GRAVITY_RIGHT = 3;
ccui.LINEAR_GRAVITY_BOTTOM = 4;
ccui.LINEAR_GRAVITY_CENTER_VERTICAL = 5;
ccui.LINEAR_GRAVITY_CENTER_HORIZONTAL = 6;

//RelativeAlign
ccui.RELATIVE_ALIGN_NONE = 0;
ccui.RELATIVE_ALIGN_PARENT_TOP_LEFT = 1;
ccui.RELATIVE_ALIGN_PARENT_TOP_CENTER_HORIZONTAL = 2;
ccui.RELATIVE_ALIGN_PARENT_TOP_RIGHT = 3;
ccui.RELATIVE_ALIGN_PARENT_LEFT_CENTER_VERTICAL = 4;
ccui.RELATIVE_ALIGN_PARENT_CENTER = 5;
ccui.RELATIVE_ALIGN_PARENT_RIGHT_CENTER_VERTICAL = 6;
ccui.RELATIVE_ALIGN_PARENT_LEFT_BOTTOM = 7;
ccui.RELATIVE_ALIGN_PARENT_BOTTOM_CENTER_HORIZONTAL = 8;
ccui.RELATIVE_ALIGN_PARENT_RIGHT_BOTTOM = 9;

ccui.RELATIVE_ALIGN_LOCATION_ABOVE_LEFT = 10;
ccui.RELATIVE_ALIGN_LOCATION_ABOVE_CENTER = 11;
ccui.RELATIVE_ALIGN_LOCATION_ABOVE_RIGHT = 12;

ccui.RELATIVE_ALIGN_LOCATION_LEFT_TOP = 13;
ccui.RELATIVE_ALIGN_LOCATION_LEFT_CENTER = 14;
ccui.RELATIVE_ALIGN_LOCATION_LEFT_BOTTOM = 15;

ccui.RELATIVE_ALIGN_LOCATION_RIGHT_TOP = 16;
ccui.RELATIVE_ALIGN_LOCATION_RIGHT_CENTER = 17;
ccui.RELATIVE_ALIGN_LOCATION_RIGHT_BOTTOM = 18;

ccui.RELATIVE_ALIGN_LOCATION_BELOW_TOP = 19;
ccui.RELATIVE_ALIGN_LOCATION_BELOW_CENTER = 20;
ccui.RELATIVE_ALIGN_LOCATION_BELOW_BOTTOM = 21;

/*
 * LayoutParameter
 */
//layout parameter type
ccui.LayoutParameter.NONE = 0;
ccui.LayoutParameter.LINEAR = 1;
ccui.LayoutParameter.RELATIVE = 2;

/*
 * UIWidget
 */
//bright style
ccui.Widget.BRIGHT_STYLE_NONE = -1;
ccui.Widget.BRIGHT_STYLE_NORMAL = 0;
ccui.Widget.BRIGHT_STYLE_HIGH_LIGHT = 1;

//widget type
ccui.Widget.TYPE_WIDGET = 0;
ccui.Widget.TYPE_CONTAINER = 1;

//texture resource type
ccui.Widget.LOCAL_TEXTURE = 0;
ccui.Widget.PLIST_TEXTURE = 1;

//touch event type
ccui.Widget.TOUCH_BEGAN = 0;
ccui.Widget.TOUCH_MOVED = 1;
ccui.Widget.TOUCH_ENDED = 2;
ccui.Widget.TOUCH_CANCELED = 3;

//size type
ccui.Widget.SIZE_ABSOLUTE = 0;
ccui.Widget.SIZE_PERCENT = 1;

//position type
ccui.Widget.POSITION_ABSOLUTE = 0;
ccui.Widget.POSITION_PERCENT = 1;

/*
 * UIListView
 */
//listView event type
ccui.ListView.EVENT_SELECTED_ITEM = 0;

//listView gravity
ccui.ListView.GRAVITY_LEFT = 0;
ccui.ListView.GRAVITY_RIGHT = 1;
ccui.ListView.GRAVITY_CENTER_HORIZONTAL = 2;
ccui.ListView.GRAVITY_TOP = 3;
ccui.ListView.GRAVITY_BOTTOM = 4;
ccui.ListView.GRAVITY_CENTER_VERTICAL = 5;

/*
 * UIScrollView
 */
//ScrollView direction
ccui.ScrollView.DIR_NONE = 0;
ccui.ScrollView.DIR_VERTICAL = 1;
ccui.ScrollView.DIR_HORIZONTAL = 2;
ccui.ScrollView.DIR_BOTH = 3;

//ScrollView event
ccui.ScrollView.EVENT_SCROLL_TO_TOP = 0;
ccui.ScrollView.EVENT_SCROLL_TO_BOTTOM = 1;
ccui.ScrollView.EVENT_SCROLL_TO_LEFT = 2;
ccui.ScrollView.EVENT_SCROLL_TO_RIGHT = 3;
ccui.ScrollView.EVENT_SCROLLING = 4;
ccui.ScrollView.EVENT_BOUNCE_TOP = 5;
ccui.ScrollView.EVENT_BOUNCE_BOTTOM = 6;
ccui.ScrollView.EVENT_BOUNCE_LEFT = 7;
ccui.ScrollView.EVENT_BOUNCE_RIGHT = 8;

ccui.ScrollView.AUTO_SCROLL_MAX_SPEED = 1000;
ccui.ScrollView.SCROLLDIR_UP = cc.p(0, 1);
ccui.ScrollView.SCROLLDIR_DOWN = cc.p(0, -1);
ccui.ScrollView.SCROLLDIR_LEFT = cc.p(-1, 0);
ccui.ScrollView.SCROLLDIR_RIGHT = cc.p(1, 0);

/*
 * UIPageView
 */
//PageView event
ccui.PageView.EVENT_TURNING = 0;

//PageView touch direction
ccui.PageView.TOUCH_DIR_LEFT = 0;
ccui.PageView.TOUCH_DIR_RIGHT = 1;

/*
 * UIButton
 */
ccui.NORMAL_RENDERER_ZORDER = -2;
ccui.PRESSED_RENDERER_ZORDER = -2;
ccui.DISABLED_RENDERER_ZORDER = -2;
ccui.TITLE_RENDERER_ZORDER = -1;

/*
 * UICheckBox
 */
//CheckBoxEvent type
ccui.CheckBox.EVENT_SELECTED = 0;
ccui.CheckBox.EVENT_UNSELECTED = 1;

//Render zorder
ccui.CheckBox.BOX_RENDERER_ZORDER = -1;
ccui.CheckBox.BOX_SELECTED_RENDERER_ZORDER = -1;
ccui.CheckBox.BOX_DISABLED_RENDERER_ZORDER = -1;
ccui.CheckBox.FRONT_CROSS_RENDERER_ZORDER = -1;
ccui.CheckBox.FRONT_CROSS_DISABLED_RENDERER_ZORDER = -1;

/*
 * UIImageView
 */
ccui.ImageView.RENDERER_ZORDER = -1;

/*
 * UILoadingBar
 */
//loadingBar Type
ccui.LoadingBar.TYPE_LEFT = 0;
ccui.LoadingBar.TYPE_RIGHT = 1;

ccui.LoadingBar.RENDERER_ZORDER = -1;

/*
 * UIRichElement
 */
//Rich element type
//ccui.RichElement.TYPE_TEXT = 0;
//ccui.RichElement.TYPE_IMAGE = 1;
//ccui.RichElement.TYPE_CUSTOM = 2;

/*
 * UISlider
 */
//Slider event type
ccui.Slider.EVENT_PERCENT_CHANGED = 0;

//Render zorder
ccui.Slider.BASEBAR_RENDERER_ZORDER = -3;
ccui.Slider.PROGRESSBAR_RENDERER_ZORDER = -2;
ccui.Slider.BALL_RENDERER_ZORDER = -1;

/*
 * UIText
 */
ccui.Text.RENDERER_ZORDER = -1;

/*
 * UITextAtlas
 */
ccui.TextAtlas.RENDERER_ZORDER = -1;

/*
 * UITextBMFont
 */
ccui.TextBMFont.RENDERER_ZORDER = -1;

/*
 * UITextField
 */
//TextField event
ccui.TextField.EVENT_ATTACH_WITH_ME = 0;
ccui.TextField.EVENT_DETACH_WITH_ME = 1;
ccui.TextField.EVENT_INSERT_TEXT = 2;
ccui.TextField.EVENT_DELETE_BACKWARD = 3;

ccui.TextField.RENDERER_ZORDER = -1;

/*
 * UIMargin
 */
ccui.Margin = cc.Class.extend({
    left: 0,
    top: 0,
    right: 0,
    bottom: 0,
    ctor: function () {
        if (arguments.length == 1) {
            var uiMargin = arguments[0];
            this.left = uiMargin.left;
            this.top = uiMargin.top;
            this.right = uiMargin.right;
            this.bottom = uiMargin.bottom;
        }
        if (arguments.length == 4) {
            this.left = arguments[0];
            this.top = arguments[1];
            this.right = arguments[2];
            this.bottom = arguments[3];
        }
    },
    setMargin: function (l, t, r, b) {
        this.left = l;
        this.top = t;
        this.right = r;
        this.bottom = b;
    },
    equals: function (target) {
        return (this.left == target.left && this.top == target.top && this.right == target.right && this.bottom == target.bottom);
    }
});

ccui.MarginZero = function(){
    return new ccui.Margin(0,0,0,0);
};

/*
 * UIWidget temporary solution to addChild
 * addNode and addChild function should be merged in ccui.Widget
 */
ccui.Widget.prototype.addNode = ccui.Widget.prototype.addChild;
ccui.Widget.prototype.getSize = ccui.Widget.prototype.getContentSize;
ccui.Widget.prototype.setSize = ccui.Widget.prototype.setContentSize;

/*
 * UITextField temporary solution to getString, wait for -x patch
 */
ccui.TextField.prototype.getString = ccui.TextField.prototype.getStringValue;<|endoftext|>