<commit_before>// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the LICENSE.txt file included with this file.

/** @scope modules */

const AutoCommand = new Struct("event", "pattern", "command");

/**
 * @instance autocommands
 */
const AutoCommands = Module("autocommands", {
    requires: ["config"],

    init: function () {
        this._store = [];
    },

    __iterator__: function () util.Array.itervalues(this._store),

    /**
     * Adds a new autocommand. cmd will be executed when one of the
     * specified events occurs and the URL of the applicable buffer
     * matches regex.
     *
     * @param {Array} events The array of event names for which this
     *     autocommand should be executed.
     * @param {string} regex The URL pattern to match against the buffer URL.
     * @param {string} cmd The Ex command to run.
     */
    add: function (events, regex, cmd) {
        if (typeof events == "string") {
            events = events.split(",");
            liberator.log("DEPRECATED: the events list arg to autocommands.add() should be an array of event names");
        }
        events.forEach(function (event) {
            this._store.push(new AutoCommand(event, RegExp(regex), cmd));
        }, this);
    },

    /**
     * Returns all autocommands with a matching event and
     * regex.
     *
     * @param {string} event The event name filter.
     * @param {string} regex The URL pattern filter.
     * @returns {AutoCommand[]}
     */
    get: function (event, regex) {
        return this._store.filter(function (autoCmd) matchAutoCmd(autoCmd, event, regex));
    },

    /**
     * Deletes all autocommands with a matching event and
     * regex.
     *
     * @param {string} event The event name filter.
     * @param {string} regex The URL pattern filter.
     */
    remove: function (event, regex) {
        this._store = this._store.filter(function (autoCmd) !matchAutoCmd(autoCmd, event, regex));
    },

    /**
     * Lists all autocommands with a matching event and
     * regex.
     *
     * @param {string} event The event name filter.
     * @param {string} regex The URL pattern filter.
     */
    list: function (event, regex) {
        let cmds = {};

        // XXX
        this._store.forEach(function (autoCmd) {
            if (matchAutoCmd(autoCmd, event, regex)) {
                cmds[autoCmd.event] = cmds[autoCmd.event] || [];
                cmds[autoCmd.event].push(autoCmd);
            }
        });

        let list = template.commandOutput(

                    ----- Auto Commands -----

                {
                    template.map(cmds, function ([event, items])

                        {event}

                    +
                        template.map(items, function (item)

                             {item.pattern.source}
                            {item.command}

))
                }

);

        commandline.echo(list, commandline.HL_NORMAL, commandline.FORCE_MULTILINE);
    },

    /**
     * Triggers the execution of all autocommands registered for
     * event. A map of args is passed to each autocommand
     * when it is being executed.
     *
     * @param {string} event The event to fire.
     * @param {Object} args The args to pass to each autocommand.
     */
    trigger: function (event, args) {
        if (options.get("eventignore").has("all", event))
            return;

        let autoCmds = this._store.filter(function (autoCmd) autoCmd.event == event);

        liberator.echomsg("Executing " + event + " Auto commands for \"*\"", 8);

        let lastPattern = null;
        let url = args.url || "";

        for (let [, autoCmd] in Iterator(autoCmds)) {
            if (autoCmd.pattern.test(url)) {
                if (!lastPattern || lastPattern.source != autoCmd.pattern.source)
                    liberator.echomsg("Executing " + event + " Auto commands for \"" + autoCmd.pattern.source + "\"", 8);

                lastPattern = autoCmd.pattern;
                liberator.echomsg("autocommand " + autoCmd.command, 9);

                if (typeof autoCmd.command == "function") {
                    try {
                        autoCmd.command.call(autoCmd, args);
                    }
                    catch (e) {
                        liberator.reportError(e);
                        liberator.echoerr(e);
                    }
                }
                else
                    liberator.execute(commands.replaceTokens(autoCmd.command, args), null, true);
            }
        }
    }
}, {
    matchAutoCmd: function (autoCmd, event, regex) {
        return (!event || autoCmd.event == event) && (!regex || autoCmd.pattern.source == regex);
    }
}, {
    commands: function () {
        commands.add(["au[tocmd]"],
            "Execute commands automatically on events",
            function (args) {
                let [event, regex, cmd] = args;
                let events = [];

                try {
                    RegExp(regex);
                }
                catch (e) {
                    liberator.assert(false, "E475: Invalid argument: " + regex);
                }

                if (event) {
                    // NOTE: event can only be a comma separated list for |:au {event} {pat} {cmd}|
                    let validEvents = config.autocommands.map(function (event) event[0]);
                    validEvents.push("*");

                    events = event.split(",");
                    liberator.assert(events.every(function (event) validEvents.indexOf(event) >= 0),
                        "E216: No such group or event: " + event);
                }

                if (cmd) { // add new command, possibly removing all others with the same event/pattern
                    if (args.bang)
                        autocommands.remove(event, regex);
                    if (args["-javascript"])
                        cmd = eval("(function (args) { with(args) {" + cmd + "} })");
                    autocommands.add(events, regex, cmd);
                }
                else {
                    if (event == "*")
                        event = null;

                    if (args.bang) {
                        // TODO: "*" only appears to work in Vim when there is a {group} specified
                        if (args[0] != "*" || regex)
                            autocommands.remove(event, regex); // remove all
                    }
                    else
                        autocommands.list(event, regex);   // list all
                }
            }, {
                bang: true,
                completer: function (context) completion.autocmdEvent(context),
                literal: 2,
                options: [[["-javascript", "-js"], commands.OPTION_NOARG]]
            });

        [
            {
                name: "do[autocmd]",
                description: "Apply the autocommands matching the specified URL pattern to the current buffer"
            }, {
                name: "doautoa[ll]",
                description: "Apply the autocommands matching the specified URL pattern to all buffers"
            }
        ].forEach(function (command) {
            commands.add([command.name],
                command.description,
                // TODO: Perhaps this should take -args to pass to the command?
                function (args) {
                    // Vim compatible
                    if (args.length == 0)
                        return void liberator.echomsg("No matching autocommands");

                    let [event, url] = args;
                    let defaultURL = url || buffer.URL;
                    let validEvents = config.autocommands.map(function (e) e[0]);

                    // TODO: add command validators
                    liberator.assert(event != "*",
                        "E217: Can't execute autocommands for ALL events");
                    liberator.assert(validEvents.indexOf(event) >= 0,
                        "E216: No such group or event: " + args);
                    liberator.assert(autocommands.get(event).some(function (c) c.pattern.test(defaultURL)),
                        "No matching autocommands");

                    if (this.name == "doautoall" && liberator.has("tabs")) {
                        let current = tabs.index();

                        for (let i = 0; i < tabs.count; i++) {
                            tabs.select(i);
                            // if no url arg is specified use the current buffer's URL
                            autocommands.trigger(event, { url: url || buffer.URL });
                        }

                        tabs.select(current);
                    }
                    else
                        autocommands.trigger(event, { url: defaultURL });
                }, {
                    argCount: "*", // FIXME: kludged for proper error message should be "1".
                    completer: function (context) completion.autocmdEvent(context)
                });
        });
    },
    completion: function () {
        completion.setFunctionCompleter(autocommands.get, [function () config.autocommands]);

        completion.autocmdEvent = function autocmdEvent(context) {
            context.completions = config.autocommands;
        };

        completion.macro = function macro(context) {
            context.title = ["Macro", "Keys"];
            context.completions = [item for (item in events.getMacros())];
        };
    },
    options: function () {
        options.add(["eventignore", "ei"],
            "List of autocommand event names which should be ignored",
            "stringlist", "",
            {
                completer: function () config.autocommands.concat([["all", "All events"]]),
                validator: Option.validateCompleter
            });

        options.add(["focuscontent", "fc"],
            "Try to stay in normal mode after loading a web page",
            "boolean", false);
    }
});

// vim: set fdm=marker sw=4 ts=4 et:
<commit_msg>Fix autocommands.<commit_after>// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the LICENSE.txt file included with this file.

/** @scope modules */

const AutoCommand = new Struct("event", "pattern", "command");

/**
 * @instance autocommands
 */
