<commit_before>/**
 * @projectDescription The Next-Generation Embryology Project
 *
 * School of Informatics, University of Edinburgh
 * Funded by the JISC (http://www.jisc.ac.uk/)
 *
 * @author gyaikhom
 * @version 0.0.1
 */
function reformatTextArea(f, n){
    /* Remove new line characters. */
    f.value = f.value.replace(/\n/g, ''); // Firefox.
    f.value = f.value.replace(/\s/g, ' ').replace(/  ,/g, ''); // IE and Opera needs this.

	/* Check string limit. */
    if (f.value.length > n) {
        f.value = f.value.substring(0, n);
    }
}

/**
 * @classDescription This class encapsulates a dialog manager.
 *
 * The dialog manager maintains all of the dialogs that are used by
 * the Dojo application. These include help information, about
 * information etc., which could change over time. By using Dojo.xhr
 * Ajax interfaces, we can dynamically load these information at run-time
 * thus providing up-to-date information on the dialog panels.
 */
var DialogManager = new Class({
    initialize: function(){
        dialog = new dijit.Dialog({
            id: "dialog"
        });
        dojo.body().appendChild(dialog.domNode);
        dialog.startup();
    },

    /**
     * Sets the about information.
     */
    setAboutDialog: function(){
        dojo.xhrGet({
            url: "about.html",
            handleAs: "text",
            timeout: 5000, // Time in milliseconds
            load: function(response, ioArgs){
                dialog.attr({
                    title: "About: Information about the Next-Generation Embryology Project",
                    style: "height: 500px; width: 60%;",
                    content: "
" + response + "
"
                });
                return response;
            },

            error: function(response, ioArgs){
                console.error("HTTP status code: ", ioArgs.xhr.status);
                return response;
            }
        });
    },

    /**
     * Sets the help information.
     */
    setHelpDialog: function(){
        dojo.xhrGet({
            url: "help.html",
            handleAs: "text",
            timeout: 5000, // Time in milliseconds
            load: function(response, ioArgs){
                dialog.attr({
                    title: "Help: Users' manual on using the portal",
                    style: "height: 500px; width: 80%;",
                    content: "
" + response + "
"
                });
                return response;
            },

            error: function(response, ioArgs){
                console.error("HTTP status code: ", ioArgs.xhr.status);
                return response;
            }
        });
    },

    /**
     * Sets the 2D marker creation dialog.
     *
     * @param {Object} x x-coordinate of the marker.
     * @param {Object} y y-coordinate of the marker.
     */
    setCreate2DMarkerDialog: function(x, y, scale, dst, yaw, rol, pit){
        dojo.xhrGet({
            url: "c2dm.php?x=" + x + "&y=" + y + "&scale=" + scale + "&dst=" + dst + "&yaw=" + yaw + "&rol=" + rol + "&pit=" + pit,
            handleAs: "text",
            timeout: 5000, // Time in milliseconds
            load: function(response, ioArgs){
                dialog.attr({
                    title: "Create 2D marker at (" + x + ", " + y + ")",
                    style: "height: 375px; width: 590px;",
                    content: "
" + response + "
"
                });
                var theForm = dojo.byId("c2dm");
                dojo.connect(theForm, "onsubmit", function(event){
                    // prevent the form from actually submitting
                    event.preventDefault();
                    // submit the form in the background
                    dojo.xhrPost({
                        url: "create2DMarker.php",
                        form: "c2dm",
                        handleAs: "text",
                        handle: function(data, args){
                            if (typeof data == "error") {
                                console.warn("Error", args);
                            }
                            else {
                                console.log(data);
                            }
                        }
                    });
                    dijit.byId('dialog').hide();
                    ngembryo.engine.refresh();
                });
            },

            error: function(response, ioArgs){
                console.error("HTTP status code: ", ioArgs.xhr.status);
            }
        });
    },

    /**
     * Sets the 2D region creation dialog.
     */
    setCreate2DRegionDialog: function(polyline, scale, dst, yaw, rol, pit){
        var str = "";
        var i = 0;
        if (i < polyline.length) {
            while (1) {
                str += polyline[i].x + "," + polyline[i].y;
                i++;
                if (i < polyline.length) {
                    str += ":";
                }
                else {
                    break;
                }
            }
        }
        dojo.xhrGet({
            url: "c2dr.php?polyline=" + str + "&scale=" + scale + "&dst=" + dst + "&yaw=" + yaw + "&rol=" + rol + "&pit=" + pit,
            handleAs: "text",
            timeout: 5000, // Time in milliseconds
            load: function(response, ioArgs){
                dialog.attr({
                    title: "Create 2D region",
                    style: "height: 375px; width: 590px;",
                    content: "
" + response + "
"
                });
                var theForm = dojo.byId("c2dr");
                dojo.connect(theForm, "onsubmit", function(event){
                    // prevent the form from actually submitting
                    event.preventDefault();
                    // submit the form in the background
                    dojo.xhrPost({
                        url: "create2DRegion.php",
                        form: "c2dr",
                        handleAs: "text",
                        handle: function(data, args){
                            if (typeof data == "error") {
                                console.warn("Error", args);
                            }
                            else {
                                console.log(data);
                            }
                        }
                    });
                    dijit.byId('dialog').hide();
                    ngembryo.engine.refresh();
                });
            },

            error: function(response, ioArgs){
                console.error("HTTP status code: ", ioArgs.xhr.status);
            }
        });
    },

    /**
     * Parses the response data and retrieves list of resources.
     *
     * @param {Object} JSON response.
     */
    __parseResources: function(data){
        content = "

";
        for (var i = 0; i < data.length; i++) {
            content += "
" + data[i].id + data[i].title + data[i].summary + data[i].url + "
";
        }
        content += "

";
        return content;
    },

    /**
     * Retrieve resource information from the repository.
     */
    setResourceGrid: function(id, label, description, type){
        var store = new dojox.data.CsvStore({
            url: "getResource.php?id=" + id + "&type=" + type + "&format=csv"
        });
        var layout = [{
            field: 'id',
            name: 'id',
            width: '20px'
        }, {
            field: 'title',
            name: 'title',
            width: '200px'
        }, {
            field: 'abstract',
            name: 'abstract',
            width: 'auto'
        }, {
            field: 'url',
            name: 'url',
            width: '200px'
        }];
        var grid = new dojox.grid.DataGrid({
            query: {
                id: '*'
            },
            store: store,
            clientSort: true,
            rowSelector: '20px',
            structure: layout
        });

        var c = dojo.create("div");
        var d = dojo.create("div");
        dojo.attr(d, {
            id: "description",
            style: "text-align: left; height: 150px; width: 100%;",
            innerHTML: "Description: " + description
        });
        c.appendChild(d);

        var t = dojo.create("div");
        dojo.attr(t, {
            id: "resourceGrid",
            style: "height: 350px; width: 100%;"
        });
        t.appendChild(grid.domNode);
        c.appendChild(t);
        grid.startup();

        dialog.attr({
            title: label,
            style: "height: 500px; width: 50%;",
            content: c
        });

    },

    /**
     * Displays the about dialog box.
     */
    showAbout: function(){
        this.setAboutDialog();
        dialog.show();
    },

    /**
     * Displays the help dialog box.
     */
    showHelp: function(){
        this.setHelpDialog();
        dialog.show();
    },

    /**
     * Displays the resources associated with an annotation.
     */
    showResources: function(id, label, description, type){
        this.setResourceGrid(id, label, description, type);
        dialog.show();
    },

    /**
     * Creates a 2D marker at the specified coordinate.
     *
     * @param {Object} x x-coordinate of the marker.
     * @param {Object} y y-coordinate of the marker.
     */
    create2DMarker: function(x, y, scale, dst, yaw, rol, pit){
        this.setCreate2DMarkerDialog(x, y, scale, dst, yaw, rol, pit);
        dialog.show();
    },

    /**
     * Creates a 2D region using the specified polyline.
     *
     * @param {Object} p Points in the polyline.
     */
    create2DRegion: function(p, scale, dst, yaw, rol, pit){
        this.setCreate2DRegionDialog(p, scale, dst, yaw, rol, pit);
        dialog.show();
    }

});
<commit_msg>Refined creation of resources dialog.<commit_after>/**
 * @projectDescription The Next-Generation Embryology Project
 *
 * School of Informatics, University of Edinburgh
 * Funded by the JISC (http://www.jisc.ac.uk/)
 *
 * @author gyaikhom
 * @version 0.0.1
 */
function reformatTextArea(f, n){
    /* Remove new line characters. */
    f.value = f.value.replace(/\n/g, ''); // Firefox.
    f.value = f.value.replace(/\s/g, ' ').replace(/  ,/g, ''); // IE and Opera needs this.

	/* Check string limit. */
    if (f.value.length > n) {
        f.value = f.value.substring(0, n);
    }
}

/**
 * @classDescription This class encapsulates a dialog manager.
 *
 * The dialog manager maintains all of the dialogs that are used by
 * the Dojo application. These include help information, about
 * information etc., which could change over time. By using Dojo.xhr
 * Ajax interfaces, we can dynamically load these information at run-time
 * thus providing up-to-date information on the dialog panels.
 */
