<commit_before>'use strict';

/**
 * Requirements
 * @ignore
 */
const BaseRoute = require('./BaseRoute.js').BaseRoute;
const GlobalConfiguration = require('../../model/configuration/GlobalConfiguration.js').GlobalConfiguration;
const PathesConfiguration = require('../../model/configuration/PathesConfiguration.js').PathesConfiguration;
const UrlsConfiguration = require('../../model/configuration/UrlsConfiguration.js').UrlsConfiguration;
const BuildConfiguration = require('../../model/configuration/BuildConfiguration.js').BuildConfiguration;
const EntitiesRepository = require('../../model/entity/EntitiesRepository.js').EntitiesRepository;
const Environment = require('../../nunjucks/Environment.js').Environment;
const HtmlFormatter = require('../../formatter/html/HtmlFormatter.js').HtmlFormatter;
const CallParser = require('../../parser/jinja/CallParser.js').CallParser;
const CliLogger = require('../../cli/CliLogger.js').CliLogger;
const assertParameter = require('../../utils/assert.js').assertParameter;
const fs = require('fs');
const pathes = require('../../utils/pathes.js');
const synchronize = require('../../utils/synchronize.js');
const path = require('path');
const shortenLeft = require('../../utils/string.js').shortenLeft;
const co = require('co');

/**
 * @memberOf server.routes
 */
class SitesRoute extends BaseRoute
{
    /**
     * @param {cli.CliLogger} cliLogger
     * @param {model.entity.EntitiesRepository} entitiesRepository
     * @param {model.configuration.GlobalConfiguration} globalConfiguration
     * @param {model.configuration.PathesConfiguration} pathesConfiguration
     * @param {model.configuration.UrlsConfiguration} urlsConfiguration
     * @param {model.configuration.BuildConfiguration} buildConfiguration
     * @param {nunjucks.Environment} nunjucks
     * @param {object} [options]
     */
    constructor(cliLogger, entitiesRepository, globalConfiguration, pathesConfiguration, urlsConfiguration, buildConfiguration, nunjucks, options)
    {
        super(cliLogger.createPrefixed('routes.sitesroute'));

        // Check params
        assertParameter(this, 'entitiesRepository', entitiesRepository, true, EntitiesRepository);
        assertParameter(this, 'pathesConfiguration', pathesConfiguration, true, PathesConfiguration);
        assertParameter(this, 'urlsConfiguration', urlsConfiguration, true, UrlsConfiguration);
        assertParameter(this, 'globalConfiguration', globalConfiguration, true, GlobalConfiguration);
        assertParameter(this, 'buildConfiguration', buildConfiguration, true, BuildConfiguration);
        assertParameter(this, 'nunjucks', nunjucks, true, Environment);

        // Assign options
        const opts = options || {};
        this._entitiesRepository = entitiesRepository;
        this._pathesConfiguration = pathesConfiguration;
        this._urlsConfiguration = urlsConfiguration;
        this._buildConfiguration = buildConfiguration;
        this._nunjucks = nunjucks;
        this._path = opts.path || pathesConfiguration.sites;
        this._rootUrl = opts.rootUrl || '/:site/:entityCategory/*';
        this._formatHtml = opts.formatHtml || false;
        this._staticFileExtensions = opts.staticFileExtensions || ['.js', '.css', '.png', '.jpg', '.gif', '.svg', '.woff', '.json', '.ico'];
        this._staticRoutes = opts.staticRoutes || [];
        this._htmlFormatter = new HtmlFormatter();
        this._jinjaParser = new CallParser();

        // Configure nunjucks
        this._nunjucks.path = this._path;
    }

    /**
     * @inheritDoc
     */
    static get injections()
    {
        return { 'parameters': [CliLogger, EntitiesRepository, GlobalConfiguration,
            PathesConfiguration, UrlsConfiguration, BuildConfiguration, Environment, 'server.routes/SitesRoute.options'] };

    }

    /**
     * @inheritDocs
     */
    static get className()
    {
        return 'server.routes/SitesRoute';
    }

    /**
     * @inheritDocs
     */
    get nunjucks()
    {
        return this._nunjucks;
    }

    /**
     * @inheritDocs
     */
    handle404(request, response, next)
    {
        //this._cliLogger.info('SiteRoute.handle404: Could not find url ' + request.url);
        next();
    }

    /**
     * @inheritDocs
     */
    handleStatic(rootPath, fileExtensions, log, request, response, next)
    {
        const scope = this;
        //scope._cliLogger.info('handleStatic: from <' + rootPath + '> <' + fileExtensions.join(', ') + '> trying <' + request.url + '>');

        // Check extension
        const extension = path.extname(request.path);
        if (fileExtensions.indexOf(extension) === -1)
        {
            next();
            return;
        }

        // Check straight file
        const filename = pathes.concat(rootPath, request.path);
        if (!fs.existsSync(filename))
        {
            //console.log('Not found:', rootPath, request.path, filename);
            next();
            return;
        }

        // Serve it
        let work;
        if (log)
        {
            const filenameShort = shortenLeft(synchronize.execute(scope._pathesConfiguration, 'shorten', [filename]), 60);
            /*
            response.setHeader("Cache-Control", "public, max-age=2592000");
            response.setHeader("Expires", new Date(Date.now() + 2592000000).toUTCString());
            */
            //work = scope._cliLogger.work('Serving static <' + filenameShort + '> as <' + request.url + '>');
        }
        response.sendFile(filename);
        if (work)
        {
            scope._cliLogger.end(work);
        }
        return Promise.resolve(true);
    }

    /**
     * @inheritDocs
     */
    handleTemplate(request, response, next)
    {
        const scope = this;
        const promise = co(function *()
        {
            scope._cliLogger.info('handleTemplate: from <' + scope._path + '> trying <' + request.url + '>');

            // Check extension
            if (!request.path.endsWith('.j2'))
            {
                next();
                return;
            }

            // Check direct hit
            let filename = pathes.concat(scope._path, request.path);
            if (!fs.existsSync(filename))
            {
                scope.logger.debug('handleTemplate: no direct hit at <' + filename + '>');

                // Check entity file
                const match = yield scope._urlsConfiguration.matchEntityFile(request.path);
                if (!match.file)
                {
                    next();
                    return;
                }
                filename = match.file.filename;
            }

            // Render template
            scope._nunjucks.isStatic = (typeof request.query.static !== 'undefined');
            const data = yield scope._urlsConfiguration.matchEntity(request.path, true);
            const filenameShort = shortenLeft(synchronize.execute(scope._pathesConfiguration, 'shorten', [filename]), 60);
            const tpl = fs.readFileSync(filename, { encoding: 'utf8' });
            const work = scope._cliLogger.work('Serving ' + (scope._nunjucks.isStatic ? '<static>' : '') + ' template <' + filenameShort + '> as <' + request.url + '>');
            let html;
            try
            {
                scope._nunjucks.addGlobal('site', data.site);
                html = scope._nunjucks.renderString(tpl, data);
            }
            catch (e)
            {
                scope._cliLogger.error(scope.className + '::handleTemplate', e);
                next();
                return;
            }

            // Format
            if (scope._formatHtml)
            {
                const formatted = yield scope._htmlFormatter.format(html);
                response.send(formatted);
                scope._cliLogger.end(work);
            }
            else
            {
                response.send(html);
                scope._cliLogger.end(work);
            }
            return true;
        })
        .catch(function(error)
        {
            scope._cliLogger.error(scope.className + '::handleTemplate', error.stack);
        });
        return promise;
    }

    /**
     * @param {Express}
     */
    register(express)
    {
        const work = this._cliLogger.work('Registering <' + this.className + '> as middleware');

        for (const staticRoute of this._staticRoutes)
        {
            const rootUrl = staticRoute.rootUrl || this._rootUrl;
            let rootPath = this._path;
            if (staticRoute.rootPath)
            {
                rootPath = synchronize.execute(this._pathesConfiguration, 'resolve', [staticRoute.rootPath]);
            }
            const fileExtensions = staticRoute.fileExtensions || [];
            express.all(rootUrl, this.handleStatic.bind(this, rootPath, fileExtensions, true));
        }
        express.all(this._rootUrl, this.handleStatic.bind(this, this._path, this._staticFileExtensions, true));
        if (this._pathesConfiguration.jspm)
        {
            const jspmPath = path.resolve(this._pathesConfiguration.jspm + '/..');
            express.all('/jspm_packages/*', this.handleStatic.bind(this, jspmPath, ['.js'], true));
            express.all('/*', this.handleStatic.bind(this, jspmPath, ['.js'], true));
        }
        express.all(this._rootUrl, this.handleTemplate.bind(this));
        express.all('*', this.handle404.bind(this));

        this._cliLogger.end(work);
    }
}

/**
 * Exports
 * @ignore
 */
module.exports.SitesRoute = SitesRoute;
<commit_msg>feat(server): adds request to nunjucks globals<commit_after>'use strict';

/**
 * Requirements
 * @ignore
 */
const BaseRoute = require('./BaseRoute.js').BaseRoute;
const GlobalConfiguration = require('../../model/configuration/GlobalConfiguration.js').GlobalConfiguration;
const PathesConfiguration = require('../../model/configuration/PathesConfiguration.js').PathesConfiguration;
const UrlsConfiguration = require('../../model/configuration/UrlsConfiguration.js').UrlsConfiguration;
const BuildConfiguration = require('../../model/configuration/BuildConfiguration.js').BuildConfiguration;
const EntitiesRepository = require('../../model/entity/EntitiesRepository.js').EntitiesRepository;
const Environment = require('../../nunjucks/Environment.js').Environment;
const HtmlFormatter = require('../../formatter/html/HtmlFormatter.js').HtmlFormatter;
const CallParser = require('../../parser/jinja/CallParser.js').CallParser;
const CliLogger = require('../../cli/CliLogger.js').CliLogger;
const assertParameter = require('../../utils/assert.js').assertParameter;
const fs = require('fs');
const pathes = require('../../utils/pathes.js');
const synchronize = require('../../utils/synchronize.js');
const path = require('path');
const shortenLeft = require('../../utils/string.js').shortenLeft;
const co = require('co');

/**
 * @memberOf server.routes
 */