const AutoCommands = Module("autocommands", {
    requires: ["config"],

    init: function () {
        this._store = [];
    },

    __iterator__: function () util.Array.itervalues(this._store),

    /**
     * Adds a new autocommand. cmd will be executed when one of the
     * specified events occurs and the URL of the applicable buffer
     * matches regex.
     *
     * @param {Array} events The array of event names for which this
     *     autocommand should be executed.
     * @param {string} regex The URL pattern to match against the buffer URL.
     * @param {string} cmd The Ex command to run.
     */
    add: function (events, regex, cmd) {
        if (typeof events == "string") {
            events = events.split(",");
            liberator.log("DEPRECATED: the events list arg to autocommands.add() should be an array of event names");
        }
        events.forEach(function (event) {
            this._store.push(new AutoCommand(event, RegExp(regex), cmd));
        }, this);
    },

    /**
     * Returns all autocommands with a matching event and
     * regex.
     *
     * @param {string} event The event name filter.
     * @param {string} regex The URL pattern filter.
     * @returns {AutoCommand[]}
     */
    get: function (event, regex) {
        return this._store.filter(function (autoCmd) AutoCommands.matchAutoCmd(autoCmd, event, regex));
    },

    /**
     * Deletes all autocommands with a matching event and
     * regex.
     *
     * @param {string} event The event name filter.
     * @param {string} regex The URL pattern filter.
     */
    remove: function (event, regex) {
        this._store = this._store.filter(function (autoCmd) !AutoCommands.matchAutoCmd(autoCmd, event, regex));
    },

    /**
     * Lists all autocommands with a matching event and
     * regex.
     *
     * @param {string} event The event name filter.
     * @param {string} regex The URL pattern filter.
     */
    list: function (event, regex) {
        let cmds = {};

        // XXX
        this._store.forEach(function (autoCmd) {
            if (AutoCommands.matchAutoCmd(autoCmd, event, regex)) {
                cmds[autoCmd.event] = cmds[autoCmd.event] || [];
                cmds[autoCmd.event].push(autoCmd);
            }
        });

        let list = template.commandOutput(

                    ----- Auto Commands -----

                {
                    template.map(cmds, function ([event, items])

                        {event}

                    +
                        template.map(items, function (item)

                             {item.pattern.source}
                            {item.command}

))
                }

);

        commandline.echo(list, commandline.HL_NORMAL, commandline.FORCE_MULTILINE);
    },

    /**
     * Triggers the execution of all autocommands registered for
     * event. A map of args is passed to each autocommand
     * when it is being executed.
     *
     * @param {string} event The event to fire.
     * @param {Object} args The args to pass to each autocommand.
     */
    trigger: function (event, args) {
        if (options.get("eventignore").has("all", event))
            return;

        let autoCmds = this._store.filter(function (autoCmd) autoCmd.event == event);

        liberator.echomsg("Executing " + event + " Auto commands for \"*\"", 8);

        let lastPattern = null;
        let url = args.url || "";

        for (let [, autoCmd] in Iterator(autoCmds)) {
            if (autoCmd.pattern.test(url)) {
                if (!lastPattern || lastPattern.source != autoCmd.pattern.source)
                    liberator.echomsg("Executing " + event + " Auto commands for \"" + autoCmd.pattern.source + "\"", 8);

                lastPattern = autoCmd.pattern;
                liberator.echomsg("autocommand " + autoCmd.command, 9);

                if (typeof autoCmd.command == "function") {
                    try {
                        autoCmd.command.call(autoCmd, args);
                    }
                    catch (e) {
                        liberator.reportError(e);
                        liberator.echoerr(e);
                    }
                }
                else
                    liberator.execute(commands.replaceTokens(autoCmd.command, args), null, true);
            }
        }
    }
}, {
    matchAutoCmd: function (autoCmd, event, regex) {
        return (!event || autoCmd.event == event) && (!regex || autoCmd.pattern.source == regex);
    }
}, {
    commands: function () {
        commands.add(["au[tocmd]"],
            "Execute commands automatically on events",
            function (args) {
                let [event, regex, cmd] = args;
                let events = [];

                try {
                    RegExp(regex);
                }
                catch (e) {
                    liberator.assert(false, "E475: Invalid argument: " + regex);
                }

                if (event) {
                    // NOTE: event can only be a comma separated list for |:au {event} {pat} {cmd}|
                    let validEvents = config.autocommands.map(function (event) event[0]);
                    validEvents.push("*");

                    events = event.split(",");
                    liberator.assert(events.every(function (event) validEvents.indexOf(event) >= 0),
                        "E216: No such group or event: " + event);
                }

                if (cmd) { // add new command, possibly removing all others with the same event/pattern
                    if (args.bang)
                        autocommands.remove(event, regex);
                    if (args["-javascript"])
                        cmd = eval("(function (args) { with(args) {" + cmd + "} })");
                    autocommands.add(events, regex, cmd);
                }
                else {
                    if (event == "*")
                        event = null;

                    if (args.bang) {
                        // TODO: "*" only appears to work in Vim when there is a {group} specified
                        if (args[0] != "*" || regex)
                            autocommands.remove(event, regex); // remove all
                    }
                    else
                        autocommands.list(event, regex);   // list all
                }
            }, {
                bang: true,
                completer: function (context) completion.autocmdEvent(context),
                literal: 2,
                options: [[["-javascript", "-js"], commands.OPTION_NOARG]]
            });

        [
            {
                name: "do[autocmd]",
                description: "Apply the autocommands matching the specified URL pattern to the current buffer"
            }, {
                name: "doautoa[ll]",
                description: "Apply the autocommands matching the specified URL pattern to all buffers"
            }
        ].forEach(function (command) {
            commands.add([command.name],
                command.description,
                // TODO: Perhaps this should take -args to pass to the command?
                function (args) {
                    // Vim compatible
                    if (args.length == 0)
                        return void liberator.echomsg("No matching autocommands");

                    let [event, url] = args;
                    let defaultURL = url || buffer.URL;
                    let validEvents = config.autocommands.map(function (e) e[0]);

                    // TODO: add command validators
                    liberator.assert(event != "*",
                        "E217: Can't execute autocommands for ALL events");
                    liberator.assert(validEvents.indexOf(event) >= 0,
                        "E216: No such group or event: " + args);
                    liberator.assert(autocommands.get(event).some(function (c) c.pattern.test(defaultURL)),
                        "No matching autocommands");

                    if (this.name == "doautoall" && liberator.has("tabs")) {
                        let current = tabs.index();

                        for (let i = 0; i < tabs.count; i++) {
                            tabs.select(i);
                            // if no url arg is specified use the current buffer's URL
                            autocommands.trigger(event, { url: url || buffer.URL });
                        }

                        tabs.select(current);
                    }
                    else
                        autocommands.trigger(event, { url: defaultURL });
                }, {
                    argCount: "*", // FIXME: kludged for proper error message should be "1".
                    completer: function (context) completion.autocmdEvent(context)
                });
        });
    },
    completion: function () {
        completion.setFunctionCompleter(autocommands.get, [function () config.autocommands]);

        completion.autocmdEvent = function autocmdEvent(context) {
            context.completions = config.autocommands;
        };

        completion.macro = function macro(context) {
            context.title = ["Macro", "Keys"];
            context.completions = [item for (item in events.getMacros())];
        };
    },
    options: function () {
        options.add(["eventignore", "ei"],
            "List of autocommand event names which should be ignored",
            "stringlist", "",
            {
                completer: function () config.autocommands.concat([["all", "All events"]]),
                validator: Option.validateCompleter
            });

        options.add(["focuscontent", "fc"],
            "Try to stay in normal mode after loading a web page",
            "boolean", false);
    }
});

// vim: set fdm=marker sw=4 ts=4 et:
<|endoftext|>


<commit_before>//Target
//http://codepen.io/Sambego/pen/zDLxe
/*

 <input type="checkbox"> Checkbox

 */
var builder = require('focus').component.builder;
var React = require('react');
var type = require('focus').component.types;
var fieldGridBehaviourMixin = require('../../mixin/field-grid-behaviour');
var jQuery = require('jquery');
var isBoolean = require('lodash/lang/isBoolean');

var checkBoxMixin = {
    mixins: [fieldGridBehaviourMixin],
    /**
     * Get the checkbox default attributes.
     */
    getDefaultProps: function getInputDefaultProps() {
        return {
            value: undefined,
            label: undefined,
            style: {}
        };
    },
    /**
     * Properties validation.
     * @type {Object}
     */
    propTypes: {
        value: type('bool'),
        label: type('string'),
        style: type('object'),
        onChange: type('function')
    },
    getInitialState: function () {
        return {
            isChecked: this.props.isChecked ? this.props.isChecked : this.props.value
        };
    },
    _onChange: function onChange(event) {
        this.setState({
            isChecked: !this.state.isChecked
        }, this.props.onChange);
    },
    /**
     * Get the value from the input in  the DOM.
     * @returns The DOM node value.
     */
    getValue: function getValue() {
        if (isBoolean(this.props.value)) {
            return this.state.isChecked;
        }
        return this.state.isChecked ? this.props.value : undefined;
    },
    /**
     * Build the label class name.
     * @returns The label classame with the grid informations.
     */
    _labelClassName: function labelClassName() {
        return `${this._getContentOffsetClassName()} ${this._getContentGridClassName()}`;
    },
    /**
     * Render the Checkbox HTML.
     * @return {VirtualDOM} - The virtual DOM of the checkbox.
     */
    render: function renderCheckBox() {
        return (

                    <input ref='checkbox' checked={this.state.isChecked} onChange={this._onChange} type='checkbox' value={this.props.value} />
                    {this.props.label ? this.props.label : ''}

        );
    },
    /** @inheritedDoc*/
    componentWillReceiveProps: function checkBoxWillreceiveProps(nextProps) {
        if (nextProps.value !== undefined) {
            this.setState({isChecked: nextProps.value});
        }
    }
};

module.exports = builder(checkBoxMixin);
<commit_msg>[checkbox] Fix ugly warning in console<commit_after>//Target
//http://codepen.io/Sambego/pen/zDLxe
/*

 <input type="checkbox"> Checkbox

 */
var builder = require('focus').component.builder;
var React = require('react');
var type = require('focus').component.types;
var fieldGridBehaviourMixin = require('../../mixin/field-grid-behaviour');
var jQuery = require('jquery');
var isBoolean = require('lodash/lang/isBoolean');

var checkBoxMixin = {
    mixins: [fieldGridBehaviourMixin],
    /**
     * Get the checkbox default attributes.
     */
    getDefaultProps: function getInputDefaultProps() {
        return {
            value: undefined,
            label: undefined,
            style: {}
        };
    },
    /**
     * Properties validation.
     * @type {Object}
     */
    propTypes: {
        value: type('bool'),
        label: type('string'),
        style: type('object'),
        onChange: type(['function', 'object'])
    },
    getInitialState: function () {
        return {
            isChecked: this.props.isChecked ? this.props.isChecked : this.props.value
        };
    },
    _onChange: function onChange(event) {
        this.setState({
            isChecked: !this.state.isChecked
        }, this.props.onChange);
    },
    /**
     * Get the value from the input in  the DOM.
     * @returns The DOM node value.
     */
    getValue: function getValue() {
        if (isBoolean(this.props.value)) {
            return this.state.isChecked;
        }
        return this.state.isChecked ? this.props.value : undefined;
    },
    /**
     * Build the label class name.
     * @returns The label classame with the grid informations.
     */
    _labelClassName: function labelClassName() {
        return `${this._getContentOffsetClassName()} ${this._getContentGridClassName()}`;
    },
    /**
     * Render the Checkbox HTML.
     * @return {VirtualDOM} - The virtual DOM of the checkbox.
     */
    render: function renderCheckBox() {
        return (

                    <input ref='checkbox' checked={this.state.isChecked} onChange={this._onChange} type='checkbox' value={this.props.value} />
                    {this.props.label ? this.props.label : ''}

        );
    },
    /** @inheritedDoc*/
    componentWillReceiveProps: function checkBoxWillreceiveProps(nextProps) {
        if (nextProps.value !== undefined) {
            this.setState({isChecked: nextProps.value});
        }
    }
};

module.exports = builder(checkBoxMixin);
<|endoftext|>


<commit_before>// newick tree
// console.log(JSON.stringify(tnt.tree.parse_newick(newick)))
var newick = "";
var tree = tnt.tree();
var treeCreated = false;
var numOpenPar = 0;
var numClosedPar = 0;
var numCommas = 0;
var expanded_node = tnt.tree.node_display.circle();
var collapsed_node = tnt.tree.node_display.triangle();
var node_display = tree.node_display()
            .size(3)
            .fill("black")
            .display (function (node) {
            if (node.is_collapsed()) {
                collapsed_node.display().call(this, node);
            } else {
                expanded_node.display().call(this, node);
            }
        })
var clickoption = 0;

function makeTree(newick) {
    document.getElementById("treemaker").innerHTML=""
    numCommas=0;

    /*errorcheck begins here*/
  for (var x=0; x<newick.length; x++)
    {
      if (newick.charAt(x)==='(')
        {
        numOpenPar++;
        }
      if (newick.charAt(x)===')')
        {
        numClosedPar++;
        }
      if (newick.charAt(x)==',')
        {
          numCommas++;
        }
    }
  if (numOpenPar!==numClosedPar || newick.charAt(0)!=='(' || newick.charAt(newick.length-1)!==';')
    {  document.getElementById("errorspot").style.color="Red"
    /*errorcheck ends here*/
      document.getElementById("errorspot").innerHTML = "ERROR: INVALID INPUT";
      resetPar();
  }
  else
    {
      resetPar();
        tree
        .data(tnt.tree.parse_newick(newick))
        .node_display(node_display)
        .label (tnt.tree.label.text()
        .fontsize(12)
        .height(window.innerHeight*0.68/(numCommas+1))
            )
        .layout(tnt.tree.layout.vertical()
        .width(window.innerWidth*0.58)
        .scale(false)
            );
    tree(treemaker);
    }
}

function submitNewick ()
{
  document.getElementById("errorspot").innerHTML = "";
  var newick=document.getElementById("userInput").value;
  makeTree(newick);
}

function resetPar() {
  numOpenPar=0;
  numClosedPar=0;
}

function submitFile() {
    document.getElementById("errorspot").innerHTML = "";
    var fileInput = document.getElementById("fileInput")
    console.log(fileInput.files[0])
    var newick = ''

    var file = fileInput.files[0]
    var reader = new FileReader()

    reader.onload = function(e) {
        newick = reader.result
        makeTree(newick);
    }
    reader.readAsText(file);
}

function updateVertical()
{
            tree.layout(tnt.tree.layout.vertical().width(window.innerWidth*0.58).scale(false));
            tree.update();
}

function updateRadial()
{
  {
            tree.layout(tnt.tree.layout.radial().width(Math.min(window.innerWidth*0.58, window.innerHeight*0.58)).scale(false));
            tree.update();
        }
}

 function download () {
        var pngExporter = tnt.utils.png()
            .filename("treeSample.png")
        pngExporter(d3.select("svg"));
    };