var DialogManager = new Class({
    initialize: function(){
        dialog = new dijit.Dialog({
            id: "dialog"
        });
        dojo.body().appendChild(dialog.domNode);
        dialog.startup();
    },

    /**
     * Sets the about information.
     */
    setAboutDialog: function(){
        dojo.xhrGet({
            url: "about.html",
            handleAs: "text",
            timeout: 5000, // Time in milliseconds
            load: function(response, ioArgs){
                dialog.attr({
                    title: "About: Information about the Next-Generation Embryology Project",
                    style: "height: 500px; width: 60%;",
                    content: "
" + response + "
"
                });
                return response;
            },

            error: function(response, ioArgs){
                console.error("HTTP status code: ", ioArgs.xhr.status);
                return response;
            }
        });
    },

    /**
     * Sets the help information.
     */
    setHelpDialog: function(){
        dojo.xhrGet({
            url: "help.html",
            handleAs: "text",
            timeout: 5000, // Time in milliseconds
            load: function(response, ioArgs){
                dialog.attr({
                    title: "Help: Users' manual on using the portal",
                    style: "height: 500px; width: 80%;",
                    content: "
" + response + "
"
                });
                return response;
            },

            error: function(response, ioArgs){
                console.error("HTTP status code: ", ioArgs.xhr.status);
                return response;
            }
        });
    },

    /**
     * Sets the 2D marker creation dialog.
     *
     * @param {Object} x x-coordinate of the marker.
     * @param {Object} y y-coordinate of the marker.
     */
    setCreate2DMarkerDialog: function(x, y, scale, dst, yaw, rol, pit){
        dojo.xhrGet({
            url: "c2dm.php?x=" + x + "&y=" + y + "&scale=" + scale + "&dst=" + dst + "&yaw=" + yaw + "&rol=" + rol + "&pit=" + pit,
            handleAs: "text",
            timeout: 5000, // Time in milliseconds
            load: function(response, ioArgs){
                dialog.attr({
                    title: "Create 2D marker at (" + x + ", " + y + ")",
                    style: "height: 375px; width: 590px;",
                    content: "
" + response + "
"
                });
                var theForm = dojo.byId("c2dm");
                dojo.connect(theForm, "onsubmit", function(event){
                    // prevent the form from actually submitting
                    event.preventDefault();
                    // submit the form in the background
                    dojo.xhrPost({
                        url: "create2DMarker.php",
                        form: "c2dm",
                        handleAs: "text",
                        handle: function(data, args){
                            if (typeof data == "error") {
                                console.warn("Error", args);
                            }
                            else {
                                console.log(data);
                            }
                        }
                    });
                    dijit.byId('dialog').hide();
                    ngembryo.engine.refresh();
                });
            },

            error: function(response, ioArgs){
                console.error("HTTP status code: ", ioArgs.xhr.status);
            }
        });
    },

    /**
     * Sets the 2D region creation dialog.
     */
    setCreate2DRegionDialog: function(polyline, scale, dst, yaw, rol, pit){
        var str = "";
        var i = 0;
        if (i < polyline.length) {
            while (1) {
                str += polyline[i].x + "," + polyline[i].y;
                i++;
                if (i < polyline.length) {
                    str += ":";
                }
                else {
                    break;
                }
            }
        }
        dojo.xhrGet({
            url: "c2dr.php?polyline=" + str + "&scale=" + scale + "&dst=" + dst + "&yaw=" + yaw + "&rol=" + rol + "&pit=" + pit,
            handleAs: "text",
            timeout: 5000, // Time in milliseconds
            load: function(response, ioArgs){
                dialog.attr({
                    title: "Create 2D region",
                    style: "height: 375px; width: 590px;",
                    content: "
" + response + "
"
                });
                var theForm = dojo.byId("c2dr");
                dojo.connect(theForm, "onsubmit", function(event){
                    // prevent the form from actually submitting
                    event.preventDefault();
                    // submit the form in the background
                    dojo.xhrPost({
                        url: "create2DRegion.php",
                        form: "c2dr",
                        handleAs: "text",
                        handle: function(data, args){
                            if (typeof data == "error") {
                                console.warn("Error", args);
                            }
                            else {
                                console.log(data);
                            }
                        }
                    });
                    dijit.byId('dialog').hide();
                    ngembryo.engine.refresh();
                });
            },

            error: function(response, ioArgs){
                console.error("HTTP status code: ", ioArgs.xhr.status);
            }
        });
    },

    /**
     * Parses the response data and retrieves list of resources.
     *
     * @param {Object} JSON response.
     */
    __parseResources: function(data){
        content = "

";
        for (var i = 0; i < data.length; i++) {
            content += "
" + data[i].id + data[i].title + data[i].summary + data[i].url + "
";
        }
        content += "

";
        return content;
    },

    /**
     * Retrieve resource information from the repository.
     */
    setResourceGrid: function(id, label, description, type){
        var store = new dojox.data.CsvStore({
            url: "getResource.php?id=" + id + "&type=" + type + "&format=csv"
        });
        var layout = [{
            field: 'id',
            name: 'id',
            width: '20px'
        }, {
            field: 'title',
            name: 'title',
            width: '200px'
        }, {
            field: 'abstract',
            name: 'abstract',
            width: 'auto'
        }, {
            field: 'url',
            name: 'url',
            width: '200px'
        }];
        var grid = new dojox.grid.DataGrid({
            query: {
                id: '*'
            },
            store: store,
            clientSort: true,
            rowSelector: '20px',
            structure: layout
        });

        var c = dojo.create("div", {
			id: "resourceContent"
			});
        var d = dojo.create("div", {
            id: "resourceDescription",
			innerHTML: "Description: " + description
        });
        c.appendChild(d);
        var t = dojo.create("div", {
            id: "resourceGrid",
        });
        t.appendChild(grid.domNode);
        c.appendChild(t);
        grid.startup();

        dialog.attr({
            title: label,
            style: "height: 500px; width: 50%;",
            content: c
        });
    },

    /**
     * Displays the about dialog box.
     */
    showAbout: function(){
        this.setAboutDialog();
        dialog.show();
    },

    /**
     * Displays the help dialog box.
     */
    showHelp: function(){
        this.setHelpDialog();
        dialog.show();
    },

    /**
     * Displays the resources associated with an annotation.
     */
    showResources: function(id, label, description, type){
        this.setResourceGrid(id, label, description, type);
        dialog.show();
    },

    /**
     * Creates a 2D marker at the specified coordinate.
     *
     * @param {Object} x x-coordinate of the marker.
     * @param {Object} y y-coordinate of the marker.
     */
    create2DMarker: function(x, y, scale, dst, yaw, rol, pit){
        this.setCreate2DMarkerDialog(x, y, scale, dst, yaw, rol, pit);
        dialog.show();
    },

    /**
     * Creates a 2D region using the specified polyline.
     *
     * @param {Object} p Points in the polyline.
     */
    create2DRegion: function(p, scale, dst, yaw, rol, pit){
        this.setCreate2DRegionDialog(p, scale, dst, yaw, rol, pit);
        dialog.show();
    }

});
<|endoftext|>


<commit_before>/**
 * power-assert - Empower your assertions
 *
 * https://github.com/twada/power-assert
 *
 * Copyright (c) 2013 Takuto Wada
 * Licensed under the MIT license.
 *   https://raw.github.com/twada/power-assert/master/MIT-LICENSE.txt
 */
(function (root, factory) {
    'use strict';

    // using returnExports UMD pattern
    if (typeof define === 'function' && define.amd) {
        define(factory);
    } else if (typeof exports === 'object') {
        module.exports = factory();
    } else {
        root.powerAssertFormatter = factory();
    }
}(this, function () {
    'use strict';

    var widthOf = function (str) {
        var i, c, width = 0;
        for(i = 0; i < str.length; i+=1){
            c = str.charCodeAt(i);
            if ((0x0 <= c && c < 0x81) || (c == 0xf8f0) || (0xff61 <= c && c < 0xffa0) || (0xf8f1 <= c && c < 0xf8f4)) {
                width += 1;
            } else {
                width += 2;
            }
        }
        return width;
    };

    var newRowFor = (function () {
        var createRow = function (numCols, initial) {
            var row = [], i;
            for(i = 0; i < numCols; i += 1) {
                row[i] = initial;
            }
            return row;
        };
        return function (assertionLine) {
            return createRow(widthOf(assertionLine), ' ');
        };
    })();

    var isOverlapped = function (prevCapturing, nextCaputuring, dumpedValue) {
        return (typeof prevCapturing !== 'undefined') && prevCapturing.location.start.column <= (nextCaputuring.location.start.column + widthOf(dumpedValue));
    };

    function rightToLeft (a, b) {
        return b.location.start.column - a.location.start.column;
    }

    function PowerAssertContextRenderer (dump) {
        this.dump = dump;
        this.initialVertivalBarLength = 1;
    }
    PowerAssertContextRenderer.prototype.addOneMoreRow = function () {
        this.rows.push(newRowFor(this.assertionLine));
    };
    PowerAssertContextRenderer.prototype.lastRow = function () {
        return this.rows[this.rows.length - 1];
    };
    PowerAssertContextRenderer.prototype.renderVerticalBarAt = function (columnIndex) {
        var lastRowIndex = this.rows.length - 1;
        for (var i = 0; i < lastRowIndex; i += 1) {
            this.rows[i].splice(columnIndex, 1, '|');
        }
    };
    PowerAssertContextRenderer.prototype.renderValueAt = function (columnIndex, dumpedValue) {
        var width = widthOf(dumpedValue);
        for (var i = 0; i < width; i += 1) {
            this.lastRow().splice(columnIndex + i, 1, dumpedValue.charAt(i));
        }
    };
    PowerAssertContextRenderer.prototype.constructRows = function (capturedEvents) {
        var that = this,
            prevCaptured;
        capturedEvents.forEach(function (captured) {
            var dumpedValue = that.dump(captured.value);
            if (isOverlapped(prevCaptured, captured, dumpedValue)) {
                that.addOneMoreRow();
            }
            that.renderVerticalBarAt(captured.location.start.column);
            that.renderValueAt(captured.location.start.column, dumpedValue);
            prevCaptured = captured;
        });
    };
    PowerAssertContextRenderer.prototype.initWithContext = function (context) {
        this.assertionLine = context.content;
        this.assertionLocation = context.location;
        this.rows = [];
        for (var i = 0; i <= this.initialVertivalBarLength; i += 1) {
            this.addOneMoreRow();
        }
    };
    PowerAssertContextRenderer.prototype.formatLines = function () {
        var lines = [];
        if (this.assertionLocation.path) {
            lines.push('# ' + [this.assertionLocation.path, this.assertionLocation.start.line].join(':'));
        } else {
            lines.push('# at line: ' + this.assertionLocation.start.line);
        }
        lines.push('');
        lines.push(this.assertionLine);
        this.rows.forEach(function (columns) {
            lines.push(columns.join(''));
        });
        lines.push('');
        return lines;
    };
    PowerAssertContextRenderer.prototype.render = function (context) {
        var capturedEvents = context.events;
        capturedEvents.sort(rightToLeft);
        this.initWithContext(context);
        this.constructRows(capturedEvents);
        return this.formatLines();
    };

    return {
        dump: function (obj) {
            return JSON.stringify(obj);
        },
        format: function (context) {
            var renderer = new PowerAssertContextRenderer(this.dump);
            var lines = renderer.render(context);
            return lines;
        },
        PowerAssertContextRenderer: PowerAssertContextRenderer
    };
}));
<commit_msg>Methods should not look like reentrant since PowerAssertContextRenderer is not.<commit_after>/**
 * power-assert - Empower your assertions
 *
 * https://github.com/twada/power-assert
 *
 * Copyright (c) 2013 Takuto Wada
 * Licensed under the MIT license.
 *   https://raw.github.com/twada/power-assert/master/MIT-LICENSE.txt
 */