class SitesRoute extends BaseRoute
{
    /**
     * @param {cli.CliLogger} cliLogger
     * @param {model.entity.EntitiesRepository} entitiesRepository
     * @param {model.configuration.GlobalConfiguration} globalConfiguration
     * @param {model.configuration.PathesConfiguration} pathesConfiguration
     * @param {model.configuration.UrlsConfiguration} urlsConfiguration
     * @param {model.configuration.BuildConfiguration} buildConfiguration
     * @param {nunjucks.Environment} nunjucks
     * @param {object} [options]
     */
    constructor(cliLogger, entitiesRepository, globalConfiguration, pathesConfiguration, urlsConfiguration, buildConfiguration, nunjucks, options)
    {
        super(cliLogger.createPrefixed('routes.sitesroute'));

        // Check params
        assertParameter(this, 'entitiesRepository', entitiesRepository, true, EntitiesRepository);
        assertParameter(this, 'pathesConfiguration', pathesConfiguration, true, PathesConfiguration);
        assertParameter(this, 'urlsConfiguration', urlsConfiguration, true, UrlsConfiguration);
        assertParameter(this, 'globalConfiguration', globalConfiguration, true, GlobalConfiguration);
        assertParameter(this, 'buildConfiguration', buildConfiguration, true, BuildConfiguration);
        assertParameter(this, 'nunjucks', nunjucks, true, Environment);

        // Assign options
        const opts = options || {};
        this._entitiesRepository = entitiesRepository;
        this._pathesConfiguration = pathesConfiguration;
        this._urlsConfiguration = urlsConfiguration;
        this._buildConfiguration = buildConfiguration;
        this._nunjucks = nunjucks;
        this._path = opts.path || pathesConfiguration.sites;
        this._rootUrl = opts.rootUrl || '/:site/:entityCategory/*';
        this._formatHtml = opts.formatHtml || false;
        this._staticFileExtensions = opts.staticFileExtensions || ['.js', '.css', '.png', '.jpg', '.gif', '.svg', '.woff', '.json', '.ico'];
        this._staticRoutes = opts.staticRoutes || [];
        this._htmlFormatter = new HtmlFormatter();
        this._jinjaParser = new CallParser();

        // Configure nunjucks
        this._nunjucks.path = this._path;
    }

    /**
     * @inheritDoc
     */
    static get injections()
    {
        return { 'parameters': [CliLogger, EntitiesRepository, GlobalConfiguration,
            PathesConfiguration, UrlsConfiguration, BuildConfiguration, Environment, 'server.routes/SitesRoute.options'] };

    }

    /**
     * @inheritDocs
     */
    static get className()
    {
        return 'server.routes/SitesRoute';
    }

    /**
     * @inheritDocs
     */
    get nunjucks()
    {
        return this._nunjucks;
    }

    /**
     * @inheritDocs
     */
    handle404(request, response, next)
    {
        //this._cliLogger.info('SiteRoute.handle404: Could not find url ' + request.url);
        next();
    }

    /**
     * @inheritDocs
     */
    handleStatic(rootPath, fileExtensions, log, request, response, next)
    {
        const scope = this;
        //scope._cliLogger.info('handleStatic: from <' + rootPath + '> <' + fileExtensions.join(', ') + '> trying <' + request.url + '>');

        // Check extension
        const extension = path.extname(request.path);
        if (fileExtensions.indexOf(extension) === -1)
        {
            next();
            return;
        }

        // Check straight file
        const filename = pathes.concat(rootPath, request.path);
        if (!fs.existsSync(filename))
        {
            //console.log('Not found:', rootPath, request.path, filename);
            next();
            return;
        }

        // Serve it
        let work;
        if (log)
        {
            const filenameShort = shortenLeft(synchronize.execute(scope._pathesConfiguration, 'shorten', [filename]), 60);
            /*
            response.setHeader("Cache-Control", "public, max-age=2592000");
            response.setHeader("Expires", new Date(Date.now() + 2592000000).toUTCString());
            */
            //work = scope._cliLogger.work('Serving static <' + filenameShort + '> as <' + request.url + '>');
        }
        response.sendFile(filename);
        if (work)
        {
            scope._cliLogger.end(work);
        }
        return Promise.resolve(true);
    }

    /**
     * @inheritDocs
     */
    handleTemplate(request, response, next)
    {
        const scope = this;
        const promise = co(function *()
        {
            scope._cliLogger.info('handleTemplate: from <' + scope._path + '> trying <' + request.url + '>');

            // Check extension
            if (!request.path.endsWith('.j2'))
            {
                next();
                return;
            }

            // Check direct hit
            let filename = pathes.concat(scope._path, request.path);
            if (!fs.existsSync(filename))
            {
                scope.logger.debug('handleTemplate: no direct hit at <' + filename + '>');

                // Check entity file
                const match = yield scope._urlsConfiguration.matchEntityFile(request.path);
                if (!match.file)
                {
                    next();
                    return;
                }
                filename = match.file.filename;
            }

            // Render template
            scope._nunjucks.isStatic = (typeof request.query.static !== 'undefined');
            const data = yield scope._urlsConfiguration.matchEntity(request.path, true);
            const filenameShort = shortenLeft(synchronize.execute(scope._pathesConfiguration, 'shorten', [filename]), 60);
            const tpl = fs.readFileSync(filename, { encoding: 'utf8' });
            const work = scope._cliLogger.work('Serving ' + (scope._nunjucks.isStatic ? '<static>' : '') + ' template <' + filenameShort + '> as <' + request.url + '>');
            let html;
            try
            {
                scope._nunjucks.addGlobal('site', data.site);
                scope._nunjucks.addGlobal('request', request);
                html = scope._nunjucks.renderString(tpl, data);
            }
            catch (e)
            {
                scope._cliLogger.error(scope.className + '::handleTemplate', e);
                next();
                return;
            }

            // Format
            if (scope._formatHtml)
            {
                const formatted = yield scope._htmlFormatter.format(html);
                response.send(formatted);
                scope._cliLogger.end(work);
            }
            else
            {
                response.send(html);
                scope._cliLogger.end(work);
            }
            return true;
        })
        .catch(function(error)
        {
            scope._cliLogger.error(scope.className + '::handleTemplate', error.stack);
        });
        return promise;
    }

    /**
     * @param {Express}
     */
    register(express)
    {
        const work = this._cliLogger.work('Registering <' + this.className + '> as middleware');

        for (const staticRoute of this._staticRoutes)
        {
            const rootUrl = staticRoute.rootUrl || this._rootUrl;
            let rootPath = this._path;
            if (staticRoute.rootPath)
            {
                rootPath = synchronize.execute(this._pathesConfiguration, 'resolve', [staticRoute.rootPath]);
            }
            const fileExtensions = staticRoute.fileExtensions || [];
            express.all(rootUrl, this.handleStatic.bind(this, rootPath, fileExtensions, true));
        }
        express.all(this._rootUrl, this.handleStatic.bind(this, this._path, this._staticFileExtensions, true));
        if (this._pathesConfiguration.jspm)
        {
            const jspmPath = path.resolve(this._pathesConfiguration.jspm + '/..');
            express.all('/jspm_packages/*', this.handleStatic.bind(this, jspmPath, ['.js'], true));
            express.all('/*', this.handleStatic.bind(this, jspmPath, ['.js'], true));
        }
        express.all(this._rootUrl, this.handleTemplate.bind(this));
        express.all('*', this.handle404.bind(this));

        this._cliLogger.end(work);
    }
}

/**
 * Exports
 * @ignore
 */
module.exports.SitesRoute = SitesRoute;
<|endoftext|>


<commit_before>'use strict';

const SPACE_BETWEEN_MENU_ICONS = 20;
const ONE_SECOND = 1.0;
const ANIMATION_TIME = ONE_SECOND / 4;
const MENU_DISTANCE_FROM_PLAYER = 150;

function PlayerMenu(world) {
    this.__init__(world);
}

function MenuIcon(icon_type, world, row) {
    this.__init__(icon_type, world, row);
}

function global_save() {
    l('PERFORM A GLOBAL SAVE!');

    GUI_TYPING_INTERFACE.add_server_message('Saving changes to the server! TODO : Get a response back!');

    MANAGER_WORLD.world_home.prepare_for_save();

    // Any changes to entities will be saved.
    MANAGER_ENTITY.update_server_and_database();
}

function go_to_settings_world() {
    MANAGER_WORLD.set_current_world(MANAGER_WORLD.world_settings);
}

function go_to_home_world() {
    MANAGER_WORLD.set_current_world(MANAGER_WORLD.world_home);
}

function create_entity_wall() {
    l('Creating entity wall!');
    MANAGER_WORLD.world_home.create_entity_wall_command_entered();
}

function exit_function() {
    if (MANAGER_WORLD.current_world === MANAGER_WORLD.world_login) {
        window.close();
    } else {
        l('TODO : regular log out functionality');
    }
}

function toggle_fullscreen() {
    MANAGER_RENDERER.toggle_fullscreen();
}