/*dynamic resizing*/
$(window).resize(function() {
  var newick=document.getElementById("userInput").value;
  makeTree(newick);
});

if (clickoption == 0)
  {
tree.on ("click", function(node){
        node.toggle();
        tree.update();
    });
  }

if (clickoption == 1)
{
tree.on("click", function (d) {
                tnt.tooltip.table()
                    .width(120)
                    .call(this, {
                        "header" : "Node",
                        "rows" : [
                            {"label": "id", "value": d.id()}
                        ]
                    })
            })
}<commit_msg>inactivated errocheck<commit_after>// newick tree
// console.log(JSON.stringify(tnt.tree.parse_newick(newick)))
var newick = "";
var tree = tnt.tree();
var treeCreated = false;
var expanded_node = tnt.tree.node_display.circle();
var collapsed_node = tnt.tree.node_display.triangle();
var node_display = tree.node_display()
            .size(3)
            .fill("black")
            .display (function (node) {
            if (node.is_collapsed()) {
                collapsed_node.display().call(this, node);
            } else {
                expanded_node.display().call(this, node);
            }
        })
var clickoption = 0;

function makeTree(newick) {
    document.getElementById("treemaker").innerHTML=""
        tree
        .data(tnt.tree.parse_newick(newick))
        .node_display(node_display)
        .label (tnt.tree.label.text()
        .fontsize(12)
        .height(window.innerHeight*0.68/(numCommas+1))
            )
        .layout(tnt.tree.layout.vertical()
        .width(window.innerWidth*0.58)
        .scale(false)
            );
    tree(treemaker);
    }

function submitNewick ()
{
  document.getElementById("errorspot").innerHTML = "";
  var newick=document.getElementById("userInput").value;
  makeTree(newick);
}

function resetPar() {
  numOpenPar=0;
  numClosedPar=0;
}

function submitFile() {
    document.getElementById("errorspot").innerHTML = "";
    var fileInput = document.getElementById("fileInput")
    console.log(fileInput.files[0])
    var newick = ''

    var file = fileInput.files[0]
    var reader = new FileReader()

    reader.onload = function(e) {
        newick = reader.result
        makeTree(newick);
    }
    reader.readAsText(file);
}

function updateVertical()
{
            tree.layout(tnt.tree.layout.vertical().width(window.innerWidth*0.58).scale(false));
            tree.update();
}

function updateRadial()
{
  {
            tree.layout(tnt.tree.layout.radial().width(Math.min(window.innerWidth*0.58, window.innerHeight*0.58)).scale(false));
            tree.update();
        }
}

 function download () {
        var pngExporter = tnt.utils.png()
            .filename("treeSample.png")
        pngExporter(d3.select("svg"));
    };

/*dynamic resizing*/
$(window).resize(function() {
  var newick=document.getElementById("userInput").value;
  makeTree(newick);
});

if (clickoption == 0)
  {
tree.on ("click", function(node){
        node.toggle();
        tree.update();
    });
  }

if (clickoption == 1)
{
tree.on("click", function (d) {
                tnt.tooltip.table()
                    .width(120)
                    .call(this, {
                        "header" : "Node",
                        "rows" : [
                            {"label": "id", "value": d.id()}
                        ]
                    })
            })
}<|endoftext|>


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

function ShadeLayerPart ( context , z ) {

    this.context    = context;
    this.assets     = context.assets;
    this.gl         = context.assets.ctx;

    this.tex        = null;
    this.data       = null;
    this.w          = 0;
    this.h          = 0;

    this.resolution = context.coordS.Resolution ( z );
}

//---------------------------------------------------------------------------

ShadeLayerPart.prototype.dataReady = function(){

    if(this.data.content){
        return true
    }
    else{
        this.data.tryToFillContent()

        if(this.data.content){
            this.prepare()
            return true
        }
    }

    return false;
}

//---------------------------------------------------------------------------

ShadeLayerPart.prototype.Init = function ( data ) {
    if (this.tex)
        return;

    console.log("init shade")

    if (data) {
        var newV                   = []
        /*
      for (var y = 255 ; y >= 0 ; y-- ) {
         for (var x = 0 ; x < 256 ; x++ ) {
            newV.push(data[y + x * 256] & 255)
            newV.push((data[y + x * 256] >> 8) & 255)
            newV.push(0)
         }
      }
      var byteArray              = new Uint8Array        ( newV );
         */
        /*
      for (var y = 0 ; y <= 256 ; y++ ) {
         for (var x = 0 ; x < 256 ; x++ ) {
            newV.push(data [y * 256 + x ] & 255)
            newV.push((data[y * 256 + x ] >> 8) & 255)
            newV.push(0)
         }
      }
      var byteArray              = new Uint8Array        ( newV );
         */
        /*
      var byteArray              = new Uint8Array        ( data['s'] );
      this.w                     = 256;
      this.h                     = 256;
      this.data                  = byteArray;
         */
        var byteArray              = new Uint8Array        ( data );
        var nl = []
        for ( var i = 0 ; i < Maperial.tileSize*Maperial.tileSize*2 ; i = i+2 ) {

            var a = ( byteArray[i] / 255.0 ) * 2.0 - 1.0;
            var b = ( byteArray[i+1] / 255.0 ) * 2.0 - 1.0;
            var tmp = - (a*a) - (b*b) + 1.0
            var c = Math.sqrt( tmp );

            var tt = (a*a) + (b*b) + (c*c);

            nl.push(  Math.ceil( ((a + 1.0)/2.0) * Maperial.tileSize-1));
            nl.push(  Math.ceil( ((b + 1.0)/2.0) * Maperial.tileSize-1));
            nl.push(  Math.ceil( ((c + 1.0)/2.0) * Maperial.tileSize-1));
        }
        this.data = new Uint8Array  (nl)
        this.w                     = Maperial.tileSize;
        this.h                     = Maperial.tileSize;
    }
}

ShadeLayerPart.prototype.reset = function (  ) {
    var gl = this.gl;
    if (this.tex) {
        gl.deleteTexture ( this.tex );
        delete this.tex;
        this.tex = null;
    }
}

ShadeLayerPart.prototype.release = function (  ) {
    var gl = this.gl;
    if (this.tex) {
        gl.deleteTexture ( this.tex );
        delete this.tex;
        this.tex = null;
    }
    if (this.data) {
        delete this.data;
        this.data = null;
    }
}

ShadeLayerPart.prototype.IsUpToDate = function ( ) {
    return this.tex != null;
}