(function (root, factory) {
    'use strict';

    // using returnExports UMD pattern
    if (typeof define === 'function' && define.amd) {
        define(factory);
    } else if (typeof exports === 'object') {
        module.exports = factory();
    } else {
        root.powerAssertFormatter = factory();
    }
}(this, function () {
    'use strict';

    var widthOf = function (str) {
        var i, c, width = 0;
        for(i = 0; i < str.length; i+=1){
            c = str.charCodeAt(i);
            if ((0x0 <= c && c < 0x81) || (c == 0xf8f0) || (0xff61 <= c && c < 0xffa0) || (0xf8f1 <= c && c < 0xf8f4)) {
                width += 1;
            } else {
                width += 2;
            }
        }
        return width;
    };

    var newRowFor = (function () {
        var createRow = function (numCols, initial) {
            var row = [], i;
            for(i = 0; i < numCols; i += 1) {
                row[i] = initial;
            }
            return row;
        };
        return function (assertionLine) {
            return createRow(widthOf(assertionLine), ' ');
        };
    })();

    var isOverlapped = function (prevCapturing, nextCaputuring, dumpedValue) {
        return (typeof prevCapturing !== 'undefined') && prevCapturing.location.start.column <= (nextCaputuring.location.start.column + widthOf(dumpedValue));
    };

    function rightToLeft (a, b) {
        return b.location.start.column - a.location.start.column;
    }

    function PowerAssertContextRenderer (dump, context) {
        this.dump = dump;
        this.initialVertivalBarLength = 1;
        this.initWithContext(context);
    }
    PowerAssertContextRenderer.prototype.initWithContext = function (context) {
        context.events.sort(rightToLeft);
        this.events = context.events;
        this.assertionLine = context.content;
        this.assertionLocation = context.location;
        this.rows = [];
        for (var i = 0; i <= this.initialVertivalBarLength; i += 1) {
            this.addOneMoreRow();
        }
    };
    PowerAssertContextRenderer.prototype.addOneMoreRow = function () {
        this.rows.push(newRowFor(this.assertionLine));
    };
    PowerAssertContextRenderer.prototype.lastRow = function () {
        return this.rows[this.rows.length - 1];
    };
    PowerAssertContextRenderer.prototype.renderVerticalBarAt = function (columnIndex) {
        var lastRowIndex = this.rows.length - 1;
        for (var i = 0; i < lastRowIndex; i += 1) {
            this.rows[i].splice(columnIndex, 1, '|');
        }
    };
    PowerAssertContextRenderer.prototype.renderValueAt = function (columnIndex, dumpedValue) {
        var width = widthOf(dumpedValue);
        for (var i = 0; i < width; i += 1) {
            this.lastRow().splice(columnIndex + i, 1, dumpedValue.charAt(i));
        }
    };
    PowerAssertContextRenderer.prototype.constructRows = function (capturedEvents) {
        var that = this,
            prevCaptured;
        capturedEvents.forEach(function (captured) {
            var dumpedValue = that.dump(captured.value);
            if (isOverlapped(prevCaptured, captured, dumpedValue)) {
                that.addOneMoreRow();
            }
            that.renderVerticalBarAt(captured.location.start.column);
            that.renderValueAt(captured.location.start.column, dumpedValue);
            prevCaptured = captured;
        });
    };
    PowerAssertContextRenderer.prototype.renderLines = function () {
        var lines = [];
        this.constructRows(this.events);
        if (this.assertionLocation.path) {
            lines.push('# ' + [this.assertionLocation.path, this.assertionLocation.start.line].join(':'));
        } else {
            lines.push('# at line: ' + this.assertionLocation.start.line);
        }
        lines.push('');
        lines.push(this.assertionLine);
        this.rows.forEach(function (columns) {
            lines.push(columns.join(''));
        });
        lines.push('');
        return lines;
    };

    return {
        dump: function (obj) {
            return JSON.stringify(obj);
        },
        format: function (context) {
            var renderer = new PowerAssertContextRenderer(this.dump, context);
            return renderer.renderLines();
        },
        PowerAssertContextRenderer: PowerAssertContextRenderer
    };
}));
<|endoftext|>


<commit_before>
// send graphml to cytoscape web for visualization
function send2cytoscapeweb(graphml, div_id) {
    var visual_style = {
        global: {
            backgroundColor: "#fefefe", //#F7F6C9 //#F3F7FE
            tooltipDelay: 250
        },
        nodes: {
                                    shape: {
                                       discreteMapper: {
                                                    attrName: "type",
                                                    entries: [
                                                            { attrValue: "Protein", value: "ELLIPSE" },
                                                            { attrValue: "SmallMolecule", value: "DIAMOND" },
                                                            { attrValue: "Unknown", value: "TRIANGLE" }
                                                    ]
                                            }
                                    },
            borderWidth: 1,
                                    borderColor: {
                                            discreteMapper: {
                                                    attrName: "type",
                                                    entries: [
                                                            { attrValue: "Protein", value: "#000000" },
                                                            { attrValue: "SmallMolecule", value: "#000000" },
                                                            { attrValue: "Unknown", value: "#000000" }
                                                    ]
                                            }
                                    },
            size: {
                defaultValue: 25,
                continuousMapper: { attrName: "weight", minValue: 25, maxValue: 75 }
            },
            color: {
                discreteMapper: {
                    attrName: "type",
                    entries: [
                                                            { attrValue: "Protein", value: "#FFFFFF" },
                                                            { attrValue: "SmallMolecule", value: "#FFFFFF" }, //#D7AC85
                                                            { attrValue: "Unknown", value: "#FFFFFF" } //#69A19E
                    ]
                }
            },
            labelHorizontalAnchor: "center",
            labelVerticalAnchor: "bottom",
            labelFontSize: 10,
            selectionGlowColor: "#f6f779",
                                    selectionGlowOpacity: 0.8,
                                    hoverGlowColor: "#cbcbcb", //#ffff33
                                    hoverGlowOpacity: 1.0,
                                    hoverGlowStrength: 8,
                                    tooltipFont: "Verdana",
                tooltipFontSize: 12,
                tooltipFontColor: "#EE0505",
                tooltipBackgroundColor: "#000000",
                tooltipBorderColor: "#000000"
        },
        edges: {
            width: 1,
                                    mergeWidth: 2,
                                    mergeColor: "#666666",
                                    targetArrowShape: {
                    defaultValue: "NONE",
                                            discreteMapper: {
                                                    attrName: "type",
                                                    entries: [
                                                            { attrValue: "STATE_CHANGE", value: "DELTA" } ]
                                    }
            },
                                    color: {
                                            defaultValue: "#A583AB", // color of all other types
                                            discreteMapper: {
                                                    attrName: "type",
                                                    entries: [
                                                            { attrValue: "IN_SAME_COMPONENT", value: "#CD976B" },
                                                            { attrValue: "REACTS_WITH", value: "#7B7EF7" },
                                                            { attrValue: "STATE_CHANGE", value: "#67C1A9" } ]
                                    }
                            }
                            }
                    };

    // initialization options
    var options = {
        swfPath: "swf/CytoscapeWeb",
        flashInstallerPath: "swf/playerProductInstall"
    };

    var vis = new org.cytoscapeweb.Visualization(div_id, options);

    vis.ready(function() {
            // init UI of the network tab
            initNetworkUI(vis);

        // set the style programmatically
        document.getElementById("color").onclick = function(){
            vis.visualStyle(visual_style);
        };
    });

    var draw_options = {
        // your data goes here
        network: graphml,
        edgeLabelsVisible: false,
        edgesMerged: true,
        layout: "ForceDirected",
        visualStyle: visual_style,
        panZoomControlVisible: true
    };

    vis.draw(draw_options);
};<commit_msg>-	Customizations made to represent the drugs on networks.<commit_after>
// send graphml to cytoscape web for visualization
function send2cytoscapeweb(graphml, div_id)
{
    var visual_style =
    {
        global:
        {
            backgroundColor: "#fefefe", //#F7F6C9 //#F3F7FE
            tooltipDelay: 250
        },
        nodes:
        {
            shape:
            {
               discreteMapper:
               {
                            attrName: "type",
                            entries: [
                                      { attrValue: "Protein", value: "ELLIPSE" },
                                      { attrValue: "SmallMolecule", value: "DIAMOND" },
                                      { attrValue: "Unknown", value: "TRIANGLE" },
                                      { attrValue: "Drug", value: "HEXAGON"}	]
                }
            },
            borderWidth: 1,
            borderColor:
            {
                    discreteMapper:
                    {
                            attrName: "type",
                            entries: [
                                    { attrValue: "Protein", value: "#000000" },
                                    { attrValue: "SmallMolecule", value: "#000000" },
                                    { attrValue: "Drug", value: "#000000"},
                                    { attrValue: "Unknown", value: "#000000" } ]
                    }
            },
            size:
            {
            	 defaultValue: 24,
            	 discreteMapper:
                 {
                              attrName: "type",
                              entries: [ { attrValue: "Drug", value: 16}	]
                 }
            },
            color: {customMapper: {functionName: "colorFunc"}},
            label: {customMapper: {functionName: "labelFunc"}},
            labelHorizontalAnchor: "center",
            labelVerticalAnchor: "bottom",
            labelFontSize: 10,
            selectionGlowColor: "#f6f779",
            selectionGlowOpacity: 0.8,
            hoverGlowColor: "#cbcbcb", //#ffff33
            hoverGlowOpacity: 1.0,
            hoverGlowStrength: 8,
            tooltipFont: "Verdana",
            tooltipFontSize: 12,
            tooltipFontColor: "#EE0505",
            tooltipBackgroundColor: "#000000",
            tooltipBorderColor: "#000000"
        },
        edges:
        {
        	width: 1,
	        mergeWidth: 2,
	        mergeColor: "#666666",
		    targetArrowShape:
		    {
		    	defaultValue: "NONE",
		        discreteMapper:
		        {
			        attrName: "type",
			        entries: [
				                   { attrValue: "STATE_CHANGE", value: "DELTA" },
				                   { attrValue: "DRUG_TARGET", value: "T" }
			                 ]
		        }
	        },
            color:
            {
                    defaultValue: "#A583AB", // color of all other types
                    discreteMapper:
                    {
                            attrName: "type",
                            entries: [
                                    { attrValue: "IN_SAME_COMPONENT", value: "#CD976B" },
                                    { attrValue: "REACTS_WITH", value: "#7B7EF7" },
                                    { attrValue: "DRUG_TARGET", value: "#E6A90F" },
                                    { attrValue: "STATE_CHANGE", value: "#67C1A9" } ]
                    }
            },
            weight:
            {
               discreteMapper:
                {
            	   		defaultValue: 100,
                        attrName: "type",
                        entries: [{ attrValue: "DRUG_TARGET", value: 40 }]
                }
            }
        }
};

    // initialization options
    var options = {
        swfPath: "swf/CytoscapeWeb",
        flashInstallerPath: "swf/playerProductInstall"
    };

    var vis = new org.cytoscapeweb.Visualization(div_id, options);

    /*
     * Force Directed Layout variable
     * */
    var forceDirectedLayout =
    {
 	   name: "ForceDirected",
 	   options:
 	   {
 		   weightAttr: "weight"
 	   }
    };

    /*Custom Label function for Drugs
     *
     * This function truncates the drug names on the graph,
     * if their name length is less than 20 characters,
     * else original name is printed
     *
    */
    vis["labelFunc"] = function(data)
    {
    	var name = data["label"];

    	if (data["type"] == "Drug")
    	{
    		name = data["NAME"];

    		var truncateIndicator = '...';
    		var nameSize = name.length;

    		if (nameSize > 20)
    		{
    			name = name.substring(0, 20);
    			name = name.concat(truncateIndicator);
    		}

		}

    	return name;

    };

    /*Custom color function for Drugs
     *
     * FDA approved drugs are shown with orange like color
     * non FDA approved ones are shown with white color
     * */
    vis["colorFunc"] = function(data)
    {
    	if (data["type"] == "Drug")
    	{
			if (data["FDA_APPROVAL"] == "true")
			{
				return "#E6A90F";
			}
			else
			{
				return	"#FFFFFF";
			}

		}
    	else
    		return "#FFFFFF";
    };

    vis.ready(function() {
            // init UI of the network tab
            initNetworkUI(vis);

        // set the style programmatically
        document.getElementById("color").onclick = function(){
            vis.visualStyle(visual_style);
        };
    });

    var draw_options = {
        // your data goes here
        network: graphml,
        edgeLabelsVisible: false,
        edgesMerged: true,
        layout: "ForceDirected",
        visualStyle: visual_style,
        panZoomControlVisible: true
    };

    vis.draw(draw_options);
};<|endoftext|>