MenuIcon.prototype = {
    display_teleport_worlds: function() {
        this.teleport_wall.show();
    },

    hide_teleport_worlds: function() {
        this.teleport_wall.hide();
    },

    select_a_world_to_teleport_to: function() {

    },

    __init__: function(icon_type, world, row) {
        this._icon_type = icon_type;

        this.world = world;
        this.row = row;
        this.object3D = new THREE.Object3D();

        if (this._icon_type === ICON_TELEPORT) {
            this.teleport_wall = new FloatingWall(150, 200, new THREE.Vector3(0, 0, 0), new THREE.Vector3(0, 0, 0), this.world, false, 0);
            this.teleport_wall.add_floating_2d_text(0, 1, 'TELEPORT WALL?', TYPE_TITLE, 0);
            this.teleport_wall.add_floating_2d_text(0, 1, 'TELEPORT WALL?', TYPE_BUTTON, 2);
            this.teleport_wall.add_floating_2d_text(.1, .9, 'Can you see this text?', TYPE_BUTTON, 4);
            this.teleport_wall.hide();
        }

        this.geometry = new THREE.CircleGeometry(10, 32);
        // TODO : Eventually just do FrontSide
        // TODO : Eventually add some transparency.

        var texture = MANAGER_LOADING.get_texture(TEXTURE_GROUP_ICONS, icon_type);

        this.material = new THREE.MeshBasicMaterial({map: texture, side: THREE.DoubleSide, transparent: true, opacity: .75});
        //var cursor_material = new THREE.MeshBasicMaterial({map: texture, side: THREE.DoubleSide, transparent: true, opacity: CURSOR_DEFAULT_OPACITY});
        this.icon = new THREE.Mesh(this.geometry, this.material);

        var icon_label = '';
        var function_to_bind = null;
        var function_look_at_bind = null;
        var function_look_away_bind = null;
        switch (icon_type) {
        case ICON_SAVE:
            icon_label = 'save';
            function_to_bind = global_save;
            break;
        case ICON_EXIT:
            icon_label = 'exit';
            l('TODO : Logout');
            break;
        case ICON_MULTIPLAYER:
            icon_label = 'online';
            l('TODO : Go online');
            break;
        case ICON_TELEPORT:
            icon_label = 'teleport';
            function_look_at_bind = this.display_teleport_worlds.bind(this);
            function_look_away_bind = this.hide_teleport_worlds.bind(this);
            function_to_bind = this.select_a_world_to_teleport_to.bind(this);
            break;
        case ICON_HOME:
            icon_label = 'home';
            function_to_bind = go_to_home_world;
            break;
        case ICON_SETTINGS:
            icon_label = 'settings';
            function_to_bind = go_to_settings_world;
            break;
        case ICON_ENTITY_GROUP:
            icon_label = 'entities';
            function_to_bind = create_entity_wall;
            break;
        case ICON_FULLSCREEN:
            icon_label = 'fullscreen';
            function_to_bind = toggle_fullscreen;
            break;
        }
        this.floating_label = new Floating2DText(90, icon_label, TYPE_BUTTON, this.world.scene);
        if (is_defined(function_to_bind)) {
            this.floating_label.set_engage_function(function_to_bind);
        }
        if (is_defined(function_look_at_bind)) {
            this.floating_label.set_look_at_function(function_look_at_bind);
        }
        if (is_defined(function_look_away_bind)) {
            this.floating_label.set_look_away_function(function_look_away_bind);
        }

        this.object3D.add(this.icon);

        this.world.add_to_scene(this.object3D);

        // Inherit from Interactive.
        //Interactive.call(this);
        // Inherit from Visibility.
        //Visibility.call(this);

        this.world.interactive_objects.push(this.floating_label);
    },

    set_position_and_normal: function(position, nx, nz) {
        this.y_position = position.y + SPACE_BETWEEN_MENU_ICONS * 2;
        this.object3D.position.set(position.x, this.y_position, position.z);
        this.object3D.lookAt(new THREE.Vector3(position.x + nx * 5, this.y_position, position.z + nz * 5));

        this.normal = new THREE.Vector3(nx, 0, nz);
        this.left_right = new THREE.Vector3(0, 1, 0);
        this.left_right.cross(this.normal);
        this.left_right.normalize();

        var horizontal_shift = 60;

        this.floating_label.update_position_and_normal(new THREE.Vector3(this.object3D.position.x + this.left_right.x * horizontal_shift, this.object3D.position.y, this.object3D.position.z + this.left_right.z * horizontal_shift), this.normal);

        if (is_defined(this.teleport_wall)) {
            var player_position = CURRENT_PLAYER.get_position();
            var teleport_wall_position = new THREE.Vector3(this.object3D.position.x + this.left_right.x * horizontal_shift * 3, this.object3D.position.y, this.object3D.position.z + this.left_right.z * horizontal_shift * 3);
            var teleport_wall_look_at = new THREE.Vector3(teleport_wall_position.x - player_position.x, 0, teleport_wall_position.z - player_position.z);
            teleport_wall_look_at.normalize();
            this.teleport_wall.set_position_and_normal(teleport_wall_position, teleport_wall_look_at, false);
        }
    },

    update_y_position: function(y_offset) {
        this.object3D.position.y = this.y_position - y_offset;
        this.floating_label.object3D.position.y = this.y_position - y_offset;
    },

    set_to_invisible: function() {
        this.icon.visible = false;
        this.floating_label.set_to_invisible();
    },

    set_to_visible: function() {
        this.icon.visible = true;
        this.floating_label.set_to_visible();
    }
};

PlayerMenu.prototype = {

    world: null,

    __init__: function(world) {
        this.world = world;

        this.visible = false;
        this.total_delta = 0;

        // Only used for the initial loading.
        this.current_row = 0;
    },

    set_to_invisible: function() {
        this.visible = false;
        if (is_defined(this.icons)) {
            for (var i = 0; i < this.icons.length; i++) {
                this.icons[i].set_to_invisible();
            }
        }
    },

    set_to_visible: function() {
        if (is_defined(MANAGER_WORLD.current_world.currently_looked_at_object)) {
            return;
        }

        this.visible = true;
        this.total_delta = 0;

        var pp = CURRENT_PLAYER.get_position();
        var pd = CURRENT_PLAYER.get_direction();

        var start_position = new THREE.Vector3(pp.x + pd.x * MENU_DISTANCE_FROM_PLAYER, pp.y + pd.y * MENU_DISTANCE_FROM_PLAYER, pp.z + pd.z * MENU_DISTANCE_FROM_PLAYER);

        for (var i = 0; i < this.icons.length; i++) {
            this.icons[i].set_position_and_normal(start_position, -pd.x, -pd.z);
            this.icons[i].set_to_visible();
        }
    },

    is_visible: function() {
        return this.visible;
    },

    update: function(delta) {
        this.total_delta += delta;
        if (this.total_delta >= ANIMATION_TIME) {
            this.percentage = 1.0;
        } else {
            this.percentage = this.total_delta / ANIMATION_TIME;
        }

        // TODO : Refactor this!!!!
        if (is_defined(this.icons)) {
            for (var i = 0; i < this.icons.length; i++) {
                if (this.icons[i].row !== 0) {
                    var this_icons_max_delta = this.time_needed_for_each_row * this.icons[i].row;
                    if (this.percentage < this_icons_max_delta) {
                        this.icons[i].update_y_position(this.percentage * this.total_distance);
                    } else {
                        this.icons[i].update_y_position(this_icons_max_delta * this.total_distance);
                    }
                }
            }
        }

    },

    _add_menu_icon: function(icon, list_of_icons_not_to_load) {
        if (this.current_row === 0) {
            this.icons = [];
        }
        if (!list_of_icons_not_to_load.contains(icon)) {
            this.icons.push(new MenuIcon(icon, this.world, this.current_row));
            this.current_row += 1;
        }
    },

    // This function gets called once per player menu object.
    load_icon_textures: function(list_of_icons_not_to_load) {
        this._add_menu_icon(ICON_ENTITY_GROUP, list_of_icons_not_to_load);
        this._add_menu_icon(ICON_SAVE        , list_of_icons_not_to_load);
        this._add_menu_icon(ICON_TELEPORT    , list_of_icons_not_to_load);
        this._add_menu_icon(ICON_MULTIPLAYER , list_of_icons_not_to_load);
        this._add_menu_icon(ICON_FULLSCREEN  , list_of_icons_not_to_load);
        this._add_menu_icon(ICON_EXIT        , list_of_icons_not_to_load);

        this.time_needed_for_each_row = ONE_SECOND / (this.icons.length);
        this.total_distance = this.icons.length * SPACE_BETWEEN_MENU_ICONS;

        this.set_to_invisible();
    }

};
<commit_msg>general updating 133<commit_after>'use strict';

const SPACE_BETWEEN_MENU_ICONS = 20;
const ONE_SECOND = 1.0;
const ANIMATION_TIME = ONE_SECOND / 4;
const MENU_DISTANCE_FROM_PLAYER = 150;

function PlayerMenu(world) {
    this.__init__(world);
}

function MenuIcon(icon_type, world, row) {
    this.__init__(icon_type, world, row);
}

function global_save() {
    l('PERFORM A GLOBAL SAVE!');

    GUI_TYPING_INTERFACE.add_server_message('Saving changes to the server! TODO : Get a response back!');

    MANAGER_WORLD.world_home.prepare_for_save();

    // Any changes to entities will be saved.
    MANAGER_ENTITY.update_server_and_database();
}

function go_to_settings_world() {
    MANAGER_WORLD.set_current_world(MANAGER_WORLD.world_settings);
}

function go_to_home_world() {
    MANAGER_WORLD.set_current_world(MANAGER_WORLD.world_home);
}

function create_entity_wall() {
    l('Creating entity wall!');
    MANAGER_WORLD.world_home.create_entity_wall_command_entered();
}

function exit_function() {
    if (MANAGER_WORLD.current_world === MANAGER_WORLD.world_login) {
        window.close();
    } else {
        l('TODO : regular log out functionality');
    }
}

function toggle_fullscreen() {
    MANAGER_RENDERER.toggle_fullscreen();
}

MenuIcon.prototype = {
    display_teleport_worlds: function() {
        this.teleport_wall.show();
    },

    hide_teleport_worlds: function() {
        this.teleport_wall.hide();
    },

    select_a_world_to_teleport_to: function() {
        this._player_menu.set_to_invisible();
        this.teleport_wall.show();
    },

    __init__: function(icon_type, world, row, player_menu) {
        this._icon_type = icon_type;
        this._player_menu = player_menu;

        this.world = world;
        this.row = row;
        this.object3D = new THREE.Object3D();

        if (this._icon_type === ICON_TELEPORT) {
            this.teleport_wall = new FloatingWall(150, 200, new THREE.Vector3(0, 0, 0), new THREE.Vector3(0, 0, 0), this.world, false, 0);
            this.teleport_wall.add_floating_2d_text(0, 1, 'TELEPORT WALL?', TYPE_TITLE, 0);
            this.teleport_wall.add_floating_2d_text(0, 1, 'TELEPORT WALL?', TYPE_BUTTON, 2);
            this.teleport_wall.add_floating_2d_text(.1, .9, 'Can you see this text?', TYPE_BUTTON, 4);
            this.teleport_wall.hide();
        }

        this.geometry = new THREE.CircleGeometry(10, 32);
        // TODO : Eventually just do FrontSide
        // TODO : Eventually add some transparency.

        var texture = MANAGER_LOADING.get_texture(TEXTURE_GROUP_ICONS, icon_type);

        this.material = new THREE.MeshBasicMaterial({map: texture, side: THREE.DoubleSide, transparent: true, opacity: .75});
        //var cursor_material = new THREE.MeshBasicMaterial({map: texture, side: THREE.DoubleSide, transparent: true, opacity: CURSOR_DEFAULT_OPACITY});
        this.icon = new THREE.Mesh(this.geometry, this.material);

        var icon_label = '';
        var function_to_bind = null;
        var function_look_at_bind = null;
        var function_look_away_bind = null;
        switch (icon_type) {
        case ICON_SAVE:
            icon_label = 'save';
            function_to_bind = global_save;
            break;
        case ICON_EXIT:
            icon_label = 'exit';
            l('TODO : Logout');
            break;
        case ICON_MULTIPLAYER:
            icon_label = 'online';
            l('TODO : Go online');
            break;
        case ICON_TELEPORT:
            icon_label = 'teleport';
            function_look_at_bind = this.display_teleport_worlds.bind(this);
            function_look_away_bind = this.hide_teleport_worlds.bind(this);
            function_to_bind = this.select_a_world_to_teleport_to.bind(this);
            break;
        case ICON_HOME:
            icon_label = 'home';
            function_to_bind = go_to_home_world;
            break;
        case ICON_SETTINGS:
            icon_label = 'settings';
            function_to_bind = go_to_settings_world;
            break;
        case ICON_ENTITY_GROUP:
            icon_label = 'entities';
            function_to_bind = create_entity_wall;
            break;
        case ICON_FULLSCREEN:
            icon_label = 'fullscreen';
            function_to_bind = toggle_fullscreen;
            break;
        }
        this.floating_label = new Floating2DText(90, icon_label, TYPE_BUTTON, this.world.scene);
        if (is_defined(function_to_bind)) {
            this.floating_label.set_engage_function(function_to_bind);
        }
        if (is_defined(function_look_at_bind)) {
            this.floating_label.set_look_at_function(function_look_at_bind);
        }
        if (is_defined(function_look_away_bind)) {
            this.floating_label.set_look_away_function(function_look_away_bind);
        }

        this.object3D.add(this.icon);

        this.world.add_to_scene(this.object3D);

        // Inherit from Interactive.
        //Interactive.call(this);
        // Inherit from Visibility.
        //Visibility.call(this);

        this.world.interactive_objects.push(this.floating_label);
    },

    set_position_and_normal: function(position, nx, nz) {
        this.y_position = position.y + SPACE_BETWEEN_MENU_ICONS * 2;
        this.object3D.position.set(position.x, this.y_position, position.z);
        this.object3D.lookAt(new THREE.Vector3(position.x + nx * 5, this.y_position, position.z + nz * 5));

        this.normal = new THREE.Vector3(nx, 0, nz);
        this.left_right = new THREE.Vector3(0, 1, 0);
        this.left_right.cross(this.normal);
        this.left_right.normalize();

        var horizontal_shift = 60;

        this.floating_label.update_position_and_normal(new THREE.Vector3(this.object3D.position.x + this.left_right.x * horizontal_shift, this.object3D.position.y, this.object3D.position.z + this.left_right.z * horizontal_shift), this.normal);

        if (is_defined(this.teleport_wall)) {
            var player_position = CURRENT_PLAYER.get_position();
            var teleport_wall_position = new THREE.Vector3(this.object3D.position.x + this.left_right.x * horizontal_shift * 3 + this.normal.x * 30,
                                                           this.object3D.position.y,
                                                           this.object3D.position.z + this.left_right.z * horizontal_shift * 3 + this.normal.z * 30);
            var teleport_wall_look_at = new THREE.Vector3(teleport_wall_position.x - player_position.x, 0, teleport_wall_position.z - player_position.z);
            teleport_wall_look_at.normalize();
            this.teleport_wall.set_position_and_normal(teleport_wall_position, teleport_wall_look_at, false);
        }
    },

    update_y_position: function(y_offset) {
        this.object3D.position.y = this.y_position - y_offset;
        this.floating_label.object3D.position.y = this.y_position - y_offset;
    },

    set_to_invisible: function() {
        this.icon.visible = false;
        this.floating_label.set_to_invisible();
    },

    set_to_visible: function() {
        this.icon.visible = true;
        this.floating_label.set_to_visible();
    }
};