ShadeLayerPart.prototype.update = function ( params ) {
    if (this.tex)
        return 0;

    var date    = (new Date)
    var startT  = date.getTime()

    var gl = this.gl;

    if ( this.data ) {
        var gltools                = new GLTools ()
        var fbtx                   = gltools.CreateFrameBufferTex(gl,this.w,this.h)
        var tmpTex                 = gl.createTexture (      );
        this.tex                   = fbtx[1];
        gl.bindTexture             (gl.TEXTURE_2D, tmpTex);
        gl.pixelStorei             (gl.UNPACK_FLIP_Y_WEBGL  , false );
        gl.texImage2D              (gl.TEXTURE_2D, 0, gl.RGB, this.w , this.h, 0, gl.RGB, gl.UNSIGNED_BYTE, this.data)
        gl.texParameteri           (gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
        gl.texParameteri           (gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
        gl.texParameteri           (gl.TEXTURE_2D, gl.TEXTURE_WRAP_S    , gl.CLAMP_TO_EDGE);
        gl.texParameteri           (gl.TEXTURE_2D, gl.TEXTURE_WRAP_T    , gl.CLAMP_TO_EDGE);

        gl.bindFramebuffer         ( gl.FRAMEBUFFER, fbtx[0] );
        this.gl.clearColor         ( 1.0, 1.0,1.0, 1.0  );
        this.gl.disable            ( this.gl.DEPTH_TEST  );
        gl.viewport                ( 0, 0, fbtx[0].width, fbtx[0].height);
        gl.clear                   ( gl.COLOR_BUFFER_BIT );

        var mvMatrix               = mat4.create();
        var pMatrix                = mat4.create();
        mat4.identity              ( mvMatrix );
        mat4.scale                 ( mvMatrix, [this.w  / Maperial.tileSize , this.h / Maperial.tileSize, 1.0] );
        mat4.identity              ( pMatrix );
        mat4.ortho                 ( 0, fbtx[0].width , 0, fbtx[0].height, 0, 1, pMatrix ); // Y swap !

        var prog                   = this.assets.prog[ "Shade" ]

        gl.useProgram              (prog);
        gl.uniformMatrix4fv        (prog.params.pMatrixUniform.name , false, pMatrix);
        gl.uniformMatrix4fv        (prog.params.mvMatrixUniform.name, false, mvMatrix);
        gl.bindBuffer              (gl.ARRAY_BUFFER, this.assets.squareVertexPositionBuffer);
        gl.enableVertexAttribArray (prog.attr.vertexPositionAttribute);
        gl.vertexAttribPointer     (prog.attr.vertexPositionAttribute, this.assets.squareVertexPositionBuffer.itemSize, gl.FLOAT, false, 0, 0);

        gl.bindBuffer              (gl.ARRAY_BUFFER, this.assets.squareVertexTextureBuffer);
        gl.enableVertexAttribArray (prog.attr.textureCoordAttribute);
        gl.vertexAttribPointer     (prog.attr.textureCoordAttribute, this.assets.squareVertexTextureBuffer.itemSize, gl.FLOAT, false, 0, 0);

        gl.activeTexture           (gl.TEXTURE0);
        gl.bindTexture             (gl.TEXTURE_2D, tmpTex);
        gl.uniform1i               (prog.params.uSamplerTex1.name, 0);

        gl.uniform3fv              (prog.params.uLight.name   , [-params.uLight[0],-params.uLight[1],-params.uLight[2]]);
        gl.uniform1f               (prog.params.uScale.name   , params.scale);
        //gl.uniform3fv              (prog.params.uLight.name   , [0.0,0.0,-50.0] );
        //gl.uniform1f               (prog.params.uScale.name   , 1);

        gl.uniform1f               (prog.params.uPixRes.name  , this.resolution );

        gl.drawArrays              (gl.TRIANGLE_STRIP, 0, this.assets.squareVertexPositionBuffer.numItems);

        gl.bindFramebuffer         ( gl.FRAMEBUFFER, null );
        gl.activeTexture           (gl.TEXTURE0);
        gl.bindTexture             (gl.TEXTURE_2D, null );

        gl.deleteTexture           (tmpTex);
        gl.deleteFramebuffer       (fbtx[0]);
    }
    else { // create fake
        this.tex             = gl.createTexture();
        gl.bindTexture       ( gl.TEXTURE_2D           , this.tex     );
        gl.pixelStorei       ( gl.UNPACK_FLIP_Y_WEBGL  , false        );
        var byteArray        = new Uint8Array        ( [1,1,1,0 , 1,1,1,0 , 1,1,1,0 , 1,1,1,0] );
        gl.texImage2D        ( gl.TEXTURE_2D           , 0                           , gl.RGBA, 2 , 2, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray)
        gl.texParameteri     ( gl.TEXTURE_2D           , gl.TEXTURE_MAG_FILTER  , gl.NEAREST );
        gl.texParameteri     ( gl.TEXTURE_2D           , gl.TEXTURE_MIN_FILTER  , gl.NEAREST );
        gl.bindTexture       ( gl.TEXTURE_2D           , null         );
        this.w = 2;
        this.h = 2;
    }

    var diffT   = date.getTime() - startT;
    return diffT
}

//------------------------------------------------------------------//

module.exports = ShadeLayerPart;
<commit_msg>Refactoring logger a little more<commit_after>
//---------------------------------------------------------------------------

function ShadeLayerPart ( context , z ) {

    this.context    = context;
    this.assets     = context.assets;
    this.gl         = context.assets.ctx;

    this.tex        = null;
    this.data       = null;
    this.w          = 0;
    this.h          = 0;

    this.resolution = context.coordS.Resolution ( z );
}

//---------------------------------------------------------------------------

ShadeLayerPart.prototype.dataReady = function(){

    if(! this.data){
        return false
    }

    if(this.data.content){
        return true
    }
    else{
        this.data.tryToFillContent()

        if(this.data.content){
            this.prepare()
            return true
        }
    }

    return false;
}

//---------------------------------------------------------------------------

ShadeLayerPart.prototype.Init = function ( data ) {
    if (this.tex)
        return;

    console.log("init shade")

    if (data) {
        var newV                   = []
        /*
      for (var y = 255 ; y >= 0 ; y-- ) {
         for (var x = 0 ; x < 256 ; x++ ) {
            newV.push(data[y + x * 256] & 255)
            newV.push((data[y + x * 256] >> 8) & 255)
            newV.push(0)
         }
      }
      var byteArray              = new Uint8Array        ( newV );
         */
        /*
      for (var y = 0 ; y <= 256 ; y++ ) {
         for (var x = 0 ; x < 256 ; x++ ) {
            newV.push(data [y * 256 + x ] & 255)
            newV.push((data[y * 256 + x ] >> 8) & 255)
            newV.push(0)
         }
      }
      var byteArray              = new Uint8Array        ( newV );
         */
        /*
      var byteArray              = new Uint8Array        ( data['s'] );
      this.w                     = 256;
      this.h                     = 256;
      this.data                  = byteArray;
         */
        var byteArray              = new Uint8Array        ( data );
        var nl = []
        for ( var i = 0 ; i < Maperial.tileSize*Maperial.tileSize*2 ; i = i+2 ) {

            var a = ( byteArray[i] / 255.0 ) * 2.0 - 1.0;
            var b = ( byteArray[i+1] / 255.0 ) * 2.0 - 1.0;
            var tmp = - (a*a) - (b*b) + 1.0
            var c = Math.sqrt( tmp );

            var tt = (a*a) + (b*b) + (c*c);

            nl.push(  Math.ceil( ((a + 1.0)/2.0) * Maperial.tileSize-1));
            nl.push(  Math.ceil( ((b + 1.0)/2.0) * Maperial.tileSize-1));
            nl.push(  Math.ceil( ((c + 1.0)/2.0) * Maperial.tileSize-1));
        }
        this.data = new Uint8Array  (nl)
        this.w                     = Maperial.tileSize;
        this.h                     = Maperial.tileSize;
    }
}

ShadeLayerPart.prototype.reset = function (  ) {
    var gl = this.gl;
    if (this.tex) {
        gl.deleteTexture ( this.tex );
        delete this.tex;
        this.tex = null;
    }
}

ShadeLayerPart.prototype.release = function (  ) {
    var gl = this.gl;
    if (this.tex) {
        gl.deleteTexture ( this.tex );
        delete this.tex;
        this.tex = null;
    }
    if (this.data) {
        delete this.data;
        this.data = null;
    }
}

ShadeLayerPart.prototype.IsUpToDate = function ( ) {
    return this.tex != null;
}

ShadeLayerPart.prototype.update = function ( params ) {
    if (this.tex)
        return 0;

    var date    = (new Date)
    var startT  = date.getTime()

    var gl = this.gl;

    if ( this.data ) {
        var gltools                = new GLTools ()
        var fbtx                   = gltools.CreateFrameBufferTex(gl,this.w,this.h)
        var tmpTex                 = gl.createTexture (      );
        this.tex                   = fbtx[1];
        gl.bindTexture             (gl.TEXTURE_2D, tmpTex);
        gl.pixelStorei             (gl.UNPACK_FLIP_Y_WEBGL  , false );
        gl.texImage2D              (gl.TEXTURE_2D, 0, gl.RGB, this.w , this.h, 0, gl.RGB, gl.UNSIGNED_BYTE, this.data)
        gl.texParameteri           (gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
        gl.texParameteri           (gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
        gl.texParameteri           (gl.TEXTURE_2D, gl.TEXTURE_WRAP_S    , gl.CLAMP_TO_EDGE);
        gl.texParameteri           (gl.TEXTURE_2D, gl.TEXTURE_WRAP_T    , gl.CLAMP_TO_EDGE);

        gl.bindFramebuffer         ( gl.FRAMEBUFFER, fbtx[0] );
        this.gl.clearColor         ( 1.0, 1.0,1.0, 1.0  );
        this.gl.disable            ( this.gl.DEPTH_TEST  );
        gl.viewport                ( 0, 0, fbtx[0].width, fbtx[0].height);
        gl.clear                   ( gl.COLOR_BUFFER_BIT );

        var mvMatrix               = mat4.create();
        var pMatrix                = mat4.create();
        mat4.identity              ( mvMatrix );
        mat4.scale                 ( mvMatrix, [this.w  / Maperial.tileSize , this.h / Maperial.tileSize, 1.0] );
        mat4.identity              ( pMatrix );
        mat4.ortho                 ( 0, fbtx[0].width , 0, fbtx[0].height, 0, 1, pMatrix ); // Y swap !

        var prog                   = this.assets.prog[ "Shade" ]

        gl.useProgram              (prog);
        gl.uniformMatrix4fv        (prog.params.pMatrixUniform.name , false, pMatrix);
        gl.uniformMatrix4fv        (prog.params.mvMatrixUniform.name, false, mvMatrix);
        gl.bindBuffer              (gl.ARRAY_BUFFER, this.assets.squareVertexPositionBuffer);
        gl.enableVertexAttribArray (prog.attr.vertexPositionAttribute);
        gl.vertexAttribPointer     (prog.attr.vertexPositionAttribute, this.assets.squareVertexPositionBuffer.itemSize, gl.FLOAT, false, 0, 0);

        gl.bindBuffer              (gl.ARRAY_BUFFER, this.assets.squareVertexTextureBuffer);
        gl.enableVertexAttribArray (prog.attr.textureCoordAttribute);
        gl.vertexAttribPointer     (prog.attr.textureCoordAttribute, this.assets.squareVertexTextureBuffer.itemSize, gl.FLOAT, false, 0, 0);

        gl.activeTexture           (gl.TEXTURE0);
        gl.bindTexture             (gl.TEXTURE_2D, tmpTex);
        gl.uniform1i               (prog.params.uSamplerTex1.name, 0);

        gl.uniform3fv              (prog.params.uLight.name   , [-params.uLight[0],-params.uLight[1],-params.uLight[2]]);
        gl.uniform1f               (prog.params.uScale.name   , params.scale);
        //gl.uniform3fv              (prog.params.uLight.name   , [0.0,0.0,-50.0] );
        //gl.uniform1f               (prog.params.uScale.name   , 1);

        gl.uniform1f               (prog.params.uPixRes.name  , this.resolution );

        gl.drawArrays              (gl.TRIANGLE_STRIP, 0, this.assets.squareVertexPositionBuffer.numItems);

        gl.bindFramebuffer         ( gl.FRAMEBUFFER, null );
        gl.activeTexture           (gl.TEXTURE0);
        gl.bindTexture             (gl.TEXTURE_2D, null );

        gl.deleteTexture           (tmpTex);
        gl.deleteFramebuffer       (fbtx[0]);
    }
    else { // create fake
        this.tex             = gl.createTexture();
        gl.bindTexture       ( gl.TEXTURE_2D           , this.tex     );
        gl.pixelStorei       ( gl.UNPACK_FLIP_Y_WEBGL  , false        );
        var byteArray        = new Uint8Array        ( [1,1,1,0 , 1,1,1,0 , 1,1,1,0 , 1,1,1,0] );
        gl.texImage2D        ( gl.TEXTURE_2D           , 0                           , gl.RGBA, 2 , 2, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray)
        gl.texParameteri     ( gl.TEXTURE_2D           , gl.TEXTURE_MAG_FILTER  , gl.NEAREST );
        gl.texParameteri     ( gl.TEXTURE_2D           , gl.TEXTURE_MIN_FILTER  , gl.NEAREST );
        gl.bindTexture       ( gl.TEXTURE_2D           , null         );
        this.w = 2;
        this.h = 2;
    }

    var diffT   = date.getTime() - startT;
    return diffT
}

//------------------------------------------------------------------//

module.exports = ShadeLayerPart;
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2017 - present Instructure, Inc.
 *
 * This file is part of Canvas.
 *
 * Canvas is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the Free
 * Software Foundation, version 3 of the License.
 *
 * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */

import React from 'react'
import * as enzyme from 'old-enzyme-2.x-you-need-to-upgrade-this-spec-to-enzyme-3.x-by-importing-just-enzyme'
import SyncChange from 'jsx/blueprint_courses/components/SyncChange'
import getSampleData from '../getSampleData'

QUnit.module('SyncChange component')

const defaultProps = () => ({
  change: getSampleData().history[0].changes[0],
})

test('renders the SyncChange component', () => {
  const tree = enzyme.shallow(<SyncChange {...defaultProps()} />)
  const node = tree.find('.bcs__history-item__change')
  ok(node.exists())
})

test('renders the SyncChange component expanded when state.isExpanded = true', () => {
  const props = {...defaultProps(), isLoadingHistory: true}
  const tree = enzyme.shallow(<SyncChange {...props} />)
  tree.setState({ isExpanded: true })
  const node = tree.find('.bcs__history-item__change__expanded')
  ok(node.exists())
})

test('toggles isExpanded on click', () => {
  const props = defaultProps()
  props.isLoadingHistory = true
  const tree = enzyme.shallow(<SyncChange {...props} />)
  tree.at(0).simulate('click')

  const node = tree.find('.bcs__history-item__change__expanded')
  ok(node.exists())
})

test('displays the correct exception count', () => {
  const props = defaultProps()
  const tree = enzyme.shallow(<SyncChange {...props} />)
  const pill = tree.find('.pill')
  equal(pill.at(0).text(), '3 exceptions')
})

test('displays the correct exception types', () => {
  const props = defaultProps()
  props.isLoadingHistory = true
  const tree = enzyme.mount(<SyncChange {...props} />)
  tree.instance().setState({ isExpanded: true })
  const exceptionGroups = tree.find('li.bcs__history-item__change-exceps__group')
  let exceptionGroup = exceptionGroups.at(0).find('span').at(0)
  equal(exceptionGroup.text(), "Points changed exceptions:")
  exceptionGroup = exceptionGroups.at(1).find('span').at(0)
  equal(exceptionGroup.text(), "Content changed exceptions:")
  exceptionGroup = exceptionGroups.at(2).find('span').at(0)
  equal(exceptionGroup.text(), "Deleted content exceptions:")

})
<commit_msg>spec: fix broken enzyme test<commit_after>/*
 * Copyright (C) 2017 - present Instructure, Inc.
 *
 * This file is part of Canvas.
 *
 * Canvas is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the Free
 * Software Foundation, version 3 of the License.
 *
 * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */

import React from 'react'
import { mount, shallow } from 'enzyme'
import SyncChange from 'jsx/blueprint_courses/components/SyncChange'
import getSampleData from '../getSampleData'
import ReactDOM from 'react-dom'
import $ from 'jquery'

QUnit.module('SyncChange component')

const defaultProps = () => ({
  change: getSampleData().history[0].changes[0],
})

test('renders the SyncChange component', () => {
  const tree = shallow(<SyncChange {...defaultProps()} />)
  const node = tree.find('.bcs__history-item__change')
  ok(node.exists())
})

test('renders the SyncChange component expanded when state.isExpanded = true', () => {
  const props = {...defaultProps(), isLoadingHistory: true}
  const tree = shallow(<SyncChange {...props} />)
  tree.setState({ isExpanded: true })
  const node = tree.find('.bcs__history-item__change__expanded')
  ok(node.exists())
})

test('toggles isExpanded on click', () => {
  const props = defaultProps()
  props.isLoadingHistory = true
  const tree = shallow(<SyncChange {...props} />)
  tree.at(0).simulate('click')

  const node = tree.find('.bcs__history-item__change__expanded')
  ok(node.exists())
})

test('displays the correct exception count', () => {
  const props = defaultProps()
  const tree = shallow(<SyncChange {...props} />)
  const pill = tree.find('.pill')
  equal(pill.at(0).text(), '3 exceptions')
})

test('displays the correct exception types', () => {
  const props = defaultProps()
  props.isLoadingHistory = true
  ReactDOM.render(<SyncChange {...props} />, document.getElementById("fixtures"))
  $(".bcs__history-item__content button").click()
  const exceptionGroups = $("li.bcs__history-item__change-exceps__group")
  let exceptionGroup = exceptionGroups.first()
  equal(exceptionGroup.text(), "Points changed exceptions:Default Term - Course 1")
  exceptionGroup = $(exceptionGroups[1])
  equal(exceptionGroup.text(), "Content changed exceptions:Default Term - Course 5")
  exceptionGroup = $(exceptionGroups[2])
  equal(exceptionGroup.text(), "Deleted content exceptions:Default Term - Course 56")
  ReactDOM.unmountComponentAtNode(document.getElementById("fixtures"))
})
<|endoftext|>


<commit_before>import {Map} from 'immutable';
import {createReducer} from 'redux-immutablejs';
import {updateIntl} from 'react-intl-redux';

import i18n from './../../utils/i18n';

export const SET_APP_LOCALE = 'garchen-panel/main/SET_APP_LOCALE';
export const OPEN_EXTERNAL = 'garchen-panel/main/OPEN_EXTERNAL';
export const OPEN_EXTERNAL_SUCCESS = 'garchen-panel/main/OPEN_EXTERNAL_SUCCESS';
export const OPEN_EXTERNAL_FAIL = 'garchen-panel/main/OPEN_EXTERNAL_FAIL';
export const SET_WRITE_DELAY = 'garchen-panel/main/SET_WRITE_DELAY';
export const SET_APP_FONT = 'garchen-panel/main/SET_APP_FONT';
export const SET_INTERFACE_FONT_SIZE_SCALING_FACTOR = 'garchen/main/SET_INTERFACE_FONT_SIZE_SCALING_FACTOR';
export const SET_CONTENT_FONT_SIZE_SCALING_FACTOR = 'garchen/main/SET_CONTENT_FONT_SIZE_SCALING_FACTOR';
export const GET_APP_VERSION = 'garchen-panel/main/GET_APP_VERSION';
export const GET_APP_VERSION_SUCCESS = 'garchen-panel/main/GET_APP_VERSION_SUCCESS';
export const GET_APP_VERSION_FAIL = 'garchen-panel/main/GET_APP_VERSION_FAIL';

const initialState = Map({
  appVersion: '',
  appLocale: 'en',
  appFont: 'Tibetan Machine Uni',
  writeDelay: 50
});

export default createReducer(initialState, {

  [SET_APP_LOCALE]: (state, action) => {
    return state.set('appLocale', action.appLocale);
  },

  [SET_WRITE_DELAY]: (state, action) => {
    return state.set('writeDelay', action.writeDelay);
  },

  [SET_APP_FONT]: (state, action) => {
    return state.set('appFont', action.appFont);
  },

  [GET_APP_VERSION_SUCCESS]: (state, action) => {
    return state.set('appVersion', action.result.appVersion);
  }
});

export function setAppFont(appFont) {
  return {
    type: SET_APP_FONT,
    appFont
  };
}

export function setAppLocale(appLocale) {
  return {
    type: SET_APP_LOCALE,
    appLocale
  };
}

export function setWriteDelay(writeDelay) {
  return {
    type: SET_WRITE_DELAY,
    writeDelay
  };
}

export function setIntl(locale = 'en') {
  return (dispatch) => {
    dispatch(setAppLocale(locale));
    return dispatch(updateIntl({
      locale,
      messages: i18n.getLocaleData(locale)
    }));
  };
}

export function openExternal(url) {
  return {
    types: [OPEN_EXTERNAL, OPEN_EXTERNAL_SUCCESS, OPEN_EXTERNAL_FAIL],
    promise: (client) => {
      return client.send('open-external', {url});
    }
  };
}

export function getAppVersion() {
  return {
    types: [GET_APP_VERSION, GET_APP_VERSION_SUCCESS, GET_APP_VERSION_FAIL],
    promise: (client) => {
      return client.send('get-app-version');
    }
  };
}
<commit_msg>add const ADD_ROUTE_HISTORY<commit_after>import {Map} from 'immutable';
import {createReducer} from 'redux-immutablejs';
import {updateIntl} from 'react-intl-redux';

import i18n from './../../utils/i18n';

export const SET_APP_LOCALE = 'garchen-panel/main/SET_APP_LOCALE';
export const OPEN_EXTERNAL = 'garchen-panel/main/OPEN_EXTERNAL';
export const OPEN_EXTERNAL_SUCCESS = 'garchen-panel/main/OPEN_EXTERNAL_SUCCESS';
export const OPEN_EXTERNAL_FAIL = 'garchen-panel/main/OPEN_EXTERNAL_FAIL';
export const SET_WRITE_DELAY = 'garchen-panel/main/SET_WRITE_DELAY';
export const SET_APP_FONT = 'garchen-panel/main/SET_APP_FONT';
export const SET_INTERFACE_FONT_SIZE_SCALING_FACTOR = 'garchen/main/SET_INTERFACE_FONT_SIZE_SCALING_FACTOR';
export const SET_CONTENT_FONT_SIZE_SCALING_FACTOR = 'garchen/main/SET_CONTENT_FONT_SIZE_SCALING_FACTOR';
export const GET_APP_VERSION = 'garchen-panel/main/GET_APP_VERSION';
export const GET_APP_VERSION_SUCCESS = 'garchen-panel/main/GET_APP_VERSION_SUCCESS';
export const GET_APP_VERSION_FAIL = 'garchen-panel/main/GET_APP_VERSION_FAIL';
export const ADD_ROUTE_HISTORY = 'garchen-panel/main/ADD_ROUTE_HISTORY';

const initialState = Map({
  appVersion: '',
  appLocale: 'en',
  appFont: 'Tibetan Machine Uni',
  writeDelay: 50
});

export default createReducer(initialState, {

  [SET_APP_LOCALE]: (state, action) => {
    return state.set('appLocale', action.appLocale);
  },

  [SET_WRITE_DELAY]: (state, action) => {
    return state.set('writeDelay', action.writeDelay);
  },

  [SET_APP_FONT]: (state, action) => {
    return state.set('appFont', action.appFont);
  },

  [GET_APP_VERSION_SUCCESS]: (state, action) => {
    return state.set('appVersion', action.result.appVersion);
  }
});

export function setAppFont(appFont) {
  return {
    type: SET_APP_FONT,
    appFont
  };
}

export function setAppLocale(appLocale) {
  return {
    type: SET_APP_LOCALE,
    appLocale
  };
}

export function setWriteDelay(writeDelay) {
  return {
    type: SET_WRITE_DELAY,
    writeDelay
  };
}

export function setIntl(locale = 'en') {
  return (dispatch) => {
    dispatch(setAppLocale(locale));
    return dispatch(updateIntl({
      locale,
      messages: i18n.getLocaleData(locale)
    }));
  };
}

export function openExternal(url) {
  return {
    types: [OPEN_EXTERNAL, OPEN_EXTERNAL_SUCCESS, OPEN_EXTERNAL_FAIL],
    promise: (client) => {
      return client.send('open-external', {url});
    }
  };
}

export function getAppVersion() {
  return {
    types: [GET_APP_VERSION, GET_APP_VERSION_SUCCESS, GET_APP_VERSION_FAIL],
    promise: (client) => {
      return client.send('get-app-version');
    }
  };
}
<|endoftext|>


<commit_before>import Renderable from "./renderable.js";
import collision from "./../physics/collision.js";
import Body from "./../physics/body.js";
import level from "./../level/level.js";
import { world, viewport } from "./../game.js";
import pool from "./../system/pooling.js";

/**
 * @classdesc
 * trigger an event when colliding with another object
 * @augments Renderable
 */
class Trigger extends Renderable {
    /**
     * @param {number} x the x coordinates of the trigger area
     * @param {number} y the y coordinates of the trigger area
     * @param {number} [settings.width] width of the trigger area
     * @param {number} [settings.height] height of the trigger area
     * @param {Rect[]|Polygon[]|Line[]|Ellipse[]} [settings.shapes] collision shape(s) that will trigger the event
     * @param {string} [settings.duration] Fade duration (in ms)
     * @param {string|Color} [settings.color] Fade color
     * @param {string} [settings.event="level"] the type of event to trigger (only "level" supported for now)
     * @param {string} [settings.to] level to load if level trigger
     * @param {string|Container} [settings.container] Target container. See {@link level.load}
     * @param {Function} [settings.onLoaded] Level loaded callback. See {@link level.load}
     * @param {boolean} [settings.flatten] Flatten all objects into the target container. See {@link level.load}
     * @param {boolean} [settings.setViewportBounds] Resize the viewport to match the level. See {@link level.load}
     * @example
     * me.game.world.addChild(new me.Trigger(
     *     x, y, {
     *         shapes: [new me.Rect(0, 0, 100, 100)],
     *         "duration" : 250,
     *         "color" : "#000",
     *         "to" : "mymap2"
     *     }
     * ));
     */
    constructor(x, y, settings) {
        // call the parent constructor
        super(x, y, settings.width || 0, settings.height || 0);

        // for backward compatibility
        this.anchorPoint.set(0, 0);

        this.fade = settings.fade;
        this.duration = settings.duration;
        this.fading = false;

        // Tiled Settings
        this.name = "Trigger";
        this.type = settings.type;
        this.id = settings.id;

        // a temp variable
        this.gotolevel = settings.to;

        // Collect the defined trigger settings
        this.triggerSettings = {
            // the default (and only for now) action
            event: "level"
        };

        [ "type", "container", "onLoaded", "flatten", "setViewportBounds", "to" ].forEach(function(property) {
            if (typeof settings[property] !== "undefined") {
                this.triggerSettings[property] = settings[property];
            }
        }.bind(this));

        // add and configure the physic body
        var shape = settings.shapes;
        if (typeof shape === "undefined") {
            shape = pool.pull("Polygon", 0, 0, [
                pool.pull("Vector2d", 0,          0),
                pool.pull("Vector2d", this.width, 0),
                pool.pull("Vector2d", this.width, this.height)
            ]);
        }
        this.body = new Body(this, shape);
        this.body.collisionType = collision.types.ACTION_OBJECT;
        // by default only collides with PLAYER_OBJECT
        this.body.setCollisionMask(collision.types.PLAYER_OBJECT);
        this.body.setStatic(true);
        this.resize(this.body.getBounds().width, this.body.getBounds().height);
    }

    /**
     * @ignore
     */
     getTriggerSettings() {
         // Lookup for the container instance
         if (typeof(this.triggerSettings.container) === "string") {
             this.triggerSettings.container = world.getChildByName(this.triggerSettings.container)[0];
         }
         return this.triggerSettings;
     }

    /**
     * @ignore
     */
    onFadeComplete() {
        level.load(this.gotolevel, this.getTriggerSettings());
        viewport.fadeOut(this.fade, this.duration);
    }

    /**
     * trigger this event
     * @name triggerEvent
     * @memberof Trigger
     * @protected
     */
    triggerEvent() {
        var triggerSettings = this.getTriggerSettings();

        if (triggerSettings.event === "level") {
            this.gotolevel = triggerSettings.to;
            // load a level
            //console.log("going to : ", to);
            if (this.fade && this.duration) {
                if (!this.fading) {
                    this.fading = true;
                    viewport.fadeIn(this.fade, this.duration,
                            this.onFadeComplete.bind(this));
                }
            } else {
                level.load(this.gotolevel, triggerSettings);
            }
        } else {
            throw new Error("Trigger invalid type");
        }
    }

    /**
     * onCollision callback, triggered in case of collision with this trigger
     * @name onCollision
     * @memberof Renderable
     * @param {ResponseObject} response the collision response object
     * @param {Renderable} other the other renderable touching this one (a reference to response.a or response.b)
     * @returns {boolean} true if the object should respond to the collision (its position and velocity will be corrected)
     */
    onCollision(response, other) { // eslint-disable-line no-unused-vars
        if (this.name === "Trigger") {
            this.triggerEvent.apply(this);
        }
        return false;
    }

};

export default Trigger;
<commit_msg>webdoc: fix duplicate `onCollision` entry for Renderable<commit_after>import Renderable from "./renderable.js";
import collision from "./../physics/collision.js";
import Body from "./../physics/body.js";
import level from "./../level/level.js";
import { world, viewport } from "./../game.js";
import pool from "./../system/pooling.js";

/**
 * @classdesc
 * trigger an event when colliding with another object
 * @augments Renderable
 */
class Trigger extends Renderable {
    /**
     * @param {number} x the x coordinates of the trigger area
     * @param {number} y the y coordinates of the trigger area
     * @param {number} [settings.width] width of the trigger area
     * @param {number} [settings.height] height of the trigger area
     * @param {Rect[]|Polygon[]|Line[]|Ellipse[]} [settings.shapes] collision shape(s) that will trigger the event
     * @param {string} [settings.duration] Fade duration (in ms)
     * @param {string|Color} [settings.color] Fade color
     * @param {string} [settings.event="level"] the type of event to trigger (only "level" supported for now)
     * @param {string} [settings.to] level to load if level trigger
     * @param {string|Container} [settings.container] Target container. See {@link level.load}
     * @param {Function} [settings.onLoaded] Level loaded callback. See {@link level.load}
     * @param {boolean} [settings.flatten] Flatten all objects into the target container. See {@link level.load}
     * @param {boolean} [settings.setViewportBounds] Resize the viewport to match the level. See {@link level.load}
     * @example
     * me.game.world.addChild(new me.Trigger(
     *     x, y, {
     *         shapes: [new me.Rect(0, 0, 100, 100)],
     *         "duration" : 250,
     *         "color" : "#000",
     *         "to" : "mymap2"
     *     }
     * ));
     */
    constructor(x, y, settings) {
        // call the parent constructor
        super(x, y, settings.width || 0, settings.height || 0);

        // for backward compatibility
        this.anchorPoint.set(0, 0);

        this.fade = settings.fade;
        this.duration = settings.duration;
        this.fading = false;

        // Tiled Settings
        this.name = "Trigger";
        this.type = settings.type;
        this.id = settings.id;

        // a temp variable
        this.gotolevel = settings.to;

        // Collect the defined trigger settings
        this.triggerSettings = {
            // the default (and only for now) action
            event: "level"
        };

        [ "type", "container", "onLoaded", "flatten", "setViewportBounds", "to" ].forEach(function(property) {
            if (typeof settings[property] !== "undefined") {
                this.triggerSettings[property] = settings[property];
            }
        }.bind(this));

        // add and configure the physic body
        var shape = settings.shapes;
        if (typeof shape === "undefined") {
            shape = pool.pull("Polygon", 0, 0, [
                pool.pull("Vector2d", 0,          0),
                pool.pull("Vector2d", this.width, 0),
                pool.pull("Vector2d", this.width, this.height)
            ]);
        }
        this.body = new Body(this, shape);
        this.body.collisionType = collision.types.ACTION_OBJECT;
        // by default only collides with PLAYER_OBJECT
        this.body.setCollisionMask(collision.types.PLAYER_OBJECT);
        this.body.setStatic(true);
        this.resize(this.body.getBounds().width, this.body.getBounds().height);
    }

    /**
     * @ignore
     */
     getTriggerSettings() {
         // Lookup for the container instance
         if (typeof(this.triggerSettings.container) === "string") {
             this.triggerSettings.container = world.getChildByName(this.triggerSettings.container)[0];
         }
         return this.triggerSettings;
     }

    /**
     * @ignore
     */
    onFadeComplete() {
        level.load(this.gotolevel, this.getTriggerSettings());
        viewport.fadeOut(this.fade, this.duration);
    }

    /**
     * trigger this event
     * @name triggerEvent
     * @memberof Trigger
     * @protected
     */
    triggerEvent() {
        var triggerSettings = this.getTriggerSettings();

        if (triggerSettings.event === "level") {
            this.gotolevel = triggerSettings.to;
            // load a level
            //console.log("going to : ", to);
            if (this.fade && this.duration) {
                if (!this.fading) {
                    this.fading = true;
                    viewport.fadeIn(this.fade, this.duration,
                            this.onFadeComplete.bind(this));
                }
            } else {
                level.load(this.gotolevel, triggerSettings);
            }
        } else {
            throw new Error("Trigger invalid type");
        }
    }

    /**
     * onCollision callback, triggered in case of collision with this trigger
     * @name onCollision
     * @memberof Trigger
     * @param {ResponseObject} response the collision response object
     * @param {Renderable} other the other renderable touching this one (a reference to response.a or response.b)
     * @returns {boolean} true if the object should respond to the collision (its position and velocity will be corrected)
     */
    onCollision(response, other) { // eslint-disable-line no-unused-vars
        if (this.name === "Trigger") {
            this.triggerEvent.apply(this);
        }
        return false;
    }

};

export default Trigger;
<|endoftext|>


<commit_before>var STATE = (function(){
  var ROOT = {};

  // ---------------
  // State variables
  // ---------------

  var FILE;
  var MSGS;

  var filterFunction;
  var selectedChannel;
  var currentPage;
  var messagesPerPage;

  // ----------------------------------
  // Channel and message refresh events
  // ----------------------------------

  var eventOnChannelsRefreshed;
  var eventOnMessagesRefreshed;
  var eventOnUsersRefreshed;

  var triggerChannelsRefreshed = function(selectedChannel){
    eventOnChannelsRefreshed && eventOnChannelsRefreshed(ROOT.getChannelList(), selectedChannel);
  };

  var triggerMessagesRefreshed = function(){
    eventOnMessagesRefreshed && eventOnMessagesRefreshed(ROOT.getMessageList());
  };

  var triggerUsersRefreshed = function(){
    eventOnUsersRefreshed && eventOnUsersRefreshed(ROOT.getUserList());
  };

  ROOT.onChannelsRefreshed = function(callback){
    eventOnChannelsRefreshed = callback;
  };

  ROOT.onMessagesRefreshed = function(callback){
    eventOnMessagesRefreshed = callback;
  };

  ROOT.onUsersRefreshed = function(callback){
    eventOnUsersRefreshed = callback;
  };

  // ------------------------------------
  // File upload and basic data retrieval
  // ------------------------------------

  ROOT.uploadFile = function(file){
    FILE = file;
    MSGS = null;

    selectedChannel = null;
    currentPage = 1;

    triggerUsersRefreshed();
    triggerChannelsRefreshed();
    triggerMessagesRefreshed();
  };

  ROOT.getChannelName = function(channel){
    return FILE.getChannelById(channel).name;
  };

  ROOT.getUserName = function(user){
    return FILE.getUserById(user).name;
  };

  // --------------------------
  // Channel list and selection
  // --------------------------

  var getFilteredMessageKeys = function(channel){
    var messages = FILE.getMessages(channel);
    var keys = Object.keys(messages);

    if (filterFunction){
      keys = keys.filter(key => filterFunction(messages[key]));
    }

    return keys;
  };

  ROOT.getChannelList = function(){
    if (!FILE){
      return [];
    }

    var channels = FILE.getChannels();

    return Object.keys(channels).map(key => ({
      "id": key,
      "name": channels[key].name,
      "server": FILE.getServer(channels[key].server),
      "msgcount": getFilteredMessageKeys(key).length
    }));
  };

  ROOT.selectChannel = function(channel){
    currentPage = 1;
    selectedChannel = channel;

    MSGS = getFilteredMessageKeys(channel).sort(PROCESSOR.SORTER.oldestToNewest);
    triggerMessagesRefreshed();
  };

  ROOT.getSelectedChannel = function(){
    return selectedChannel;
  };

  // ------------
  // Message list
  // ------------

  ROOT.getMessageList = function(){
    if (!MSGS){
      return [];
    }

    var messages = FILE.getMessages(selectedChannel);
    var startIndex = messagesPerPage*(ROOT.getCurrentPage()-1);

    return MSGS.slice(startIndex, !messagesPerPage ? undefined : startIndex+messagesPerPage).map(key => {
      var message = messages[key];

      return {
        "user": FILE.getUser(message.u),
        "timestamp": message.t,
        "contents": message.m,
        "embeds": message.e,
        "attachments": message.a,
        "edited": (message.f&1) === 1
      };
    });
  };

  // ----------
  // Filtering
  // ----------

  ROOT.setActiveFilter = function(filter){
    switch(filter ? filter.type : ""){
      case "user":
        filterFunction = PROCESSOR.FILTER.byUser(FILE.getUserIndex(filter.value));
        break;

      case "contents":
        filterFunction = PROCESSOR.FILTER.byContents(filter.value);
        break;

      case "withimages":
        filterFunction = PROCESSOR.FILTER.withImages();
        break;

      case "withdownloads":
        filterFunction = PROCESSOR.FILTER.withDownloads();
        break;

      case "edited":
        filterFunction = PROCESSOR.FILTER.isEdited();
        break;

      default:
        filterFunction = null;
        break;
    }

    triggerChannelsRefreshed(selectedChannel);

    if (selectedChannel){
      ROOT.selectChannel(selectedChannel); // resets current page and updates messages
    }
  };

  // -----
  // Users
  // -----

  ROOT.getUserList = function(){
    return FILE ? FILE.getUsers() : [];
  };

  // ----------
  // Pagination
  // ----------

  ROOT.setMessagesPerPage = function(amount){
    messagesPerPage = amount;
    triggerMessagesRefreshed();
  };

  ROOT.updateCurrentPage = function(action){
    switch(action){
      case "first": currentPage = 1; break;
      case "prev": currentPage = Math.max(1, currentPage-1); break;
      case "next": currentPage = Math.min(ROOT.getPageCount(), currentPage+1); break;
      case "last": currentPage = ROOT.getPageCount(); break;

      case "pick":
        var page = parseInt(prompt("Select page:", currentPage), 10);

        if (!page){
          return;
        }

        currentPage = Math.max(1, Math.min(ROOT.getPageCount(), page));
        break;
    }

    triggerMessagesRefreshed();
  };

  ROOT.getCurrentPage = function(){
    var total = ROOT.getPageCount();

    if (currentPage > total && total > 0){
      currentPage = total;
    }

    return currentPage || 1;
  };

  ROOT.getPageCount = function(){
    return !MSGS ? 0 : (!messagesPerPage ? 1 : Math.ceil(MSGS.length/messagesPerPage));
  };

  // --------
  // Settings
  // --------

  ROOT.settings = {};

  var defineSettingProperty = (property, defaultValue) => {
    var name = "_"+property;

    Object.defineProperty(ROOT.settings, property, {
      get: (() => ROOT.settings[name]),
      set: (value => {
        ROOT.settings[name] = value;
        triggerMessagesRefreshed();
      })
    });

    ROOT.settings[name] = defaultValue;
  }

  defineSettingProperty("enableImagePreviews", true);
  defineSettingProperty("enableFormatting", true);

  // End
  return ROOT;
})();
<commit_msg>Allow specifying 0 in the page selection dialog<commit_after>var STATE = (function(){
  var ROOT = {};

  // ---------------
  // State variables
  // ---------------

  var FILE;
  var MSGS;

  var filterFunction;
  var selectedChannel;
  var currentPage;
  var messagesPerPage;

  // ----------------------------------
  // Channel and message refresh events
  // ----------------------------------

  var eventOnChannelsRefreshed;
  var eventOnMessagesRefreshed;
  var eventOnUsersRefreshed;

  var triggerChannelsRefreshed = function(selectedChannel){
    eventOnChannelsRefreshed && eventOnChannelsRefreshed(ROOT.getChannelList(), selectedChannel);
  };

  var triggerMessagesRefreshed = function(){
    eventOnMessagesRefreshed && eventOnMessagesRefreshed(ROOT.getMessageList());
  };

  var triggerUsersRefreshed = function(){
    eventOnUsersRefreshed && eventOnUsersRefreshed(ROOT.getUserList());
  };

  ROOT.onChannelsRefreshed = function(callback){
    eventOnChannelsRefreshed = callback;
  };

  ROOT.onMessagesRefreshed = function(callback){
    eventOnMessagesRefreshed = callback;
  };

  ROOT.onUsersRefreshed = function(callback){
    eventOnUsersRefreshed = callback;
  };

  // ------------------------------------
  // File upload and basic data retrieval
  // ------------------------------------

  ROOT.uploadFile = function(file){
    FILE = file;
    MSGS = null;

    selectedChannel = null;
    currentPage = 1;

    triggerUsersRefreshed();
    triggerChannelsRefreshed();
    triggerMessagesRefreshed();
  };

  ROOT.getChannelName = function(channel){
    return FILE.getChannelById(channel).name;
  };

  ROOT.getUserName = function(user){
    return FILE.getUserById(user).name;
  };

  // --------------------------
  // Channel list and selection
  // --------------------------

  var getFilteredMessageKeys = function(channel){
    var messages = FILE.getMessages(channel);
    var keys = Object.keys(messages);

    if (filterFunction){
      keys = keys.filter(key => filterFunction(messages[key]));
    }

    return keys;
  };

  ROOT.getChannelList = function(){
    if (!FILE){
      return [];
    }

    var channels = FILE.getChannels();

    return Object.keys(channels).map(key => ({
      "id": key,
      "name": channels[key].name,
      "server": FILE.getServer(channels[key].server),
      "msgcount": getFilteredMessageKeys(key).length
    }));
  };

  ROOT.selectChannel = function(channel){
    currentPage = 1;
    selectedChannel = channel;

    MSGS = getFilteredMessageKeys(channel).sort(PROCESSOR.SORTER.oldestToNewest);
    triggerMessagesRefreshed();
  };

  ROOT.getSelectedChannel = function(){
    return selectedChannel;
  };

  // ------------
  // Message list
  // ------------

  ROOT.getMessageList = function(){
    if (!MSGS){
      return [];
    }

    var messages = FILE.getMessages(selectedChannel);
    var startIndex = messagesPerPage*(ROOT.getCurrentPage()-1);

    return MSGS.slice(startIndex, !messagesPerPage ? undefined : startIndex+messagesPerPage).map(key => {
      var message = messages[key];

      return {
        "user": FILE.getUser(message.u),
        "timestamp": message.t,
        "contents": message.m,
        "embeds": message.e,
        "attachments": message.a,
        "edited": (message.f&1) === 1
      };
    });
  };

  // ----------
  // Filtering
  // ----------

  ROOT.setActiveFilter = function(filter){
    switch(filter ? filter.type : ""){
      case "user":
        filterFunction = PROCESSOR.FILTER.byUser(FILE.getUserIndex(filter.value));
        break;

      case "contents":
        filterFunction = PROCESSOR.FILTER.byContents(filter.value);
        break;

      case "withimages":
        filterFunction = PROCESSOR.FILTER.withImages();
        break;

      case "withdownloads":
        filterFunction = PROCESSOR.FILTER.withDownloads();
        break;

      case "edited":
        filterFunction = PROCESSOR.FILTER.isEdited();
        break;

      default:
        filterFunction = null;
        break;
    }

    triggerChannelsRefreshed(selectedChannel);

    if (selectedChannel){
      ROOT.selectChannel(selectedChannel); // resets current page and updates messages
    }
  };

  // -----
  // Users
  // -----

  ROOT.getUserList = function(){
    return FILE ? FILE.getUsers() : [];
  };

  // ----------
  // Pagination
  // ----------

  ROOT.setMessagesPerPage = function(amount){
    messagesPerPage = amount;
    triggerMessagesRefreshed();
  };

  ROOT.updateCurrentPage = function(action){
    switch(action){
      case "first": currentPage = 1; break;
      case "prev": currentPage = Math.max(1, currentPage-1); break;
      case "next": currentPage = Math.min(ROOT.getPageCount(), currentPage+1); break;
      case "last": currentPage = ROOT.getPageCount(); break;

      case "pick":
        var page = parseInt(prompt("Select page:", currentPage), 10);

        if (!page && page !== 0){
          return;
        }

        currentPage = Math.max(1, Math.min(ROOT.getPageCount(), page));
        break;
    }

    triggerMessagesRefreshed();
  };

  ROOT.getCurrentPage = function(){
    var total = ROOT.getPageCount();

    if (currentPage > total && total > 0){
      currentPage = total;
    }

    return currentPage || 1;
  };

  ROOT.getPageCount = function(){
    return !MSGS ? 0 : (!messagesPerPage ? 1 : Math.ceil(MSGS.length/messagesPerPage));
  };

  // --------
  // Settings
  // --------

  ROOT.settings = {};

  var defineSettingProperty = (property, defaultValue) => {
    var name = "_"+property;

    Object.defineProperty(ROOT.settings, property, {
      get: (() => ROOT.settings[name]),
      set: (value => {
        ROOT.settings[name] = value;
        triggerMessagesRefreshed();
      })
    });

    ROOT.settings[name] = defaultValue;
  }

  defineSettingProperty("enableImagePreviews", true);
  defineSettingProperty("enableFormatting", true);

  // End
  return ROOT;
})();
<|endoftext|>


<commit_before>namespace('Sy');

Sy.config = new Sy.Configurator();

Sy.config.set({
    env: 'prod',
    parameters: {},
    storage: {
        engines: {
            rest: function (version, entitiesMeta) {

                var engine = new Sy.Storage.Engine.Rest(version);

                engine.setManager(Sy.service.get('sy::core::http::rest'));
                engine.setPattern('/api/{{version}}/{{path}}/{{key}}');

                for (var i = 0, l = entitiesMeta.length; i < l; i++) {
                    engine.setStore(
                        entitiesMeta[i].name,
                        entitiesMeta[i].name.toLowerCase().replace('::', '/'),
                        entitiesMeta[i].uuid,
                        entitiesMeta[i].indexes
                    );
                }

                return engine;

            },
            indexeddb: function (version, entitiesMeta) {

                var engine =  new Sy.Storage.Engine.IndexedDB(version);

                for (var i = 0, l = entitiesMeta.length; i < l; i++) {
                    engine.setStore(
                        entitiesMeta[i].name,
                        entitiesMeta[i].name.toLowerCase(),
                        entitiesMeta[i].uuid,
                        entitiesMeta[i].indexes.concat(entitiesMeta[i].uuid)
                    );
                }

                engine
                    .setConnection(
                        window.indexedDB ||
                        window.webkitIndexedDB ||
                        window.mozIndexedDB ||
                        window.msIndexedDB
                    )
                    .setTransaction(
                        window.IDBTransaction ||
                        window.webkitIDBTransaction
                    )
                    .setKeyRange(
                        window.IDBKeyRange ||
                        window.webkitIDBKeyRange
                    )
                    .setLogger(
                        Sy.service.get('sy::core::logger')
                    )
                    .open();

                return engine;

            },
            localstorage: function (version, entitiesMeta) {

                var engine = new Sy.Storage.Engine.Localstorage(version);

                for (var i = 0, l = entitiesMeta.length; i < l; i++) {
                    engine.setStore(
                        entitiesMeta[i].name,
                        entitiesMeta[i].name.toLowerCase(),
                        entitiesMeta[i].uuid,
                        entitiesMeta[i].indexes
                    );
                }

                engine.setStorage(window.localStorage);
                engine.open();

                return engine;

            }
        }
    }
});

Sy.service = new Sy.ServiceContainer('sy::core');

Sy.service
    .setParameters(Sy.config.get('parameters'))
    .set({
        'sy::core::generator::uuid': {
            constructor: 'Sy.Lib.Generator.UUID'
        },
        'sy::core::mediator': {
            constructor: 'Sy.Lib.Mediator',
            calls: [
                ['setGenerator', ['@sy::core::generator::uuid']],
                ['setLogger', ['@sy::core::logger']]
            ]
        },
        'sy::core::http::rest': {
            constructor: 'Sy.HTTP.REST',
            calls: [
                ['setManager', ['@sy::core::http']]
            ]
        },
        'sy::core::registry::factory': {
            constructor: 'Sy.RegistryFactory'
        },
        'sy::core::queue::factory': {
            constructor: 'Sy.QueueFactory',
            calls: [
                ['setRegistryFactory', ['@sy::core::registry::factory']]
            ]
        },
        'sy::core::view::template::engine': {
            constructor: 'Sy.View.TemplateEngine'
        },
        'sy::core::view::parser': {
            constructor: 'Sy.View.Parser'
        },
        'sy::core::view::factory::list': {
            constructor: 'Sy.View.ListFactory',
            calls: [
                ['setTemplateEngine', ['@sy::core::view::template::engine']]
            ]
        },
        'sy::core::view::factory::layout': {
            constructor: 'Sy.View.LayoutFactory',
            calls: [
                ['setParser', ['@sy::core::view::parser']],
                ['setTemplateEngine', ['@sy::core::view::template::engine']],
                ['setRegistryFactory', ['@sy::core::registry::factory']],
                ['setListFactory', ['@sy::core::view::factory::list']]
            ]
        },
        'sy::core::view::factory::viewscreen': {
            constructor: 'Sy.View.ViewScreenFactory',
            calls: [
                ['setParser', ['@sy::core::view::parser']],
                ['setTemplateEngine', ['@sy::core::view::template::engine']],
                ['setRegistryFactory', ['@sy::core::registry::factory']],
                ['setLayoutFactory', ['@sy::core::view::factory::layout']]
            ]
        }
    });

Sy.service.set('sy::core::logger', function () {

    var logger = new Sy.Lib.Logger.CoreLogger('core'),
        info = new Sy.Lib.Logger.Handler.Console(logger.INFO),
        debug = new Sy.Lib.Logger.Handler.Console(logger.DEBUG),
        error = new Sy.Lib.Logger.Handler.Console(logger.ERROR),
        log = new Sy.Lib.Logger.Handler.Console(logger.LOG);

    logger.setHandler(info, logger.INFO);
    logger.setHandler(debug, logger.DEBUG);
    logger.setHandler(error, logger.ERROR);
    logger.setHandler(log, logger.LOG);

    return logger;

});

Sy.service.set('sy::core::http', function () {

    var parser = new Sy.HTTP.HeaderParser(),
        manager = new Sy.HTTP.Manager();

    manager.setParser(parser);
    manager.setGenerator(this.get('sy::core::generator::uuid'));
    manager.setRegistry(this.get('sy::core::registry::factory').make());

    return manager;

});

Sy.service.set('sy::core::storage', function () {

    var meta = [
            {
                name: 'DefaultBundle::Todo',
                repository: Sy.Storage.Repository,
                entity: App.Bundle.DefaultBundle.Entity.Todo,
                indexes: [],
                uuid: 'uuid'
            }
        ],
        storage = new Sy.Storage.Core(),
        managerFact = new Sy.Storage.ManagerFactory(),
        repositoryFact = new Sy.Storage.RepositoryFactory(),
        engineFact = new Sy.Storage.EngineFactory(),
        conf = Sy.config.get('storage'),
        registryFact = this.get('sy::core::registry::factory');

    storage.setRegistry(registryFact.make());

    repositoryFact
        .setMetaRegistry(registryFact.make())
        .setRepoRegistry(registryFact.make())
        .setQueueFactory(this.get('sy::core::queue::factory'))
        .setMeta(meta)
        .setGenerator(Sy.service.get('sy::core::generator::uuid'));

    for (var engineName in conf.engines) {
        if (conf.engines.hasOwnProperty(engineName)) {
            engineFact.setEngine(engineName, conf.engines[engineName]);
        }
    }

    managerFact
        .setEngineFactory(engineFact)
        .setRepositoryFactory(repositoryFact);

    for (var name in conf.managers) {
        if (conf.managers.hasOwnProperty(name)) {
            var manager = managerFact.make(name, conf.managers[name], meta);

            storage.setManager(name, manager);
        }
    }

    return storage;

});

Sy.service.set('sy::core::translator', function () {
    var translator = new Sy.Translator();
    translator
        .setRegistry(this.get('sy::core::registry::factory').make())
        .setQueueFactory(this.get('sy::core::queue::factory'));
    return translator;
});

Sy.service
    .set('sy::core::viewport', function () {

        var viewport = new Sy.View.ViewPort();

        return viewport
            .setNode(
                document.querySelector('.viewport')
            )
            .setViewManager(
                this.get('sy::core::view::manager')
            );

    })
    .set('sy::core::view::manager', function () {

        var manager = new Sy.View.Manager(),
            viewscreens = this.get('sy::core::view::parser').getViewScreens();

        manager
            .setViewsRegistry(
                this.get('sy::core::registry::factory').make()
            )
            .setViewScreenFactory(
                this.get('sy::core::view::factory::viewscreen')
            );

        for (var i = 0, l = viewscreens.length; i < l; i++) {
            manager.setViewScreen(viewscreens[i]);
        }

        return manager;

    });
<commit_msg>#12 updated the template engine service constructor<commit_after>namespace('Sy');

Sy.config = new Sy.Configurator();

Sy.config.set({
    env: 'prod',
    parameters: {},
    storage: {
        engines: {
            rest: function (version, entitiesMeta) {

                var engine = new Sy.Storage.Engine.Rest(version);

                engine.setManager(Sy.service.get('sy::core::http::rest'));
                engine.setPattern('/api/{{version}}/{{path}}/{{key}}');

                for (var i = 0, l = entitiesMeta.length; i < l; i++) {
                    engine.setStore(
                        entitiesMeta[i].name,
                        entitiesMeta[i].name.toLowerCase().replace('::', '/'),
                        entitiesMeta[i].uuid,
                        entitiesMeta[i].indexes
                    );
                }

                return engine;

            },
            indexeddb: function (version, entitiesMeta) {

                var engine =  new Sy.Storage.Engine.IndexedDB(version);

                for (var i = 0, l = entitiesMeta.length; i < l; i++) {
                    engine.setStore(
                        entitiesMeta[i].name,
                        entitiesMeta[i].name.toLowerCase(),
                        entitiesMeta[i].uuid,
                        entitiesMeta[i].indexes.concat(entitiesMeta[i].uuid)
                    );
                }

                engine
                    .setConnection(
                        window.indexedDB ||
                        window.webkitIndexedDB ||
                        window.mozIndexedDB ||
                        window.msIndexedDB
                    )
                    .setTransaction(
                        window.IDBTransaction ||
                        window.webkitIDBTransaction
                    )
                    .setKeyRange(
                        window.IDBKeyRange ||
                        window.webkitIDBKeyRange
                    )
                    .setLogger(
                        Sy.service.get('sy::core::logger')
                    )
                    .open();

                return engine;

            },
            localstorage: function (version, entitiesMeta) {

                var engine = new Sy.Storage.Engine.Localstorage(version);

                for (var i = 0, l = entitiesMeta.length; i < l; i++) {
                    engine.setStore(
                        entitiesMeta[i].name,
                        entitiesMeta[i].name.toLowerCase(),
                        entitiesMeta[i].uuid,
                        entitiesMeta[i].indexes
                    );
                }

                engine.setStorage(window.localStorage);
                engine.open();

                return engine;

            }
        }
    }
});

Sy.service = new Sy.ServiceContainer('sy::core');

Sy.service
    .setParameters(Sy.config.get('parameters'))
    .set({
        'sy::core::generator::uuid': {
            constructor: 'Sy.Lib.Generator.UUID'
        },
        'sy::core::mediator': {
            constructor: 'Sy.Lib.Mediator',
            calls: [
                ['setGenerator', ['@sy::core::generator::uuid']],
                ['setLogger', ['@sy::core::logger']]
            ]
        },
        'sy::core::http::rest': {
            constructor: 'Sy.HTTP.REST',
            calls: [
                ['setManager', ['@sy::core::http']]
            ]
        },
        'sy::core::registry::factory': {
            constructor: 'Sy.RegistryFactory'
        },
        'sy::core::queue::factory': {
            constructor: 'Sy.QueueFactory',
            calls: [
                ['setRegistryFactory', ['@sy::core::registry::factory']]
            ]
        },
        'sy::core::view::parser': {
            constructor: 'Sy.View.Parser'
        },
        'sy::core::view::factory::list': {
            constructor: 'Sy.View.ListFactory',
            calls: [
                ['setTemplateEngine', ['@sy::core::view::template::engine']]
            ]
        },
        'sy::core::view::factory::layout': {
            constructor: 'Sy.View.LayoutFactory',
            calls: [
                ['setParser', ['@sy::core::view::parser']],
                ['setTemplateEngine', ['@sy::core::view::template::engine']],
                ['setRegistryFactory', ['@sy::core::registry::factory']],
                ['setListFactory', ['@sy::core::view::factory::list']]
            ]
        },
        'sy::core::view::factory::viewscreen': {
            constructor: 'Sy.View.ViewScreenFactory',
            calls: [
                ['setParser', ['@sy::core::view::parser']],
                ['setTemplateEngine', ['@sy::core::view::template::engine']],
                ['setRegistryFactory', ['@sy::core::registry::factory']],
                ['setLayoutFactory', ['@sy::core::view::factory::layout']]
            ]
        }
    });

Sy.service.set('sy::core::logger', function () {

    var logger = new Sy.Lib.Logger.CoreLogger('core'),
        info = new Sy.Lib.Logger.Handler.Console(logger.INFO),
        debug = new Sy.Lib.Logger.Handler.Console(logger.DEBUG),
        error = new Sy.Lib.Logger.Handler.Console(logger.ERROR),
        log = new Sy.Lib.Logger.Handler.Console(logger.LOG);

    logger.setHandler(info, logger.INFO);
    logger.setHandler(debug, logger.DEBUG);
    logger.setHandler(error, logger.ERROR);
    logger.setHandler(log, logger.LOG);

    return logger;

});

Sy.service.set('sy::core::http', function () {

    var parser = new Sy.HTTP.HeaderParser(),
        manager = new Sy.HTTP.Manager();

    manager.setParser(parser);
    manager.setGenerator(this.get('sy::core::generator::uuid'));
    manager.setRegistry(this.get('sy::core::registry::factory').make());

    return manager;

});

Sy.service.set('sy::core::storage', function () {

    var meta = [
            {
                name: 'DefaultBundle::Todo',
                repository: Sy.Storage.Repository,
                entity: App.Bundle.DefaultBundle.Entity.Todo,
                indexes: [],
                uuid: 'uuid'
            }
        ],
        storage = new Sy.Storage.Core(),
        managerFact = new Sy.Storage.ManagerFactory(),
        repositoryFact = new Sy.Storage.RepositoryFactory(),
        engineFact = new Sy.Storage.EngineFactory(),
        conf = Sy.config.get('storage'),
        registryFact = this.get('sy::core::registry::factory');

    storage.setRegistry(registryFact.make());

    repositoryFact
        .setMetaRegistry(registryFact.make())
        .setRepoRegistry(registryFact.make())
        .setQueueFactory(this.get('sy::core::queue::factory'))
        .setMeta(meta)
        .setGenerator(Sy.service.get('sy::core::generator::uuid'));

    for (var engineName in conf.engines) {
        if (conf.engines.hasOwnProperty(engineName)) {
            engineFact.setEngine(engineName, conf.engines[engineName]);
        }
    }

    managerFact
        .setEngineFactory(engineFact)
        .setRepositoryFactory(repositoryFact);

    for (var name in conf.managers) {
        if (conf.managers.hasOwnProperty(name)) {
            var manager = managerFact.make(name, conf.managers[name], meta);

            storage.setManager(name, manager);
        }
    }

    return storage;

});

Sy.service.set('sy::core::translator', function () {
    var translator = new Sy.Translator();
    translator
        .setRegistry(this.get('sy::core::registry::factory').make())
        .setQueueFactory(this.get('sy::core::queue::factory'));
    return translator;
});

Sy.service
    .set('sy::core::view::template::engine', function () {
        var engine = new Sy.View.TemplateEngine();

        return engine
            .setRegistry(
                this.get('sy::core::registry::factory').make()
            )
            .setGenerator(
                this.get('sy::core::generator::uuid')
            );
    })
    .set('sy::core::viewport', function () {

        var viewport = new Sy.View.ViewPort();

        return viewport
            .setNode(
                document.querySelector('.viewport')
            )
            .setViewManager(
                this.get('sy::core::view::manager')
            );

    })
    .set('sy::core::view::manager', function () {

        var manager = new Sy.View.Manager(),
            viewscreens = this.get('sy::core::view::parser').getViewScreens();

        manager
            .setViewsRegistry(
                this.get('sy::core::registry::factory').make()
            )
            .setViewScreenFactory(
                this.get('sy::core::view::factory::viewscreen')
            );

        for (var i = 0, l = viewscreens.length; i < l; i++) {
            manager.setViewScreen(viewscreens[i]);
        }

        return manager;

    });
<|endoftext|>