<commit_before>/*
Copyright (c) 2003-2009, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/

CKEDITOR.editorConfig = function( config )
{
	// Define changes to default configuration here. For example:
	// config.language = 'fr';
	config.skin = 'kama';
  //TODO: This should work to remove the bottom DOM information, but doesn't
  // This way is on an instance of the config object
  config.removePlugins = "elementspath,kplahj";
};

// This way is global / static
CKEDITOR.config.removePlugins = "elementspath,kplahj";
<commit_msg>Mantis 97: HTML editor has its own resize handle<commit_after>/*
Copyright (c) 2003-2009, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/

CKEDITOR.editorConfig = function( config )
{
	// Define changes to default configuration here. For example:
	// config.language = 'fr';
	config.skin = 'kama';
  // This way is on an instance of the config object
  config.removePlugins = "elementspath,maximize,resize";
};
<|endoftext|>


<commit_before>// TODO: a work in progress

var keycloakUrl = "rest/keycloak.json";
var dukecloak = new function() {
    // Data
    var self = this;

    self.keycloakAuth = new Keycloak(keycloakUrl);

    self.auth = {
        username : ko.observable(""),
        loggedIn : ko.observable(false),
        loggedOut : ko.observable(true)
    };

    self.loadUserData = function() {
		dukecloak.keycloakAuth.loadUserProfile().success(function(profile){
			dukecloak.auth.username(profile.username);
			console.log("Logged in: " + dukecloak.auth.username());
            dukecloak.keycloakAuth.updateToken()
                .success(function() {
                    dukeconSynch.pull();
                })
                .error(function() { console.log("Unable to update token");});
		});
    };

    self.logout = function() {
        dukecloak.keycloakAuth.logout().success(function() {
			dukecloak.auth.loggedIn(false);
			dukecloak.auth.loggedOut(true);
			dukecloak.auth.username("");
        }).error(function() {
			console.log("WTF");
        });
    };

    var dukecloakInitialized = false;

    self.login = function() {
        if(!dukecloakInitialized) {
            self.init(true);
            return;
        }
        dukecloak.keycloakAuth.login().success(function () {
            dukecloak.auth.loggedIn(true);
            dukecloak.auth.loggedOut(false);
        }).error(function () {
            dukecloak.auth.loggedIn(false);
            dukecloak.auth.loggedOut(true);
        });
    };

    self.init = function(login) {
        if(dukecloakInitialized) {
            return;
        }
        dukecloak.keycloakAuth.init({ onLoad: login ? "login-required" : "check-sso" }).success(function (authenticated) {
            dukecloakInitialized = true;
            dukecloak.auth.loggedIn(authenticated);
            dukecloak.auth.loggedOut(!authenticated);
            console.log('Authenticated: ' + authenticated);
            if (authenticated){
                console.log('local time: ' + new Date().getTime()/1000);
                console.log('iat: ' + dukecloak.keycloakAuth.tokenParsed.iat);
                console.log('diff: ' + (new Date().getTime()/1000 - dukecloak.keycloakAuth.tokenParsed.iat));
                console.log('exp in: ' + (dukecloak.keycloakAuth.tokenParsed.exp - new Date().getTime()/1000));
                console.log('isExpired: ' + dukecloak.keycloakAuth.isTokenExpired());
            	dukecloak.loadUserData();
	        }
        }).error(function () {
            console.log("Error initializing keycloak");
        });
        dukecloak.keycloakAuth.onAuthSuccess = function() { console.log("Auth Success!!"); };
        dukecloak.keycloakAuth.onAuthRefreshSuccess = function() { console.log("Authenticated!!"); };
    }
};

<commit_msg>storing keycloak tokens in localstore to avoid re-auth on page reload and navigation<commit_after>// TODO: a work in progress

var keycloakUrl = "rest/keycloak.json";
var dukecloak = new function() {
    // Data
    var self = this;

    self.keycloakAuth = new Keycloak(keycloakUrl);

    self.auth = {
        username : ko.observable(""),
        loggedIn : ko.observable(false),
        loggedOut : ko.observable(true)
    };

    function saveTokens() {
        dukeconSettings.saveSetting('keycloak_token', dukecloak.keycloakAuth.token);
        dukeconSettings.saveSetting('keycloak_refreshToken', dukecloak.keycloakAuth.refreshToken);
        dukeconSettings.saveSetting('keycloak_idToken', dukecloak.keycloakAuth.idToken);
        dukeconSettings.saveSetting('keycloak_timeSkew', dukecloak.keycloakAuth.timeSkew);
    }

    function clearTokens() {
        dukeconSettings.clearSetting('keycloak_token');
        dukeconSettings.clearSetting('keycloak_refreshToken');
        dukeconSettings.clearSetting('keycloak_idToken');
        dukeconSettings.clearSetting('keycloak_timeSkew');
        dukeconSettings.clearSetting('keycloak_username');
    }

    self.loadUserData = function() {
        dukecloak.keycloakAuth.updateToken()
            .success(function() {
                var username = dukeconSettings.getSetting('keycloak_username');
                if (username) {
                    dukecloak.auth.username(username);
                } else {
                    dukecloak.keycloakAuth.loadUserProfile().success(function (profile) {
                        dukecloak.auth.username(profile.username);
                        dukeconSettings.saveSetting('keycloak_username', dukecloak.auth.username());
                        console.log("Logged in: " + dukecloak.auth.username());
                    });
                }
                dukeconSynch.pull();
            })
            .error(function() {
                /* load user data is quite close to the initial setup
                failling an update here might indicate the the saved tokens are no longer valid */
                clearTokens();
                console.log("Unable to update token");
            });
    };

    self.logout = function() {
        clearTokens();
        dukecloak.keycloakAuth.logout().success(function() {
			dukecloak.auth.loggedIn(false);
			dukecloak.auth.loggedOut(true);
			dukecloak.auth.username("");
        }).error(function() {
			console.log("WTF");
        });
    };

    var dukecloakInitialized = false;

    self.login = function() {
        if(!dukecloakInitialized) {
            self.init(true);
            return;
        }
        dukecloak.keycloakAuth.login().success(function () {
            dukecloak.auth.loggedIn(true);
            dukecloak.auth.loggedOut(false);
        }).error(function () {
            dukecloak.auth.loggedIn(false);
            dukecloak.auth.loggedOut(true);
        });
    };

    self.keycloakAuth.onAuthSuccess = function() {
        console.log("Auth Success!!");
        saveTokens();
    };

    self.keycloakAuth.onAuthRefreshSuccess = function() {
        console.log("Auth Refreshed!!");
        saveTokens();
    };

    self.keycloakAuth.onAuthLogout = function() {
        console.log("Logged out!!");
        clearTokens();
    };

    self.init = function(login) {
        if(dukecloakInitialized) {
            return;
        }

        dukecloak.keycloakAuth.timeSkew = dukeconSettings.getSetting('keycloak_timeSkew');

        dukecloak.keycloakAuth.init({
            onLoad: login ? "login-required" : "check-sso",
            token: dukeconSettings.getSetting('keycloak_token'),
            idToken: dukeconSettings.getSetting('keycloak_idToken'),
            refreshToken: dukeconSettings.getSetting('keycloak_refreshToken')
        }).success(function (authenticated) {
            dukecloakInitialized = true;
            dukecloak.auth.loggedIn(authenticated);
            dukecloak.auth.loggedOut(!authenticated);
            console.log('Authenticated: ' + authenticated);
            if (authenticated) {
                console.log('local time: ' + new Date().getTime() / 1000);
                console.log('iat: ' + dukecloak.keycloakAuth.tokenParsed.iat);
                console.log('diff: ' + (new Date().getTime() / 1000 - dukecloak.keycloakAuth.tokenParsed.iat));
                console.log('exp in: ' + (dukecloak.keycloakAuth.tokenParsed.exp - new Date().getTime() / 1000));
                console.log('isExpired: ' + dukecloak.keycloakAuth.isTokenExpired());
                dukecloak.loadUserData();
            }
        }).error(function () {
            console.log("Error initializing keycloak");
        });
    }
};

<|endoftext|>


<commit_before>import moment from 'moment';
import React from 'react';
import {ReverseLink} from 'react-router-reverse';
import urlJoin from 'url-join';

import * as constants from '../constants';

import {PageSection} from '../../site/components/page';

/*
 * Add-on component to extend from.
 */
export class Addon extends React.Component {
  static propTypes = {
    description: React.PropTypes.string,
    isDisabled: React.PropTypes.bool.isRequired,
    latest_public_version: React.PropTypes.object,
    latest_version: React.PropTypes.object.isRequired,
    linkTo: React.PropTypes.string,
    mini_manifest_url: React.PropTypes.string.isRequired,
    name: React.PropTypes.string.isRequired,
    slug: React.PropTypes.string.isRequired,
    status: React.PropTypes.string,
  };