PlayerMenu.prototype = {

    world: null,

    __init__: function(world) {
        this.world = world;

        this.visible = false;
        this.total_delta = 0;

        // Only used for the initial loading.
        this.current_row = 0;
    },

    set_to_invisible: function() {
        this.visible = false;
        if (is_defined(this.icons)) {
            for (var i = 0; i < this.icons.length; i++) {
                this.icons[i].set_to_invisible();
            }
        }
    },

    set_to_visible: function() {
        if (is_defined(MANAGER_WORLD.current_world.currently_looked_at_object)) {
            return;
        }

        this.visible = true;
        this.total_delta = 0;

        var pp = CURRENT_PLAYER.get_position();
        var pd = CURRENT_PLAYER.get_direction();

        var start_position = new THREE.Vector3(pp.x + pd.x * MENU_DISTANCE_FROM_PLAYER, pp.y + pd.y * MENU_DISTANCE_FROM_PLAYER, pp.z + pd.z * MENU_DISTANCE_FROM_PLAYER);

        for (var i = 0; i < this.icons.length; i++) {
            this.icons[i].set_position_and_normal(start_position, -pd.x, -pd.z);
            this.icons[i].set_to_visible();
        }
    },

    is_visible: function() {
        return this.visible;
    },

    update: function(delta) {
        this.total_delta += delta;
        if (this.total_delta >= ANIMATION_TIME) {
            this.percentage = 1.0;
        } else {
            this.percentage = this.total_delta / ANIMATION_TIME;
        }

        // TODO : Refactor this!!!!
        if (is_defined(this.icons)) {
            for (var i = 0; i < this.icons.length; i++) {
                if (this.icons[i].row !== 0) {
                    var this_icons_max_delta = this.time_needed_for_each_row * this.icons[i].row;
                    if (this.percentage < this_icons_max_delta) {
                        this.icons[i].update_y_position(this.percentage * this.total_distance);
                    } else {
                        this.icons[i].update_y_position(this_icons_max_delta * this.total_distance);
                    }
                }
            }
        }

    },

    _add_menu_icon: function(icon, list_of_icons_not_to_load) {
        if (this.current_row === 0) {
            this.icons = [];
        }
        if (!list_of_icons_not_to_load.contains(icon)) {
            this.icons.push(new MenuIcon(icon, this.world, this.current_row, this));
            this.current_row += 1;
        }
    },

    // This function gets called once per player menu object.
    load_icon_textures: function(list_of_icons_not_to_load) {
        this._add_menu_icon(ICON_ENTITY_GROUP, list_of_icons_not_to_load);
        this._add_menu_icon(ICON_SAVE        , list_of_icons_not_to_load);
        this._add_menu_icon(ICON_TELEPORT    , list_of_icons_not_to_load);
        this._add_menu_icon(ICON_MULTIPLAYER , list_of_icons_not_to_load);
        this._add_menu_icon(ICON_FULLSCREEN  , list_of_icons_not_to_load);
        this._add_menu_icon(ICON_EXIT        , list_of_icons_not_to_load);

        this.time_needed_for_each_row = ONE_SECOND / (this.icons.length);
        this.total_distance = this.icons.length * SPACE_BETWEEN_MENU_ICONS;

        this.set_to_invisible();
    }

};
<|endoftext|>


<commit_before>'use strict';

function Account(account_name, account_type, floating_wall) {
    this.__init__(account_name, account_type, floating_wall);
}

Account.prototype = {
    __init__: function(account_name, account_type, floating_wall) {
        this.account_name = account_name;
        this.account_type = account_type;
        this.floating_wall = floating_wall;

        this._button = null;
    },

    set_button: function(b) {
        this._button = b;
    },

    is_listed_on_floating_wall: function() {
        if (!is_defined(this.floating_wall)) {
            return false;
        }
        for (var f = 0; f < this.floating_wall._2D_rows.length; f++) {
            // 3 is the index of the floating_2D_text
            if (this.floating_wall._2D_rows[f][3].get_text() === this.account_name) {
                return true;
            }
        }
        return false;
    }
};

function AdminWorld() {
    this.__init__();
}

AdminWorld.prototype = {

    __init__: function () {
        World.call(this);
    },

    create: function() {
        // POST calls.
        this.post_get_all_accounts_information = new PostHelper('sudo_command');

        var p = new THREE.Vector3(1000, 1000, 1500);
        var n = new THREE.Vector3(-.56, 0, -.8);
        this.wall_all_accounts = new FloatingWall(1000, 1000, p, n, this, false);
        this.wall_all_accounts.add_row_3D_text(false, -1, 'All Accounts', TYPE_TITLE, COLOR_BLUE);

        this.button_load_all_accounts = this.wall_all_accounts.add_row_2D_text([0, 1], 0, 'Refresh/Load All Accounts', TYPE_BUTTON, null, COLOR_YELLOW);
        this.button_load_all_accounts.set_engage_function(this._load_all_accounts_action.bind(this));

        this.wall_all_accounts.add_row_2D_text([0, ONE_THIRD], 2, 'Name', TYPE_CONSTANT);
        this.wall_all_accounts.add_row_2D_text([ONE_THIRD, TWO_THIRDS], 2, 'Type', TYPE_CONSTANT);
        this.wall_all_accounts.add_row_2D_text([TWO_THIRDS, 1], 2, 'Actions', TYPE_CONSTANT);

        //this.wall_all_accounts.add_row_2D_text(row, text, type, sc, c)

        this.wall_all_accounts.refresh_position_and_look_at();

        this.accounts = [];
        this.number_of_accounts_listed = 0;

        // Account actions list.
        this.wall_account_actions = new FloatingWall(200, 300, null, null, this, false);
        this.wall_account_actions.add_row_3D_text(false, -1, 'Account Actions', TYPE_TITLE);
        // TODO : Add the actions here
    },

    _load_all_accounts_action: function() {
        var data = {};
        data[ENTITY_PROPERTY_USERNAME]      = ENTITY_OWNER.get_username();
        data[ENTITY_PROPERTY_PASSWORD]      = ENTITY_OWNER.get_password();
        data[SERVER_COMMAND_SUDO_OPERATION] = SERVER_COMMAND_GET_ALL_ACCOUNTS_INFORMATION;
        data[POST_KEY_GENERIC_DATA]         = 'not_needed';
        this.post_get_all_accounts_information.perform_post(data, this._all_accounts_information_result.bind(this));
    },

    _all_accounts_information_result: function(result) {
        l('ALL ACCOUNTS INFORMATION RESULT');
        l(result);

        var all_accounts = result.split('-');
        for (var a = 0; a < all_accounts.length; a++) {
            var account_data = all_accounts[a].split('+');
            if (!this._have_account(account_data[0])) {
                this.accounts.push(new Account(account_data[0], account_data[1]));
            }
        }

        this._refresh_account_list();
    },

    _refresh_account_list: function() {
        for (var a = 0; a < this.accounts.length; a++) {
            if (!this.accounts[a].is_listed_on_floating_wall()) {
                this.wall_all_accounts.add_row_2D_text([0, ONE_THIRD], 2 + this.number_of_accounts_listed, this.accounts[a].account_name, TYPE_CONSTANT);
                this.wall_all_accounts.add_row_2D_text([ONE_THIRD, TWO_THIRDS], 2 + this.number_of_accounts_listed, this.accounts[a].account_type, TYPE_CONSTANT);
                var perform_account_actions_button =  this.wall_all_accounts.add_row_2D_text([TWO_THIRDS, 1], 2 + this.number_of_accounts_listed, 'actions', TYPE_BUTTON);
                perform_account_actions_button.set_engage_function(this._perform_account_actions_button_pressed.bind(this, this.accounts[a]));

                this.accounts[a].set_button(perform_account_actions_button);

                this.number_of_accounts_listed += 1;
            }
        }
    },

    _have_account: function(account_name) {
        for (var a = 0; a < this.accounts.length; a++) {
            if (this.accounts[a].account_name === account_name) {
                return true;
            }
        }
        return false;
    },

    _perform_account_actions_button_pressed: function(account) {
        l('TODO : Perform account actions!');
    },

    enter_world: function() {
        CURRENT_PLAYER.disengage();
        if (!GUI_PAUSED_MENU.currently_displayed) {
            CURRENT_PLAYER.enable_controls();
        }
        CURRENT_PLAYER.set_position_xyz(0, 100, 0);
    },

    exit_world: function() {
    }
};

