<commit_before>import webpack from 'webpack';

function getBabelLoaderOptions({optimize = false, transpileOnlyForLastChromes = false}) {
    if (optimize || !transpileOnlyForLastChromes) {
        return {
            babelrc: false,
            presets: [
                ['es2015', {
                    // TODO
                    modules: false
                }]
            ]
        };
    }

    return {
        babelrc: false,
        presets: [
            ['env', {
                targets: {
                    browsers: ['last 2 Chrome versions']
                }
            }]
        ],
        cacheDirectory: true
    };
}

export default function config(speedupLocalDevelopment, optimize = false) {
    const config = {
        devtool: optimize ? 'source-map' : 'cheap-module-source-map',
        module: {
            rules: [
                {
                    test: /\.js$/,
                    exclude: /node_modules/,
                    loader: 'babel-loader',
                    query: getBabelLoaderOptions({
                        transpileOnlyForLastChromes: speedupLocalDevelopment
                    })
                }
            ]
        },
        plugins: []
    };

    if (optimize) {
        config.plugins.push(new webpack.optimize.UglifyJsPlugin({mangle: true, sourceMap: true}));
    }

    return config;
};<commit_msg>[GeneratorBundle] update babel preset env (#1755)<commit_after>import webpack from 'webpack';

function getBabelLoaderOptions({optimize = false, transpileOnlyForLastChromes = false}) {
    if (optimize || !transpileOnlyForLastChromes) {
        return {
            babelrc: false,
            presets: [
                require.resolve('babel-preset-env', {
                    modules: false
                })
            ]
        };
    }

    return {
        babelrc: false,
        presets: [
            require.resolve('babel-preset-env', {
                targets: {
                    browsers: ['last 2 Chrome versions']
                },
                debug: true
            })
        ],
        cacheDirectory: true
    };
}

export default function config(speedupLocalDevelopment, optimize = false) {
    const config = {
        devtool: optimize ? 'source-map' : 'cheap-module-source-map',
        module: {
            rules: [
                {
                    test: /\.js$/,
                    exclude: /node_modules/,
                    loader: 'babel-loader',
                    query: getBabelLoaderOptions({
                        transpileOnlyForLastChromes: speedupLocalDevelopment
                    })
                }
            ]
        },
        plugins: []
    };

    if (optimize) {
        config.plugins.push(new webpack.optimize.UglifyJsPlugin({mangle: true, sourceMap: true}));
    }

    return config;
};
<|endoftext|>


<commit_before>/**
 * Output widget to vizualize DomainAnnotation object.
 * Pavel Novichkov <psnovichkov@lbl.gov>, John-Marc Chandonia <jmchandonia@lbl.gov>
 * @public
 */

(function($, undefined) {
    $.KBWidget({
        name: 'kbaseDomainAnnotation',
        parent: 'kbaseAuthenticatedWidget',
        version: '1.0.2',
        options: {
            domainAnnotationID: null,
            workspaceID: null,
            domainAnnotationVer: null,
            kbCache: null,
            workspaceURL: window.kbconfig.urls.workspace,
            loadingImage: "static/kbase/images/ajax-loader.gif",
            height: null,
        },

        // Data for vizualization
        domainAnnotationData: null,
        genomeRef: null,
        genomeId: null,
        genomeName: null,
        domainModelSetRef: null,
        domainModelSetName: null,
        domainAccession2Description: {},
        annotatedGenesCount: 0,
        annotatedDomainsCount: 0,

        init: function(options) {
            this._super(options);

            // TEMPORARY
            if(this.options.domainAnnotationID == null){
                this.options.domainAnnotationID = 12;
                this.options.workspaceID = 2959;
                this.options.domainAnnotationVer = 8;
            }

            // Create a message pane
            this.$messagePane = $("
").addClass("kbwidget-message-pane kbwidget-hide-message");
            this.$elem.append(this.$messagePane);

            return this;
        },

        loggedInCallback: function(event, auth) {
            // Create a new workspace client
            this.ws = new Workspace(this.options.workspaceURL, auth);

            // Let's go...
            this.render();

            return this;
        },

        loggedOutCallback: function(event, auth) {
            this.ws = null;
            this.isLoggedIn = false;
            return this;
        },

        render: function(){
            var self = this;
            self.pref = this.uuid();
            self.loading(true);

            var container = this.$elem;
            var kbws = this.ws;

            //self.options.workspaceID + "/" + self.options.domainAnnotationID;
            //kbws.get_objects([{ref: domainAnnotationRef}], function(data) {

            var domainAnnotationRef = self.buildObjectIdentity(this.options.workspaceID, this.options.domainAnnotationID, this.options.domainAnnotationVer);
            kbws.get_objects([domainAnnotationRef], function(data) {

                self.domainAnnotationData = data[0].data;
                self.genomeRef = self.domainAnnotationData.genome_ref;
                self.domainModelSetRef = self.domainAnnotationData.used_dms_ref;

                // Job to get properties of AnnotationDomain object: name and id of the annotated genome
                var jobGetDomainAnnotationProperties = kbws.get_object_subset(
                    [
                        { 'ref':self.genomeRef, 'included':['/id'] },
                        { 'ref':self.genomeRef, 'included':['/scientific_name'] }
                    ],
                    function(data){
                        self.genomeId = data[0].data.id;
                        self.genomeName = data[1].data.scientific_name;
                    },
                    function(error){
                        self.clientError(error);
                    }
                );

                var jobGetDomainModelSet =  kbws.get_objects(
                    [{ref: self.domainModelSetRef}],
                    function(data) {
                        self.domainSetName = data[0].data.set_name;
                        self.domainAccession2Description = data[0].data.domain_accession_to_description;
                    },
                    function(error){
                        self.clientError(error);
                    }
                );

                // Launch jobs and vizualize data once they are done
                $.when.apply($, [jobGetDomainAnnotationProperties, jobGetDomainModelSet]).done( function(){
                    self.loading(false);
                    self.prepareVizData();

                    ///////////////////////////////////// Instantiating Tabs ////////////////////////////////////////////
                    container.empty();
                    var tabPane = $('
');
                    container.append(tabPane);
                    tabPane.kbaseTabs({canDelete : true, tabs : []});
                    ///////////////////////////////////// Overview table ////////////////////////////////////////////
                    var tabOverview = $("
");
                    tabPane.kbaseTabs('addTab', {tab: 'Overview', content: tabOverview, canDelete : false, show: true});
                    var tableOver = $('
');
                    tabOverview.append(tableOver);
                    tableOver
                        .append( self.makeRow(
                            'Annotated genome',
                            $('').append(self.genomeName).css('font-style', 'italic') ) )
                        .append( self.makeRow(
                            'Domain model set',
                            self.domainSetName ) )
                        .append( self.makeRow(
                            'Annotated genes',
                            self.annotatedGenesCount ) )
                        .append( self.makeRow(
                            'Annotated domains',
                            self.annotatedDomainsCount) );

                    ///////////////////////////////////// Domains table ////////////////////////////////////////////
                    var tabDomains = $("
");
                    tabPane.kbaseTabs('addTab', {tab: 'Domains', content: tabDomains, canDelete : false, show: false});
                    var tableDomains = $('
');
                    tabDomains.append(tableDomains);
                    var domainTableSettings = {
                        "sPaginationType": "full_numbers",
                        "iDisplayLength": 10,
                        "aaData": [],
                        "aaSorting": [[ 2, "asc" ], [0, "asc"]],
                        "aoColumns": [
                                      { "sTitle": "Domain", 'mData': 'id'},
                                      { "sTitle": "Description", 'mData': 'description'},
                                      { "sTitle": "#Genes", 'mData': 'geneCount'},
                                      { "sTitle": "Genes", 'mData': 'geneRefs'},
                        ],
                        "oLanguage": {
                                    "sEmptyTable": "No domains found!",
                                    "sSearch": "Search: "
                        },
                        'fnDrawCallback': events
                    };

                    var domainsTableData = [];
                    var domains = self.domains;
                    for(var domainId in domains){
                        var domain = domains[domainId];

                        // Build concatenated list of gene references
                        var geneRefs = "";
                        for(var i = 0; i < domain.genes.length; i++){
                            gene = domain.genes[i];
                            if( i > 0 ) {
                                geneRefs += '
';
                            }
                            geneRefs += '' + gene['geneId'] + '';
                        }

                        // add table data row
                        domainsTableData.push(
                            {
                                //id: '' + domainId + '',
                                id: domainId,
                                description: domain.description,
                                geneCount: domain.genes.length,
                                geneRefs: geneRefs
                            }
                        );
                    };
                    domainTableSettings.aaData = domainsTableData;
                    tableDomains = tableDomains.dataTable(domainTableSettings);

                    ///////////////////////////////////// Events ////////////////////////////////////////////

                    function events() {
                        $('.show-gene'+self.pref).unbind('click');
                        $('.show-gene'+self.pref).click(function() {
                            var id = $(this).attr('data-id');
                            var contigId = $(this).attr('data-contigId');
                            var geneIndex = $(this).attr('data-geneIndex');

                            if (tabPane.kbaseTabs('hasTab', id)) {
                                tabPane.kbaseTabs('showTab', id);
                                return;
                            }

                            ////////////////////////////// Build Gene Domains table //////////////////////////////
                            var tabContent = $("
");

                            var tableGeneDomains = $('
');
                            tabContent.append(tableGeneDomains);
                            var geneDomainTableSettings = {
                                "sPaginationType": "full_numbers",
                                "iDisplayLength": 10,
                                "aaData": [],
                                "aaSorting": [[ 3, "asc" ], [5, "desc"]],
                                "aoColumns": [
                                    {sTitle: "Domain", mData: "domainId"},
                                    {sTitle: "Description", mData: "domainDescription", sWidth:"30%"},
                                    {sTitle: "Location", mData: "image"},
                                    {sTitle: "Start", mData: "domainStart"},
                                    {sTitle: "End", mData: "domainEnd"},
                                    {sTitle: "E-value", mData: "eValue"},
                                ],
                                "oLanguage": {
                                    "sEmptyTable": "No domains found!",
                                    "sSearch": "Search: "
                                },
				'fnDrawCallback': events2
                            };
                            var geneDomainsTableData = [];

                            var gene = self.domainAnnotationData.data[contigId][geneIndex];
                            var geneId = gene[0];
                            var geneStart = gene[1];
                            var geneEnd = gene[2];
                            var domainsInfo = gene[4];
			    var geneLength = (geneEnd - geneStart + 1)/3;

			    // hack to deal with genes with incorrect lengths
                            for(var domainId in domainsInfo){
                                var domainsArray = domainsInfo[domainId];
                                for(var i = 0 ; i < domainsArray.length; i++){
                                    var domainEnd = domainsArray[i][1];
                                    if (domainEnd > geneLength)
					geneLength = domainEnd;
				}
			    }

                            for(var domainId in domainsInfo){
                                var domainsArray = domainsInfo[domainId];
                                for(var i = 0 ; i < domainsArray.length; i++){
                                    var domainStart = domainsArray[i][0];
                                    var domainEnd = domainsArray[i][1];
                                    var eValue = domainsArray[i][2];

                                    var domainImgWidth = (domainEnd - domainStart)*100/geneLength;
                                    var domainImgleftShift = (domainStart)*100/geneLength;

				    var domainRef = ''
					+ domainId + '';

                                    geneDomainsTableData.push({
                                        'contigId' : contigId,
                                        'geneId' : geneId,
                                        'geneStart' : geneStart,
                                        'geneEnd' : geneEnd,
                                        'domainId' : domainRef,
                                        'domainDescription' : self.domainAccession2Description[domainId],
                                        'domainStart': domainStart,
                                        'domainEnd' : domainEnd,
                                        'eValue' : eValue,
                                        'image' :
                                                '
'
                                                + '
'
                                                + '

'
                                                + '
'
                                    });
                                }
                            }
                            geneDomainTableSettings.aaData = geneDomainsTableData;
                            tabPane.kbaseTabs('addTab', {tab: id, content: tabContent, canDelete : true, show: true});
                            tableGeneDomains.dataTable(geneDomainTableSettings);
                        });
		    };

                    function events2() {
                        $('.show-domain'+self.pref).unbind('click');
                        $('.show-domain'+self.pref).click(function() {
                            var domainId = $(this).attr('data-id');
			    tableDomains.fnFilter(domainId);
                            tabPane.kbaseTabs('showTab', 'Domains');
			});
                    };

                });
            });
        },

        prepareVizData: function(){
            var self = this;

            var dad = self.domainAnnotationData;

            var domains = {};
            var domainsCount = 0;
            var genesCount = 0;

            for(var contigId in dad.data){

                var genesArray = dad.data[contigId];
                for(var i = 0 ; i < genesArray.length; i++){
                    var geneId = genesArray[i][0];
//                    var geneStart = genesArray[i][1];
//                    var geneEnd = genesArray[i][2];
                    var domainsInfo = genesArray[i][4];
                    if( $.isEmptyObject(domainsInfo)) continue;

                    // If we have somthing in domainsInfo, then the gene was anntoated
                    genesCount ++;
                    for(var domainId in domainsInfo){
                        var domainData = domains[domainId];
                        if(typeof domainData === 'undefined'){
                            domainData = {
                                id: domainId,
                                description: self.domainAccession2Description[domainId],
                                genes: []
                            };
                            domains[domainId] = domainData;
                            domainsCount++;
                        }

                        domainData.genes.push(
                            {
                                geneId: geneId,
                                contigId: contigId,
                                geneIndex: i
                            }
                        );
                    }
                }
                self.domains = domains;
                self.annotatedDomainsCount = domainsCount;
                self.annotatedGenesCount = genesCount;
            }
        },

        makeRow: function(name, value) {
            var $row = $("
")
                       .append($("").css('width','20%').append(name))
                       .append($("").append(value));
            return $row;
        },

        getData: function() {
            return {
                type: 'DomainAnnotation',
                id: this.options.domainAnnotationID,
                workspace: this.options.workspaceID,
                title: 'Domain Annotation'
            };
        },

        loading: function(isLoading) {
            if (isLoading)
                this.showMessage("");
            else
                this.hideMessage();
        },

        showMessage: function(message) {
            var span = $("").append(message);

            this.$messagePane.append(span);
            this.$messagePane.show();
        },

        hideMessage: function() {
            this.$messagePane.hide();
            this.$messagePane.empty();
        },

        uuid: function() {
            return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,
                function(c) {
                    var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
                    return v.toString(16);
                });
        },

        buildObjectIdentity: function(workspaceID, objectID, objectVer, wsRef) {
            var obj = {};
            if (wsRef) {
                obj['ref'] = wsRef;
            } else {
                if (/^\d+$/.exec(workspaceID))
                    obj['wsid'] = workspaceID;
                else
                    obj['workspace'] = workspaceID;

                // same for the id
                if (/^\d+$/.exec(objectID))
                    obj['objid'] = objectID;
                else
                    obj['name'] = objectID;

                if (objectVer)
                    obj['ver'] = objectVer;
            }
            return obj;
        },

        clientError: function(error){
            this.loading(false);
            this.showMessage(error.error.error);
        }

    });
})( jQuery );<commit_msg>Starting to add external URLs to domain viewer, and truncate long descriptions<commit_after>/**
 * Output widget to vizualize DomainAnnotation object.
 * Pavel Novichkov <psnovichkov@lbl.gov>, John-Marc Chandonia <jmchandonia@lbl.gov>
 * @public
 */

(function($, undefined) {
    $.KBWidget({
        name: 'kbaseDomainAnnotation',
        parent: 'kbaseAuthenticatedWidget',
        version: '1.0.2',
        options: {
            domainAnnotationID: null,
            workspaceID: null,
            domainAnnotationVer: null,
            kbCache: null,
            workspaceURL: window.kbconfig.urls.workspace,
            loadingImage: "static/kbase/images/ajax-loader.gif",
            height: null,
	    maxDescriptionLength: 100
        },

        // Data for vizualization
        domainAnnotationData: null,
        genomeRef: null,
        genomeId: null,
        genomeName: null,
        domainModelSetRef: null,
        domainModelSetName: null,
        domainAccessionToShortDescription: {},
        domainAccessionToLongDescription: {},
	domainAccessionToPrefix: {},
	prefixToUrl: {},
        annotatedGenesCount: 0,
        annotatedDomainsCount: 0,

        init: function(options) {
            this._super(options);

            // TEMPORARY
            if(this.options.domainAnnotationID == null){
                this.options.domainAnnotationID = 12;
                this.options.workspaceID = 2959;
                this.options.domainAnnotationVer = 8;
            }

            // Create a message pane
            this.$messagePane = $("
").addClass("kbwidget-message-pane kbwidget-hide-message");
            this.$elem.append(this.$messagePane);

            return this;
        },

        loggedInCallback: function(event, auth) {
            // Create a new workspace client
            this.ws = new Workspace(this.options.workspaceURL, auth);

            // Let's go...
            this.render();

            return this;
        },

        loggedOutCallback: function(event, auth) {
            this.ws = null;
            this.isLoggedIn = false;
            return this;
        },

        render: function(){
            var self = this;
            self.pref = this.uuid();
            self.loading(true);

            var container = this.$elem;
            var kbws = this.ws;

            //self.options.workspaceID + "/" + self.options.domainAnnotationID;
            //kbws.get_objects([{ref: domainAnnotationRef}], function(data) {

            var domainAnnotationRef = self.buildObjectIdentity(this.options.workspaceID, this.options.domainAnnotationID, this.options.domainAnnotationVer);
            kbws.get_objects([domainAnnotationRef], function(data) {

                self.domainAnnotationData = data[0].data;
                self.genomeRef = self.domainAnnotationData.genome_ref;
                self.domainModelSetRef = self.domainAnnotationData.used_dms_ref;

                // Job to get properties of AnnotationDomain object: name and id of the annotated genome
                var jobGetDomainAnnotationProperties = kbws.get_object_subset(
                    [
                        { 'ref':self.genomeRef, 'included':['/id'] },
                        { 'ref':self.genomeRef, 'included':['/scientific_name'] }
                    ],
                    function(data){
                        self.genomeId = data[0].data.id;
                        self.genomeName = data[1].data.scientific_name;
                    },
                    function(error){
                        self.clientError(error);
                    }
                );

                var jobGetDomainModelSet =  kbws.get_objects(
                    [{ref: self.domainModelSetRef}],
                    function(data) {
                        self.domainAccessionToShortDescription = data[0].data.domain_accession_to_description;
			// make regex for each prefix to map to external URLs
			$.each(data[0].data.domain_prefix_to_dbxref_url, function(prefix,url) {
			    self.prefixToUrl['^'+prefix] = url;
			});
			// make short & long descriptions for ones that are too long
			$.each(self.domainAccessionToShortDescription, function(domainId,description) {
			    if (description.length > self.options.maxDescriptionLength) {
				domainAccessionToLongDescription[domainId] = domainAccessionToShortDescription[domainId] + ' (show less)';
				domainAccessionToShortDescription[domainId] = domainAccessionToShortDescription[domainId].substring(0,self.options.maxDescriptionLength) + ' (show more)';
			    }
			});
                    },
                    function(error){
                        self.clientError(error);
                    }
                );

                // Launch jobs and vizualize data once they are done
                $.when.apply($, [jobGetDomainAnnotationProperties, jobGetDomainModelSet]).done( function(){
                    self.loading(false);
                    self.prepareVizData();

                    ///////////////////////////////////// Instantiating Tabs ////////////////////////////////////////////
                    container.empty();
                    var tabPane = $('
');
                    container.append(tabPane);
                    tabPane.kbaseTabs({canDelete : true, tabs : []});
                    ///////////////////////////////////// Overview table ////////////////////////////////////////////
                    var tabOverview = $("
");
                    tabPane.kbaseTabs('addTab', {tab: 'Overview', content: tabOverview, canDelete : false, show: true});
                    var tableOver = $('
');
                    tabOverview.append(tableOver);
                    tableOver
                        .append( self.makeRow(
                            'Annotated genome',
                            $('').append(self.genomeName).css('font-style', 'italic') ) )
                        .append( self.makeRow(
                            'Domain model set',
                            self.domainSetName ) )
                        .append( self.makeRow(
                            'Annotated genes',
                            self.annotatedGenesCount ) )
                        .append( self.makeRow(
                            'Annotated domains',
                            self.annotatedDomainsCount) );

                    ///////////////////////////////////// Domains table ////////////////////////////////////////////
                    var tabDomains = $("
");
                    tabPane.kbaseTabs('addTab', {tab: 'Domains', content: tabDomains, canDelete : false, show: false});
                    var tableDomains = $('
');
                    tabDomains.append(tableDomains);
                    var domainTableSettings = {
                        "sPaginationType": "full_numbers",
                        "iDisplayLength": 10,
                        "aaData": [],
                        "aaSorting": [[ 2, "asc" ], [0, "asc"]],
                        "aoColumns": [
                                      { "sTitle": "Domain", 'mData': 'id'},
                                      { "sTitle": "Description", 'mData': 'description'},
                                      { "sTitle": "#Genes", 'mData': 'geneCount'},
                                      { "sTitle": "Genes", 'mData': 'geneRefs'},
                        ],
                        "oLanguage": {
                                    "sEmptyTable": "No domains found!",
                                    "sSearch": "Search: "
                        },
                        'fnDrawCallback': events
                    };

                    var domainsTableData = [];
                    var domains = self.domains;
                    for(var domainId in domains){
                        var domain = domains[domainId];

			// try to map each domain to a prefix,
			// for external crossrefs and to show only
			// the most relevant match per set
			var domainRef = domainId;
			$.each(self.prefixToUrl, function(prefix,url) {
			    if (domainId.match(prefix)) {
				self.domainToPrefix[domainId] = prefix;
				domainRef += ' (more info)';
				return false;
			    }
			});

                        // Build concatenated list of gene references
                        var geneRefs = "";
                        for(var i = 0; i < domain.genes.length; i++){
                            gene = domain.genes[i];
                            if( i > 0 ) {
                                geneRefs += '
';
                            }
                            geneRefs += '' + gene['geneId'] + '';
                        }

                        // add table data row
                        domainsTableData.push(
                            {
                                id: domainRef,
                                description: domain.description,
                                geneCount: domain.genes.length,
                                geneRefs: geneRefs
                            }
                        );
                    };
                    domainTableSettings.aaData = domainsTableData;
                    tableDomains = tableDomains.dataTable(domainTableSettings);

                    ///////////////////////////////////// Events ////////////////////////////////////////////

                    function events() {
                        $('.show-gene'+self.pref).unbind('click');
                        $('.show-gene'+self.pref).click(function() {
                            var id = $(this).attr('data-id');
                            var contigId = $(this).attr('data-contigId');
                            var geneIndex = $(this).attr('data-geneIndex');

                            if (tabPane.kbaseTabs('hasTab', id)) {
                                tabPane.kbaseTabs('showTab', id);
                                return;
                            }

                            ////////////////////////////// Build Gene Domains table //////////////////////////////
                            var tabContent = $("
");

                            var tableGeneDomains = $('
');
                            tabContent.append(tableGeneDomains);
                            var geneDomainTableSettings = {
                                "sPaginationType": "full_numbers",
                                "iDisplayLength": 10,
                                "aaData": [],
                                "aaSorting": [[ 3, "asc" ], [5, "desc"]],
                                "aoColumns": [
                                    {sTitle: "Domain", mData: "domainId"},
                                    {sTitle: "Description", mData: "domainDescription", sWidth:"30%"},
                                    {sTitle: "Location", mData: "image"},
                                    {sTitle: "Start", mData: "domainStart"},
                                    {sTitle: "End", mData: "domainEnd"},
                                    {sTitle: "E-value", mData: "eValue"},
                                ],
                                "oLanguage": {
                                    "sEmptyTable": "No domains found!",
                                    "sSearch": "Search: "
                                },
				'fnDrawCallback': events2
                            };
                            var geneDomainsTableData = [];

                            var gene = self.domainAnnotationData.data[contigId][geneIndex];
                            var geneId = gene[0];
                            var geneStart = gene[1];
                            var geneEnd = gene[2];
                            var domainsInfo = gene[4];
			    var geneLength = (geneEnd - geneStart + 1)/3;

			    // hack to deal with genes with incorrect lengths
                            for(var domainId in domainsInfo){
                                var domainsArray = domainsInfo[domainId];
                                for(var i = 0 ; i < domainsArray.length; i++){
                                    var domainEnd = domainsArray[i][1];
                                    if (domainEnd > geneLength)
					geneLength = domainEnd;
				}
			    }

                            for(var domainId in domainsInfo){
                                var domainsArray = domainsInfo[domainId];
                                for(var i = 0 ; i < domainsArray.length; i++){
                                    var domainStart = domainsArray[i][0];
                                    var domainEnd = domainsArray[i][1];
                                    var eValue = domainsArray[i][2];

                                    var domainImgWidth = (domainEnd - domainStart)*100/geneLength;
                                    var domainImgleftShift = (domainStart)*100/geneLength;

				    var domainRef = ''
					+ domainId + '';

                                    geneDomainsTableData.push({
                                        'contigId' : contigId,
                                        'geneId' : geneId,
                                        'geneStart' : geneStart,
                                        'geneEnd' : geneEnd,
                                        'domainId' : domainRef,
                                        'domainDescription' : self.domainAccessionToShortDescription[domainId],
                                        'domainStart': domainStart,
                                        'domainEnd' : domainEnd,
                                        'eValue' : eValue,
                                        'image' :
                                                '
'
                                                + '
'
                                                + '

'
                                                + '
'
                                    });
                                }
                            }
                            geneDomainTableSettings.aaData = geneDomainsTableData;
                            tabPane.kbaseTabs('addTab', {tab: id, content: tabContent, canDelete : true, show: true});
                            tableGeneDomains.dataTable(geneDomainTableSettings);
                        });
		    };

                    function events2() {
                        $('.show-domain'+self.pref).unbind('click');
                        $('.show-domain'+self.pref).click(function() {
                            var domainId = $(this).attr('data-id');
			    tableDomains.fnFilter(domainId);
                            tabPane.kbaseTabs('showTab', 'Domains');
			});
                    };

                });
            });
        },

        prepareVizData: function(){
            var self = this;

            var dad = self.domainAnnotationData;

            var domains = {};
            var domainsCount = 0;
            var genesCount = 0;

            for(var contigId in dad.data){

                var genesArray = dad.data[contigId];
                for(var i = 0 ; i < genesArray.length; i++){
                    var geneId = genesArray[i][0];
//                    var geneStart = genesArray[i][1];
//                    var geneEnd = genesArray[i][2];
                    var domainsInfo = genesArray[i][4];
                    if($.isEmptyObject(domainsInfo)) continue;

                    // If we have somthing in domainsInfo, then the gene was anntoated
                    genesCount++;
                    for(var domainId in domainsInfo){
                        var domainData = domains[domainId];
                        if(typeof domainData === 'undefined'){
                            domainData = {
                                id: domainId,
                                description: self.domainAccessionToShortDescription[domainId],
                                genes: []
                            };
                            domains[domainId] = domainData;
                            domainsCount++;
                        }

                        domainData.genes.push(
                            {
                                geneId: geneId,
                                contigId: contigId,
                                geneIndex: i
                            }
                        );
                    }
                }
                self.domains = domains;
                self.annotatedDomainsCount = domainsCount;
                self.annotatedGenesCount = genesCount;
            }
        },

        makeRow: function(name, value) {
            var $row = $("
")
                       .append($("").css('width','20%').append(name))
                       .append($("").append(value));
            return $row;
        },

        getData: function() {
            return {
                type: 'DomainAnnotation',
                id: this.options.domainAnnotationID,
                workspace: this.options.workspaceID,
                title: 'Domain Annotation'
            };
        },

        loading: function(isLoading) {
            if (isLoading)
                this.showMessage("");
            else
                this.hideMessage();
        },

        showMessage: function(message) {
            var span = $("").append(message);

            this.$messagePane.append(span);
            this.$messagePane.show();
        },

        hideMessage: function() {
            this.$messagePane.hide();
            this.$messagePane.empty();
        },

        uuid: function() {
            return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,
                function(c) {
                    var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
                    return v.toString(16);
                });
        },

        buildObjectIdentity: function(workspaceID, objectID, objectVer, wsRef) {
            var obj = {};
            if (wsRef) {
                obj['ref'] = wsRef;
            } else {
                if (/^\d+$/.exec(workspaceID))
                    obj['wsid'] = workspaceID;
                else
                    obj['workspace'] = workspaceID;

                // same for the id
                if (/^\d+$/.exec(objectID))
                    obj['objid'] = objectID;
                else
                    obj['name'] = objectID;

                if (objectVer)
                    obj['ver'] = objectVer;
            }
            return obj;
        },

        clientError: function(error){
            this.loading(false);
            this.showMessage(error.error.error);
        }

    });
})( jQuery );<|endoftext|>


<commit_before>$(window).bind("load", function() {
	var $title = $(".site-title"),
		$titleSpacer = $(".title-spacer"),
		$fragmentFirst = $(".fragment-first"),
		$fragmentLast = $(".fragment-last"),
		$fragmentFirstInnerText = $(".fragment-first span"),
		$fragmentLastInnerText = $(".fragment-last span"),
		$fragmentNBSP = $(".fragment-nbsp"),
		nbspWidth = function() {
			return calculateWordWidth(" ", ["site-title"]);
		},
		titleFinalWidth = function () {
			return	calculateWordWidth("D", ["site-title"]) +
				calculateWordWidth("R", ["site-title"]) +
				calculateWordWidth("S", ["site-title"]);
		},
		fragmentFirstOriginalWidth = function() {
			if ($(window).width() < 1024) {
				return "auto";
			}
			return calculateWordWidth($fragmentFirstInnerText.text(), ["site-title"]);
		},
		fragmentLastOriginalWidth = function() {
			if ($(window).width() < 1024) {
				return "auto";
			}
			return calculateWordWidth($fragmentLastInnerText.text(), ["site-title"]);
		},
		titleOriginalWidth = function() {
			return $("body").width();
		};

	$("a[href='#top']").click(function (e) {
		$("html, body").animate({ scrollTop: 0 }, "fast");

		return false;
	})

	$fragmentFirstInnerText.css({"width": fragmentFirstOriginalWidth()});
	$fragmentLastInnerText.css({"width": fragmentLastOriginalWidth()});

	/* Ensure that only one event gets called at a time. */
	var scrollTimerId,
		wheelTimerId,
		orientationchangeTimerId,
		resizeTimerId;
	$(window).scroll(function() {
		clearTimeout(wheelTimerId);
		clearTimeout(orientationchangeTimerId);
		clearTimeout(resizeTimerId);
		scrollTimerId = setTimeout(updateTitle, 1);
	});
	window.addEventListener('wheel', function() {
		clearTimeout(scrollTimerId);
		clearTimeout(orientationchangeTimerId);
		clearTimeout(resizeTimerId);
		wheelTimerId= setTimeout(updateTitle, 1);
	});
	window.addEventListener('orientationchange', function() {
		clearTimeout(scrollTimerId);
		clearTimeout(wheelTimerId);
		clearTimeout(resizeTimerId);
		orientationchangeTimerId = setTimeout(updateTitle, 1);
	});
	window.addEventListener('resize', function() {
		clearTimeout(scrollTimerId);
		clearTimeout(wheelTimerId);
		clearTimeout(orientationchangeTimerId);
		resizeTimerId = setTimeout(updateTitle, 1);
	});

	function updateTitle() {
		if ($(window).width() > 1024) {
			var spacerDistanceToTop = $titleSpacer.offset().top - $(window).scrollTop(),
				distanceToTop;
			if ($title.hasClass("fixed")) {
				distanceToTop = 0;
			} else {
				distanceToTop = $title.offset().top - $(window).scrollTop();
			}

			var percentageLeft = Math.max(distanceToTop, 0)/$title.offset().top;

			if (percentageLeft >= 1) {
				$fragmentNBSP.css({"width": nbspWidth()});
				$title.css({"width": titleOriginalWidth()});
				$fragmentFirst.css({"width": fragmentFirstOriginalWidth()});
				$fragmentLast.css({"width": fragmentLastOriginalWidth()});
				$fragmentFirstInnerText.css({"width": fragmentFirstOriginalWidth()});
				$fragmentLastInnerText.css({"width": fragmentLastOriginalWidth()});

				$title.removeClass("fixed");
				$titleSpacer.removeClass("live");
			} else if (spacerDistanceToTop <= 0 && distanceToTop <= 0) {
				$fragmentFirst.css({"width": 0});
				$fragmentLast.css({"width": 0});
				$fragmentNBSP.css({"width": 0});
				$title.css({"width": titleFinalWidth()});

				$title.addClass("fixed");
				$titleSpacer.addClass("live");
			} else if (percentageLeft > 0 && distanceToTop > 0 || spacerDistanceToTop >= 0){
				$title.removeClass("fixed");
				$titleSpacer.removeClass("live");

				var fragmentFirstNewWidth = fragmentFirstOriginalWidth() * percentageLeft,
					fragmentLastNewWidth = fragmentLastOriginalWidth() * percentageLeft,
					titleNewWidth = (titleOriginalWidth() - titleFinalWidth())*percentageLeft + titleFinalWidth(),
					nbspNewWidth = nbspWidth() * percentageLeft;
				$fragmentNBSP.stop().animate({"width": nbspNewWidth}, 5);
				$fragmentFirst.stop().animate({"width": fragmentFirstNewWidth}, 5);
				$fragmentLast.stop().animate({"width": fragmentLastNewWidth}, 5);
				$title.stop().animate({"width": titleNewWidth}, 5);
			}
		}
		else {
			doMobile();
		}
	}

	function doMobile() {
		$title.removeClass("fixed");
		$fragmentNBSP.css({"width": nbspWidth()});
		$title.css({"width": titleOriginalWidth()});
		$fragmentFirst.css({"width": fragmentFirstOriginalWidth()});
		$fragmentLast.css({"width": fragmentLastOriginalWidth()});
		$fragmentFirstInnerText.css({"width": fragmentFirstOriginalWidth()});
		$fragmentLastInnerText.css({"width": fragmentLastOriginalWidth()});
	}

	function calculateWordWidth(text, classes) {
		classes = classes || [];
		classes.push('textDimensionCalculation');
		var div = document.createElement('div');
		div.setAttribute('class', classes.join(' '));
		div.innerHTML = text;
		document.body.appendChild(div);
		var width = jQuery(div).outerWidth(true);
		div.parentNode.removeChild(div);
		return width;
	}
});<commit_msg>fix scrolltop<commit_after>$(window).bind("load", function() {
	var $title = $(".site-title"),
		$titleSpacer = $(".title-spacer"),
		$fragmentFirst = $(".fragment-first"),
		$fragmentLast = $(".fragment-last"),
		$fragmentFirstInnerText = $(".fragment-first span"),
		$fragmentLastInnerText = $(".fragment-last span"),
		$fragmentNBSP = $(".fragment-nbsp"),
		nbspWidth = function() {
			return calculateWordWidth(" ", ["site-title"]);
		},
		titleFinalWidth = function () {
			return	calculateWordWidth("D", ["site-title"]) +
				calculateWordWidth("R", ["site-title"]) +
				calculateWordWidth("S", ["site-title"]);
		},
		fragmentFirstOriginalWidth = function() {
			if ($(window).width() < 1024) {
				return "auto";
			}
			return calculateWordWidth($fragmentFirstInnerText.text(), ["site-title"]);
		},
		fragmentLastOriginalWidth = function() {
			if ($(window).width() < 1024) {
				return "auto";
			}
			return calculateWordWidth($fragmentLastInnerText.text(), ["site-title"]);
		},
		titleOriginalWidth = function() {
			return $("body").width();
		};

	$("a[href='#top']").click(function (e) {
		$("html, body").animate({ scrollTop: 0 }, "fast", function() {
			updateTitle();
		});
		return false;
	});

	$fragmentFirstInnerText.css({"width": fragmentFirstOriginalWidth()});
	$fragmentLastInnerText.css({"width": fragmentLastOriginalWidth()});

	/* Ensure that only one event gets called at a time. */
	var scrollTimerId,
		wheelTimerId,
		orientationchangeTimerId,
		resizeTimerId;
	$(window).scroll(function() {
		clearTimeout(wheelTimerId);
		clearTimeout(orientationchangeTimerId);
		clearTimeout(resizeTimerId);
		scrollTimerId = setTimeout(updateTitle, 1);
	});
	window.addEventListener('wheel', function() {
		clearTimeout(scrollTimerId);
		clearTimeout(orientationchangeTimerId);
		clearTimeout(resizeTimerId);
		wheelTimerId= setTimeout(updateTitle, 1);
	});
	window.addEventListener('orientationchange', function() {
		clearTimeout(scrollTimerId);
		clearTimeout(wheelTimerId);
		clearTimeout(resizeTimerId);
		orientationchangeTimerId = setTimeout(updateTitle, 1);
	});
	window.addEventListener('resize', function() {
		clearTimeout(scrollTimerId);
		clearTimeout(wheelTimerId);
		clearTimeout(orientationchangeTimerId);
		resizeTimerId = setTimeout(updateTitle, 1);
	});

	function updateTitle() {
		if ($(window).width() > 1024) {
			var spacerDistanceToTop = $titleSpacer.offset().top - $(window).scrollTop(),
				distanceToTop;
			if ($title.hasClass("fixed")) {
				distanceToTop = 0;
			} else {
				distanceToTop = $title.offset().top - $(window).scrollTop();
			}

			var percentageLeft = Math.max(distanceToTop, 0)/$title.offset().top;

			if (percentageLeft >= 1) {
				$fragmentNBSP.css({"width": nbspWidth()});
				$title.css({"width": titleOriginalWidth()});
				$fragmentFirst.css({"width": fragmentFirstOriginalWidth()});
				$fragmentLast.css({"width": fragmentLastOriginalWidth()});
				$fragmentFirstInnerText.css({"width": fragmentFirstOriginalWidth()});
				$fragmentLastInnerText.css({"width": fragmentLastOriginalWidth()});

				$title.removeClass("fixed");
				$titleSpacer.removeClass("live");
			} else if (spacerDistanceToTop <= 0 && distanceToTop <= 0) {
				$fragmentFirst.css({"width": 0});
				$fragmentLast.css({"width": 0});
				$fragmentNBSP.css({"width": 0});
				$title.css({"width": titleFinalWidth()});

				$title.addClass("fixed");
				$titleSpacer.addClass("live");
			} else if (percentageLeft > 0 && distanceToTop > 0 || spacerDistanceToTop >= 0){
				$title.removeClass("fixed");
				$titleSpacer.removeClass("live");

				var fragmentFirstNewWidth = fragmentFirstOriginalWidth() * percentageLeft,
					fragmentLastNewWidth = fragmentLastOriginalWidth() * percentageLeft,
					titleNewWidth = (titleOriginalWidth() - titleFinalWidth())*percentageLeft + titleFinalWidth(),
					nbspNewWidth = nbspWidth() * percentageLeft;
				$fragmentNBSP.stop().animate({"width": nbspNewWidth}, 5);
				$fragmentFirst.stop().animate({"width": fragmentFirstNewWidth}, 5);
				$fragmentLast.stop().animate({"width": fragmentLastNewWidth}, 5);
				$title.stop().animate({"width": titleNewWidth}, 5);
			}
		}
		else {
			doMobile();
		}
	}

	function doMobile() {
		$title.removeClass("fixed");
		$fragmentNBSP.css({"width": nbspWidth()});
		$title.css({"width": titleOriginalWidth()});
		$fragmentFirst.css({"width": fragmentFirstOriginalWidth()});
		$fragmentLast.css({"width": fragmentLastOriginalWidth()});
		$fragmentFirstInnerText.css({"width": fragmentFirstOriginalWidth()});
		$fragmentLastInnerText.css({"width": fragmentLastOriginalWidth()});
	}

	function calculateWordWidth(text, classes) {
		classes = classes || [];
		classes.push('textDimensionCalculation');
		var div = document.createElement('div');
		div.setAttribute('class', classes.join(' '));
		div.innerHTML = text;
		document.body.appendChild(div);
		var width = jQuery(div).outerWidth(true);
		div.parentNode.removeChild(div);
		return width;
	}
});<|endoftext|>


<commit_before>var csrf_token;
$(function () {
    // This requires that we used Jinja2's {% csrf_input %} somewhere on the page.
    csrf_token = $('input[name="csrfmiddlewaretoken"]').attr('value');
    window.csrf_token = csrf_token;

    $.ajaxSetup({
        beforeSend: function (xhr, settings) {
            if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
                // Only send the token to relative URLs i.e. locally.
                xhr.setRequestHeader("X-CSRFToken", csrf_token);
            }
        },
    });
});
<commit_msg>csrf: Improve API for when no CSRF input is available.<commit_after>var csrf_token;
$(function () {
    // This requires that we used Jinja2's {% csrf_input %} somewhere on the page.
    var csrf_input = $('input[name="csrfmiddlewaretoken"]');
    if (csrf_input.length > 0) {
        csrf_token = csrf_input.attr('value');
    } else {
        csrf_token = undefined;
    }
    window.csrf_token = csrf_token;

    if (csrf_token === undefined) {
        return;
    }

    $.ajaxSetup({
        beforeSend: function (xhr, settings) {
            if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
                // Only send the token to relative URLs i.e. locally.
                xhr.setRequestHeader("X-CSRFToken", csrf_token);
            }
        },
    });
});
<|endoftext|>


<commit_before>window.addEventListener("load", function() {

  // INITIALIZE NEW GAME
  var Q = window.Q = Quintus({
      development: true
    })
    .include("Sprites, Scenes, Input, 2D, Touch, UI")
    .setup("mazeGame")
    .controls()
    .touch();

  Q.input.keyboardControls({
    X: "warp"
  });

  Q.input.touchControls({
    controls: [
      ['left', '<'],
      ['up', '^'],
      ['down', 'v'],
      ['right', '>'],
      ['warp', 'w']
    ]
  });

  var socket = io.connect('http://localhost:8080');

  Q.gravityX = 0;
  Q.gravityY = 0;

  // COLLISION MASKS
  var SPRITE_PLAYER = 1;
  var SPRITE_ACTOR = 2;
  var SPRITE_TILES = 4;
  var SPRITE_LADDER = 8;
  var SPRITE_BOOST = 16;
  var SPRITE_WARP = 32;

  // SPAWN POINTS
  var PLAYER_SPAWN_X = 688;
  var PLAYER_SPAWN_Y = 976;
  var LADDER_SPAWN_X = 688;
  var LADDER_SPAWN_Y = 800;

  // MOVEMENT
  var PLAYER_WALK_SPEED = 200;
  var PLAYER_SPRINT_SPEED = 300;

  // ITEMS
  var vials = [];

  // UI
  var players = [];
  var UiPlayers = document.getElementById("players");
  var scoreboard = [];
  var UiScoreboard = document.getElementById("scoreboard");
  var highscore = "NONE!";
  var UiHighscore = document.getElementById("highscore");
  var id = "";
  var UiID = document.getElementById("id");
  var runtime = 0;
  var UiRuntime = document.getElementById("runtime");
  var boostTime = 0;
  var UiBoostTime = document.getElementById("boostTime");
  var warpUses = 0;
  var UiWarpUses = document.getElementById("warpUses");

  // MISC
  var thisPlayer;
  var activeGame = true;

  /***************************************************************************/
  /*                            GAME CLASSES                                 */
  /***************************************************************************/

  // PLAYER CLASS
  Q.Sprite.extend("Player", {

    init: function(p) {
      this._super(p, {
        sheet: "player",
        type: SPRITE_PLAYER,
        collisionMask: SPRITE_TILES | SPRITE_LADDER | SPRITE_BOOST | SPRITE_WARP,
        lastscore: "N/A"
      });
      this.add("2d, platformerControls");
      this.on("hit.sprite", function(collision) {
        if (collision.obj.isA("Ladder")) {
          Q.stageScene("endGame", 1, {
            label: "You Conquered The Maze In " + secondsToTime(runtime) + " !"
          });
          this.p.lastscore = runtime;
          this.p.socket.emit("pushScore", {
            playerID: this.p.playerId,
            score: this.p.lastscore
          });
          this.p.x = PLAYER_SPAWN_X;
          this.p.y = PLAYER_SPAWN_Y;
          runtime = 0;
          boostTime = 0;
          warpUses = 0;
          activeGame = false;
        } else if (collision.obj.isA("BoostPad")) {
          boostTime = 8;
        }
      });
      Q.input.on("warp", this, "warpPlayer");

    },

    warpPlayer: function() {
      if (warpUses > 0) {
        warpUses--;
        if (Q.inputs['right'] && Q.inputs['up']) {
          this.p.x += 32;
          this.p.y -= 32;
        } else if (Q.inputs['right'] && Q.inputs['down']) {
          this.p.x += 32;
          this.p.y += 32;
        } else if (Q.inputs['left'] && Q.inputs['down']) {
          this.p.x -= 32;
          this.p.y += 32;
        } else if (Q.inputs['left'] && Q.inputs['up']) {
          this.p.x -= 32;
          this.p.y -= 32;
        } else if (Q.inputs['right']) {
          this.p.x += 32;
        } else if (Q.inputs['down']) {
          this.p.y += 32;
        } else if (Q.inputs['left']) {
          this.p.x -= 32;
        } else if (Q.inputs['up']) {
          this.p.y -= 32;
        }
      }
    },

    // Step is called whenever an arrow key is pressed
    step: function(dt) {

      if (activeGame == false) {
        this.p.speed = 0;
      } else {
        if (boostTime == 0) {
          this.p.speed = PLAYER_WALK_SPEED;
        } else {
          this.p.speed = PLAYER_SPRINT_SPEED;
        }

        // Add up and down movement to platformer controls
        if (Q.inputs['up']) {
          if (this.p.speed == PLAYER_SPRINT_SPEED) {
            this.p.vy = -PLAYER_SPRINT_SPEED;
          } else {
            this.p.vy = -PLAYER_WALK_SPEED;
          }
        } else if (Q.inputs['down']) {
          if (this.p.speed == PLAYER_SPRINT_SPEED) {
            this.p.vy = PLAYER_SPRINT_SPEED;
          } else {
            this.p.vy = PLAYER_WALK_SPEED;
          }
        } else if (!Q.inputs['down'] && !Q.inputs['up']) {
          this.p.vy = 0;
        }

        // Change direction of player sprite based on movement direction
        if (this.p.vx > 0 && this.p.vy < 0) {
          this.p.angle = 45;
        } else if (this.p.vx > 0 && this.p.vy > 0) {
          this.p.angle = 135;
        } else if (this.p.vx < 0 && this.p.vy > 0) {
          this.p.angle = 225;
        } else if (this.p.vx < 0 && this.p.vy < 0) {
          this.p.angle = 315;
        } else if (this.p.vx > 0) {
          this.p.angle = 90;
        } else if (this.p.vy > 0) {
          this.p.angle = 180;
        } else if (this.p.vx < 0) {
          this.p.angle = 270;
        } else if (this.p.vy < 0) {
          this.p.angle = 0;
        }

        this.p.socket.emit("updatePlayer", {
          playerId: this.p.playerId,
          x: this.p.x,
          y: this.p.y,
          sheet: this.p.sheet,
          angle: this.p.angle
        });
      }
    }

  });

  // BOOST PAD CLASS
  Q.Sprite.extend("BoostPad", {
    init: function(p) {
      this._super(p, {
        sheet: "boost_pad",
        type: SPRITE_BOOST,
        sensor: true
      });
      this.on("sensor");
    },

    sensor: function() {
      var temp = this;
      setTimeout(function() {
        temp.p.sheet = "boost_pad";
      }, 3000);
    }
  });

  Q.Sprite.extend("WarpVial", {
    init: function(p) {
      this._super(p, {
        sheet: "warp_vial",
        type: SPRITE_WARP,
        sensor: true,
        full: true
      });
      this.on("sensor");
    },

    sensor: function() {
      if (this.p.full == true) {
        warpUses++;
        this.p.sheet = "empty_vial";
        this.p.full = false;
      }
    }
  });

  // ACTOR CLASS
  Q.Sprite.extend("Actor", {
    init: function(p) {
      this._super(p, {
        sheet: "actor",
        type: SPRITE_ACTOR,
        collisionMask: SPRITE_TILES,
        update: true
      });

      var temp = this;
      setInterval(function() {
        if (!temp.p.update) {
          temp.destroy();
        }
        temp.p.update = false;
      }, 1000000);
    }
  });

  // LADDER CLASS
  Q.Sprite.extend("Ladder", {
    init: function(p) {
      this._super(p, {
        type: SPRITE_LADDER,
        sheet: "ladder"
      });
    }
  });

  /***************************************************************************/
  /*                       MAIN MULTIPLAYER LOGIC                            */
  /***************************************************************************/

  // MULTIPLAYER SOCKET
  function setUp(stage) {

    socket.on("count", function(data) {
      if (thisPlayer != undefined) {
        UiPlayers.innerHTML = "Players - " + data["playerCount"];
      }
    });

    socket.on("connectedGame", function(data) {
      selfId = data["playerId"];
      thisPlayer = new Q.Player({
        playerId: selfId,
        x: PLAYER_SPAWN_X,
        y: PLAYER_SPAWN_Y,
        socket: socket
      });
      stage.insert(thisPlayer);
      stage.add("viewport").follow(thisPlayer);
      UiID.innerHTML = "ID - " + selfId;
      runtime = 0;
    });

    socket.on("updatedActor", function(data) {
      var actor = players.filter(function(obj) {
        return obj.playerId == data["playerId"];
      })[0];
      if (actor) {
        actor.player.p.x = data["x"];
        actor.player.p.y = data["y"];
        actor.player.p.angle = data["angle"];
        actor.player.p.sheet = "actor";
        actor.player.p.update = true;
      } else {
        var temp = new Q.Actor({
          playerId: data["playerId"],
          x: data["x"],
          y: data["y"],
          sheet: "actor"
        });
        players.push({
          player: temp,
          playerId: data["playerId"]
        });
        stage.insert(temp);
      }
    });

  }

  socket.on("updatedScoreboard", function(data) {
    scoreboard = data["scoreboard"];
    var fullScoreboard = "[[Scoreboard]]
";
    var highestscore;
    var highestplayer;
    for (i = 0; i < scoreboard.length; i++) {
      fullScoreboard += "Player " + scoreboard[i].playerID + " - " + secondsToTime(scoreboard[i].score) + "
";
      if (scoreboard[i].score < highestscore || highestscore == null) {
        highestplayer = scoreboard[i].playerID;
        highestscore = scoreboard[i].score;
      }
    }
    if (thisPlayer != undefined) {
      UiScoreboard.innerHTML = fullScoreboard;
      if (scoreboard.length > 0) {
        UiHighscore.innerHTML = "[[High Score]]
" + highestplayer + " - " + secondsToTime(highestscore);
      }
      else {
        UiHighscore.innerHTML = "There's no high score!"
      }
    }
  });

  function secondsToTime(seconds) {
    return (new Date(seconds * 1000)).toUTCString().match(/(\d\d:\d\d:\d\d)/)[0].substring(3);
  }

  setInterval(function addRuntime() {
    if (activeGame == true) {
      runtime++;
    }
  }, 1000);

  setInterval(function subtractBoostTime() {
    if (boostTime > 0) {
      boostTime--;
    }
  }, 1000);

  setInterval(function updateRuntime() {
    if (thisPlayer != undefined) {
      UiRuntime.innerHTML = "Time - " + secondsToTime(runtime);
    }
  }, 10);

  setInterval(function updateBoostTime() {
    if (thisPlayer != undefined) {
      UiBoostTime.innerHTML = "Boost - " + boostTime;
    }
  }, 10);

  setInterval(function updateWarpUses() {
    if (thisPlayer != undefined) {
      UiWarpUses.innerHTML = "Warp (Press X) - " + warpUses;
    }
  }, 10);

  /***************************************************************************/
  /*                            LEVEL SCENES                                 */
  /***************************************************************************/

  // LEVEL 1 SCENE
  Q.scene("level1", function(stage) {

    stage.collisionLayer(new Q.TileLayer({
      dataAsset: "/static/maps/maze1.json",
      type: SPRITE_TILES,
      collisionMask: SPRITE_PLAYER | SPRITE_ACTOR,
      sheet: "tiles"
    }));
    stage.insert(new Q.Ladder({
      x: LADDER_SPAWN_X,
      y: LADDER_SPAWN_Y
    }));
    stage.insert(new Q.BoostPad({
      x: 688,
      y: 900
    }));
    vials.push(new Q.WarpVial({
        x: 800,
        y: 1100
      }),
      new Q.WarpVial({
        x: 700,
        y: 1100
      }),
      new Q.WarpVial({
        x: 600,
        y: 1100
      }));
    stage.insert(vials[0]);
    stage.insert(vials[1]);
    stage.insert(vials[2]);
    setUp(stage);

  });

  // END GAME SCENE
  Q.scene("endGame", function(stage) {

    var container = stage.insert(new Q.UI.Container({
      x: Q.width / 2,
      y: Q.height / 2,
      fill: "rgba(0,0,0,1)"
    }));

    var button = container.insert(new Q.UI.Button({
      x: 0,
      y: 0,
      fill: "#CCCCCC",
      label: "Play Again"
    }))

    var label = container.insert(new Q.UI.Text({
      x: 0,
      y: -50 - button.p.h,
      label: stage.options.label,
      color: "white"
    }));

    button.on("click", function() {
      for (i = 0; i < vials.length; i++) {
        vials[i].p.full = true;
        vials[i].p.sheet = "warp_vial";
      }
      activeGame = true;
      Q.clearStage(1);
    });

    container.fit(1000);

  });

  // LOAD GAME ASSETS
  Q.load("/static/images/sprites.png, /static/images/sprites.json, /static/maps/maze1.json, /static/images/tiles.png",
    function() {
      Q.sheet("tiles", "/static/images/tiles.png", {
        tilew: 32,
        tileh: 32
      });
      Q.compileSheets("/static/images/sprites.png", "/static/images/sprites.json");
      Q.stageScene("level1"); // run the game
    });

});
<commit_msg>Update game.js<commit_after>window.addEventListener("load", function() {

  // INITIALIZE NEW GAME
  var Q = window.Q = Quintus({
      development: true
    })
    .include("Sprites, Scenes, Input, 2D, Touch, UI")
    .setup("mazeGame")
    .controls()
    .touch();

  Q.input.keyboardControls({
    X: "warp"
  });

  Q.input.touchControls({
    controls: [
      ['left', '<'],
      ['up', '^'],
      ['down', 'v'],
      ['right', '>'],
      ['warp', 'w']
    ]
  });

  var socket = io.connect('http://localhost:8080');

  Q.gravityX = 0;
  Q.gravityY = 0;

  // COLLISION MASKS
  var SPRITE_PLAYER = 1;
  var SPRITE_ACTOR = 2;
  var SPRITE_TILES = 4;
  var SPRITE_LADDER = 8;
  var SPRITE_BOOST = 16;
  var SPRITE_WARP = 32;

  // SPAWN POINTS
  var PLAYER_SPAWN_X = 1230;
  var PLAYER_SPAWN_Y = 1070;
  var LADDER_SPAWN_X = 145;
  var LADDER_SPAWN_Y = 145;

  // MOVEMENT
  var PLAYER_WALK_SPEED = 200;
  var PLAYER_SPRINT_SPEED = 300;

  // ITEMS
  var vials = [];

  // UI
  var players = [];
  var UiPlayers = document.getElementById("players");
  var scoreboard = [];
  var UiScoreboard = document.getElementById("scoreboard");
  var highscore = "NONE!";
  var UiHighscore = document.getElementById("highscore");
  var id = "";
  var UiID = document.getElementById("id");
  var runtime = 0;
  var UiRuntime = document.getElementById("runtime");
  var boostTime = 0;
  var UiBoostTime = document.getElementById("boostTime");
  var warpUses = 0;
  var UiWarpUses = document.getElementById("warpUses");

  // MISC
  var thisPlayer;
  var activeGame = true;

  /***************************************************************************/
  /*                            GAME CLASSES                                 */
  /***************************************************************************/

  // PLAYER CLASS
  Q.Sprite.extend("Player", {

    init: function(p) {
      this._super(p, {
        sheet: "player",
        type: SPRITE_PLAYER,
        collisionMask: SPRITE_TILES | SPRITE_LADDER | SPRITE_BOOST | SPRITE_WARP,
        lastscore: "N/A"
      });
      this.add("2d, platformerControls");
      this.on("hit.sprite", function(collision) {
        if (collision.obj.isA("Ladder")) {
          Q.stageScene("endGame", 1, {
            label: "You Conquered The Maze In " + secondsToTime(runtime) + " !"
          });
          this.p.lastscore = runtime;
          this.p.socket.emit("pushScore", {
            playerID: this.p.playerId,
            score: this.p.lastscore
          });
          this.p.x = PLAYER_SPAWN_X;
          this.p.y = PLAYER_SPAWN_Y;
          runtime = 0;
          boostTime = 0;
          warpUses = 0;
          activeGame = false;
        } else if (collision.obj.isA("BoostPad")) {
          boostTime = 8;
        }
      });
      Q.input.on("warp", this, "warpPlayer");

    },

    warpPlayer: function() {
      if (warpUses > 0) {
        warpUses--;
        if (Q.inputs['right'] && Q.inputs['up']) {
          this.p.x += 32;
          this.p.y -= 32;
        } else if (Q.inputs['right'] && Q.inputs['down']) {
          this.p.x += 32;
          this.p.y += 32;
        } else if (Q.inputs['left'] && Q.inputs['down']) {
          this.p.x -= 32;
          this.p.y += 32;
        } else if (Q.inputs['left'] && Q.inputs['up']) {
          this.p.x -= 32;
          this.p.y -= 32;
        } else if (Q.inputs['right']) {
          this.p.x += 32;
        } else if (Q.inputs['down']) {
          this.p.y += 32;
        } else if (Q.inputs['left']) {
          this.p.x -= 32;
        } else if (Q.inputs['up']) {
          this.p.y -= 32;
        }
      }
    },

    // Step is called whenever an arrow key is pressed
    step: function(dt) {

      if (activeGame == false) {
        this.p.speed = 0;
      } else {
        if (boostTime == 0) {
          this.p.speed = PLAYER_WALK_SPEED;
        } else {
          this.p.speed = PLAYER_SPRINT_SPEED;
        }

        // Add up and down movement to platformer controls
        if (Q.inputs['up']) {
          if (this.p.speed == PLAYER_SPRINT_SPEED) {
            this.p.vy = -PLAYER_SPRINT_SPEED;
          } else {
            this.p.vy = -PLAYER_WALK_SPEED;
          }
        } else if (Q.inputs['down']) {
          if (this.p.speed == PLAYER_SPRINT_SPEED) {
            this.p.vy = PLAYER_SPRINT_SPEED;
          } else {
            this.p.vy = PLAYER_WALK_SPEED;
          }
        } else if (!Q.inputs['down'] && !Q.inputs['up']) {
          this.p.vy = 0;
        }

        // Change direction of player sprite based on movement direction
        if (this.p.vx > 0 && this.p.vy < 0) {
          this.p.angle = 45;
        } else if (this.p.vx > 0 && this.p.vy > 0) {
          this.p.angle = 135;
        } else if (this.p.vx < 0 && this.p.vy > 0) {
          this.p.angle = 225;
        } else if (this.p.vx < 0 && this.p.vy < 0) {
          this.p.angle = 315;
        } else if (this.p.vx > 0) {
          this.p.angle = 90;
        } else if (this.p.vy > 0) {
          this.p.angle = 180;
        } else if (this.p.vx < 0) {
          this.p.angle = 270;
        } else if (this.p.vy < 0) {
          this.p.angle = 0;
        }

        this.p.socket.emit("updatePlayer", {
          playerId: this.p.playerId,
          x: this.p.x,
          y: this.p.y,
          sheet: this.p.sheet,
          angle: this.p.angle
        });
      }
    }

  });

  // BOOST PAD CLASS
  Q.Sprite.extend("BoostPad", {
    init: function(p) {
      this._super(p, {
        sheet: "boost_pad",
        type: SPRITE_BOOST,
        sensor: true
      });
      this.on("sensor");
    },

    sensor: function() {
      var temp = this;
      setTimeout(function() {
        temp.p.sheet = "boost_pad";
      }, 3000);
    }
  });

  Q.Sprite.extend("WarpVial", {
    init: function(p) {
      this._super(p, {
        sheet: "warp_vial",
        type: SPRITE_WARP,
        sensor: true,
        full: true
      });
      this.on("sensor");
    },

    sensor: function() {
      if (this.p.full == true) {
        warpUses++;
        this.p.sheet = "empty_vial";
        this.p.full = false;
      }
    }
  });

  // ACTOR CLASS
  Q.Sprite.extend("Actor", {
    init: function(p) {
      this._super(p, {
        sheet: "actor",
        type: SPRITE_ACTOR,
        collisionMask: SPRITE_TILES,
        update: true
      });

      var temp = this;
      setInterval(function() {
        if (!temp.p.update) {
          temp.destroy();
        }
        temp.p.update = false;
      }, 1000000);
    }
  });

  // LADDER CLASS
  Q.Sprite.extend("Ladder", {
    init: function(p) {
      this._super(p, {
        type: SPRITE_LADDER,
        sheet: "ladder"
      });
    }
  });

  /***************************************************************************/
  /*                       MAIN MULTIPLAYER LOGIC                            */
  /***************************************************************************/

  // MULTIPLAYER SOCKET
  function setUp(stage) {

    socket.on("count", function(data) {
      if (thisPlayer != undefined) {
        UiPlayers.innerHTML = "Players - " + data["playerCount"];
      }
    });

    socket.on("connectedGame", function(data) {
      selfId = data["playerId"];
      thisPlayer = new Q.Player({
        playerId: selfId,
        x: PLAYER_SPAWN_X,
        y: PLAYER_SPAWN_Y,
        socket: socket
      });
      stage.insert(thisPlayer);
      stage.add("viewport").follow(thisPlayer);
      UiID.innerHTML = "ID - " + selfId;
      runtime = 0;
    });

    socket.on("updatedActor", function(data) {
      var actor = players.filter(function(obj) {
        return obj.playerId == data["playerId"];
      })[0];
      if (actor) {
        actor.player.p.x = data["x"];
        actor.player.p.y = data["y"];
        actor.player.p.angle = data["angle"];
        actor.player.p.sheet = "actor";
        actor.player.p.update = true;
      } else {
        var temp = new Q.Actor({
          playerId: data["playerId"],
          x: data["x"],
          y: data["y"],
          sheet: "actor"
        });
        players.push({
          player: temp,
          playerId: data["playerId"]
        });
        stage.insert(temp);
      }
    });

  }

  socket.on("updatedScoreboard", function(data) {
    scoreboard = data["scoreboard"];
    var fullScoreboard = "[[Scoreboard]]
";
    var highestscore;
    var highestplayer;
    for (i = 0; i < scoreboard.length; i++) {
      fullScoreboard += "Player " + scoreboard[i].playerID + " - " + secondsToTime(scoreboard[i].score) + "
";
      if (scoreboard[i].score < highestscore || highestscore == null) {
        highestplayer = scoreboard[i].playerID;
        highestscore = scoreboard[i].score;
      }
    }
    if (thisPlayer != undefined) {
      UiScoreboard.innerHTML = fullScoreboard;
      if (scoreboard.length > 0) {
        UiHighscore.innerHTML = "[[High Score]]
" + highestplayer + " - " + secondsToTime(highestscore);
      }
      else {
        UiHighscore.innerHTML = "There's no high score!"
      }
    }
  });

  function secondsToTime(seconds) {
    return (new Date(seconds * 1000)).toUTCString().match(/(\d\d:\d\d:\d\d)/)[0].substring(3);
  }

  setInterval(function addRuntime() {
    if (activeGame == true) {
      runtime++;
    }
  }, 1000);

  setInterval(function subtractBoostTime() {
    if (boostTime > 0) {
      boostTime--;
    }
  }, 1000);

  setInterval(function updateRuntime() {
    if (thisPlayer != undefined) {
      UiRuntime.innerHTML = "Time - " + secondsToTime(runtime);
    }
  }, 10);

  setInterval(function updateBoostTime() {
    if (thisPlayer != undefined) {
      UiBoostTime.innerHTML = "Boost - " + boostTime;
    }
  }, 10);

  setInterval(function updateWarpUses() {
    if (thisPlayer != undefined) {
      UiWarpUses.innerHTML = "Warp (Press X) - " + warpUses;
    }
  }, 10);

  /***************************************************************************/
  /*                            LEVEL SCENES                                 */
  /***************************************************************************/

  // LEVEL 1 SCENE
  Q.scene("level1", function(stage) {

    stage.collisionLayer(new Q.TileLayer({
      dataAsset: "/static/maps/maze1.json",
      type: SPRITE_TILES,
      collisionMask: SPRITE_PLAYER | SPRITE_ACTOR,
      sheet: "tiles"
    }));
    stage.insert(new Q.Ladder({
      x: LADDER_SPAWN_X,
      y: LADDER_SPAWN_Y
    }));
    stage.insert(new Q.BoostPad({
      x: 688,
      y: 900
    }));
    vials.push(new Q.WarpVial({
        x: 800,
        y: 1100
      }),
      new Q.WarpVial({
        x: 700,
        y: 1100
      }),
      new Q.WarpVial({
        x: 600,
        y: 1100
      }));
    stage.insert(vials[0]);
    stage.insert(vials[1]);
    stage.insert(vials[2]);
    setUp(stage);

  });

  // END GAME SCENE
  Q.scene("endGame", function(stage) {

    var container = stage.insert(new Q.UI.Container({
      x: Q.width / 2,
      y: Q.height / 2,
      fill: "rgba(0,0,0,1)"
    }));

    var button = container.insert(new Q.UI.Button({
      x: 0,
      y: 0,
      fill: "#CCCCCC",
      label: "Play Again"
    }))

    var label = container.insert(new Q.UI.Text({
      x: 0,
      y: -50 - button.p.h,
      label: stage.options.label,
      color: "white"
    }));

    button.on("click", function() {
      for (i = 0; i < vials.length; i++) {
        vials[i].p.full = true;
        vials[i].p.sheet = "warp_vial";
      }
      activeGame = true;
      Q.clearStage(1);
    });

    container.fit(1000);

  });

  // LOAD GAME ASSETS
  Q.load("/static/images/sprites.png, /static/images/sprites.json, /static/maps/maze1.json, /static/images/tiles.png",
    function() {
      Q.sheet("tiles", "/static/images/tiles.png", {
        tilew: 32,
        tileh: 32
      });
      Q.compileSheets("/static/images/sprites.png", "/static/images/sprites.json");
      Q.stageScene("level1"); // run the game
    });

});
<|endoftext|>


<commit_before>/*jshint browser:true, indent:2, laxcomma:true, loopfunc: true */
/*global NodeList, HTMLCollection */

(function () {

  'use strict';

  document.querySelector('body').classList.add('loaded');

})();<commit_msg>Add timeout to animation<commit_after>/*jshint browser:true, indent:2, laxcomma:true, loopfunc: true */
/*global NodeList, HTMLCollection */

(function () {

  'use strict';

  setTimeout(function () {
    document.querySelector('body').classList.add('loaded');
  }, 50);

})();<|endoftext|>


<commit_before>/**
 * Copyright (C) 2015 Wasabeef
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

window.onload = function() {
    RE.callback("ready");
};

var RE = {};

RE.currentSelection;

RE.editor = document.getElementById('editor');

RE.editor.addEventListener("mousedown", function() { RE.backuprange(); });
RE.editor.addEventListener("mouseup", function() { RE.backuprange(); });
RE.editor.addEventListener("keydown", function() { RE.backuprange(); });
RE.editor.addEventListener("keyup", function() { RE.backuprange(); });

RE.editor.addEventListener("input", function() {
    RE.backuprange();
    RE.callback("input");
});

RE.editor.addEventListener("focus", function() {
    RE.backuprange();
    RE.callback("focus");
});

RE.editor.addEventListener("blur", function() {
    RE.callback("blur");
});

RE.callback = function(method) {
    window.location.href = "re-callback://" + method;
}

RE.setHtml = function(contents) {
    RE.editor.innerHTML = contents;
}

RE.getHtml = function() {
    return RE.editor.innerHTML;
}

RE.getText = function() {
    return RE.editor.innerText;
}

RE.removeFormat = function() {
    document.execCommand('removeFormat', false, null);
}

RE.setFontSize = function(size) {
    RE.editor.style.fontSize = size;
}

RE.setBackgroundColor = function(color) {
    RE.editor.style.backgroundColor = color;
}

RE.setHeight = function(size) {
    RE.editor.style.height = size;
}

RE.undo = function() {
    document.execCommand('undo', false, null);
}

RE.redo = function() {
    document.execCommand('redo', false, null);
}

RE.setBold = function() {
    document.execCommand('bold', false, null);
}

RE.setItalic = function() {
    document.execCommand('italic', false, null);
}

RE.setSubscript = function() {
    document.execCommand('subscript', false, null);
}

RE.setSuperscript = function() {
    document.execCommand('superscript', false, null);
}

RE.setStrikeThrough = function() {
    document.execCommand('strikeThrough', false, null);
}

RE.setUnderline = function() {
    document.execCommand('underline', false, null);
}

RE.setTextColor = function(color) {
    RE.restorerange();
    document.execCommand("styleWithCSS", null, true);
    document.execCommand('foreColor', false, color);
    document.execCommand("styleWithCSS", null, false);
}

RE.setTextBackgroundColor = function(color) {
    RE.restorerange();
    document.execCommand("styleWithCSS", null, true);
    document.execCommand('hiliteColor', false, color);
    document.execCommand("styleWithCSS", null, false);
}

RE.setHeading = function(heading) {
    document.execCommand('formatBlock', false, '<h'+heading+'>');
}

RE.setIndent = function() {
    document.execCommand('indent', false, null);
}

RE.setOutdent = function() {
    document.execCommand('outdent', false, null);
}

RE.setJustifyLeft = function() {
    document.execCommand('justifyLeft', false, null);
}

RE.setJustifyCenter = function() {
    document.execCommand('justifyCenter', false, null);
}

RE.setJustifyRight = function() {
    document.execCommand('justifyRight', false, null);
}

RE.insertImage = function(url, alt) {
    var html = '';
    RE.insertHTML(html);
    RE.callback("input");
}

RE.setBlockquote = function() {
    document.execCommand('formatBlock', false, '
');
}

RE.insertHTML = function(html) {
    RE.restorerange();
    document.execCommand('insertHTML', false, html);
}

RE.insertLink = function(url, title) {
    RE.restorerange();
    var sel = document.getSelection();
    if (sel.toString().length != 0) {
        if (sel.rangeCount) {

            var el = document.createElement("a");
            el.setAttribute("href", url);
            el.setAttribute("title", title);

            var range = sel.getRangeAt(0).cloneRange();
            range.surroundContents(el);
            sel.removeAllRanges();
            sel.addRange(range);
        }
    }
    RE.callback("input");
}

RE.prepareInsert = function() {
    RE.backuprange();
}

RE.backuprange = function(){
    var selection = window.getSelection();
    var range = selection.getRangeAt(0);
    RE.currentSelection = {
        "startContainer": range.startContainer,
        "startOffset": range.startOffset,
        "endContainer": range.endContainer,
        "endOffset": range.endOffset};
}

RE.restorerange = function(){
    var selection = window.getSelection();
    selection.removeAllRanges();
    var range = document.createRange();
    range.setStart(RE.currentSelection.startContainer, RE.currentSelection.startOffset);
    range.setEnd(RE.currentSelection.endContainer, RE.currentSelection.endOffset);
    selection.addRange(range);
}

RE.focus = function() {
    var range = document.createRange();
    range.selectNodeContents(RE.editor);
    range.collapse(false);
    var selection = window.getSelection();
    selection.removeAllRanges();
    selection.addRange(range);
    RE.editor.focus();
}

RE.blurFocus = function() {
    RE.editor.blur();
}<commit_msg>Improve selection updates<commit_after>/**
 * Copyright (C) 2015 Wasabeef
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

window.onload = function() {
    RE.callback("ready");
};

var RE = {};

RE.currentSelection;

RE.editor = document.getElementById('editor');

// Not universally supported, but seems to work in iOS 7 and 8
document.addEventListener("selectionchange", function() { RE.backuprange(); });

RE.editor.addEventListener("input", function() {
    RE.backuprange();
    RE.callback("input");
});

RE.editor.addEventListener("focus", function() {
    RE.backuprange();
    RE.callback("focus");
});

RE.editor.addEventListener("blur", function() {
    RE.callback("blur");
});

RE.callback = function(method) {
    window.location.href = "re-callback://" + method;
}

RE.setHtml = function(contents) {
    RE.editor.innerHTML = contents;
}

RE.getHtml = function() {
    return RE.editor.innerHTML;
}

RE.getText = function() {
    return RE.editor.innerText;
}

RE.removeFormat = function() {
    document.execCommand('removeFormat', false, null);
}

RE.setFontSize = function(size) {
    RE.editor.style.fontSize = size;
}

RE.setBackgroundColor = function(color) {
    RE.editor.style.backgroundColor = color;
}

RE.setHeight = function(size) {
    RE.editor.style.height = size;
}

RE.undo = function() {
    document.execCommand('undo', false, null);
}

RE.redo = function() {
    document.execCommand('redo', false, null);
}

RE.setBold = function() {
    document.execCommand('bold', false, null);
}

RE.setItalic = function() {
    document.execCommand('italic', false, null);
}

RE.setSubscript = function() {
    document.execCommand('subscript', false, null);
}

RE.setSuperscript = function() {
    document.execCommand('superscript', false, null);
}

RE.setStrikeThrough = function() {
    document.execCommand('strikeThrough', false, null);
}

RE.setUnderline = function() {
    document.execCommand('underline', false, null);
}

RE.setTextColor = function(color) {
    RE.restorerange();
    document.execCommand("styleWithCSS", null, true);
    document.execCommand('foreColor', false, color);
    document.execCommand("styleWithCSS", null, false);
}

RE.setTextBackgroundColor = function(color) {
    RE.restorerange();
    document.execCommand("styleWithCSS", null, true);
    document.execCommand('hiliteColor', false, color);
    document.execCommand("styleWithCSS", null, false);
}

RE.setHeading = function(heading) {
    document.execCommand('formatBlock', false, '<h'+heading+'>');
}

RE.setIndent = function() {
    document.execCommand('indent', false, null);
}

RE.setOutdent = function() {
    document.execCommand('outdent', false, null);
}

RE.setJustifyLeft = function() {
    document.execCommand('justifyLeft', false, null);
}

RE.setJustifyCenter = function() {
    document.execCommand('justifyCenter', false, null);
}

RE.setJustifyRight = function() {
    document.execCommand('justifyRight', false, null);
}

RE.insertImage = function(url, alt) {
    var html = '';
    RE.insertHTML(html);
    RE.callback("input");
}

RE.setBlockquote = function() {
    document.execCommand('formatBlock', false, '
');
}

RE.insertHTML = function(html) {
    RE.restorerange();
    document.execCommand('insertHTML', false, html);
}

RE.insertLink = function(url, title) {
    RE.restorerange();
    var sel = document.getSelection();
    if (sel.toString().length != 0) {
        if (sel.rangeCount) {

            var el = document.createElement("a");
            el.setAttribute("href", url);
            el.setAttribute("title", title);

            var range = sel.getRangeAt(0).cloneRange();
            range.surroundContents(el);
            sel.removeAllRanges();
            sel.addRange(range);
        }
    }
    RE.callback("input");
}

RE.prepareInsert = function() {
    RE.backuprange();
}

RE.backuprange = function(){
    var selection = window.getSelection();
    if (selection.rangeCount > 0) {
        var range = selection.getRangeAt(0);
        RE.currentSelection = {
            "startContainer": range.startContainer,
            "startOffset": range.startOffset,
            "endContainer": range.endContainer,
            "endOffset": range.endOffset};
    }
}

RE.restorerange = function(){
    var selection = window.getSelection();
    selection.removeAllRanges();
    var range = document.createRange();
    range.setStart(RE.currentSelection.startContainer, RE.currentSelection.startOffset);
    range.setEnd(RE.currentSelection.endContainer, RE.currentSelection.endOffset);
    selection.addRange(range);
}

RE.focus = function() {
    var range = document.createRange();
    range.selectNodeContents(RE.editor);
    range.collapse(false);
    var selection = window.getSelection();
    selection.removeAllRanges();
    selection.addRange(range);
    RE.editor.focus();
}

RE.blurFocus = function() {
    RE.editor.blur();
}<|endoftext|>


<commit_before>let init = false;
let eHeadText;
function activate() {
  if (init) return;
  init = true;
  document.getElementById('wrapper').classList.add('active');
  const eHead = document.getElementById('header-text');
  while (eHead.firstChild) eHead.firstChild.remove();
  eHeadText = document.createElement('div');
  eHeadText.setAttribute('id', 'header-text-only');
  eHead.appendChild(eHeadText);
}

const eNavLeft = document.getElementById('nav-left');
const eNavRight = document.getElementById('nav-right');
const eSwapper = document.getElementById('swap-wrapper');
const ePageLeft = document.getElementById('page-left');
const ePageRight = document.getElementById('page-right');
function showL() {
  activate();
  eHeadText.innerHTML = 'LEGO\u00ae Robotics';
  eNavLeft.classList.remove('active');
  eNavRight.classList.add('active');
  eSwapper.style.left = '0';
  ePageRight.classList.remove('active');
  ePageLeft.classList.add('active');
}

function showR() {
  activate();
  eHeadText.innerText = 'Python Programming';
  eNavLeft.classList.add('active');
  eNavRight.classList.remove('active');
  eSwapper.style.left = '-100vw';
  ePageLeft.classList.remove('active');
  ePageRight.classList.add('active');
}

document.getElementById('header-left').onclick = showL;
document.getElementById('nav-left').onclick = showL;
document.getElementById('header-right').onclick = showR;
document.getElementById('nav-right').onclick = showR;

window.onwheel = event => {
  if (!init && event.deltaY > 0) {
    showL();
  }
};
<commit_msg>Add gesture detection to mobile<commit_after>let init = false;
let eHeadText;
function activate() {
  if (init) return;
  init = true;
  document.getElementById('wrapper').classList.add('active');
  const eHead = document.getElementById('header-text');
  while (eHead.firstChild) eHead.firstChild.remove();
  eHeadText = document.createElement('div');
  eHeadText.setAttribute('id', 'header-text-only');
  eHead.appendChild(eHeadText);
}

const eNavLeft = document.getElementById('nav-left');
const eNavRight = document.getElementById('nav-right');
const eSwapper = document.getElementById('swap-wrapper');
const ePageLeft = document.getElementById('page-left');
const ePageRight = document.getElementById('page-right');
function showL() {
  activate();
  eHeadText.innerHTML = 'LEGO\u00ae Robotics';
  eNavLeft.classList.remove('active');
  eNavRight.classList.add('active');
  eSwapper.style.left = '0';
  ePageRight.classList.remove('active');
  ePageLeft.classList.add('active');
}

function showR() {
  activate();
  eHeadText.innerText = 'Python Programming';
  eNavLeft.classList.add('active');
  eNavRight.classList.remove('active');
  eSwapper.style.left = '-100vw';
  ePageLeft.classList.remove('active');
  ePageRight.classList.add('active');
}

document.getElementById('header-left').onclick = showL;
document.getElementById('nav-left').onclick = showL;
document.getElementById('header-right').onclick = showR;
document.getElementById('nav-right').onclick = showR;

window.onwheel = event => {
  if (!init && event.deltaY > 0) {
    showL();
  }
};

// Detect gestures on mobile since window.onwheel doesn't work
const wrapper = document.getElementById('wrapper');
let touchStartX = 0;
let touchStartY = 0;
let touchEndX = 0;
let touchEndY = 0;

wrapper.addEventListener('touchstart', event => {
  touchStartX = event.changedTouches[0].screenX;
  touchStartY = event.changedTouches[0].screenY;
}, false);
wrapper.addEventListener('touchend', event => {
  touchEndX = event.changedTouches[0].screenX;
  touchEndY = event.changedTouches[0].screenY;
  handleGesture();
}, false);

const {width, height} = wrapper.getBoundingClientRect();
function handleGesture() {
  const deltaX = touchEndX - touchStartX;
  const deltaY = touchEndY - touchStartY;
  const ratioX = deltaX / width;
  const ratioY = deltaY / height;

  if (deltaX > deltaY && ratioX > 0.1 && !init) { // Right
    showL();
  } else if (deltaY > deltaX && ratioY > 0.1) { // Down
  } else if (deltaX < deltaY && ratioX < -0.1 && !init) { // Left
    showR();
  } else if (deltaY < deltaX && ratioY < -0.1 && !init) { // Up
    showL()
  }
}
<|endoftext|>