  getMarketplaceUrl() {
    // FIXME: this is bad, mmkay?
    if (this.props.status === constants.STATUS_PUBLIC) {
      return urlJoin(process.env.MKT_ROOT, 'addon/', this.props.slug);
    }
  }

  renderAddonStatusForDashboard() {
    return (

        {this.props.status === constants.STATUS_PUBLIC &&

            Your add-on
            is published and is
            currently available on Marketplace.

        }
        {this.props.status === constants.STATUS_PENDING &&

              Your add-on is currently
              pending approval.

              It is not currently available in Marketplace. You will receive an
              email when it has been reviewed.

        }
        {this.props.status === constants.STATUS_INCOMPLETE &&

              Your add-on is currently
               incomplete.

              This means that there are no public versions. It is not currently
              available in Marketplace. Please submit a new version for review.

        }
        {this.props.status === constants.STATUS_REJECTED &&

              Your add-on has been
              rejected.

              It is not currently available in Marketplace. You have been sent
              an email with further instructions.

        }

    );
  }

  renderAddonStatusForReview() {
    return (

        {this.props.status === constants.STATUS_PUBLIC &&

            This add-on
            is published and is
            currently available on Marketplace.

        }
        {this.props.status === constants.STATUS_PENDING &&

              This add-on is currently
              pending approval.

        }
        {this.props.status === constants.STATUS_INCOMPLETE &&

              This add-on is currently
               incomplete.

        }
        {this.props.status === constants.STATUS_REJECTED &&

              This add-on has been
              rejected.

        }

    );
  }

  renderLastUpdated() {
    if (this.props.latest_version) {
      return (
        <di>

Updated

            {moment(this.props.latest_version.created).format('MMMM Do, YYYY')}

        </di>
      );
    }
  }

  renderVersionStatusesForDashboard() {
    return (

        {this.props.latest_version.status === constants.STATUS_PENDING &&

            Version {this.props.latest_version.version} of your add-on
            is pending approval.

        }
        {this.props.latest_version.status === constants.STATUS_REJECTED &&

            Version {this.props.latest_version.version} of your add-on
            has been rejected.

        }
        {this.props.latest_public_version &&

            Version {this.props.latest_public_version.version} of your add-on
            is public.

        }

    );
  }

  renderVersionStatusesForReview() {
    return (

        {this.props.latest_version.status === constants.STATUS_PENDING &&

            Version {this.props.latest_version.version} of this add-on
            is pending approval.

        }
        {this.props.latest_version.status === constants.STATUS_REJECTED &&

            Version {this.props.latest_version.version} of this add-on
            has been rejected.

        }
        {this.props.latest_public_version &&

            Version {this.props.latest_public_version.version} of this add-on
            is public.

        }

    );
  }

  renderWaitingTime() {
    if (this.props.latest_version &&
        this.props.latest_version.status == constants.STATUS_PENDING) {
      return (
        <di>

Time in Queue

            {moment().diff(this.props.latest_version.created, 'days')} Days

        </di>
      );
    }
  }

  render() {
    return (

{this.props.name}

    );
  }
}

/*
 * Add-on for dashboard listing.
 */
export class AddonForDashboard extends Addon {
  render() {
    const marketplaceUrl = this.getMarketplaceUrl();
    return (

          <ReverseLink to={this.props.linkTo} params={{slug: this.props.slug}}>
            {this.props.name}
          </ReverseLink>

          <di className={`addon--status-${this.props.status}`}>

Status

              {constants.humanizeAddonStatus(this.props.status,
                                             this.props.disabled)}

          </di>
          {this.renderLastUpdated()}

              <ReverseLink to={this.props.linkTo}
                           params={{slug: this.props.slug}}>
                Edit this Add-on »
              </ReverseLink>

            {marketplaceUrl &&

                  View on Marketplace »

            }

    );
  }
}

/*
 * Add-on for dashboard detail.
 */
export class AddonForDashboardDetail extends Addon {
  render() {
    return (
      <PageSection className="addon-dashboard-detail--status">
        {this.renderAddonStatusForDashboard()}
        {this.props.latest_version && this.renderVersionStatusesForDashboard()}
      </PageSection>
    );
  }
}

/*
 * Add-on for review listing.
 */
export class AddonForReview extends Addon {
  render() {
    const marketplaceUrl = this.getMarketplaceUrl();
    return (

          <ReverseLink to={this.props.linkTo} params={{slug: this.props.slug}}>
            {this.props.name}
          </ReverseLink>

          <di className={`addon--status-${this.props.status}`}>

Status

              {constants.humanizeAddonStatus(this.props.status,
                                             this.props.disabled)}

          </di>
          {this.renderWaitingTime()}

              <ReverseLink to={this.props.linkTo}
                           params={{slug: this.props.slug}}>
                Review this Add-on »
              </ReverseLink>

            {marketplaceUrl &&

                  View on Marketplace »

            }

    );
  }
}

/*
 * Add-on for review detail.
 */
export class AddonForReviewDetail extends Addon {
  render() {
    return (
      <PageSection className="addon-review-detail-addon">

Slug

{this.props.slug}

            {this.props.latest_version &&
              <di>

Last Version Uploaded

{moment(this.props.latest_version.created)
                     .format('MMMM Do, YYYY')}

              </di>
            }

Description

{this.props.description}

Mini Manifest URL

              View

          {this.renderAddonStatusForReview()}
          {this.props.latest_version && this.renderVersionStatusesForReview()}

      </PageSection>
    );
  }
}
<commit_msg>add link to listing page on review detail if public<commit_after>import moment from 'moment';
import React from 'react';
import {ReverseLink} from 'react-router-reverse';
import urlJoin from 'url-join';

import * as constants from '../constants';

import {PageSection} from '../../site/components/page';

/*
 * Add-on component to extend from.
 */
export class Addon extends React.Component {
  static propTypes = {
    description: React.PropTypes.string,
    isDisabled: React.PropTypes.bool.isRequired,
    latest_public_version: React.PropTypes.object,
    latest_version: React.PropTypes.object.isRequired,
    linkTo: React.PropTypes.string,
    mini_manifest_url: React.PropTypes.string.isRequired,
    name: React.PropTypes.string.isRequired,
    slug: React.PropTypes.string.isRequired,
    status: React.PropTypes.string,
  };

  getMarketplaceUrl() {
    // FIXME: this is bad, mmkay?
    if (this.props.status === constants.STATUS_PUBLIC) {
      return urlJoin(process.env.MKT_ROOT, 'addon/', this.props.slug);
    }
  }

  renderAddonStatusForDashboard() {
    return (

        {this.props.status === constants.STATUS_PUBLIC &&

            Your add-on
            is published and is
            currently available on Marketplace.

        }
        {this.props.status === constants.STATUS_PENDING &&

              Your add-on is currently
              pending approval.

              It is not currently available in Marketplace. You will receive an
              email when it has been reviewed.

        }
        {this.props.status === constants.STATUS_INCOMPLETE &&

              Your add-on is currently
               incomplete.

              This means that there are no public versions. It is not currently
              available in Marketplace. Please submit a new version for review.

        }
        {this.props.status === constants.STATUS_REJECTED &&

              Your add-on has been
              rejected.

              It is not currently available in Marketplace. You have been sent
              an email with further instructions.

        }

    );
  }

  renderAddonStatusForReview() {
    return (

        {this.props.status === constants.STATUS_PUBLIC &&

            This add-on
            is published and is
            currently available on Marketplace.

        }
        {this.props.status === constants.STATUS_PENDING &&

              This add-on is currently
              pending approval.

        }
        {this.props.status === constants.STATUS_INCOMPLETE &&

              This add-on is currently
               incomplete.

        }
        {this.props.status === constants.STATUS_REJECTED &&

              This add-on has been
              rejected.

        }

    );
  }

  renderLastUpdated() {
    if (this.props.latest_version) {
      return (
        <di>

Updated

            {moment(this.props.latest_version.created).format('MMMM Do, YYYY')}

        </di>
      );
    }
  }

  renderVersionStatusesForDashboard() {
    return (

        {this.props.latest_version.status === constants.STATUS_PENDING &&

            Version {this.props.latest_version.version} of your add-on
            is pending approval.

        }
        {this.props.latest_version.status === constants.STATUS_REJECTED &&

            Version {this.props.latest_version.version} of your add-on
            has been rejected.

        }
        {this.props.latest_public_version &&

            Version {this.props.latest_public_version.version} of your add-on
            is public.

        }

    );
  }

  renderVersionStatusesForReview() {
    return (

        {this.props.latest_version.status === constants.STATUS_PENDING &&

            Version {this.props.latest_version.version} of this add-on
            is pending approval.

        }
        {this.props.latest_version.status === constants.STATUS_REJECTED &&

            Version {this.props.latest_version.version} of this add-on
            has been rejected.

        }
        {this.props.latest_public_version &&

            Version {this.props.latest_public_version.version} of this add-on
            is public.

        }

    );
  }

  renderWaitingTime() {
    if (this.props.latest_version &&
        this.props.latest_version.status == constants.STATUS_PENDING) {
      return (
        <di>

Time in Queue

            {moment().diff(this.props.latest_version.created, 'days')} Days

        </di>
      );
    }
  }

  render() {
    return (

{this.props.name}

    );
  }
}

/*
 * Add-on for dashboard listing.
 */
export class AddonForDashboard extends Addon {
  render() {
    const marketplaceUrl = this.getMarketplaceUrl();
    return (

          <ReverseLink to={this.props.linkTo} params={{slug: this.props.slug}}>
            {this.props.name}
          </ReverseLink>

          <di className={`addon--status-${this.props.status}`}>

Status

              {constants.humanizeAddonStatus(this.props.status,
                                             this.props.disabled)}

          </di>
          {this.renderLastUpdated()}

              <ReverseLink to={this.props.linkTo}
                           params={{slug: this.props.slug}}>
                Edit this Add-on »
              </ReverseLink>

            {marketplaceUrl &&

                  View on Marketplace »

            }

    );
  }
}

/*
 * Add-on for dashboard detail.
 */
export class AddonForDashboardDetail extends Addon {
  render() {
    return (
      <PageSection className="addon-dashboard-detail--status">
        {this.renderAddonStatusForDashboard()}
        {this.props.latest_version && this.renderVersionStatusesForDashboard()}
      </PageSection>
    );
  }
}

/*
 * Add-on for review listing.
 */
export class AddonForReview extends Addon {
  render() {
    const marketplaceUrl = this.getMarketplaceUrl();
    return (

          <ReverseLink to={this.props.linkTo} params={{slug: this.props.slug}}>
            {this.props.name}
          </ReverseLink>

          <di className={`addon--status-${this.props.status}`}>

Status

              {constants.humanizeAddonStatus(this.props.status,
                                             this.props.disabled)}

          </di>
          {this.renderWaitingTime()}

              <ReverseLink to={this.props.linkTo}
                           params={{slug: this.props.slug}}>
                Review this Add-on »
              </ReverseLink>

            {marketplaceUrl &&

                  View on Marketplace »

            }

    );
  }
}