// utarsuno+sudo-aaaa+not_verified-bbbb+not_verified-Ryan+not_verified-cccc+not_verified-zzzz+not_verified-
<commit_msg>general updating 116<commit_after>'use strict';

function Account(account_name, account_type, floating_wall) {
    this.__init__(account_name, account_type, floating_wall);
}

Account.prototype = {
    __init__: function(account_name, account_type, floating_wall) {
        this.account_name = account_name;
        this.account_type = account_type;
        this.floating_wall = floating_wall;

        this._button = null;
    },

    set_button: function(b) {
        this._button = b;
    },

    is_listed_on_floating_wall: function() {
        if (!is_defined(this.floating_wall)) {
            return false;
        }
        for (var f = 0; f < this.floating_wall._2D_rows.length; f++) {
            // 3 is the index of the floating_2D_text
            if (this.floating_wall._2D_rows[f][3].get_text() === this.account_name) {
                return true;
            }
        }
        return false;
    }
};

function AdminWorld() {
    this.__init__();
}

AdminWorld.prototype = {

    __init__: function () {
        World.call(this);
    },

    create: function() {
        // POST calls.
        this.post_get_all_accounts_information = new PostHelper('sudo_command');

        var p = new THREE.Vector3(1000, 1000, 1500);
        var n = new THREE.Vector3(-.56, 0, -.8);
        this.wall_all_accounts = new FloatingWall(1000, 1000, p, n, this, false);
        this.wall_all_accounts.add_row_3D_text(false, -1, 'All Accounts', TYPE_TITLE, COLOR_BLUE);

        this.button_load_all_accounts = this.wall_all_accounts.add_row_2D_text([0, 1], 0, 'Refresh/Load All Accounts', TYPE_BUTTON, null, COLOR_YELLOW);
        this.button_load_all_accounts.set_engage_function(this._load_all_accounts_action.bind(this));

        this.wall_all_accounts.add_row_2D_text([0, ONE_THIRD], 2, 'Name', TYPE_CONSTANT);
        this.wall_all_accounts.add_row_2D_text([ONE_THIRD, TWO_THIRDS], 2, 'Type', TYPE_CONSTANT);
        this.wall_all_accounts.add_row_2D_text([TWO_THIRDS, 1], 2, 'Actions', TYPE_CONSTANT);

        //this.wall_all_accounts.add_row_2D_text(row, text, type, sc, c)

        this.wall_all_accounts.refresh_position_and_look_at();

        this.accounts = [];
        this.number_of_accounts_listed = 0;

        // Account actions list.
        this.wall_account_actions = new FloatingWall(200, 300, null, null, this, false);
        this.wall_account_actions.add_row_3D_text(false, -1, 'Account Actions', TYPE_TITLE);
        // TODO : Add the actions here

        this.wall_account_actions.set_to_invisible();
    },

    _load_all_accounts_action: function() {
        var data = {};
        data[ENTITY_PROPERTY_USERNAME]      = ENTITY_OWNER.get_username();
        data[ENTITY_PROPERTY_PASSWORD]      = ENTITY_OWNER.get_password();
        data[SERVER_COMMAND_SUDO_OPERATION] = SERVER_COMMAND_GET_ALL_ACCOUNTS_INFORMATION;
        data[POST_KEY_GENERIC_DATA]         = 'not_needed';
        this.post_get_all_accounts_information.perform_post(data, this._all_accounts_information_result.bind(this));
    },

    _all_accounts_information_result: function(result) {
        l('ALL ACCOUNTS INFORMATION RESULT');
        l(result);

        var all_accounts = result.split('-');
        for (var a = 0; a < all_accounts.length; a++) {
            var account_data = all_accounts[a].split('+');
            if (is_defined(account_data[0] && is_defined(account_data[1]))) {
                if (!this._have_account(account_data[0])) {
                    this.accounts.push(new Account(account_data[0], account_data[1]));
                }
            }
        }

        this._refresh_account_list();
    },

    _refresh_account_list: function() {
        var account_added_or_removed = false;

        for (var a = 0; a < this.accounts.length; a++) {
            if (!this.accounts[a].is_listed_on_floating_wall()) {
                this.wall_all_accounts.add_row_2D_text([0, ONE_THIRD], 2 + this.number_of_accounts_listed, this.accounts[a].account_name, TYPE_CONSTANT);
                this.wall_all_accounts.add_row_2D_text([ONE_THIRD, TWO_THIRDS], 2 + this.number_of_accounts_listed, this.accounts[a].account_type, TYPE_CONSTANT);
                var perform_account_actions_button =  this.wall_all_accounts.add_row_2D_text([TWO_THIRDS, 1], 2 + this.number_of_accounts_listed, 'actions', TYPE_BUTTON);
                perform_account_actions_button.set_engage_function(this._perform_account_actions_button_pressed.bind(this, this.accounts[a]));

                this.accounts[a].set_button(perform_account_actions_button);

                this.number_of_accounts_listed += 1;

                account_added_or_removed = true;
            }
        }

        if (account_added_or_removed) {
            this.wall_all_accounts.refresh_position_and_look_at();
        }
    },

    _have_account: function(account_name) {
        for (var a = 0; a < this.accounts.length; a++) {
            if (this.accounts[a].account_name === account_name) {
                return true;
            }
        }
        return false;
    },

    _perform_account_actions_button_pressed: function(account) {
        l('TODO : Perform account actions!');
    },

    enter_world: function() {
        CURRENT_PLAYER.disengage();
        if (!GUI_PAUSED_MENU.currently_displayed) {
            CURRENT_PLAYER.enable_controls();
        }
        CURRENT_PLAYER.set_position_xyz(0, 100, 0);
    },

    exit_world: function() {
    }
};

// utarsuno+sudo-aaaa+not_verified-bbbb+not_verified-Ryan+not_verified-cccc+not_verified-zzzz+not_verified-
<|endoftext|>


<commit_before>/*
 * This file is part of the TwitterBootstrapBundle and it is distributed
 * under the MIT LICENSE. To use this application you must leave intact this copyright
 * notice.
 *
 * Copyright (c) RedKite Labs <info@redkite-labs.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * For extra documentation and help please visit http://www.redkite-labs.com
 *
 * @license    MIT LICENSE
 *
 */

$(document).ready(function()
{
    var expandAccordion = function() {
        $("#al-accordion").find('.collapse').removeClass('in').addClass('in');
    };

    $(document).on("cmsStarted", function(event){
        expandAccordion();
    });

    $(document).on("cmsStopped", function(event){
        $("#al-accordion").find('.collapse').removeClass('in');
    });

    $(document).on("startEditingBlocks", function(event, element){
        if (element.attr('data-type') != 'BootstrapAccordionBlock') {
            return;
        }

        element.inlinelist('start', {
            target: '> div',
            addValue: '{"operation": "add", "value": { "0": "item" }}',
            addItemCallback: expandAccordion,
            deleteItemCallback: expandAccordion
        });
    });

    $(document).on("stopEditingBlocks", function(event, element){
        if (element.attr('data-type') != 'BootstrapAccordionBlock') {
            return;
        }

        element.inlinelist('stop');
    });
});
<commit_msg>called method to expand the accordion when the list is started<commit_after>/*
 * This file is part of the TwitterBootstrapBundle and it is distributed
 * under the MIT LICENSE. To use this application you must leave intact this copyright
 * notice.
 *
 * Copyright (c) RedKite Labs <info@redkite-labs.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * For extra documentation and help please visit http://www.redkite-labs.com
 *
 * @license    MIT LICENSE
 *
 */

$(document).ready(function()
{
    var expandAccordion = function() {
        $("#al-accordion").find('.collapse').removeClass('in').addClass('in');
    };

    $(document).on("cmsStarted", function(event){
        expandAccordion();
    });

    $(document).on("cmsStopped", function(event){
        $("#al-accordion").find('.collapse').removeClass('in');
    });

    $(document).on("startEditingBlocks", function(event, element){
        if (element.attr('data-type') != 'BootstrapAccordionBlock') {
            return;
        }

        element.inlinelist('start', {
            target: '> div',
            addValue: '{"operation": "add", "value": { "0": "item" }}',
            startListCallback: expandAccordion,
            addItemCallback: expandAccordion,
            deleteItemCallback: expandAccordion
        });
    });

    $(document).on("stopEditingBlocks", function(event, element){
        if (element.attr('data-type') != 'BootstrapAccordionBlock') {
            return;
        }

        element.inlinelist('stop');
    });
});
<|endoftext|>


<commit_before>jQuery(function () {
    window.setTimeout(function () {
    	Wicket.Ajax.get({'u': '${destroyTokenUrl}', 'e' : 'click', 'c' : 'destroyToken${uuidValidForJs}'});
    }, 1000);
});<commit_msg>FIXED destroy token listener bug<commit_after>window.setTimeout(function () {
    Wicket.Ajax.get({'u': '${destroyTokenUrl}', 'e' : 'click', 'c' : 'destroyToken${uuidValidForJs}'});
}, 1500);<|endoftext|>


<commit_before>commands.addUserCommand(
    ["toggleshowingmenutoolbar"],
    "Toggle the apperance of menu and toolbar",
    function() {
        if (options.get("gui").has("nonavigation")) {
            liberator.execute(":set gui='tabs,nomenu,navigation,addons,bookmarks'");
        } else {
            liberator.execute(":set gui='tabs,nomenu,nonavigation,noaddons,nobookmarks'");
        }
    }
)
<commit_msg>adjust vimperator setting<commit_after>commands.addUserCommand(
    ["toggleshowingmenutoolbar"],
    "Toggle the apperance of menu and toolbar",
    function() {
        if (options.get("gui").has("nonavigation")) {
            liberator.execute(":set gui='tabs,nomenu,nobookmarks,navigation,addons'");
        } else {
            liberator.execute(":set gui='tabs,nomenu,nobookmarks,nonavigation,noaddons'");
        }
    }
)
<|endoftext|>


<commit_before>/**
* Copyright 2012-2016, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var isNumeric = require('fast-isnumeric');

var Axes = require('../../plots/cartesian/axes');
var Lib = require('../../lib');

var subTypes = require('../scatter/subtypes');
var calcColorscale = require('../scatter/colorscale_calc');

var dataArrays = ['a', 'b', 'c'];
var arraysToFill = {a: ['b', 'c'], b: ['a', 'c'], c: ['a', 'b']};

module.exports = function calc(gd, trace) {
    var ternary = gd._fullLayout[trace.subplot],
        displaySum = ternary.sum,
        normSum = trace.sum || displaySum;

    var i, j, dataArray, newArray, fillArray1, fillArray2;

    // fill in one missing component
    for(i = 0; i < dataArrays.length; i++) {
        dataArray = dataArrays[i];
        if(trace[dataArray]) continue;

        fillArray1 = trace[arraysToFill[dataArray][0]];
        fillArray2 = trace[arraysToFill[dataArray][1]];
        newArray = new Array(fillArray1.length);
        for(j = 0; j < fillArray1.length; j++) {
            newArray[j] = normSum - fillArray1[j] - fillArray2[j];
        }
        trace[dataArray] = newArray;
    }

    // make the calcdata array
    var serieslen = trace.a.length;
    var cd = new Array(serieslen);
    var a, b, c, norm, x, y;
    for(i = 0; i < serieslen; i++) {
        a = trace.a[i];
        b = trace.b[i];
        c = trace.c[i];
        if(isNumeric(a) && isNumeric(b) && isNumeric(c)) {
            a = +a;
            b = +b;
            c = +c;
            norm = displaySum / (a + b + c);
            if(norm !== 1) {
                a *= norm;
                b *= norm;
                c *= norm;
            }
            // map a, b, c onto x and y where the full scale of y
            // is [0, sum], and x is [-sum, sum]
            // TODO: this makes `a` always the top, `b` the bottom left,
            // and `c` the bottom right. Do we want options to rearrange
            // these?
            y = a;
            x = c - b;
            cd[i] = {x: x, y: y, a: a, b: b, c: c};
        }
        else cd[i] = {x: false, y: false};
    }

    // fill in some extras
    var marker, s;
    if(subTypes.hasMarkers(trace)) {
        // Treat size like x or y arrays --- Run d2c
        // this needs to go before ppad computation
        marker = trace.marker;
        s = marker.size;

        if(Array.isArray(s)) {
            var ax = {type: 'linear'};
            Axes.setConvert(ax);
            s = ax.makeCalcdata(trace.marker, 'size');
            if(s.length > serieslen) s.splice(serieslen, s.length - serieslen);
        }
    }

    calcColorscale(trace);

    // this has migrated up from arraysToCalcdata as we have a reference to 's' here
    if(typeof s !== undefined) Lib.mergeArray(s, cd, 'ms');

    return cd;
};
<commit_msg>Correct check for undefined variable<commit_after>/**
* Copyright 2012-2016, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var isNumeric = require('fast-isnumeric');

var Axes = require('../../plots/cartesian/axes');
var Lib = require('../../lib');

var subTypes = require('../scatter/subtypes');
var calcColorscale = require('../scatter/colorscale_calc');

var dataArrays = ['a', 'b', 'c'];
var arraysToFill = {a: ['b', 'c'], b: ['a', 'c'], c: ['a', 'b']};

module.exports = function calc(gd, trace) {
    var ternary = gd._fullLayout[trace.subplot],
        displaySum = ternary.sum,
        normSum = trace.sum || displaySum;

    var i, j, dataArray, newArray, fillArray1, fillArray2;

    // fill in one missing component
    for(i = 0; i < dataArrays.length; i++) {
        dataArray = dataArrays[i];
        if(trace[dataArray]) continue;

        fillArray1 = trace[arraysToFill[dataArray][0]];
        fillArray2 = trace[arraysToFill[dataArray][1]];
        newArray = new Array(fillArray1.length);
        for(j = 0; j < fillArray1.length; j++) {
            newArray[j] = normSum - fillArray1[j] - fillArray2[j];
        }
        trace[dataArray] = newArray;
    }

    // make the calcdata array
    var serieslen = trace.a.length;
    var cd = new Array(serieslen);
    var a, b, c, norm, x, y;
    for(i = 0; i < serieslen; i++) {
        a = trace.a[i];
        b = trace.b[i];
        c = trace.c[i];
        if(isNumeric(a) && isNumeric(b) && isNumeric(c)) {
            a = +a;
            b = +b;
            c = +c;
            norm = displaySum / (a + b + c);
            if(norm !== 1) {
                a *= norm;
                b *= norm;
                c *= norm;
            }
            // map a, b, c onto x and y where the full scale of y
            // is [0, sum], and x is [-sum, sum]
            // TODO: this makes `a` always the top, `b` the bottom left,
            // and `c` the bottom right. Do we want options to rearrange
            // these?
            y = a;
            x = c - b;
            cd[i] = {x: x, y: y, a: a, b: b, c: c};
        }
        else cd[i] = {x: false, y: false};
    }

    // fill in some extras
    var marker, s;
    if(subTypes.hasMarkers(trace)) {
        // Treat size like x or y arrays --- Run d2c
        // this needs to go before ppad computation
        marker = trace.marker;
        s = marker.size;

        if(Array.isArray(s)) {
            var ax = {type: 'linear'};
            Axes.setConvert(ax);
            s = ax.makeCalcdata(trace.marker, 'size');
            if(s.length > serieslen) s.splice(serieslen, s.length - serieslen);
        }
    }

    calcColorscale(trace);

    // this has migrated up from arraysToCalcdata as we have a reference to 's' here
    if(typeof s !== 'undefined') Lib.mergeArray(s, cd, 'ms');

    return cd;
};
<|endoftext|>


<commit_before>import * as ACTIONS from 'constants/action_types';
import * as SETTINGS from 'constants/settings';
import moment from 'moment';

const reducers = {};
const defaultState = {
  isNight: false,
  languages: { en: 'English', pl: 'Polish', id: 'Bahasa Indonesia', de: 'German' }, // this could/should be loaded directly from Transifex and/or lbry.com
  isFetchingLanguage: false,
  daemonSettings: {},
  clientSettings: {
    // UX
    [SETTINGS.NEW_USER_ACKNOWLEDGED]: false,
    [SETTINGS.EMAIL_COLLECTION_ACKNOWLEDGED]: false,
    [SETTINGS.ENABLE_SYNC]: true,

    // UI
    [SETTINGS.LANGUAGE]: window.localStorage.getItem(SETTINGS.LANGUAGE) || 'en',
    [SETTINGS.THEME]: 'light',
    [SETTINGS.THEMES]: [],
    [SETTINGS.SUPPORT_OPTION]: false,
    [SETTINGS.HIDE_SPLASH_ANIMATION]: false,
    [SETTINGS.HIDE_BALANCE]: false,
    [SETTINGS.OS_NOTIFICATIONS_ENABLED]: true,
    [SETTINGS.AUTOMATIC_DARK_MODE_ENABLED]: false,
    [SETTINGS.DARK_MODE_TIMES]: {
      from: { hour: '21', min: '00', formattedTime: '21:00' },
      to: { hour: '8', min: '00', formattedTime: '8:00' },
    },

    // Purchasing
    [SETTINGS.INSTANT_PURCHASE_ENABLED]: false,
    [SETTINGS.INSTANT_PURCHASE_MAX]: {
      currency: 'LBC',
      amount: 0.1,
    },

    // Content
    [SETTINGS.SHOW_MATURE]: false,
    [SETTINGS.AUTOPLAY]: true,
    [SETTINGS.FLOATING_PLAYER]: true,
    [SETTINGS.AUTO_DOWNLOAD]: true,
  },
};

reducers[ACTIONS.DAEMON_SETTINGS_RECEIVED] = (state, action) =>
  Object.assign({}, state, {
    daemonSettings: action.data.settings,
  });

reducers[ACTIONS.CLIENT_SETTING_CHANGED] = (state, action) => {
  const { key, value } = action.data;
  const clientSettings = Object.assign({}, state.clientSettings);

  clientSettings[key] = value;

  return Object.assign({}, state, {
    clientSettings,
  });
};

reducers[ACTIONS.UPDATE_IS_NIGHT] = state => {
  const { from, to } = state.clientSettings[SETTINGS.DARK_MODE_TIMES];
  const momentNow = moment();
  const startNightMoment = moment(from.formattedTime, 'HH:mm');
  const endNightMoment = moment(to.formattedTime, 'HH:mm');
  const isNight = !(momentNow.isAfter(endNightMoment) && momentNow.isBefore(startNightMoment));

  return Object.assign({}, state, {
    isNight,
  });
};

export default function reducer(state = defaultState, action) {
  const handler = reducers[action.type];
  if (handler) return handler(state, action);
  return state;
}
<commit_msg>Renamed language names to their natives<commit_after>import * as ACTIONS from 'constants/action_types';
import * as SETTINGS from 'constants/settings';
import moment from 'moment';

const reducers = {};
const defaultState = {
  isNight: false,
  languages: { en: 'English', pl: 'Polski', id: 'Bahasa Indonesia', de: 'Deutsche' }, // this could/should be loaded directly from Transifex and/or lbry.com
  isFetchingLanguage: false,
  daemonSettings: {},
  clientSettings: {
    // UX
    [SETTINGS.NEW_USER_ACKNOWLEDGED]: false,
    [SETTINGS.EMAIL_COLLECTION_ACKNOWLEDGED]: false,
    [SETTINGS.ENABLE_SYNC]: true,

    // UI
    [SETTINGS.LANGUAGE]: window.localStorage.getItem(SETTINGS.LANGUAGE) || 'en',
    [SETTINGS.THEME]: 'light',
    [SETTINGS.THEMES]: [],
    [SETTINGS.SUPPORT_OPTION]: false,
    [SETTINGS.HIDE_SPLASH_ANIMATION]: false,
    [SETTINGS.HIDE_BALANCE]: false,
    [SETTINGS.OS_NOTIFICATIONS_ENABLED]: true,
    [SETTINGS.AUTOMATIC_DARK_MODE_ENABLED]: false,
    [SETTINGS.DARK_MODE_TIMES]: {
      from: { hour: '21', min: '00', formattedTime: '21:00' },
      to: { hour: '8', min: '00', formattedTime: '8:00' },
    },

    // Purchasing
    [SETTINGS.INSTANT_PURCHASE_ENABLED]: false,
    [SETTINGS.INSTANT_PURCHASE_MAX]: {
      currency: 'LBC',
      amount: 0.1,
    },

    // Content
    [SETTINGS.SHOW_MATURE]: false,
    [SETTINGS.AUTOPLAY]: true,
    [SETTINGS.FLOATING_PLAYER]: true,
    [SETTINGS.AUTO_DOWNLOAD]: true,
  },
};

reducers[ACTIONS.DAEMON_SETTINGS_RECEIVED] = (state, action) =>
  Object.assign({}, state, {
    daemonSettings: action.data.settings,
  });

reducers[ACTIONS.CLIENT_SETTING_CHANGED] = (state, action) => {
  const { key, value } = action.data;
  const clientSettings = Object.assign({}, state.clientSettings);

  clientSettings[key] = value;

  return Object.assign({}, state, {
    clientSettings,
  });
};

reducers[ACTIONS.UPDATE_IS_NIGHT] = state => {
  const { from, to } = state.clientSettings[SETTINGS.DARK_MODE_TIMES];
  const momentNow = moment();
  const startNightMoment = moment(from.formattedTime, 'HH:mm');
  const endNightMoment = moment(to.formattedTime, 'HH:mm');
  const isNight = !(momentNow.isAfter(endNightMoment) && momentNow.isBefore(startNightMoment));

  return Object.assign({}, state, {
    isNight,
  });
};

export default function reducer(state = defaultState, action) {
  const handler = reducers[action.type];
  if (handler) return handler(state, action);
  return state;
}
<|endoftext|>


<commit_before>import * as ACTIONS from 'constants/action_types';
import LANGUAGES from 'constants/languages';
import * as SETTINGS from 'constants/settings';

function getLocalStorageSetting(setting, fallback) {
  const localStorageVal = localStorage.getItem(`setting_${setting}`);
  return localStorageVal === null ? fallback : JSON.parse(localStorageVal);
}

const reducers = {};
const defaultState = {
  clientSettings: {
    [SETTINGS.INSTANT_PURCHASE_ENABLED]: getLocalStorageSetting(SETTINGS.INSTANT_PURCHASE_ENABLED, false),
    [SETTINGS.INSTANT_PURCHASE_MAX]: getLocalStorageSetting(SETTINGS.INSTANT_PURCHASE_MAX, {
      currency: 'LBC',
      amount: 0.1,
    }),
    [SETTINGS.SHOW_NSFW]: getLocalStorageSetting(SETTINGS.SHOW_NSFW, false),
    [SETTINGS.SHOW_UNAVAILABLE]: getLocalStorageSetting(SETTINGS.SHOW_UNAVAILABLE, true),
    [SETTINGS.NEW_USER_ACKNOWLEDGED]: getLocalStorageSetting(SETTINGS.NEW_USER_ACKNOWLEDGED, false),
    [SETTINGS.EMAIL_COLLECTION_ACKNOWLEDGED]: getLocalStorageSetting(SETTINGS.EMAIL_COLLECTION_ACKNOWLEDGED, false),
    [SETTINGS.CREDIT_REQUIRED_ACKNOWLEDGED]: false, // this needs to be re-acknowledged every run
    [SETTINGS.LANGUAGE]: getLocalStorageSetting(SETTINGS.LANGUAGE, 'en'),
    [SETTINGS.THEME]: getLocalStorageSetting(SETTINGS.THEME, 'light'),
    [SETTINGS.THEMES]: getLocalStorageSetting(SETTINGS.THEMES, []),
    [SETTINGS.AUTOMATIC_DARK_MODE_ENABLED]: getLocalStorageSetting(SETTINGS.AUTOMATIC_DARK_MODE_ENABLED, false),
    [SETTINGS.AUTOPLAY]: getLocalStorageSetting(SETTINGS.AUTOPLAY, false),
    [SETTINGS.RESULT_COUNT]: Number(getLocalStorageSetting(SETTINGS.RESULT_COUNT, 50)),
    [SETTINGS.AUTO_DOWNLOAD]: getLocalStorageSetting(SETTINGS.AUTO_DOWNLOAD, true),
    [SETTINGS.OS_NOTIFICATIONS_ENABLED]: Boolean(getLocalStorageSetting(SETTINGS.OS_NOTIFICATIONS_ENABLED, true)),
  },
  isNight: false,
  languages: { en: 'English', pl: 'Polish' }, // temporarily hard code these so we can advance i18n testing
  daemonSettings: {},
};

reducers[ACTIONS.DAEMON_SETTINGS_RECEIVED] = (state, action) =>
  Object.assign({}, state, {
    daemonSettings: action.data.settings,
  });

reducers[ACTIONS.CLIENT_SETTING_CHANGED] = (state, action) => {
  const { key, value } = action.data;
  const clientSettings = Object.assign({}, state.clientSettings);

  clientSettings[key] = value;

  // this technically probably shouldn't happen here, and should be fixed when we're no longer using localStorage at all for persistent app state
  // @if TARGET='app'
  localStorage.setItem(`setting_${key}`, JSON.stringify(value));
  // @endif

  return Object.assign({}, state, {
    clientSettings,
  });
};

reducers[ACTIONS.UPDATE_IS_NIGHT] = (state, action) =>
  Object.assign({}, state, {
    isNight: action.data.isNight,
  });

reducers[ACTIONS.DOWNLOAD_LANGUAGE_SUCCEEDED] = (state, action) => {
  const languages = Object.assign({}, state.languages);
  const { language } = action.data;

  const langCode = language.substring(0, 2);

  if (LANGUAGES[langCode]) {
    languages[language] = `${LANGUAGES[langCode][0]} (${LANGUAGES[langCode][1]})`;
  } else {
    languages[langCode] = langCode;
  }

  return Object.assign({}, state, { languages });
};

reducers[ACTIONS.DOWNLOAD_LANGUAGE_FAILED] = (state, action) => {
  const languages = Object.assign({}, state.languages);
  delete languages[action.data.language];
  return Object.assign({}, state, { languages });
};

export default function reducer(state = defaultState, action) {
  const handler = reducers[action.type];
  if (handler) return handler(state, action);
  return state;
}
<commit_msg>Update settings.js<commit_after>import * as ACTIONS from 'constants/action_types';
import LANGUAGES from 'constants/languages';
import * as SETTINGS from 'constants/settings';

function getLocalStorageSetting(setting, fallback) {
  const localStorageVal = localStorage.getItem(`setting_${setting}`);
  return localStorageVal === null ? fallback : JSON.parse(localStorageVal);
}

const reducers = {};
const defaultState = {
  clientSettings: {
    [SETTINGS.INSTANT_PURCHASE_ENABLED]: getLocalStorageSetting(SETTINGS.INSTANT_PURCHASE_ENABLED, false),
    [SETTINGS.INSTANT_PURCHASE_MAX]: getLocalStorageSetting(SETTINGS.INSTANT_PURCHASE_MAX, {
      currency: 'LBC',
      amount: 0.1,
    }),
    [SETTINGS.SHOW_NSFW]: getLocalStorageSetting(SETTINGS.SHOW_NSFW, false),
    [SETTINGS.SHOW_UNAVAILABLE]: getLocalStorageSetting(SETTINGS.SHOW_UNAVAILABLE, true),
    [SETTINGS.NEW_USER_ACKNOWLEDGED]: getLocalStorageSetting(SETTINGS.NEW_USER_ACKNOWLEDGED, false),
    [SETTINGS.EMAIL_COLLECTION_ACKNOWLEDGED]: getLocalStorageSetting(SETTINGS.EMAIL_COLLECTION_ACKNOWLEDGED, false),
    [SETTINGS.CREDIT_REQUIRED_ACKNOWLEDGED]: false, // this needs to be re-acknowledged every run
    [SETTINGS.LANGUAGE]: getLocalStorageSetting(SETTINGS.LANGUAGE, 'en'),
    [SETTINGS.THEME]: getLocalStorageSetting(SETTINGS.THEME, 'light'),
    [SETTINGS.THEMES]: getLocalStorageSetting(SETTINGS.THEMES, []),
    [SETTINGS.AUTOMATIC_DARK_MODE_ENABLED]: getLocalStorageSetting(SETTINGS.AUTOMATIC_DARK_MODE_ENABLED, false),
    [SETTINGS.AUTOPLAY]: getLocalStorageSetting(SETTINGS.AUTOPLAY, false),
    [SETTINGS.RESULT_COUNT]: Number(getLocalStorageSetting(SETTINGS.RESULT_COUNT, 50)),
    [SETTINGS.AUTO_DOWNLOAD]: getLocalStorageSetting(SETTINGS.AUTO_DOWNLOAD, true),
    [SETTINGS.OS_NOTIFICATIONS_ENABLED]: Boolean(getLocalStorageSetting(SETTINGS.OS_NOTIFICATIONS_ENABLED, true)),
  },
  isNight: false,
  languages: { en: 'English', pl: 'Polish', id: 'Bahasa Indonesia' }, // temporarily hard code these so we can advance i18n testing
  daemonSettings: {},
};

reducers[ACTIONS.DAEMON_SETTINGS_RECEIVED] = (state, action) =>
  Object.assign({}, state, {
    daemonSettings: action.data.settings,
  });

reducers[ACTIONS.CLIENT_SETTING_CHANGED] = (state, action) => {
  const { key, value } = action.data;
  const clientSettings = Object.assign({}, state.clientSettings);

  clientSettings[key] = value;

  // this technically probably shouldn't happen here, and should be fixed when we're no longer using localStorage at all for persistent app state
  // @if TARGET='app'
  localStorage.setItem(`setting_${key}`, JSON.stringify(value));
  // @endif

  return Object.assign({}, state, {
    clientSettings,
  });
};

reducers[ACTIONS.UPDATE_IS_NIGHT] = (state, action) =>
  Object.assign({}, state, {
    isNight: action.data.isNight,
  });

reducers[ACTIONS.DOWNLOAD_LANGUAGE_SUCCEEDED] = (state, action) => {
  const languages = Object.assign({}, state.languages);
  const { language } = action.data;

  const langCode = language.substring(0, 2);

  if (LANGUAGES[langCode]) {
    languages[language] = `${LANGUAGES[langCode][0]} (${LANGUAGES[langCode][1]})`;
  } else {
    languages[langCode] = langCode;
  }

  return Object.assign({}, state, { languages });
};

reducers[ACTIONS.DOWNLOAD_LANGUAGE_FAILED] = (state, action) => {
  const languages = Object.assign({}, state.languages);
  delete languages[action.data.language];
  return Object.assign({}, state, { languages });
};

export default function reducer(state = defaultState, action) {
  const handler = reducers[action.type];
  if (handler) return handler(state, action);
  return state;
}
<|endoftext|>


<commit_before>/**
 * mSupply Mobile
 * Sustainable Solutions (NZ) Ltd. 2019
 */