/*
 * Add-on for review detail.
 */
export class AddonForReviewDetail extends Addon {
  render() {
    const marketplaceUrl = this.getMarketplaceUrl();
    return (
      <PageSection className="addon-review-detail-addon">

Slug

{this.props.slug}

            {this.props.latest_version &&
              <di>

Last Version Uploaded

{moment(this.props.latest_version.created)
                     .format('MMMM Do, YYYY')}

              </di>
            }

Description

{this.props.description}

Mini Manifest URL

              View

            {marketplaceUrl && this.props.status === constants.STATUS_PUBLIC &&
              <di>

Listing Page

                    View on Marketplace

              </di>
            }

          {this.renderAddonStatusForReview()}
          {this.props.latest_version && this.renderVersionStatusesForReview()}

      </PageSection>
    );
  }
}
<|endoftext|>


<commit_before>
import Searchbar from '../../molecules/searchbar/searchbar';

export default function Header(selector = 'header') {
  const element = document.querySelector(selector);

  Searchbar('header .searchbar', {
    mouseover: () => {
      console.log('header:', 'you hovered over my searchbar');
    },
  });

  // alternativ:
  // new Searchbar();
  // new Searchbar('header .searchbar');

  // -> Logik der Searchbar selbst wird immer ausgeführt
  // -> Callbacks ermöglichen das Erweitern der Funktionalität
}
<commit_msg>Remove unnecessary parameter in header.js<commit_after>
import Searchbar from '../../molecules/searchbar/searchbar';

export default function Header() {
  Searchbar('header .searchbar', {
    mouseover: () => {
      console.log('header:', 'you hovered over my searchbar');
    },
  });

  // alternativ:
  // new Searchbar();
  // new Searchbar('header .searchbar');

  // -> Logik der Searchbar selbst wird immer ausgeführt
  // -> Callbacks ermöglichen das Erweitern der Funktionalität
}
<|endoftext|>


<commit_before>

var renderElements = {};
var renderidOffset = 0;
var addRenderElement = function () {
    var element = this;
    if (!isNode(element)) return;
    if (!element.renderid) {
        element.renderid = ++renderidOffset;
    }
    renderElements[element.renderid] = element;
};
var removeRenderElement = function () {
    var element = this;
    delete renderElements[element.renderid];
};
function refresh() {
    for (var k in renderElements) {
        var element = renderElements[k];
        rebuild(element);
    }
}
function rebuild(element) {
    element.renders.map(a => a.call(element));
}
var createGetter = function (search) {
    return new Function("scope", `try{with(scope)return ${search}}catch(e){/*console.warn(String(e))*/}`);
};
var directives = {
    click(scope, search) {
        var getter = createGetter(search);
        onclick(this, getter.bind(this, scope));
    },
    bind(scope, search) {
        var getter = createGetter(search);
        this.renders.push(function () {
            var value = getter(scope);
            if (text(this) !== value) text(this, value);
        });
    },
    model(scope, search) {
        var getter = createGetter(search);
        if (/select|input|textarea/i.test(this.tagName)) {
            this.renders.push(function () {
                var value = getter(scope);
                if (value === undefined) value = "";
                if (this.value != value) this.value = value;

            });
            var change = new Function("scope", `with(scope)${search}=this.value`).bind(this, scope);
        } else {
            this.renders.push(function () {
                var value = getter(scope);
                if (value === undefined) value = "";
                if (html(this) != value) html(this, value);
            });
            var change = new Function("scope", "html", `with(scope)${search}=html(this)`).bind(this, scope, html);
        }
        var onchange = lazy(change);
        eventsHandlers.map(on => on(this, onchange));
    },
    hide(scope, search) {
        var getter = createGetter(search);
        this.renders.push(function () {
            if (getter(scope)) {
                this.style.display = "none";
            } else {
                this.style.display = "";
            }
        });
    },
    show(scope, search) {
        var getter = createGetter(search);
        this.renders.push(function () {
            if (getter(scope)) {
                this.style.display = "";
            } else {
                this.style.display = "none";
            }
        });
    },
    "if"(scope, search) {
        // 懒渲染
        var getter = createGetter(search);
        var cancelonappend = onappend(this, function () {
            cancelonappend();
            var comment = document.createComment("-if:" + search);
            comment.renders = [function () {
                if (getter(scope)) {
                    if (!this.parentNode) appendChild.before(comment, this);
                } else {
                    remove(this);
                }
            }.bind(this)];
            onappend(comment, addRenderElement);
            onremove(comment, removeRenderElement);
            appendChild.after(this, comment);
            rebuild(comment);
        });
    },
    repeat(scope, search) {
        // 懒渲染
        throw new Error("repeat is not supported! use list component instead");
    },
    "class"(scope, search) {
        var getter = createGetter(search);
        var originClassName = [];
        this.className.split(/\s+/).map(function (k) {
            if (k && !hasOwnProperty.call(originClassName, k)) {
                originClassName.push(originClassName[k] = k);
            }
        });
        this.renders.push(function () {
            var className = getter(scope);
            var deltaClassNames = [];
            if (isString(className)) {
                className.split(/\s+/).map(function (k) {
                    if (!hasOwnProperty.call(originClassName, k)) {
                        deltaClassNames.push(deltaClassNames[k] = k);
                    }
                });
            } else if (className instanceof Object) {
                for (var k in className) {
                    if (!hasOwnProperty.call(originClassName, k)) {
                        deltaClassNames.push(deltaClassNames[k] = k);
                    }
                }
            }
            var destClassName = originClassName.concat(deltaClassNames).join(" ");
            if (this.className !== destClassName) {
                this.className = destClassName;
            }
        });
    },
    style(scope, search) {
        var getter = createGetter(search);
        this.renders.push(function () {
            var stylesheet = getter(scope);
            if (isString(stylesheet)) {
                stylesheet.replace(/[\s\u00a0]+/g, "").split(/;/).map(function (kv) {
                    var [k, v] = kv.split(":");
                    if (this.style[k] !== v) {
                        this.style[k] = v;
                    }
                }, this);
            } else if (stylesheet instanceof Object) {
                for (var k in stylesheet) {
                    if (this.style[k] !== stylesheet[k]) {
                        this.style[k] = stylesheet[k];
                    }
                }
            }
        });
    }
};
function renderElement(element, scope) {
    if (element.renderid) return element;
    var children = element.children;
    if (!children) {
        return [].slice.call(element, 0).map(function (element) {
            return renderElement(element, scope);
        });
    }
    var attrs = element.attributes;
    element.renders = [];
    [].slice.call(attrs, 0).map(function (attr) {
        var { name, value } = attr;
        if (/^(?:class|style)$/i.test(name)) return;
        name = name.replace(/^(ng|v|.*?)\-/i, "").toLowerCase();
        if (directives.hasOwnProperty(name) && isFunction(directives[name])) {
            directives[name].call(element, scope, value);
        }
    });
    if (children.length) renderElement(children, scope);
    if (element.renders.length) {
        onappend(element, addRenderElement);
        onremove(element, removeRenderElement);
        rebuild(element);
    }
}
function render(element, scope) {
    return renderElement(element, scope);
}

var digest = lazy(refresh);
render.digest = digest;

var eventsHandlers = "change,paste,resize,keydown,keypress,keyup,mousedown,mouseup,dragend,drop".split(",").map(k => on(k));
eventsHandlers.map(on => on(window, digest));<commit_msg>当ng-class是object时，只有value为真的key生效<commit_after>

var renderElements = {};
var renderidOffset = 0;
var addRenderElement = function () {
    var element = this;
    if (!isNode(element)) return;
    if (!element.renderid) {
        element.renderid = ++renderidOffset;
    }
    renderElements[element.renderid] = element;
};
var removeRenderElement = function () {
    var element = this;
    delete renderElements[element.renderid];
};
function refresh() {
    for (var k in renderElements) {
        var element = renderElements[k];
        rebuild(element);
    }
}
function rebuild(element) {
    element.renders.map(a => a.call(element));
}
var createGetter = function (search) {
    return new Function("scope", `try{with(scope)return ${search}}catch(e){/*console.warn(String(e))*/}`);
};
var directives = {
    click(scope, search) {
        var getter = createGetter(search);
        onclick(this, getter.bind(this, scope));
    },
    bind(scope, search) {
        var getter = createGetter(search);
        this.renders.push(function () {
            var value = getter(scope);
            if (text(this) !== value) text(this, value);
        });
    },
    model(scope, search) {
        var getter = createGetter(search);
        if (/select|input|textarea/i.test(this.tagName)) {
            this.renders.push(function () {
                var value = getter(scope);
                if (value === undefined) value = "";
                if (this.value != value) this.value = value;

            });
            var change = new Function("scope", `with(scope)${search}=this.value`).bind(this, scope);
        } else {
            this.renders.push(function () {
                var value = getter(scope);
                if (value === undefined) value = "";
                if (html(this) != value) html(this, value);
            });
            var change = new Function("scope", "html", `with(scope)${search}=html(this)`).bind(this, scope, html);
        }
        var onchange = lazy(change);
        eventsHandlers.map(on => on(this, onchange));
    },
    hide(scope, search) {
        var getter = createGetter(search);
        this.renders.push(function () {
            if (getter(scope)) {
                this.style.display = "none";
            } else {
                this.style.display = "";
            }
        });
    },
    show(scope, search) {
        var getter = createGetter(search);
        this.renders.push(function () {
            if (getter(scope)) {
                this.style.display = "";
            } else {
                this.style.display = "none";
            }
        });
    },
    "if"(scope, search) {
        // 懒渲染
        var getter = createGetter(search);
        var cancelonappend = onappend(this, function () {
            cancelonappend();
            var comment = document.createComment("-if:" + search);
            comment.renders = [function () {
                if (getter(scope)) {
                    if (!this.parentNode) appendChild.before(comment, this);
                } else {
                    remove(this);
                }
            }.bind(this)];
            onappend(comment, addRenderElement);
            onremove(comment, removeRenderElement);
            appendChild.after(this, comment);
            rebuild(comment);
        });
    },
    repeat(scope, search) {
        // 懒渲染
        throw new Error("repeat is not supported! use list component instead");
    },
    "class"(scope, search) {
        var getter = createGetter(search);
        var originClassName = [];
        this.className.split(/\s+/).map(function (k) {
            if (k && !hasOwnProperty.call(originClassName, k)) {
                originClassName.push(originClassName[k] = k);
            }
        });
        this.renders.push(function () {
            var className = getter(scope);
            var deltaClassNames = [];
            if (isString(className)) {
                className.split(/\s+/).map(function (k) {
                    if (!hasOwnProperty.call(originClassName, k)) {
                        deltaClassNames.push(deltaClassNames[k] = k);
                    }
                });
            } else if (className instanceof Object) {
                for (var k in className) {
                    if (!hasOwnProperty.call(originClassName, k) && className[k]) {
                        deltaClassNames.push(deltaClassNames[k] = k);
                    }
                }
            }
            var destClassName = originClassName.concat(deltaClassNames).join(" ");
            if (this.className !== destClassName) {
                this.className = destClassName;
            }
        });
    },
    style(scope, search) {
        var getter = createGetter(search);
        this.renders.push(function () {
            var stylesheet = getter(scope);
            if (isString(stylesheet)) {
                stylesheet.replace(/[\s\u00a0]+/g, "").split(/;/).map(function (kv) {
                    var [k, v] = kv.split(":");
                    if (this.style[k] !== v) {
                        this.style[k] = v;
                    }
                }, this);
            } else if (stylesheet instanceof Object) {
                for (var k in stylesheet) {
                    if (this.style[k] !== stylesheet[k]) {
                        this.style[k] = stylesheet[k];
                    }
                }
            }
        });
    }
};
function renderElement(element, scope) {
    if (element.renderid) return element;
    var children = element.children;
    if (!children) {
        return [].slice.call(element, 0).map(function (element) {
            return renderElement(element, scope);
        });
    }
    var attrs = element.attributes;
    element.renders = [];
    [].slice.call(attrs, 0).map(function (attr) {
        var { name, value } = attr;
        if (/^(?:class|style)$/i.test(name)) return;
        name = name.replace(/^(ng|v|.*?)\-/i, "").toLowerCase();
        if (directives.hasOwnProperty(name) && isFunction(directives[name])) {
            directives[name].call(element, scope, value);
        }
    });
    if (children.length) renderElement(children, scope);
    if (element.renders.length) {
        onappend(element, addRenderElement);
        onremove(element, removeRenderElement);
        rebuild(element);
    }
}
function render(element, scope) {
    return renderElement(element, scope);
}