/**
 * File contains constants and config objects which declaritively define
 * form inputs to be used with `FormControl`.
 *
 * For a particular form, add a field to FIELD_CONFIGS, which will define what
 * form input configs to use.
 *
 * FormInputConfig have the following structure:
 * {
 *     type: 'text' : A ValidationTextInput component
 *     initialValue : The value to seed the form input component with.
 *     key: A key for the underlying record.
 *     isRequired : Indicator whether this input is required to be filled for completion.
 *     label: A label for the form input.
 *     invalidMessage: A message when the input is invalid.
 *     validator: A function to call to determine if the current input is valid.
 * }
 */

const FORM_INPUT_KEYS = {
  FIRST_NAME: 'firstName',
  LAST_NAME: 'lastName',
  CODE: 'code',
  DATE_OF_BIRTH: 'dateOfBirth',
  EMAIL: 'emailAddress',
  PHONE: 'phoneNumber',
  COUNTRY: 'country',
  ADDRESS_ONE: 'addressOne',
  ADDRESS_TWO: 'addressTwo',
  REGISTRATION_CODE: 'registrationCode',
};

const FORM_INPUT_CONFIGS = {
  [FORM_INPUT_KEYS.FIRST_NAME]: {
    type: 'text',
    initialValue: '',
    key: 'firstName',
    isRequired: true,
    label: 'First name:',
    invalidMessage: 'need to be x',
  },
  [FORM_INPUT_KEYS.LAST_NAME]: {
    type: 'text',
    initialValue: '',
    key: 'lastName',
    isRequired: true,
    label: 'Last name:',
  },
  [FORM_INPUT_KEYS.CODE]: {
    type: 'text',
    initialValue: '',
    key: 'code',
    validator: input => input.length < 20,
    isRequired: true,
    label: 'Code:',
  },
  [FORM_INPUT_KEYS.DATE_OF_BIRTH]: {
    type: 'text',
    initialValue: '',
    key: 'dateOfBirth',
    invalidMessage: 'Must be a valid date',
    validator: input => {
      // Ensure the entered value is castable to a date and is less than
      // the current date.
      const dateTime = new Date(input).getTime();
      const dateTimeNow = new Date().getTime();
      if (!input) return true;

      const inputIsAValidDate = !Number.isNaN(dateTime);
      const inputIsLessThanNow = dateTime < dateTimeNow;
      const inputHasAForwardSlash = input.includes('/');

      return inputIsAValidDate && inputIsLessThanNow && inputHasAForwardSlash;
    },
    label: 'Date of birth:',
  },
  [FORM_INPUT_KEYS.EMAIL]: {
    type: 'text',
    initialValue: '',
    key: 'emailAddress',
    isRequired: false,
    label: 'Email:',
  },
  [FORM_INPUT_KEYS.PHONE]: {
    type: 'text',
    initialValue: '',
    key: 'phoneNumber',
    isRequired: false,
    label: 'Phone:',
  },
  [FORM_INPUT_KEYS.COUNTRY]: {
    type: 'text',
    initialValue: '',
    key: 'country',
    validator: input => input.length < 20,
    isRequired: false,
    label: 'Country:',
  },
  [FORM_INPUT_KEYS.ADDRESS_ONE]: {
    type: 'text',
    initialValue: '',
    key: 'addressOne',
    validator: input => input.length < 50,
    isRequired: false,
    label: 'Address 1:',
  },
  [FORM_INPUT_KEYS.ADDRESS_TWO]: {
    type: 'text',
    initialValue: '',
    key: 'addressTwo',
    validator: input => input.length < 50,
    isRequired: false,
    label: 'Address 2:',
  },
  [FORM_INPUT_KEYS.REGISTRATION_CODE]: {
    type: 'text',
    initialValue: '',
    key: 'registrationCode',
    validator: input => input.length < 50,
    isRequired: false,
    label: 'Registration code:',
  },
  [FORM_INPUT_KEYS.REGISTRATION_CODE]: {
    type: 'text',
    initialValue: '',
    key: 'registrationCode',
    validator: input => input.length < 50,
    isRequired: true,
    label: 'Registration code:',
  },
};

const FORM_CONFIGS = {
  patient: [
    FORM_INPUT_CONFIGS[FORM_INPUT_KEYS.FIRST_NAME],
    FORM_INPUT_CONFIGS[FORM_INPUT_KEYS.LAST_NAME],
    FORM_INPUT_CONFIGS[FORM_INPUT_KEYS.CODE],
    FORM_INPUT_CONFIGS[FORM_INPUT_KEYS.DATE_OF_BIRTH],
    FORM_INPUT_CONFIGS[FORM_INPUT_KEYS.EMAIL],
    FORM_INPUT_CONFIGS[FORM_INPUT_KEYS.PHONE],
    FORM_INPUT_CONFIGS[FORM_INPUT_KEYS.ADDRESS_ONE],
    FORM_INPUT_CONFIGS[FORM_INPUT_KEYS.ADDRESS_TWO],
    FORM_INPUT_CONFIGS[FORM_INPUT_KEYS.COUNTRY],
  ],
  prescriber: [
    FORM_INPUT_CONFIGS[FORM_INPUT_KEYS.FIRST_NAME],
    FORM_INPUT_CONFIGS[FORM_INPUT_KEYS.LAST_NAME],
    FORM_INPUT_CONFIGS[FORM_INPUT_KEYS.REGISTRATION_CODE],
    FORM_INPUT_CONFIGS[FORM_INPUT_KEYS.EMAIL],
    FORM_INPUT_CONFIGS[FORM_INPUT_KEYS.PHONE],
    FORM_INPUT_CONFIGS[FORM_INPUT_KEYS.ADDRESS_ONE],
    FORM_INPUT_CONFIGS[FORM_INPUT_KEYS.ADDRESS_TWO],
  ],
};

export const getFormInputConfig = (formName, seedObject) => {
  const formConfig = FORM_CONFIGS[formName];

  if (!seedObject) return formConfig;

  return formConfig.map(({ key, ...restOfConfig }) => ({
    ...restOfConfig,
    key,
    initialValue: seedObject[key] || '',
  }));
};
<commit_msg>Add remove duplicate registration code config definition<commit_after>/**
 * mSupply Mobile
 * Sustainable Solutions (NZ) Ltd. 2019
 */

/**
 * File contains constants and config objects which declaritively define
 * form inputs to be used with `FormControl`.
 *
 * For a particular form, add a field to FIELD_CONFIGS, which will define what
 * form input configs to use.
 *
 * FormInputConfig have the following structure:
 * {
 *     type: 'text' : A ValidationTextInput component
 *     initialValue : The value to seed the form input component with.
 *     key: A key for the underlying record.
 *     isRequired : Indicator whether this input is required to be filled for completion.
 *     label: A label for the form input.
 *     invalidMessage: A message when the input is invalid.
 *     validator: A function to call to determine if the current input is valid.
 * }
 */

const FORM_INPUT_KEYS = {
  FIRST_NAME: 'firstName',
  LAST_NAME: 'lastName',
  CODE: 'code',
  DATE_OF_BIRTH: 'dateOfBirth',
  EMAIL: 'emailAddress',
  PHONE: 'phoneNumber',
  COUNTRY: 'country',
  ADDRESS_ONE: 'addressOne',
  ADDRESS_TWO: 'addressTwo',
  REGISTRATION_CODE: 'registrationCode',
};

const FORM_INPUT_CONFIGS = {
  [FORM_INPUT_KEYS.FIRST_NAME]: {
    type: 'text',
    initialValue: '',
    key: 'firstName',
    isRequired: true,
    label: 'First name:',
    invalidMessage: 'need to be x',
  },
  [FORM_INPUT_KEYS.LAST_NAME]: {
    type: 'text',
    initialValue: '',
    key: 'lastName',
    isRequired: true,
    label: 'Last name:',
  },
  [FORM_INPUT_KEYS.CODE]: {
    type: 'text',
    initialValue: '',
    key: 'code',
    validator: input => input.length < 20,
    isRequired: true,
    label: 'Code:',
  },
  [FORM_INPUT_KEYS.DATE_OF_BIRTH]: {
    type: 'text',
    initialValue: '',
    key: 'dateOfBirth',
    invalidMessage: 'Must be a valid date',
    validator: input => {
      // Ensure the entered value is castable to a date and is less than
      // the current date.
      const dateTime = new Date(input).getTime();
      const dateTimeNow = new Date().getTime();
      if (!input) return true;

      const inputIsAValidDate = !Number.isNaN(dateTime);
      const inputIsLessThanNow = dateTime < dateTimeNow;
      const inputHasAForwardSlash = input.includes('/');

      return inputIsAValidDate && inputIsLessThanNow && inputHasAForwardSlash;
    },
    label: 'Date of birth:',
  },
  [FORM_INPUT_KEYS.EMAIL]: {
    type: 'text',
    initialValue: '',
    key: 'emailAddress',
    isRequired: false,
    label: 'Email:',
  },
  [FORM_INPUT_KEYS.PHONE]: {
    type: 'text',
    initialValue: '',
    key: 'phoneNumber',
    isRequired: false,
    label: 'Phone:',
  },
  [FORM_INPUT_KEYS.COUNTRY]: {
    type: 'text',
    initialValue: '',
    key: 'country',
    validator: input => input.length < 20,
    isRequired: false,
    label: 'Country:',
  },
  [FORM_INPUT_KEYS.ADDRESS_ONE]: {
    type: 'text',
    initialValue: '',
    key: 'addressOne',
    validator: input => input.length < 50,
    isRequired: false,
    label: 'Address 1:',
  },
  [FORM_INPUT_KEYS.ADDRESS_TWO]: {
    type: 'text',
    initialValue: '',
    key: 'addressTwo',
    validator: input => input.length < 50,
    isRequired: false,
    label: 'Address 2:',
  },
  [FORM_INPUT_KEYS.REGISTRATION_CODE]: {
    type: 'text',
    initialValue: '',
    key: 'registrationCode',
    validator: input => input.length < 50,
    isRequired: true,
    label: 'Registration code:',
  },
};

const FORM_CONFIGS = {
  patient: [
    FORM_INPUT_CONFIGS[FORM_INPUT_KEYS.FIRST_NAME],
    FORM_INPUT_CONFIGS[FORM_INPUT_KEYS.LAST_NAME],
    FORM_INPUT_CONFIGS[FORM_INPUT_KEYS.CODE],
    FORM_INPUT_CONFIGS[FORM_INPUT_KEYS.DATE_OF_BIRTH],
    FORM_INPUT_CONFIGS[FORM_INPUT_KEYS.EMAIL],
    FORM_INPUT_CONFIGS[FORM_INPUT_KEYS.PHONE],
    FORM_INPUT_CONFIGS[FORM_INPUT_KEYS.ADDRESS_ONE],
    FORM_INPUT_CONFIGS[FORM_INPUT_KEYS.ADDRESS_TWO],
    FORM_INPUT_CONFIGS[FORM_INPUT_KEYS.COUNTRY],
  ],
  prescriber: [
    FORM_INPUT_CONFIGS[FORM_INPUT_KEYS.FIRST_NAME],
    FORM_INPUT_CONFIGS[FORM_INPUT_KEYS.LAST_NAME],
    FORM_INPUT_CONFIGS[FORM_INPUT_KEYS.REGISTRATION_CODE],
    FORM_INPUT_CONFIGS[FORM_INPUT_KEYS.EMAIL],
    FORM_INPUT_CONFIGS[FORM_INPUT_KEYS.PHONE],
    FORM_INPUT_CONFIGS[FORM_INPUT_KEYS.ADDRESS_ONE],
    FORM_INPUT_CONFIGS[FORM_INPUT_KEYS.ADDRESS_TWO],
  ],
};

export const getFormInputConfig = (formName, seedObject) => {
  const formConfig = FORM_CONFIGS[formName];

  if (!seedObject) return formConfig;

  return formConfig.map(({ key, ...restOfConfig }) => ({
    ...restOfConfig,
    key,
    initialValue: seedObject[key] || '',
  }));
};
<|endoftext|>