var digest = lazy(refresh);
render.digest = digest;

var eventsHandlers = "change,paste,resize,keydown,keypress,keyup,mousedown,mouseup,dragend,drop".split(",").map(k => on(k));
eventsHandlers.map(on => on(window, digest));<|endoftext|>


<commit_before>/*
 * 不枝雀
 * 2017-3-18 16:16:20
 */
//main
var body = document.body;
var onbacks = [];
var target_hash, exit_ing;
var window_history = window.history;
var window_history_length = window_history.length;
var load_count = "__zimoli_load_times";
var loadTime = +sessionStorage.getItem(load_count) || 0;
if (!loadTime) {
    location.replace("#reload");
}
loadTime++;
sessionStorage.setItem(load_count, loadTime);

if (/MSIE\s*[2-7]/.test(navigator.userAgent)) {
    window.onhistorychange = function (url) {
        if (exit_ing) return exit_ing = false, window_history.go(-1);
        if (exit_ing === void 0 ? onback && onback() === true : exit_ing = void 0) { }
    };
    onselectstart(body, function (e) {
        return e.preventDefault();
    });
    var frame = createElement("iframe");
    css(frame, "display:none");
    appendChild(body, frame);
    var doc = frame.contentWindow.document;
    var backman = function (isloaded) {
        doc.open();
        doc.write(isloaded !== false ? "" : "<script>result=parent.onhistorychange();onload=function(){history.forward()}</script>");
        doc.close();
    };
    backman(false);
    backman();
} else {
    onhashchange(window, function (event) {
        if (/#$/.test(event.newURL || event.actionURL || location.href)) return;
        if (exit_ing) return exit_ing = false, window_history.go(-1);
        event.preventDefault();
        if (exit_ing === void 0 ? onback() === true : exit_ing = void 0) { }
    });
}
// body
css("html", {
    height: "100%",
    fontFamily: `"SF Pro SC","SF Pro Text","SF Pro Icons","PingFang SC","Helvetica Neue","Helvetica","Arial",sans-serif`,
    backgroundColor: "#f2f4f9"
});
css("body", {
    border: "none",
    margin: "0",
    padding: "0",
    height: "100%",
    overflow: "hidden",
});
var location_pathname = location.pathname;
var _zimoli_params_key = `_zimoli_parameters:${location_pathname}#`;
var _zimoli_state_prefix = `_zimoli_page_state:${location_pathname}#`;

function go(url, args, history_name, oldpagepath) {
    if (isNumber(url)) {
        if (!history_name)
            history_name = current_history;
        if (isString(history_name)) {
            var _history = history[history_name] || [];
            url = _history[url < 1 ? _history.length + url - 1 : url];
            oldpagepath = _history[_history.length - 1];
        }
    }
    if (!url) return true;
    var stringified_args = JSON.stringify({ data: args, from: oldpagepath });
    if (stringified_args.length === 2) localStorage.removeItem(_zimoli_params_key + url);
    else localStorage.setItem(_zimoli_params_key + url, stringified_args);
    if (!page_generators[url]) {
        return zimoli(url, args, history_name, oldpagepath);
    }
    if (isNode(history_name)) {
        if (history_name.activate === url) return;
        history_name.activate = url;
    }
    var pg = page_generators[url];
    var _with_elements = [].concat(pg.with);
    var _pageback_listener = pg.onback;
    var state = pg.state;
    state.with = function (element) {
        element && _with_elements.push(element);
        return _with_elements;
    };
    state.onback = function (handler) {
        _pageback_listener = handler;
    };
    if (undefined === args || null === args) args = {};
    var _page = pg.call(state, args, oldpagepath);
    if (_page) {
        if (pg.className) _page.className = pg.className;
        _page.with = _with_elements;
        if (args.initialStyle) _page.initialStyle = args.initialStyle;
        _page.onback = _pageback_listener;
    }
    pushstate(url, history_name, oldpagepath);
    addGlobal(_page, history_name);
    return _page;
}
var page_generators = {};
/**
 * 加载一个页面到document.body
 * 如果args是一个字符串，那么当下次指定一个相同的字符串时，此对象被新对象代替
 * 如果args是bool值true，那么当执行history.back()时，此对象被清除
 */
function zimoli(pagepath, args, history_name, oldpagepath) {
    if (arguments.length === 0) {
        exit_ing = false;
        history_name = current_history;
        var _history = history[history_name] || [];
        pagepath = _history[_history.length - 1] || "/main";
        try {
            var saveddata = JSON.parse(localStorage.getItem(_zimoli_params_key + pagepath)) || {};
        } catch (e) {
            var saveddata = {};
        }
        var { data, from } = saveddata;
        args = data;
        oldpagepath = from;
    }
    var _zimoli_state_key = _zimoli_state_prefix + pagepath;
    var state = function state(condition, setAsAdditional = condition !== null) {
        var state_string = localStorage.getItem(_zimoli_state_key);
        var state_object;
        if (state_string) {
            try {
                state_object = JSON.parse(state_string);
            } catch (e) {
                state_object = {};
            }
        } else {
            state_object = {}
        }
        if (condition instanceof Object && setAsAdditional) {
            if (!(state_object instanceof Object)) {
                state_object = {
                    toString() {
                        return String(this.valueOf());
                    },
                    valueOf: new Function(`return ${state_object}`),
                };
            }
            state_object = extend(state_object, condition);
        } else if (arguments.length) {
            state_object = condition;
        }
        if (arguments.length) {
            localStorage.setItem(_zimoli_state_key, JSON.stringify(state_object) || null);
        }
        return state_object;
    };
    state.state = state;
    if (page_generators[pagepath]) return go(pagepath, args, history_name, oldpagepath);
    var _with_elements = [];
    state.with = function (element) {
        element && _with_elements.push(element);
        return _with_elements;
    };
    state.path = function (url) {
        if (isString(url) && /^[^\\\/]/.test(url)) {
            url = pagepath.replace(/[^\/]*$/, url);
        }
        return url;
    }
    state.go = function (url, args, history_name) {
        return go(state.path(url), args, history_name, pagepath);
    };

    var _pageback_listener = [];
    state.onback = state.onrelease = state.ondestroy = function (handler) {
        //只能在page上使用
        _pageback_listener = handler;
    };
    state.titlebar = function () {
        var realTitleBar = titlebar.apply(null, arguments);
        state.with(realTitleBar);
        return realTitleBar;
    };
    return init(pagepath, function (pg) {
        if (!pg) return;
        pg.with = _with_elements;
        pg.state = state;
        pg.onback = _pageback_listener;
        page_generators[pagepath] = pg;
        return go(pagepath, args, history_name, oldpagepath);
    }, state);
}
var global = {};
var history = {};
var current_history = "default";
history[current_history] = [];
var history_session_object_key = `_zimoli_history_key:${location_pathname}`;
try {
    history = JSON.parse(localStorage.getItem(history_session_object_key)) || history;
} catch (e) {
}
var pushstate = function (path_name, history_name, oldpagepath) {
    if (!history_name) {
        history_name = current_history;
    }
    if (!isString(history_name)) return;
    if (!history[history_name]) {
        history[history_name] = [path_name];
    } else {
        var _history = history[history_name];
        if (_history.indexOf(oldpagepath) < 0) {
            console.log(oldpagepath, path_name);
            _history.splice(_history[0] === ":empty", _history.length);
        }
        for (var cx = 0, dx = _history.length; cx < dx; cx++) {
            if (_history[cx] === path_name) {
                _history.splice(cx, dx - cx);
                break;
            }
        }
        _history.push(path_name);
        if (_history.length > 1) fixurl();
    }
    localStorage.setItem(history_session_object_key, JSON.stringify(history) || null);
};
var fixurl = function () {
    setTimeout(function () {
        exit_ing = void 0;
        if (!/#$/.test(location.href)) location.href = "#";
    }, 0);
}
var checkonback = function (elements) {
    for (var cx = 0, dx = elements.length; cx < dx; cx++) {
        var element = elements[cx];
        var onback = element && element.onback;
        if (isFunction(onback)) {
            onback = element.onback();
        }
        if (onback === false || isString(onback)) {
            break;
        }
    }
    return onback;
}
put(":empty", function () {
    return null;
});

var onback = function () {
    if (rootElements.length) {
        fixurl();
        remove(rootElements.pop());
        return;
    }
    var onback = checkonback([
        global[current_history],
    ]);
    if (onback === false) {
        fixurl();
        return;
    }
    if (isString(onback)) {
        return go(onback);
    }
    if (go(-1, onback) === true) {
        try {
            navigator.app.exitApp();
        } catch (e) {
            if (window_history.length > 2) exit_ing = true, window_history.go(-1);
        };
    } else { };
};

function addGlobal(element, name) {
    if (!name) {
        name = current_history;
    }
    if (isString(name)) {
        if (global[name] === element) return;
        if (isFunction(body.layer)) {
            body.layer(element, global[name], history);
        } else {
            if (global[name]) {
                remove(global[name]);
            }
            appendChild(body, element);
        }
        global[name] = element;
    } else if (isNode(name)) {
        appendChild(name, element);
    } else if (isFunction(name)) {
        name(element);
    } else if (element) {
        popup(element);
        fixurl();
    }
}
var _switch = zimoli.switch = function (history_name, target_body, emptyState) {
    if (history_name)
        current_history = history_name;
    if (target_body)
        body = target_body;
    if (emptyState !== false && !history[history_name]) history[history_name] = [emptyState || ":empty"];
};
zimoli.global = addGlobal;
popup.go = zimoli.go = go;
rootElements.push = function () {
    [].push.apply(this, arguments);
    fixurl();
};
appendChild.transition = transition;
remove.transition = transition;
window.modules = modules;<commit_msg>解决onback时缺少oldpagepath的问题<commit_after>/*
 * 不枝雀
 * 2017-3-18 16:16:20
 */
//main
var body = document.body;
var onbacks = [];
var target_hash, exit_ing;
var window_history = window.history;
var window_history_length = window_history.length;
var load_count = "__zimoli_load_times";
var loadTime = +sessionStorage.getItem(load_count) || 0;
if (!loadTime) {
    location.replace("#reload");
}
loadTime++;
sessionStorage.setItem(load_count, loadTime);

if (/MSIE\s*[2-7]/.test(navigator.userAgent)) {
    window.onhistorychange = function (url) {
        if (exit_ing) return exit_ing = false, window_history.go(-1);
        if (exit_ing === void 0 ? onback && onback() === true : exit_ing = void 0) { }
    };
    onselectstart(body, function (e) {
        return e.preventDefault();
    });
    var frame = createElement("iframe");
    css(frame, "display:none");
    appendChild(body, frame);
    var doc = frame.contentWindow.document;
    var backman = function (isloaded) {
        doc.open();
        doc.write(isloaded !== false ? "" : "<script>result=parent.onhistorychange();onload=function(){history.forward()}</script>");
        doc.close();
    };
    backman(false);
    backman();
} else {
    onhashchange(window, function (event) {
        if (/#$/.test(event.newURL || event.actionURL || location.href)) return;
        if (exit_ing) return exit_ing = false, window_history.go(-1);
        event.preventDefault();
        if (exit_ing === void 0 ? onback() === true : exit_ing = void 0) { }
    });
}
// body
css("html", {
    height: "100%",
    fontFamily: `"SF Pro SC","SF Pro Text","SF Pro Icons","PingFang SC","Helvetica Neue","Helvetica","Arial",sans-serif`,
    backgroundColor: "#f2f4f9"
});
css("body", {
    border: "none",
    margin: "0",
    padding: "0",
    height: "100%",
    overflow: "hidden",
});
var location_pathname = location.pathname;
var _zimoli_params_key = `_zimoli_parameters:${location_pathname}#`;
var _zimoli_state_prefix = `_zimoli_page_state:${location_pathname}#`;

function go(url, args, history_name, oldpagepath) {
    if (isNumber(url)) {
        if (!history_name)
            history_name = current_history;
        if (isString(history_name)) {
            var _history = history[history_name] || [];
            url = _history[url < 1 ? _history.length + url - 1 : url];
            oldpagepath = _history[_history.length - 1];
        }
    }
    if (!url) return true;
    var stringified_args = JSON.stringify({ data: args, from: oldpagepath });
    if (stringified_args.length === 2) localStorage.removeItem(_zimoli_params_key + url);
    else localStorage.setItem(_zimoli_params_key + url, stringified_args);
    if (!page_generators[url]) {
        return zimoli(url, args, history_name, oldpagepath);
    }
    if (isNode(history_name)) {
        if (history_name.activate === url) return;
        history_name.activate = url;
    }
    var pg = page_generators[url];
    var _with_elements = [].concat(pg.with);
    var _pageback_listener = pg.onback;
    var state = pg.state;
    state.with = function (element) {
        element && _with_elements.push(element);
        return _with_elements;
    };
    state.onback = function (handler) {
        _pageback_listener = handler;
    };
    if (undefined === args || null === args) args = {};
    var _page = pg.call(state, args, oldpagepath);
    if (_page) {
        if (pg.className) _page.className = pg.className;
        _page.with = _with_elements;
        if (args.initialStyle) _page.initialStyle = args.initialStyle;
        _page.onback = _pageback_listener;
    }
    pushstate(url, history_name, oldpagepath);
    addGlobal(_page, history_name);
    return _page;
}
var page_generators = {};
/**
 * 加载一个页面到document.body
 * 如果args是一个字符串，那么当下次指定一个相同的字符串时，此对象被新对象代替
 * 如果args是bool值true，那么当执行history.back()时，此对象被清除
 */
function zimoli(pagepath, args, history_name, oldpagepath) {
    if (arguments.length === 0) {
        exit_ing = false;
        history_name = current_history;
        var _history = history[history_name] || [];
        pagepath = _history[_history.length - 1] || "/main";
        try {
            var saveddata = JSON.parse(localStorage.getItem(_zimoli_params_key + pagepath)) || {};
        } catch (e) {
            var saveddata = {};
        }
        var { data, from } = saveddata;
        args = data;
        oldpagepath = from;
    }
    var _zimoli_state_key = _zimoli_state_prefix + pagepath;
    var state = function state(condition, setAsAdditional = condition !== null) {
        var state_string = localStorage.getItem(_zimoli_state_key);
        var state_object;
        if (state_string) {
            try {
                state_object = JSON.parse(state_string);
            } catch (e) {
                state_object = {};
            }
        } else {
            state_object = {}
        }
        if (condition instanceof Object && setAsAdditional) {
            if (!(state_object instanceof Object)) {
                state_object = {
                    toString() {
                        return String(this.valueOf());
                    },
                    valueOf: new Function(`return ${state_object}`),
                };
            }
            state_object = extend(state_object, condition);
        } else if (arguments.length) {
            state_object = condition;
        }
        if (arguments.length) {
            localStorage.setItem(_zimoli_state_key, JSON.stringify(state_object) || null);
        }
        return state_object;
    };
    state.state = state;
    if (page_generators[pagepath]) return go(pagepath, args, history_name, oldpagepath);
    var _with_elements = [];
    state.with = function (element) {
        element && _with_elements.push(element);
        return _with_elements;
    };
    state.path = function (url) {
        if (isString(url) && /^[^\\\/]/.test(url)) {
            url = pagepath.replace(/[^\/]*$/, url);
        }
        return url;
    }
    state.go = function (url, args, history_name) {
        return go(state.path(url), args, history_name, pagepath);
    };

    var _pageback_listener = [];
    state.onback = state.onrelease = state.ondestroy = function (handler) {
        //只能在page上使用
        _pageback_listener = handler;
    };
    state.titlebar = function () {
        var realTitleBar = titlebar.apply(null, arguments);
        state.with(realTitleBar);
        return realTitleBar;
    };
    return init(pagepath, function (pg) {
        if (!pg) return;
        pg.with = _with_elements;
        pg.state = state;
        pg.onback = _pageback_listener;
        page_generators[pagepath] = pg;
        return go(pagepath, args, history_name, oldpagepath);
    }, state);
}
var global = {};
var history = {};
var current_history = "default";
history[current_history] = [];
var history_session_object_key = `_zimoli_history_key:${location_pathname}`;
try {
    history = JSON.parse(localStorage.getItem(history_session_object_key)) || history;
} catch (e) {
}
var pushstate = function (path_name, history_name, oldpagepath) {
    if (!history_name) {
        history_name = current_history;
    }
    if (!isString(history_name)) return;
    if (!history[history_name]) {
        history[history_name] = [path_name];
    } else {
        var _history = history[history_name];
        if (_history.indexOf(oldpagepath) < 0) {
            _history.splice(_history[0] === ":empty", _history.length);
        }
        for (var cx = 0, dx = _history.length; cx < dx; cx++) {
            if (_history[cx] === path_name) {
                _history.splice(cx, dx - cx);
                break;
            }
        }
        _history.push(path_name);
        if (_history.length > 1) fixurl();
    }
    localStorage.setItem(history_session_object_key, JSON.stringify(history) || null);
};
var fixurl = function () {
    setTimeout(function () {
        exit_ing = void 0;
        if (!/#$/.test(location.href)) location.href = "#";
    }, 0);
}
var checkonback = function (elements) {
    for (var cx = 0, dx = elements.length; cx < dx; cx++) {
        var element = elements[cx];
        var onback = element && element.onback;
        if (isFunction(onback)) {
            onback = element.onback();
        }
        if (onback === false || isString(onback)) {
            break;
        }
    }
    return onback;
}
put(":empty", function () {
    return null;
});

var onback = function () {
    if (rootElements.length) {
        fixurl();
        remove(rootElements.pop());
        return;
    }
    var onback = checkonback([
        global[current_history],
    ]);
    if (onback === false) {
        fixurl();
        return;
    }
    if (isString(onback)) {
        return go(onback);
    }
    if (go(-1, onback) === true) {
        try {
            navigator.app.exitApp();
        } catch (e) {
            if (window_history.length > 2) exit_ing = true, window_history.go(-1);
        };
    } else { };
};

function addGlobal(element, name) {
    if (!name) {
        name = current_history;
    }
    if (isString(name)) {
        if (global[name] === element) return;
        if (isFunction(body.layer)) {
            body.layer(element, global[name], history);
        } else {
            if (global[name]) {
                remove(global[name]);
            }
            appendChild(body, element);
        }
        global[name] = element;
    } else if (isNode(name)) {
        appendChild(name, element);
    } else if (isFunction(name)) {
        name(element);
    } else if (element) {
        popup(element);
        fixurl();
    }
}
var _switch = zimoli.switch = function (history_name, target_body, emptyState) {
    if (history_name)
        current_history = history_name;
    if (target_body)
        body = target_body;
    if (emptyState !== false && !history[history_name]) history[history_name] = [emptyState || ":empty"];
};
zimoli.global = addGlobal;
popup.go = zimoli.go = go;
rootElements.push = function () {
    [].push.apply(this, arguments);
    fixurl();
};
appendChild.transition = transition;
remove.transition = transition;
window.modules = modules;<|endoftext|>