<commit_before>"use strict";

// Using "use strict" global

(function ($) {
    window.api = {
        getGeneInformation: function (symbol) {
            var serializer = new XMLSerializer();
            var getUniProtInfo = function (geneSymbol) {
                return $.get({
                    url: "http://www.uniprot.org/uploadlists/",
                    data: {
                        from: "GENENAME",
                        to: "ACC",
                        format: "tab",
                        taxon: "559292",
                        query: geneSymbol,
                    },
                    dataType: "text",
                    timeout: 5000,
                }).then(function (data) {
                    var regex = new RegExp(geneSymbol + "[ \t\r\n\v\f]*([A-Z0-9]+)", "gm");
                    var id = regex.exec(data)[1];
                    return $.get({
                        url: "http://www.uniprot.org/uniprot/" + id + ".xml",
                        timeout: 5000,
                    });
                });
            };

            var getNCBIInfo = function (geneSymbol) {
                return $.get({
                    url: "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi",
                    data: {
                        db: "gene",
                        term: geneSymbol + "[gene]+Saccharomyces+cerevisiae[Organism]",
                    },
                    dataType: "text",
                    timeout: 5000,
                }).then(function (data) {
                    var regex = /<Id>(\d*)<\/Id>/gm;
                    var id = regex.exec(data)[1];
                    return $.get({
                        url: "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=gene&id=" + id,
                        dataType: "xml",
                        timeout: 5000,
                    });
                });
            };

            var getYeastMineInfo = function (geneSymbol) {
<<<<<<< HEAD
                // return $.get({
                //     url: "https://yeastmine.yeastgenome.org/yeastmine/service/data/Gene?symbol=" + geneSymbol,
                //     dataType: "json",
                //     timeout: 5000,
                //     beforeSend: function (xhr) {
                //         xhr.setRequestHeader("content-type", "application/json");
                //     },
                // }).then(function (data) {
                //     return $.get({
                //        // TODO: This part
                //     });
                // });
=======
                return $.get({
                    url: "https://yeastmine.yeastgenome.org/yeastmine/service/data/Gene?symbol=" + geneSymbol,
                    dataType: "json",
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader("content-type", "application/json");
                    },
                }).then(function (data) {
                    console.log(data.results.filter(function (data) {
                        return data.primaryIdentifier[0] === "S";
                    }));
                    return(data.results.filter(function (data) {

                        return data.primaryIdentifier[0] === "S";
                    }));
                });
>>>>>>> f1f68674238dc3331d2b926dd6fb88811def7666
            };

            var getEnsemblInfo = function (geneSymbol) {
                return $.get({
                    url: "http://rest.ensembl.org/lookup/symbol/saccharomyces_cerevisiae/" + geneSymbol,
                    dataType: "json",
                    timeout: 5000,
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader("content-type", "application/json");
                    },
                }).then(function (data) {
                    return $.get({
                        url: "http://rest.ensembl.org/lookup/id/" + data.id + "?expand=1",
                        dataType: "json",
                        timeout: 5000,
                        beforeSend: function (xhr) {
                            xhr.setRequestHeader("content-type", "application/json");
                        },
                    });
                });
            };

            var getJasparInfo = function (geneSymbol) {
                return $.get({
                    url: "http://jaspar.genereg.net/api/v1/matrix/?tax_id=4932&search=" + geneSymbol,
                    dataType: "json",
                    timeout: 5000,
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader("content-type", "application/json");
                    },
                }).then(function (data) {
                    return (data.count === 0 ?
                        null :
                        $.get({
                            url: "http://jaspar.genereg.net/api/v1/matrix/" + data.results[0].matrix_id,
                            dataType: "json",
                            timeout: 5000,
                            beforeSend: function (xhr) {
                                xhr.setRequestHeader("content-type", "application/json");
                            },
                        })
                    );
                });
            };

            // change if any preprocessing needs to be done on the data before being given to the application
            var filterData = function (uniprotInfo, ncbiInfo, yeastmineInfo, ensemblInfo, jasparInfo) {
                var parseUniprot = function (data) {
                    console.log(uniprotInfo[0]);
                    return {
                        uniprotID: serializer.serializeToString(data.getElementsByTagName("name")[0]),
                        proteinSequence: serializer.serializeToString(data.getElementsByTagName("sequence")[0]),
                        similarProtein: { name: "etc.", id: "etc." },
                        proteinType:serializer.serializeToString(data.getElementsByTagName("protein")[0].childNodes[1].childNodes[1]),
                        species: serializer.serializeToString(data.getElementsByTagName("organism")[0].childNodes[1]),
                    }
                }

                var parseNCBI = function (data) {
                    var tagArray = serializer.serializeToString(data.getElementsByTagName("OtherAliases")[0]).split(",");
                    return {
                        ncbiID: "etc.",
                        locusTag: tagArray[0],
                        alsoKnownAs: tagArray.slice(1),
                        chromosomeSequence: "etc.",
                        genomicSequence: "etc.",
                        proteinSequence: "etc.",
                    }
                }

                var parseYeastmine = function (data) {
                    return {
                        sgdID: data.primaryIdentifier, //string
                        standardName: data.symbol, //string
                        systematicName: data.secondaryIdentifier, //string
                        regulators: 1,
                        targets: 12,
                        totalInteractions: "etc.",
                        affinityCaptureMS: 11,
                        affinityCaptureRNA: 1,
                        affinityCaptureWestern: 4,
                        biochemicalActivity: 11,
                        colocalization: 3,
                        reconstitutedComplex: 2,
                        twoHybrid: 3,
                        dosageRescue: 16,
                        negativeGenetic: 8,
                        phenotypicEnhancement: 1,
                        phenotypicSuppression: 5,
                        syntheticGrowthDefect: 2,
                        syntheticHaploinsufficiency: 1,
                        syntheticLethality: 6,
                        syntheticRescue: 11,
                        geneOntologySummary: data.functionSummary, //string
                        molecularFunction: "etc.",
                        biologicalProcess: "etc.",
                        cellularComponent: "etc.",
                    }
                }

                var parseEnsembl = function (data) {
                    return {
                        ensemblID: "etc.",
                        description: "etc.",
                        dnaSequence: "etc.",
                        geneLocation: "etc.",
                        geneMap: "URL",
                    }
                }

                var parseJaspar = function (data) {
                    return {
                        jasparID : data.matrix_id, // string
                        class: data.class, // string
                        family: data.family, // array
                        sequenceLogo: data.sequence_logo, // string: URL to image
                        frequencyMatrix: data.pfm,  // object with keys ACIG, each key mapping to an array of ints
                    }
                }
                return {
                    // jaspar: parseJaspar(),
                    ncbi: parseNCBI(ncbiInfo[0]),
                    emsembl: parseEnsembl(ensemblInfo[0]),
                    uniprot: parseUniprot(uniprotInfo[0]) ,
                    sgd: parseYeastmine(yeastmineInfo[0]),
                };
            };

            // TODO: Error Handling, Mock Testing, Data filtering
            return $.when(
                getUniProtInfo(symbol),
                getNCBIInfo(symbol),
                getYeastMineInfo(symbol),
<<<<<<< HEAD
                getEnsemblInfo(symbol),
                getJasparInfo(symbol)
            ).then(function (uniprotInfo, ncbiInfo, yeastmineInfo, ensemblInfo, jasparInfo) {
                console.log(uniprotInfo[2].responseXML, ncbiInfo, yeastmineInfo, ensemblInfo, jasparInfo);
                return filterData(uniprotInfo, ncbiInfo, yeastmineInfo, ensemblInfo, jasparInfo[0]);
            }).fail(function () {
                alert("There was an error retrieving the data from the databases. Please try again later.");
=======
                getEnsemblInfo(symbol)
                // getJasparInfo(symbol)
            ).done(function (uniprotInfo, ncbiInfo, yeastmineInfo, ensemblInfo, jasparInfo) {
                return filterData(uniprotInfo, ncbiInfo, yeastmineInfo, ensemblInfo, jasparInfo);
>>>>>>> f1f68674238dc3331d2b926dd6fb88811def7666
            });
        }
    };
})($);
<commit_msg>commenting out Jaspar<commit_after>"use strict";

// Using "use strict" global

(function ($) {
    window.api = {
        getGeneInformation: function (symbol) {
            var serializer = new XMLSerializer();
            var getUniProtInfo = function (geneSymbol) {
                return $.get({
                    url: "http://www.uniprot.org/uploadlists/",
                    data: {
                        from: "GENENAME",
                        to: "ACC",
                        format: "tab",
                        taxon: "559292",
                        query: geneSymbol,
                    },
                    dataType: "text",
                    timeout: 5000,
                }).then(function (data) {
                    var regex = new RegExp(geneSymbol + "[ \t\r\n\v\f]*([A-Z0-9]+)", "gm");
                    var id = regex.exec(data)[1];
                    return $.get({
                        url: "http://www.uniprot.org/uniprot/" + id + ".xml",
                        timeout: 5000,
                    });
                });
            };

            var getNCBIInfo = function (geneSymbol) {
                return $.get({
                    url: "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi",
                    data: {
                        db: "gene",
                        term: geneSymbol + "[gene]+Saccharomyces+cerevisiae[Organism]",
                    },
                    dataType: "text",
                    timeout: 5000,
                }).then(function (data) {
                    var regex = /<Id>(\d*)<\/Id>/gm;
                    var id = regex.exec(data)[1];
                    return $.get({
                        url: "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=gene&id=" + id,
                        dataType: "xml",
                        timeout: 5000,
                    });
                });
            };

            var getYeastMineInfo = function (geneSymbol) {
<<<<<<< HEAD
                // return $.get({
                //     url: "https://yeastmine.yeastgenome.org/yeastmine/service/data/Gene?symbol=" + geneSymbol,
                //     dataType: "json",
                //     timeout: 5000,
                //     beforeSend: function (xhr) {
                //         xhr.setRequestHeader("content-type", "application/json");
                //     },
                // }).then(function (data) {
                //     return $.get({
                //        // TODO: This part
                //     });
                // });
=======
                return $.get({
                    url: "https://yeastmine.yeastgenome.org/yeastmine/service/data/Gene?symbol=" + geneSymbol,
                    dataType: "json",
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader("content-type", "application/json");
                    },
                }).then(function (data) {
                    console.log(data.results.filter(function (data) {
                        return data.primaryIdentifier[0] === "S";
                    }));
                    return(data.results.filter(function (data) {

                        return data.primaryIdentifier[0] === "S";
                    }));
                });
>>>>>>> f1f68674238dc3331d2b926dd6fb88811def7666
            };

            var getEnsemblInfo = function (geneSymbol) {
                return $.get({
                    url: "http://rest.ensembl.org/lookup/symbol/saccharomyces_cerevisiae/" + geneSymbol,
                    dataType: "json",
                    timeout: 5000,
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader("content-type", "application/json");
                    },
                }).then(function (data) {
                    return $.get({
                        url: "http://rest.ensembl.org/lookup/id/" + data.id + "?expand=1",
                        dataType: "json",
                        timeout: 5000,
                        beforeSend: function (xhr) {
                            xhr.setRequestHeader("content-type", "application/json");
                        },
                    });
                });
            };

            var getJasparInfo = function (geneSymbol) {
                return $.get({
                    url: "http://jaspar.genereg.net/api/v1/matrix/?tax_id=4932&search=" + geneSymbol,
                    dataType: "json",
                    timeout: 5000,
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader("content-type", "application/json");
                    },
                }).then(function (data) {
                    return (data.count === 0 ?
                        null :
                        $.get({
                            url: "http://jaspar.genereg.net/api/v1/matrix/" + data.results[0].matrix_id,
                            dataType: "json",
                            timeout: 5000,
                            beforeSend: function (xhr) {
                                xhr.setRequestHeader("content-type", "application/json");
                            },
                        })
                    );
                });
            };

            // change if any preprocessing needs to be done on the data before being given to the application
            var filterData = function (uniprotInfo, ncbiInfo, yeastmineInfo, ensemblInfo, jasparInfo) {
                var parseUniprot = function (data) {
                    console.log(uniprotInfo[0]);
                    return {
                        uniprotID: serializer.serializeToString(data.getElementsByTagName("name")[0]),
                        proteinSequence: serializer.serializeToString(data.getElementsByTagName("sequence")[0]),
                        similarProtein: { name: "etc.", id: "etc." },
                        proteinType:serializer.serializeToString(data.getElementsByTagName("protein")[0].childNodes[1].childNodes[1]),
                        species: serializer.serializeToString(data.getElementsByTagName("organism")[0].childNodes[1]),
                    }
                }

                var parseNCBI = function (data) {
                    var tagArray = serializer.serializeToString(data.getElementsByTagName("OtherAliases")[0]).split(",");
                    return {
                        ncbiID: "etc.",
                        locusTag: tagArray[0],
                        alsoKnownAs: tagArray.slice(1),
                        chromosomeSequence: "etc.",
                        genomicSequence: "etc.",
                        proteinSequence: "etc.",
                    }
                }

                var parseYeastmine = function (data) {
                    return {
                        sgdID: data.primaryIdentifier, //string
                        standardName: data.symbol, //string
                        systematicName: data.secondaryIdentifier, //string
                        regulators: 1,
                        targets: 12,
                        totalInteractions: "etc.",
                        affinityCaptureMS: 11,
                        affinityCaptureRNA: 1,
                        affinityCaptureWestern: 4,
                        biochemicalActivity: 11,
                        colocalization: 3,
                        reconstitutedComplex: 2,
                        twoHybrid: 3,
                        dosageRescue: 16,
                        negativeGenetic: 8,
                        phenotypicEnhancement: 1,
                        phenotypicSuppression: 5,
                        syntheticGrowthDefect: 2,
                        syntheticHaploinsufficiency: 1,
                        syntheticLethality: 6,
                        syntheticRescue: 11,
                        geneOntologySummary: data.functionSummary, //string
                        molecularFunction: "etc.",
                        biologicalProcess: "etc.",
                        cellularComponent: "etc.",
                    }
                }

                var parseEnsembl = function (data) {
                    return {
                        ensemblID: "etc.",
                        description: "etc.",
                        dnaSequence: "etc.",
                        geneLocation: "etc.",
                        geneMap: "URL",
                    }
                }

                // var parseJaspar = function (data) {
                //     return {
                //         jasparID : data.matrix_id, // string
                //         class: data.class, // string
                //         family: data.family, // array
                //         sequenceLogo: data.sequence_logo, // string: URL to image
                //         frequencyMatrix: data.pfm,  // object with keys ACIG, each key mapping to an array of ints
                //     }
                // }
                return {
                    // jaspar: parseJaspar(),
                    ncbi: parseNCBI(ncbiInfo[0]),
                    emsembl: parseEnsembl(ensemblInfo[0]),
                    uniprot: parseUniprot(uniprotInfo[0]),
                    sgd: parseYeastmine(yeastmineInfo[0]),
                };
            };

            // TODO: Error Handling, Mock Testing, Data filtering
            return $.when(
                getUniProtInfo(symbol),
                getNCBIInfo(symbol),
                getYeastMineInfo(symbol),
                getEnsemblInfo(symbol)
                // getJasparInfo(symbol)
            ).then(function (uniprotInfo, ncbiInfo, yeastmineInfo, ensemblInfo, jasparInfo) {
                console.log(uniprotInfo[2].responseXML, ncbiInfo, yeastmineInfo, ensemblInfo, jasparInfo);
                return filterData(uniprotInfo, ncbiInfo, yeastmineInfo, ensemblInfo, jasparInfo);
            }).fail(function () {
                alert("There was an error retrieving the data from the databases. Please try again later.");
            });
        }
    };
})($);
<|endoftext|>


<commit_before>exports.BattleScripts = {
	        init: function() {
                for (var i in this.data.FormatsData)
                        this.data.FormatsData[i].dreamWorldRelease = true;

			this.data.Learnsets.serperior.learnset.zenheadbutt = ['5L0'];
			this.data.Learnsets.serperior.learnset.psychoboost = ['5L0'];
			this.data.Learnsets.serperior.learnset.naturepower = ['5L0'];
			this.data.Learnsets.serperior.learnset.earthpower = ['5L0'];
			this.data.Learnsets.serperior.learnset.lunardance = ['5L0'];
			this.data.Learnsets.serperior.learnset.psystrike = ['5L0'];
			this.data.Learnsets.serperior.learnset.aurasphere = ['5L0'];

			this.data.Learnsets.articuno.learnset.airslash = ['5L0'];
			this.data.Learnsets.articuno.learnset.earthpower = ['5L0'];

			this.data.Learnsets.vulpix.learnset.psychic = ['5L0'];
			this.data.Learnsets.vulpix.learnset.psyshock = ['5L0'];
			this.data.Learnsets.vulpix.learnset.morningsun = ['5L0'];
			this.data.Learnsets.vulpix.learnset.wish = ['5L0'];

			this.data.Learnsets.carracosta.learnset.xscissor = ['5L0'];
			this.data.Learnsets.carracosta.learnset.headsmash = ['5L0'];

			this.data.Learnsets.torterra.learnset.shellsmash = ['5L0'];
			this.data.Learnsets.torterra.learnset.rockblast = ['5L0'];

			this.data.Learnsets.girafarig.learnset.bulkup = ['5L0'];
			this.data.Learnsets.girafarig.learnset.focusblast = ['5L0'];
			this.data.Learnsets.girafarig.learnset.shadowclaw = ['5L0'];

			this.data.Learnsets.masquerain.learnset.earthpower = ['5L0'];

			delete this.data.Learnsets.simipour.learnset.nastyplot;
			this.data.Learnsets.simipour.learnset.wish = ['5L0'];
			this.data.Learnsets.simipour.learnset.calmmind = ['5L0'];
			this.data.Learnsets.simipour.learnset.futuresight = ['5L0'];
			this.data.Learnsets.simipour.learnset.shadowball = ['5L0'];
			this.data.Learnsets.simipour.learnset.psychic = ['5L0'];
			this.data.Learnsets.simipour.learnset.psyshock = ['5L0'];
			this.data.Learnsets.simipour.learnset.lightscreen = ['5L0'];
			this.data.Learnsets.simipour.learnset.reflect = ['5L0'];

			delete this.data.Learnsets.simisage.learnset.nastyplot;
			this.data.Learnsets.simisage.learnset.leafblade = ['5L0'];
			this.data.Learnsets.simisage.learnset.bulkup = ['5L0'];
			this.data.Learnsets.simisage.learnset.naturepower = ['5L0'];
			this.data.Learnsets.simisage.learnset.closecombat = ['5L0'];

			delete this.data.Learnsets.simisear.learnset.nastyplot;
			this.data.Learnsets.simisear.learnset.darkpulse = ['5L0'];
			this.data.Learnsets.simisear.learnset.earthpower = ['5L0'];
			this.data.Learnsets.simisear.learnset.extrasensory = ['5L0'];
			this.data.Learnsets.simisear.learnset.grassknot = ['5L0'];

			this.data.Learnsets.whirlipede.learnset.rapidspin = ['5L0'];
			this.data.Learnsets.whirlipede.learnset.earthquake = ['5L0'];
			this.data.Learnsets.whirlipede.learnset.hornleech = ['5L0'];
			this.data.Learnsets.whirlipede.learnset.gunkshot = ['5L0'];
			this.data.Learnsets.whirlipede.learnset.encore = ['5L0'];
			this.data.Learnsets.whirlipede.learnset.glare = ['5L0'];

			this.data.Learnsets.linoone.learnset.extremespeed = ['5L0'];
			this.data.Learnsets.linoone.learnset.superpower = ['5L0'];

			this.data.Learnsets.butterfree.learnset.hurricane = ['5L0'];

			this.data.Learnsets.golurk.learnset.closecombat = ['5L0'];
			this.data.Learnsets.golurk.learnset.machpunch = ['5L0'];
			this.data.Learnsets.golurk.learnset.bulkup = ['5L0'];
			this.data.Learnsets.golurk.learnset.drainpunch = ['5L0'];
			this.data.Learnsets.golurk.learnset.shadowforce = ['5L0'];

			this.data.Learnsets.frillish.learnset.wish = ['5L0'];
			this.data.Learnsets.frillish.learnset.darkvoid = ['5L0'];
			this.data.Learnsets.frillish.learnset.calmmind = ['5L0'];

			this.data.Learnsets.torkoal.learnset.paleowave = ['5L0'];
			this.data.Learnsets.torkoal.learnset.stoneedge = ['5L0'];
			this.data.Learnsets.torkoal.learnset.recover = ['5L0'];

			this.data.Learnsets.tangela.learnset.paleowave = ['5L0'];
			this.data.Learnsets.tangela.learnset.spore = ['5L0'];
			this.data.Learnsets.tangela.learnset.earthpower = ['5L0'];

			this.data.Learnsets.solrock.learnset.flareblitz = ['5L0'];
			this.data.Learnsets.solrock.learnset.rapidspin = ['5L0'];

			this.data.Learnsets.jumpluff.learnset.naturepower = ['5L0'];

			this.data.Learnsets.dodrio.learnset.submission = ['5L0'];
			this.data.Learnsets.dodrio.learnset.extremespeed = ['5L0'];

			this.data.Learnsets.electrode.learnset.icebeam = ['5L0'];

			this.data.Learnsets.scolipede.learnset.rapidspin = ['5L0'];
			this.data.Learnsets.scolipede.learnset.earthquake = ['5L0'];
			this.data.Learnsets.scolipede.learnset.hornleech = ['5L0'];
			this.data.Learnsets.scolipede.learnset.gunkshot = ['5L0'];
			this.data.Learnsets.scolipede.learnset.encore = ['5L0'];
			this.data.Learnsets.scolipede.learnset.glare = ['5L0'];

			this.data.Learnsets.primeape.learnset.machpunch = ['5L0'];

			this.data.Learnsets.munchlax.learnset.slackoff = ['5L0'];

			this.data.Learnsets.escavalier.learnset.superpower = ['5L0'];
			this.data.Learnsets.escavalier.learnset.stoneedge = ['5L0'];
			this.data.Learnsets.escavalier.learnset.meteormash = ['5L0'];
			this.data.Learnsets.escavalier.learnset.bullletpunch = ['5L0'];

			this.data.Learnsets.aerodactyl.learnset.bravebird = ['5L0'];
			this.data.Learnsets.aerodactyl.learnset.uturn = ['5L0'];
			this.data.Learnsets.aerodactyl.learnset.headsmash = ['5L0'];

			this.data.Learnsets.gligar.learnset.rockblast = ['5L0'];
			this.data.Learnsets.gligar.learnset.bravebird = ['5L0'];

			this.data.Learnsets.roselia.learnset.spore = ['5L0'];
			this.data.Learnsets.roselia.learnset.morningsun = ['5L0'];
			this.data.Learnsets.roselia.learnset.leafstorm = ['5L0'];
			this.data.Learnsets.roselia.learnset.taunt = ['5L0'];

			this.data.Learnsets.darmanitan.learnset.submission = ['5L0'];
			this.data.Learnsets.darmanitan.learnset.closecombat = ['5L0'];

			this.data.Learnsets.bisharp.learnset.trickroom = ['5L0'];

			this.data.Learnsets.braviary.learnset.submission = ['5L0'];
			this.data.Learnsets.braviary.learnset.submission = ['5L0'];

			this.data.Learnsets.gardevoir.learnset.lunardance = ['5L0'];
			this.data.Learnsets.gardevoir.learnset.aurasphere = ['5L0'];

			this.data.Learnsets.musharna.learnset.aurasphere = ['5L0'];

			this.data.Learnsets.emboar.learnset.doubleedge = ['5L0'];

			this.data.Learnsets.entei.learnset.flareblitz = ['5L0'];
			this.data.Learnsets.entei.learnset.extremespeed = ['5L0'];
			this.data.Learnsets.entei.learnset.earthquake = ['5L0'];

			this.data.Learnsets.sigilyph.learnset.quiverdance = ['5L0'];
			this.data.Learnsets.sigilyph.learnset.hurricane = ['5L0'];
		}
};
<commit_msg>Update scripts.js<commit_after>exports.BattleScripts = {
	        init: function() {
                for (var i in this.data.FormatsData)
                        this.data.FormatsData[i].dreamWorldRelease = true;

			this.data.Learnsets.serperior.learnset.zenheadbutt = ['5L0'];
			this.data.Learnsets.serperior.learnset.psychoboost = ['5L0'];
			this.data.Learnsets.serperior.learnset.naturepower = ['5L0'];
			this.data.Learnsets.serperior.learnset.earthpower = ['5L0'];
			this.data.Learnsets.serperior.learnset.lunardance = ['5L0'];
			this.data.Learnsets.serperior.learnset.psyshock = ['5L0'];
			this.data.Learnsets.serperior.learnset.aurasphere = ['5L0'];

			this.data.Learnsets.articuno.learnset.airslash = ['5L0'];
			this.data.Learnsets.articuno.learnset.earthpower = ['5L0'];

			this.data.Learnsets.vulpix.learnset.psychic = ['5L0'];
			this.data.Learnsets.vulpix.learnset.psyshock = ['5L0'];
			this.data.Learnsets.vulpix.learnset.morningsun = ['5L0'];
			this.data.Learnsets.vulpix.learnset.wish = ['5L0'];

			this.data.Learnsets.carracosta.learnset.xscissor = ['5L0'];
			this.data.Learnsets.carracosta.learnset.headsmash = ['5L0'];

			this.data.Learnsets.torterra.learnset.shellsmash = ['5L0'];
			this.data.Learnsets.torterra.learnset.rockblast = ['5L0'];

			this.data.Learnsets.girafarig.learnset.bulkup = ['5L0'];
			this.data.Learnsets.girafarig.learnset.focusblast = ['5L0'];
			this.data.Learnsets.girafarig.learnset.shadowclaw = ['5L0'];

			this.data.Learnsets.masquerain.learnset.earthpower = ['5L0'];

			delete this.data.Learnsets.simipour.learnset.nastyplot;
			this.data.Learnsets.simipour.learnset.wish = ['5L0'];
			this.data.Learnsets.simipour.learnset.calmmind = ['5L0'];
			this.data.Learnsets.simipour.learnset.futuresight = ['5L0'];
			this.data.Learnsets.simipour.learnset.shadowball = ['5L0'];
			this.data.Learnsets.simipour.learnset.psychic = ['5L0'];
			this.data.Learnsets.simipour.learnset.psyshock = ['5L0'];
			this.data.Learnsets.simipour.learnset.lightscreen = ['5L0'];
			this.data.Learnsets.simipour.learnset.reflect = ['5L0'];

			delete this.data.Learnsets.simisage.learnset.nastyplot;
			this.data.Learnsets.simisage.learnset.leafblade = ['5L0'];
			this.data.Learnsets.simisage.learnset.bulkup = ['5L0'];
			this.data.Learnsets.simisage.learnset.naturepower = ['5L0'];
			this.data.Learnsets.simisage.learnset.closecombat = ['5L0'];

			delete this.data.Learnsets.simisear.learnset.nastyplot;
			this.data.Learnsets.simisear.learnset.darkpulse = ['5L0'];
			this.data.Learnsets.simisear.learnset.earthpower = ['5L0'];
			this.data.Learnsets.simisear.learnset.extrasensory = ['5L0'];
			this.data.Learnsets.simisear.learnset.grassknot = ['5L0'];

			this.data.Learnsets.whirlipede.learnset.rapidspin = ['5L0'];
			this.data.Learnsets.whirlipede.learnset.earthquake = ['5L0'];
			this.data.Learnsets.whirlipede.learnset.hornleech = ['5L0'];
			this.data.Learnsets.whirlipede.learnset.gunkshot = ['5L0'];
			this.data.Learnsets.whirlipede.learnset.encore = ['5L0'];
			this.data.Learnsets.whirlipede.learnset.glare = ['5L0'];

			this.data.Learnsets.linoone.learnset.extremespeed = ['5L0'];
			this.data.Learnsets.linoone.learnset.superpower = ['5L0'];

			this.data.Learnsets.butterfree.learnset.hurricane = ['5L0'];

			this.data.Learnsets.golurk.learnset.closecombat = ['5L0'];
			this.data.Learnsets.golurk.learnset.machpunch = ['5L0'];
			this.data.Learnsets.golurk.learnset.bulkup = ['5L0'];
			this.data.Learnsets.golurk.learnset.drainpunch = ['5L0'];
			this.data.Learnsets.golurk.learnset.shadowforce = ['5L0'];

			this.data.Learnsets.frillish.learnset.wish = ['5L0'];
			this.data.Learnsets.frillish.learnset.darkvoid = ['5L0'];
			this.data.Learnsets.frillish.learnset.calmmind = ['5L0'];

			this.data.Learnsets.torkoal.learnset.paleowave = ['5L0'];
			this.data.Learnsets.torkoal.learnset.stoneedge = ['5L0'];
			this.data.Learnsets.torkoal.learnset.recover = ['5L0'];

			this.data.Learnsets.tangela.learnset.paleowave = ['5L0'];
			this.data.Learnsets.tangela.learnset.spore = ['5L0'];
			this.data.Learnsets.tangela.learnset.earthpower = ['5L0'];

			this.data.Learnsets.solrock.learnset.flareblitz = ['5L0'];
			this.data.Learnsets.solrock.learnset.rapidspin = ['5L0'];

			this.data.Learnsets.jumpluff.learnset.naturepower = ['5L0'];

			this.data.Learnsets.dodrio.learnset.submission = ['5L0'];
			this.data.Learnsets.dodrio.learnset.extremespeed = ['5L0'];

			this.data.Learnsets.electrode.learnset.icebeam = ['5L0'];

			this.data.Learnsets.scolipede.learnset.rapidspin = ['5L0'];
			this.data.Learnsets.scolipede.learnset.earthquake = ['5L0'];
			this.data.Learnsets.scolipede.learnset.hornleech = ['5L0'];
			this.data.Learnsets.scolipede.learnset.gunkshot = ['5L0'];
			this.data.Learnsets.scolipede.learnset.encore = ['5L0'];
			this.data.Learnsets.scolipede.learnset.glare = ['5L0'];

			this.data.Learnsets.primeape.learnset.machpunch = ['5L0'];

			this.data.Learnsets.munchlax.learnset.slackoff = ['5L0'];

			this.data.Learnsets.escavalier.learnset.superpower = ['5L0'];
			this.data.Learnsets.escavalier.learnset.stoneedge = ['5L0'];
			this.data.Learnsets.escavalier.learnset.meteormash = ['5L0'];
			this.data.Learnsets.escavalier.learnset.bullletpunch = ['5L0'];

			this.data.Learnsets.aerodactyl.learnset.bravebird = ['5L0'];
			this.data.Learnsets.aerodactyl.learnset.uturn = ['5L0'];
			this.data.Learnsets.aerodactyl.learnset.headsmash = ['5L0'];

			this.data.Learnsets.gligar.learnset.rockblast = ['5L0'];
			this.data.Learnsets.gligar.learnset.bravebird = ['5L0'];

			this.data.Learnsets.roselia.learnset.spore = ['5L0'];
			this.data.Learnsets.roselia.learnset.morningsun = ['5L0'];
			this.data.Learnsets.roselia.learnset.leafstorm = ['5L0'];
			this.data.Learnsets.roselia.learnset.taunt = ['5L0'];

			this.data.Learnsets.darmanitan.learnset.submission = ['5L0'];
			this.data.Learnsets.darmanitan.learnset.closecombat = ['5L0'];

			this.data.Learnsets.bisharp.learnset.trickroom = ['5L0'];

			this.data.Learnsets.braviary.learnset.submission = ['5L0'];
			this.data.Learnsets.braviary.learnset.submission = ['5L0'];

			this.data.Learnsets.gardevoir.learnset.lunardance = ['5L0'];
			this.data.Learnsets.gardevoir.learnset.aurasphere = ['5L0'];

			this.data.Learnsets.musharna.learnset.aurasphere = ['5L0'];

			this.data.Learnsets.emboar.learnset.doubleedge = ['5L0'];

			this.data.Learnsets.entei.learnset.flareblitz = ['5L0'];
			this.data.Learnsets.entei.learnset.extremespeed = ['5L0'];
			this.data.Learnsets.entei.learnset.earthquake = ['5L0'];

			this.data.Learnsets.sigilyph.learnset.quiverdance = ['5L0'];
			this.data.Learnsets.sigilyph.learnset.hurricane = ['5L0'];
		}
};
<|endoftext|>


<commit_before>lingcod.Manipulator = function(gex, form, render_target, div){

    this.altitude = 100;
    var json = false;
    var data = form.find('.json').html();
    if(data){
        json = JSON.parse(data);
    }
    this.needed = true;
    // Return false if manipulations are not needed, else proceed.
    if(!json || !json.manipulators){
        this.needed = false;
        return false;
    }
    this.div = div;
    this.shape_;
    this.manipulators_ = json.manipulators;
    this.gex_ = gex;
    this.form_ = form;
    this.render_target_ = render_target;
    this.formats_ = new lingcod.Formats();

    // Fill in the form with content from map.html
    this.render_target_.html($('#geopanel').html());

    var self = this;

    // Setup event listeners
    this.render_target_.find('.draw_shape').click(function(){
        if(!$(this).hasClass('disabled')){
            $(this).addClass('disabled');
            self.drawNewShape_();
        }
    });

    this.render_target_.find('div.manipulated .edit_shape').click(function(){
        if(!$(this).hasClass('disabled')){
            $(this).addClass('disabled');
            self.editExistingShape_();
        }
    });

    this.render_target_.find('.done_editing').click(function(){
        self.render_target_.find('.done_editing').addClass('disabled');
        self.finishedEditingCallback_();
    });

    this.render_target_.find('div.edit .edit_shape').click(function(){
        if(!$(this).hasClass('disabled')){
            $(this).addClass('disabled');
            self.editExistingShape_();
        }
    });

    // Figure out if there is an existing shape in the form, or if a new one
    // needs to be drawn
    if(this.form_.find('#id_geometry_final').val()){
        this.enterExistingShapeState_();
    }else{
        this.enterNewState_();
    }
}

lingcod.Manipulator.prototype.drawNewShape_ = function(){
    this.is_defining_shape_ = true;
    this.is_defining_new_shape_ = true;
    this.addNewShape_();
    var bounds = this.shape_.getGeometry().getOuterBoundary();
    var self = this;
    this.gex_.edit.drawLineString(bounds, {
        bounce: false,
        finishCallback: function(){
            self.finishedEditingCallback_();
        },
        drawCallback: function(i){
            var coords = bounds.getCoordinates();
            var coord = coords.get(i);
            coord.setAltitude(this.altitude);
            coords.set(i, coord);
        },
        ensureCounterClockwise: false
    });
}

lingcod.Manipulator.prototype.addNewShape_ = function(kml){
    this.clearShape_();
    if(kml){
        this.shape_ = this.gex_.util.displayKmlString(kml);
    }else{
        this.shape_ = this.gex_.dom.addPlacemark({
            visibility: true,
            polygon: [],
            style: {
                line: { width: 2, color: 'ffffffff' },
                poly: { color: '8000ff00' }
            }
        });
    }
    this.shape_.getGeometry().setAltitudeMode(ge.ALTITUDE_ABSOLUTE);
    this.shape_.getGeometry().setExtrude(true);
    var coords = this.shape_.getGeometry().getOuterBoundary().getCoordinates();
    var length = coords.getLength();
    for(var i =0; i<length;i++){
        var coord = coords.get(i)
        coord.setAltitude(this.altitude);
        coords.set(i, coord);
    }
    return this.shape_;
}

lingcod.Manipulator.prototype.finishedEditingCallback_ = function(){
    var orig_wkt = this.formats_.kmlToWkt(this.shape_);
    var self = this;
    this.process(orig_wkt, this.manipulators_, function(data){
        if(data.success === '1'){
            var g = JSON.parse(data.geojson_clipped);
            var kml = self.formats_.geojsonToKmlPlacemark(g);
            var kmlObject = self.addNewShape_(kml);
            // that.finalKmlObject = gex.util.displayKmlString(kml);
            self.gex_.util.flyToObject(kmlObject, {
                boundsFallback: true, aspectRatio: $(this.div).width() / $(this.div).height()});
            self.setGeometryFields_(orig_wkt, self.formats_.geojsonToWkt(g));
            // setGeomFields(wkt, formats.geojsonToWkt(g));
            self.enterManipulatedState_(data.html, true);
        }else{
            self.setGeometryFields_(orig_wkt, '');
            var shape = self.shape_;
            self.addNewShape_(shape.getKml());
            self.gex_.util.flyToObject(self.shape_, {
                boundsFallback: true, aspectRatio: $(this.div).width() / $(this.div).height()});
            self.enterManipulatedState_(data.html, false);
        }
    });
}

lingcod.Manipulator.prototype.setGeometryFields_ = function(original_wkt, final_wkt){
    this.form_.find('#id_geometry_final').val('SRID=4326;'+final_wkt);
    this.form_.find('#id_geometry_orig').val('SRID=4326;'+original_wkt);
}

lingcod.Manipulator.prototype.hideStates_ = function(){
    this.render_target_.find('div.new, div.edit, div.manipulated, div.editing').hide();
}

lingcod.Manipulator.prototype.enterManipulatedState_ = function(html, success){
    this.hideStates_();
    if(success === true){
        this.render_target_.find('div.manipulated').removeClass('error');
        this.is_invalid_geometry = false;
        this.is_defining_shape_ = false;
        this.is_defining_new_shape_ = false;
    }else{
        this.is_invalid_geometry = true;
        this.render_target_.find('div.manipulated').addClass('error');
    }
    this.render_target_.find('div.manipulated a.edit_shape').removeClass('disabled');
    this.render_target_.find('div.manipulated').show().find('>p')
        .html(html);
}

lingcod.Manipulator.prototype.isInvalidGeometry = function(){
    return this.is_invalid_geometry;
}

lingcod.Manipulator.prototype.enterNewState_ = function(){
    this.hideStates_();
    // this.is_defining_shape_ = true;
    this.render_target_.find('div.new').show();
    this.render_target_.find('a.draw_shape').removeClass('disabled');
}

lingcod.Manipulator.prototype.isDefiningNewShape = function(){
    return this.is_defining_new_shape_;
}

lingcod.Manipulator.prototype.enterEditingState_ = function(){
    this.hideStates_();
    this.is_invalid_geometry = false;
    this.is_defining_shape_ = true;
    this.is_defining_new_shape_ = false;
    this.render_target_.find('.done_editing').removeClass('disabled');
    this.render_target_.find('div.editing').show();
}

lingcod.Manipulator.prototype.enterExistingShapeState_ = function(){
    this.hideStates_();
    this.is_defining_shape = false;
    this.render_target_.find('div.edit .edit_shape').removeClass('disabled');
    this.render_target_.find('div.edit').show();
    var wkt = this.form_.find('#id_geometry_final').val();
    var kml = this.formats_.wktPolyToKml(wkt);
    this.addNewShape_(kml);
    this.gex_.util.flyToObject(this.shape_, {
        boundsFallback: true, aspectRatio: $(this.div).width() / $(this.div).height()});
}

lingcod.Manipulator.prototype.isShapeDefined = function(){
    return !!this.form_.find('#id_geometry_final').val();
}

lingcod.Manipulator.prototype.isDefiningShape = function(){
    return this.is_defining_shape_;
}

lingcod.Manipulator.prototype.process = function(wkt, url, callback){
    $.ajax({
        url: url,
        type: 'POST',
        data: { target_shape: wkt },
        success: function(data, status){
            if(status === 'success'){
                callback(JSON.parse(data));
            }else{
                alert('there was an error processing your shape.');
                $(this).trigger('error', "There was an error processing your shape.");
                callback({success: false, html: $('#manipulators_server_error')});
            }
        },
        error: function(data, status){
            $(this).trigger('error', 'There was an error processing your shape.');
            callback({success: false, html: $('#manipulators_server_error').html()});
        }
    });
}

lingcod.Manipulator.prototype.editExistingShape_ = function(){
    var wkt = this.form_.find('#id_geometry_orig').val();
    var kml = this.formats_.wktPolyToKml(wkt);
    this.addNewShape_(kml);
    window.shape = this.shape_;
    this.gex_.util.flyToObject(this.shape_, {
        boundsFallback: true, aspectRatio: $(this.div).width() / $(this.div).height()});
    this.gex_.edit.editLineString(this.shape_.getGeometry().getOuterBoundary());
    this.enterEditingState_();

}

lingcod.Manipulator.prototype.clearShape_ = function(){
    if(this.shape_ && this.shape_.getParentNode()){
        this.gex_.edit.endEditLineString(this.shape_.getGeometry().getOuterBoundary());
        gex.dom.removeObject(this.shape_);
        this.shape_ = false;
    }
}

lingcod.Manipulator.prototype.destroy = function(){
    this.clearShape_();
}<commit_msg>fixed altitude setting problem when drawing a new mpa<commit_after>lingcod.Manipulator = function(gex, form, render_target, div){

    this.altitude = 100;
    var json = false;
    var data = form.find('.json').html();
    if(data){
        json = JSON.parse(data);
    }
    this.needed = true;
    // Return false if manipulations are not needed, else proceed.
    if(!json || !json.manipulators){
        this.needed = false;
        return false;
    }
    this.div = div;
    this.shape_;
    this.manipulators_ = json.manipulators;
    this.gex_ = gex;
    this.form_ = form;
    this.render_target_ = render_target;
    this.formats_ = new lingcod.Formats();

    // Fill in the form with content from map.html
    this.render_target_.html($('#geopanel').html());

    var self = this;

    // Setup event listeners
    this.render_target_.find('.draw_shape').click(function(){
        if(!$(this).hasClass('disabled')){
            $(this).addClass('disabled');
            self.drawNewShape_();
        }
    });

    this.render_target_.find('div.manipulated .edit_shape').click(function(){
        if(!$(this).hasClass('disabled')){
            $(this).addClass('disabled');
            self.editExistingShape_();
        }
    });

    this.render_target_.find('.done_editing').click(function(){
        self.render_target_.find('.done_editing').addClass('disabled');
        self.finishedEditingCallback_();
    });

    this.render_target_.find('div.edit .edit_shape').click(function(){
        if(!$(this).hasClass('disabled')){
            $(this).addClass('disabled');
            self.editExistingShape_();
        }
    });

    // Figure out if there is an existing shape in the form, or if a new one
    // needs to be drawn
    if(this.form_.find('#id_geometry_final').val()){
        this.enterExistingShapeState_();
    }else{
        this.enterNewState_();
    }
}

lingcod.Manipulator.prototype.drawNewShape_ = function(){
    this.is_defining_shape_ = true;
    this.is_defining_new_shape_ = true;
    this.addNewShape_();
    var bounds = this.shape_.getGeometry().getOuterBoundary();
    var self = this;
    this.gex_.edit.drawLineString(bounds, {
        bounce: false,
        finishCallback: function(){
            self.finishedEditingCallback_();
        },
        drawCallback: function(i){
            var coords = bounds.getCoordinates();
            var coord = coords.get(i);
            coord.setAltitude(self.altitude);
            coords.set(i, coord);
        },
        ensureCounterClockwise: false
    });
}

lingcod.Manipulator.prototype.addNewShape_ = function(kml){
    this.clearShape_();
    if(kml){
        this.shape_ = this.gex_.util.displayKmlString(kml);
    }else{
        this.shape_ = this.gex_.dom.addPlacemark({
            visibility: true,
            polygon: [],
            style: {
                line: { width: 2, color: 'ffffffff' },
                poly: { color: '8000ff00' }
            }
        });
    }
    this.shape_.getGeometry().setAltitudeMode(ge.ALTITUDE_ABSOLUTE);
    this.shape_.getGeometry().setExtrude(true);
    var coords = this.shape_.getGeometry().getOuterBoundary().getCoordinates();
    var length = coords.getLength();
    for(var i =0; i<length;i++){
        var coord = coords.get(i)
        coord.setAltitude(this.altitude);
        coords.set(i, coord);
    }
    return this.shape_;
}

lingcod.Manipulator.prototype.finishedEditingCallback_ = function(){
    var orig_wkt = this.formats_.kmlToWkt(this.shape_);
    var self = this;
    this.process(orig_wkt, this.manipulators_, function(data){
        if(data.success === '1'){
            var g = JSON.parse(data.geojson_clipped);
            var kml = self.formats_.geojsonToKmlPlacemark(g);
            var kmlObject = self.addNewShape_(kml);
            // that.finalKmlObject = gex.util.displayKmlString(kml);
            self.gex_.util.flyToObject(kmlObject, {
                boundsFallback: true, aspectRatio: $(this.div).width() / $(this.div).height()});
            self.setGeometryFields_(orig_wkt, self.formats_.geojsonToWkt(g));
            // setGeomFields(wkt, formats.geojsonToWkt(g));
            self.enterManipulatedState_(data.html, true);
        }else{
            self.setGeometryFields_(orig_wkt, '');
            var shape = self.shape_;
            self.addNewShape_(shape.getKml());
            self.gex_.util.flyToObject(self.shape_, {
                boundsFallback: true, aspectRatio: $(this.div).width() / $(this.div).height()});
            self.enterManipulatedState_(data.html, false);
        }
    });
}

lingcod.Manipulator.prototype.setGeometryFields_ = function(original_wkt, final_wkt){
    this.form_.find('#id_geometry_final').val('SRID=4326;'+final_wkt);
    this.form_.find('#id_geometry_orig').val('SRID=4326;'+original_wkt);
}

lingcod.Manipulator.prototype.hideStates_ = function(){
    this.render_target_.find('div.new, div.edit, div.manipulated, div.editing').hide();
}

lingcod.Manipulator.prototype.enterManipulatedState_ = function(html, success){
    this.hideStates_();
    if(success === true){
        this.render_target_.find('div.manipulated').removeClass('error');
        this.is_invalid_geometry = false;
        this.is_defining_shape_ = false;
        this.is_defining_new_shape_ = false;
    }else{
        this.is_invalid_geometry = true;
        this.render_target_.find('div.manipulated').addClass('error');
    }
    this.render_target_.find('div.manipulated a.edit_shape').removeClass('disabled');
    this.render_target_.find('div.manipulated').show().find('>p')
        .html(html);
}

lingcod.Manipulator.prototype.isInvalidGeometry = function(){
    return this.is_invalid_geometry;
}

lingcod.Manipulator.prototype.enterNewState_ = function(){
    this.hideStates_();
    // this.is_defining_shape_ = true;
    this.render_target_.find('div.new').show();
    this.render_target_.find('a.draw_shape').removeClass('disabled');
}

lingcod.Manipulator.prototype.isDefiningNewShape = function(){
    return this.is_defining_new_shape_;
}

lingcod.Manipulator.prototype.enterEditingState_ = function(){
    this.hideStates_();
    this.is_invalid_geometry = false;
    this.is_defining_shape_ = true;
    this.is_defining_new_shape_ = false;
    this.render_target_.find('.done_editing').removeClass('disabled');
    this.render_target_.find('div.editing').show();
}

lingcod.Manipulator.prototype.enterExistingShapeState_ = function(){
    this.hideStates_();
    this.is_defining_shape = false;
    this.render_target_.find('div.edit .edit_shape').removeClass('disabled');
    this.render_target_.find('div.edit').show();
    var wkt = this.form_.find('#id_geometry_final').val();
    var kml = this.formats_.wktPolyToKml(wkt);
    this.addNewShape_(kml);
    this.gex_.util.flyToObject(this.shape_, {
        boundsFallback: true, aspectRatio: $(this.div).width() / $(this.div).height()});
}

lingcod.Manipulator.prototype.isShapeDefined = function(){
    return !!this.form_.find('#id_geometry_final').val();
}

lingcod.Manipulator.prototype.isDefiningShape = function(){
    return this.is_defining_shape_;
}

lingcod.Manipulator.prototype.process = function(wkt, url, callback){
    $.ajax({
        url: url,
        type: 'POST',
        data: { target_shape: wkt },
        success: function(data, status){
            if(status === 'success'){
                callback(JSON.parse(data));
            }else{
                alert('there was an error processing your shape.');
                $(this).trigger('error', "There was an error processing your shape.");
                callback({success: false, html: $('#manipulators_server_error')});
            }
        },
        error: function(data, status){
            $(this).trigger('error', 'There was an error processing your shape.');
            callback({success: false, html: $('#manipulators_server_error').html()});
        }
    });
}

lingcod.Manipulator.prototype.editExistingShape_ = function(){
    var wkt = this.form_.find('#id_geometry_orig').val();
    var kml = this.formats_.wktPolyToKml(wkt);
    this.addNewShape_(kml);
    window.shape = this.shape_;
    this.gex_.util.flyToObject(this.shape_, {
        boundsFallback: true, aspectRatio: $(this.div).width() / $(this.div).height()});
    this.gex_.edit.editLineString(this.shape_.getGeometry().getOuterBoundary());
    this.enterEditingState_();

}

lingcod.Manipulator.prototype.clearShape_ = function(){
    if(this.shape_ && this.shape_.getParentNode()){
        this.gex_.edit.endEditLineString(this.shape_.getGeometry().getOuterBoundary());
        gex.dom.removeObject(this.shape_);
        this.shape_ = false;
    }
}

lingcod.Manipulator.prototype.destroy = function(){
    this.clearShape_();
}<|endoftext|>


<commit_before>exports.help = function() {
	return '/associate "<hook>" "<text>" : Associate and disassociate a phrase with another.';
};

exports.match = function(text, thread, api) {
	if (text.startsWith('/associate')) {
		return true;
	}

	var s = text.toLowerCase();
	for (var assoc in this.config[thread]) {
		if (s.indexOf(assoc.toLowerCase()) !== -1) {
			if (api) {
				api.sendMessage(this.config[thread][assoc], thread);
			}
			return true;
		}
	}
	return false;
};

exports.toggleAssociation = function(thread, hook, text) {
	hook = hook.toLowerCase();
	if (this.config[thread] && this.config[thread][hook] && !text) {
		delete this.config[thread][hook];
		return false;
	}

	if (!this.config[thread]) {
		this.config[thread] = {};
	}
	this.config[thread][hook] = text;
	return true;
};

exports.printAssociations = function(api, event) {
	var assoc = this.config[event.thread_id];
	var message = '';
	for (var a in assoc) {
		message += a + ' → ' + assoc[a] + '\n';
	}
	api.sendMessage(message, event.thread_id);
};

exports.clear = function(api, event) {
	this.config[event.thread_id] = {};
	api.sendMessage('Associations cleared.', event.thread_id);
};

exports.run = function(api, event) {
	if (!event.body.startsWith('/associate')) {
		return exports.match(event.body, event.thread_id, api);
	}

	if (event.body === '/associate') {
		return exports.printAssociations(api, event);
	}

	if (event.body === '/associate clear') {
		return exports.clear(api, event);
	}

	var spl = event.body.split('"');
	if (spl.length !== 3 && spl.length !== 5)  {
		api.sendMessage('WTF are you doing????!', event.thread_id);
		return;
	}

	exports.toggleAssociation(event.thread_id, spl[1], spl[3]);
	api.sendMessage('Association changed.', event.thread_id);
};
<commit_msg>fixes for pr<commit_after>exports.help = function() {
	return '/associate "<hook>" "<text>" or clear : Associate and disassociate a phrase with another.';
};

exports.match = function(text, thread, api) {
	if (text.startsWith('/associate')) {
		return true;
	}

	var s = text.toLowerCase();
	for (var assoc in this.config[thread]) {
		if (s.indexOf(assoc.toLowerCase()) !== -1) {
			if (api) {
				api.sendMessage(this.config[thread][assoc], thread);
			}
			return true;
		}
	}
	return false;
};

exports.toggleAssociation = function(thread, hook, text) {
	hook = hook.toLowerCase();
	if (this.config[thread] && this.config[thread][hook] && !text) {
		delete this.config[thread][hook];
		return false;
	}

	if (!this.config[thread]) {
		this.config[thread] = {};
	}
	this.config[thread][hook] = text;
	return true;
};

exports.printAssociations = function(api, event) {
	var assoc = this.config[event.thread_id];
	var message = '';
	for (var a in assoc) {
		message += a + ' → ' + assoc[a] + '\n';
	}
	message.trim();
	api.sendMessage(message, event.thread_id);
};

exports.clear = function(api, event) {
	this.config[event.thread_id] = {};
	api.sendMessage('Associations cleared.', event.thread_id);
};

exports.run = function(api, event) {
	if (!event.body.startsWith('/associate')) {
		return exports.match(event.body, event.thread_id, api);
	}

	if (event.body === '/associate') {
		return exports.printAssociations(api, event);
	}

	if (event.body === '/associate clear') {
		return exports.clear(api, event);
	}

	var spl = event.body.split('"');
	if (spl.length !== 3 && spl.length !== 5)  {
		api.sendMessage('WTF are you doing????!', event.thread_id);
		return;
	}

	exports.toggleAssociation(event.thread_id, spl[1], spl[3]);
	api.sendMessage('Association changed.', event.thread_id);
};
<|endoftext|>


<commit_before>import extend from 'extend';
import Delta from 'quill-delta';
import {
  Attributor,
  ClassAttributor,
  EmbedBlot,
  Scope,
  StyleAttributor,
} from 'parchment';
import Quill from '../core/quill';
import logger from '../core/logger';
import Module from '../core/module';

import { AlignAttribute, AlignStyle } from '../formats/align';
import { BackgroundStyle } from '../formats/background';
import CodeBlock from '../formats/code';
import { ColorStyle } from '../formats/color';
import { DirectionAttribute, DirectionStyle } from '../formats/direction';
import { FontStyle } from '../formats/font';
import { SizeStyle } from '../formats/size';

const debug = logger('quill:clipboard');

const CLIPBOARD_CONFIG = [
  [Node.TEXT_NODE, matchText],
  [Node.TEXT_NODE, matchNewline],
  ['br', matchBreak],
  [Node.ELEMENT_NODE, matchNewline],
  [Node.ELEMENT_NODE, matchBlot],
  [Node.ELEMENT_NODE, matchAttributor],
  [Node.ELEMENT_NODE, matchStyles],
  ['li', matchIndent],
  ['ol, ul', matchList],
  ['pre', matchCodeBlock],
  ['tr', matchTable],
  ['b', matchAlias.bind(matchAlias, 'bold')],
  ['i', matchAlias.bind(matchAlias, 'italic')],
  ['style', matchIgnore],
];

const ATTRIBUTE_ATTRIBUTORS = [AlignAttribute, DirectionAttribute].reduce(
  (memo, attr) => {
    memo[attr.keyName] = attr;
    return memo;
  },
  {},
);

const STYLE_ATTRIBUTORS = [
  AlignStyle,
  BackgroundStyle,
  ColorStyle,
  DirectionStyle,
  FontStyle,
  SizeStyle,
].reduce((memo, attr) => {
  memo[attr.keyName] = attr;
  return memo;
}, {});

class Clipboard extends Module {
  constructor(quill, options) {
    super(quill, options);
    this.quill.root.addEventListener('copy', this.onCaptureCopy.bind(this));
    this.quill.root.addEventListener('cut', this.onCaptureCut.bind(this));
    this.quill.root.addEventListener('paste', this.onCapturePaste.bind(this));
    this.matchers = [];
    CLIPBOARD_CONFIG.concat(this.options.matchers).forEach(
      ([selector, matcher]) => {
        this.addMatcher(selector, matcher);
      },
    );
  }

  addMatcher(selector, matcher) {
    this.matchers.push([selector, matcher]);
  }

  convert({ html, text }) {
    const formats = this.quill.getFormat(this.quill.selection.savedRange.index);
    if (formats[CodeBlock.blotName]) {
      return new Delta().insert(text, {
        [CodeBlock.blotName]: formats[CodeBlock.blotName],
      });
    } else if (!html) {
      return new Delta().insert(text || '');
    }
    const container = this.quill.root.ownerDocument.createElement('div');
    container.innerHTML = html.replace(/>\r?\n +</g, '><'); // Remove spaces between tags
    const nodeMatches = new WeakMap();
    const [elementMatchers, textMatchers] = this.prepareMatching(
      container,
      nodeMatches,
    );
    const delta = traverse(
      this.quill.scroll,
      container,
      elementMatchers,
      textMatchers,
      nodeMatches,
    );
    // Remove trailing newline
    if (
      deltaEndsWith(delta, '\n') &&
      delta.ops[delta.ops.length - 1].attributes == null
    ) {
      return delta.compose(new Delta().retain(delta.length() - 1).delete(1));
    }
    return delta;
  }

  dangerouslyPasteHTML(index, html, source = Quill.sources.API) {
    if (typeof index === 'string') {
      const delta = this.convert({ html: index, text: '' });
      this.quill.setContents(delta, html);
      this.quill.setSelection(0, Quill.sources.SILENT);
    } else {
      const paste = this.convert({ html, text: '' });
      this.quill.updateContents(
        new Delta().retain(index).concat(paste),
        source,
      );
      this.quill.setSelection(index + paste.length(), Quill.sources.SILENT);
    }
  }

  onCaptureCopy(e) {
    if (e.defaultPrevented) return;
    this.quill.update();
    const [range] = this.quill.selection.getRange();
    if (range) {
      this.onCopy(e, range);
      e.preventDefault();
    }
  }

  onCaptureCut(e) {
    if (e.defaultPrevented) return;
    this.quill.update();
    const [range] = this.quill.selection.getRange();
    if (range) {
      this.onCopy(e, range);
      this.quill.deleteText(range, Quill.sources.USER);
      e.preventDefault();
    }
  }

  onCapturePaste(e) {
    if (e.defaultPrevented || !this.quill.isEnabled()) return;
    const range = this.quill.getSelection(true);
    const files = Array.from(e.clipboardData.files || []);
    if (files.length > 0) {
      this.quill.uploader.upload(range, files);
    } else {
      this.onPaste(e, range);
    }
    e.preventDefault();
  }

  onCopy(e, range) {
    const text = this.quill.getText(range);
    const delta = this.quill.getContents(range);
    const html = this.quill.getSemanticHTML(range);
    e.clipboardData.setData('text/plain', text);
    e.clipboardData.setData('text/html', html);
    e.clipboardData.setData('text/delta', JSON.stringify(delta));
  }

  onPaste(e, range) {
    const json = e.clipboardData.getData('text/delta');
    let delta = new Delta().retain(range.index).delete(range.length);
    if (json) {
      const directDelta = new Delta(JSON.parse(json));
      debug.log('onPaste direct', directDelta);
      delta = delta.concat(directDelta);
    } else {
      const html = e.clipboardData.getData('text/html');
      const text = e.clipboardData.getData('text/plain');
      const pastedDelta = this.convert({ text, html });
      debug.log('onPaste converted', pastedDelta, { text, html });
      delta = delta.concat(pastedDelta);
    }
    this.quill.updateContents(delta, Quill.sources.USER);
    // range.length contributes to delta.length()
    this.quill.setSelection(
      delta.length() - range.length,
      Quill.sources.SILENT,
    );
    this.quill.scrollIntoView();
  }

  prepareMatching(container, nodeMatches) {
    const elementMatchers = [];
    const textMatchers = [];
    this.matchers.forEach(pair => {
      const [selector, matcher] = pair;
      switch (selector) {
        case Node.TEXT_NODE:
          textMatchers.push(matcher);
          break;
        case Node.ELEMENT_NODE:
          elementMatchers.push(matcher);
          break;
        default:
          Array.from(container.querySelectorAll(selector)).forEach(node => {
            if (nodeMatches.has(node)) {
              const matches = nodeMatches.get(node);
              matches.push(matcher);
            } else {
              nodeMatches.set(node, [matcher]);
            }
          });
          break;
      }
    });
    return [elementMatchers, textMatchers];
  }
}
Clipboard.DEFAULTS = {
  matchers: [],
};

function applyFormat(delta, format, value) {
  if (typeof format === 'object') {
    return Object.keys(format).reduce((newDelta, key) => {
      return applyFormat(newDelta, key, format[key]);
    }, delta);
  }
  return delta.reduce((newDelta, op) => {
    if (op.attributes && op.attributes[format]) {
      return newDelta.push(op);
    }
    return newDelta.insert(
      op.insert,
      extend({}, { [format]: value }, op.attributes),
    );
  }, new Delta());
}

function deltaEndsWith(delta, text) {
  let endText = '';
  for (
    let i = delta.ops.length - 1;
    i >= 0 && endText.length < text.length;
    --i // eslint-disable-line no-plusplus
  ) {
    const op = delta.ops[i];
    if (typeof op.insert !== 'string') break;
    endText = op.insert + endText;
  }
  return endText.slice(-1 * text.length) === text;
}

function isLine(node) {
  if (node.childNodes.length === 0) return false; // Exclude embed blocks
  return [
    'address',
    'article',
    'blockquote',
    'canvas',
    'dd',
    'div',
    'dl',
    'dt',
    'fieldset',
    'figcaption',
    'figure',
    'footer',
    'form',
    'h1',
    'h2',
    'h3',
    'h4',
    'h5',
    'h6',
    'header',
    'iframe',
    'li',
    'main',
    'nav',
    'ol',
    'output',
    'p',
    'pre',
    'section',
    'table',
    'td',
    'tr',
    'ul',
    'video',
  ].includes(node.tagName.toLowerCase());
}

const preNodes = new WeakMap();
function isPre(node) {
  if (node == null) return false;
  if (!preNodes.has(node)) {
    if (node.tagName === 'PRE') {
      preNodes.set(node, true);
    } else {
      preNodes.set(node, isPre(node.parentNode));
    }
  }
  return preNodes.get(node);
}

function traverse(scroll, node, elementMatchers, textMatchers, nodeMatches) {
  // Post-order
  if (node.nodeType === node.TEXT_NODE) {
    return textMatchers.reduce((delta, matcher) => {
      return matcher(node, delta, scroll);
    }, new Delta());
  } else if (node.nodeType === node.ELEMENT_NODE) {
    return Array.from(node.childNodes || []).reduce((delta, childNode) => {
      let childrenDelta = traverse(
        scroll,
        childNode,
        elementMatchers,
        textMatchers,
        nodeMatches,
      );
      if (childNode.nodeType === node.ELEMENT_NODE) {
        childrenDelta = elementMatchers.reduce((reducedDelta, matcher) => {
          return matcher(childNode, reducedDelta, scroll);
        }, childrenDelta);
        childrenDelta = (nodeMatches.get(childNode) || []).reduce(
          (reducedDelta, matcher) => {
            return matcher(childNode, reducedDelta, scroll);
          },
          childrenDelta,
        );
      }
      return delta.concat(childrenDelta);
    }, new Delta());
  }
  return new Delta();
}

function matchAlias(format, node, delta) {
  return applyFormat(delta, format, true);
}

function matchAttributor(node, delta, scroll) {
  const attributes = Attributor.keys(node);
  const classes = ClassAttributor.keys(node);
  const styles = StyleAttributor.keys(node);
  const formats = {};
  attributes
    .concat(classes)
    .concat(styles)
    .forEach(name => {
      let attr = scroll.query(name, Scope.ATTRIBUTE);
      if (attr != null) {
        formats[attr.attrName] = attr.value(node);
        if (formats[attr.attrName]) return;
      }
      attr = ATTRIBUTE_ATTRIBUTORS[name];
      if (attr != null && (attr.attrName === name || attr.keyName === name)) {
        formats[attr.attrName] = attr.value(node) || undefined;
      }
      attr = STYLE_ATTRIBUTORS[name];
      if (attr != null && (attr.attrName === name || attr.keyName === name)) {
        attr = STYLE_ATTRIBUTORS[name];
        formats[attr.attrName] = attr.value(node) || undefined;
      }
    });
  if (Object.keys(formats).length > 0) {
    return applyFormat(delta, formats);
  }
  return delta;
}

function matchBlot(node, delta, scroll) {
  const match = scroll.query(node);
  if (match == null) return delta;
  if (match.prototype instanceof EmbedBlot) {
    const embed = {};
    const value = match.value(node);
    if (value != null) {
      embed[match.blotName] = value;
      return new Delta().insert(embed, match.formats(node, scroll));
    }
  } else if (typeof match.formats === 'function') {
    return applyFormat(delta, match.blotName, match.formats(node, scroll));
  }
  return delta;
}

function matchBreak(node, delta) {
  if (!deltaEndsWith(delta, '\n')) {
    delta.insert('\n');
  }
  return delta;
}

function matchCodeBlock(node, delta, scroll) {
  const match = scroll.query('code-block');
  const language = match ? match.formats(node, scroll) : true;
  return applyFormat(delta, 'code-block', language);
}

function matchIgnore() {
  return new Delta();
}

function matchIndent(node, delta, scroll) {
  const match = scroll.query(node);
  if (
    match == null ||
    match.blotName !== 'list' ||
    !deltaEndsWith(delta, '\n')
  ) {
    return delta;
  }
  let indent = -1;
  let parent = node.parentNode;
  while (parent != null) {
    if (['OL', 'UL'].includes(parent.tagName)) {
      indent += 1;
    }
    parent = parent.parentNode;
  }
  if (indent <= 0) return delta;
  return delta.compose(
    new Delta().retain(delta.length() - 1).retain(1, { indent }),
  );
}

function matchList(node, delta) {
  const list = node.tagName === 'OL' ? 'ordered' : 'bullet';
  return applyFormat(delta, 'list', list);
}

function matchNewline(node, delta) {
  if (!deltaEndsWith(delta, '\n')) {
    if (
      isLine(node) ||
      (delta.length() > 0 && node.nextSibling && isLine(node.nextSibling))
    ) {
      delta.insert('\n');
    }
  }
  return delta;
}

function matchStyles(node, delta) {
  const formats = {};
  const style = node.style || {};
  if (style.fontStyle === 'italic') {
    formats.italic = true;
  }
  if (
    style.fontWeight.startsWith('bold') ||
    parseInt(style.fontWeight, 10) >= 700
  ) {
    formats.bold = true;
  }
  if (Object.keys(formats).length > 0) {
    delta = applyFormat(delta, formats);
  }
  if (parseFloat(style.textIndent || 0) > 0) {
    // Could be 0.5in
    return new Delta().insert('\t').concat(delta);
  }
  return delta;
}

function matchTable(node, delta) {
  const table =
    node.parentNode.tagName === 'TABLE'
      ? node.parentNode
      : node.parentNode.parentNode;
  const rows = Array.from(table.querySelectorAll('tr'));
  const row = rows.indexOf(node) + 1;
  return applyFormat(delta, 'table', row);
}

function matchText(node, delta) {
  let text = node.data;
  // Word represents empty line with <o:p> </o:p>
  if (node.parentNode.tagName === 'O:P') {
    return delta.insert(text.trim());
  }
  if (text.trim().length === 0 && node.parentNode == null) {
    return delta;
  }
  if (!isPre(node)) {
    const replacer = (collapse, match) => {
      const replaced = match.replace(/[^\u00a0]/g, ''); // \u00a0 is nbsp;
      return replaced.length < 1 && collapse ? ' ' : replaced;
    };
    text = text.replace(/\r\n/g, ' ').replace(/\n/g, ' ');
    text = text.replace(/\s\s+/g, replacer.bind(replacer, true)); // collapse whitespace
    if (
      (node.previousSibling == null && isLine(node.parentNode)) ||
      (node.previousSibling != null && isLine(node.previousSibling))
    ) {
      text = text.replace(/^\s+/, replacer.bind(replacer, false));
    }
    if (
      (node.nextSibling == null && isLine(node.parentNode)) ||
      (node.nextSibling != null && isLine(node.nextSibling))
    ) {
      text = text.replace(/\s+$/, replacer.bind(replacer, false));
    }
  }
  return delta.insert(text);
}

export {
  Clipboard as default,
  matchAttributor,
  matchBlot,
  matchNewline,
  matchText,
  traverse,
};
<commit_msg>simplify copy/cut logic<commit_after>import extend from 'extend';
import Delta from 'quill-delta';
import {
  Attributor,
  ClassAttributor,
  EmbedBlot,
  Scope,
  StyleAttributor,
} from 'parchment';
import Quill from '../core/quill';
import logger from '../core/logger';
import Module from '../core/module';

import { AlignAttribute, AlignStyle } from '../formats/align';
import { BackgroundStyle } from '../formats/background';
import CodeBlock from '../formats/code';
import { ColorStyle } from '../formats/color';
import { DirectionAttribute, DirectionStyle } from '../formats/direction';
import { FontStyle } from '../formats/font';
import { SizeStyle } from '../formats/size';

const debug = logger('quill:clipboard');

const CLIPBOARD_CONFIG = [
  [Node.TEXT_NODE, matchText],
  [Node.TEXT_NODE, matchNewline],
  ['br', matchBreak],
  [Node.ELEMENT_NODE, matchNewline],
  [Node.ELEMENT_NODE, matchBlot],
  [Node.ELEMENT_NODE, matchAttributor],
  [Node.ELEMENT_NODE, matchStyles],
  ['li', matchIndent],
  ['ol, ul', matchList],
  ['pre', matchCodeBlock],
  ['tr', matchTable],
  ['b', matchAlias.bind(matchAlias, 'bold')],
  ['i', matchAlias.bind(matchAlias, 'italic')],
  ['style', matchIgnore],
];

const ATTRIBUTE_ATTRIBUTORS = [AlignAttribute, DirectionAttribute].reduce(
  (memo, attr) => {
    memo[attr.keyName] = attr;
    return memo;
  },
  {},
);

const STYLE_ATTRIBUTORS = [
  AlignStyle,
  BackgroundStyle,
  ColorStyle,
  DirectionStyle,
  FontStyle,
  SizeStyle,
].reduce((memo, attr) => {
  memo[attr.keyName] = attr;
  return memo;
}, {});

class Clipboard extends Module {
  constructor(quill, options) {
    super(quill, options);
    this.quill.root.addEventListener('copy', e => this.onCopy(e, false));
    this.quill.root.addEventListener('cut', e => this.onCopy(e, true));
    this.quill.root.addEventListener('paste', this.onCapturePaste.bind(this));
    this.matchers = [];
    CLIPBOARD_CONFIG.concat(this.options.matchers).forEach(
      ([selector, matcher]) => {
        this.addMatcher(selector, matcher);
      },
    );
  }

  addMatcher(selector, matcher) {
    this.matchers.push([selector, matcher]);
  }

  convert({ html, text }) {
    const formats = this.quill.getFormat(this.quill.selection.savedRange.index);
    if (formats[CodeBlock.blotName]) {
      return new Delta().insert(text, {
        [CodeBlock.blotName]: formats[CodeBlock.blotName],
      });
    } else if (!html) {
      return new Delta().insert(text || '');
    }
    const container = this.quill.root.ownerDocument.createElement('div');
    container.innerHTML = html.replace(/>\r?\n +</g, '><'); // Remove spaces between tags
    const nodeMatches = new WeakMap();
    const [elementMatchers, textMatchers] = this.prepareMatching(
      container,
      nodeMatches,
    );
    const delta = traverse(
      this.quill.scroll,
      container,
      elementMatchers,
      textMatchers,
      nodeMatches,
    );
    // Remove trailing newline
    if (
      deltaEndsWith(delta, '\n') &&
      delta.ops[delta.ops.length - 1].attributes == null
    ) {
      return delta.compose(new Delta().retain(delta.length() - 1).delete(1));
    }
    return delta;
  }

  dangerouslyPasteHTML(index, html, source = Quill.sources.API) {
    if (typeof index === 'string') {
      const delta = this.convert({ html: index, text: '' });
      this.quill.setContents(delta, html);
      this.quill.setSelection(0, Quill.sources.SILENT);
    } else {
      const paste = this.convert({ html, text: '' });
      this.quill.updateContents(
        new Delta().retain(index).concat(paste),
        source,
      );
      this.quill.setSelection(index + paste.length(), Quill.sources.SILENT);
    }
  }

  onCaptureCopy(range) {
    const text = this.quill.getText(range);
    const delta = this.quill.getContents(range);
    const html = this.quill.getSemanticHTML(range);
    return { delta, html, text };
  }

  onCapturePaste(e) {
    if (e.defaultPrevented || !this.quill.isEnabled()) return;
    e.preventDefault();
    const range = this.quill.getSelection(true);
    if (range == null) return;
    const files = Array.from(e.clipboardData.files || []);
    if (files.length > 0) {
      this.quill.uploader.upload(range, files);
    } else {
      this.onPaste(e, range);
    }
  }

  onCopy(e, isCut = false) {
    if (e.defaultPrevented) return;
    e.preventDefault();
    const [range] = this.quill.selection.getRange();
    if (range == null) return;
    const { delta, html, text } = this.onCaptureCopy(range, isCut);
    e.clipboardData.setData('text/plain', text);
    e.clipboardData.setData('text/html', html);
    e.clipboardData.setData('text/delta', JSON.stringify(delta));
    if (isCut) {
      this.quill.deleteText(range, Quill.sources.USER);
    }
  }

  onPaste(e, range) {
    const json = e.clipboardData.getData('text/delta');
    let delta = new Delta().retain(range.index).delete(range.length);
    if (json) {
      const directDelta = new Delta(JSON.parse(json));
      debug.log('onPaste direct', directDelta);
      delta = delta.concat(directDelta);
    } else {
      const html = e.clipboardData.getData('text/html');
      const text = e.clipboardData.getData('text/plain');
      const pastedDelta = this.convert({ text, html });
      debug.log('onPaste converted', pastedDelta, { text, html });
      delta = delta.concat(pastedDelta);
    }
    this.quill.updateContents(delta, Quill.sources.USER);
    // range.length contributes to delta.length()
    this.quill.setSelection(
      delta.length() - range.length,
      Quill.sources.SILENT,
    );
    this.quill.scrollIntoView();
  }

  prepareMatching(container, nodeMatches) {
    const elementMatchers = [];
    const textMatchers = [];
    this.matchers.forEach(pair => {
      const [selector, matcher] = pair;
      switch (selector) {
        case Node.TEXT_NODE:
          textMatchers.push(matcher);
          break;
        case Node.ELEMENT_NODE:
          elementMatchers.push(matcher);
          break;
        default:
          Array.from(container.querySelectorAll(selector)).forEach(node => {
            if (nodeMatches.has(node)) {
              const matches = nodeMatches.get(node);
              matches.push(matcher);
            } else {
              nodeMatches.set(node, [matcher]);
            }
          });
          break;
      }
    });
    return [elementMatchers, textMatchers];
  }
}
Clipboard.DEFAULTS = {
  matchers: [],
};

function applyFormat(delta, format, value) {
  if (typeof format === 'object') {
    return Object.keys(format).reduce((newDelta, key) => {
      return applyFormat(newDelta, key, format[key]);
    }, delta);
  }
  return delta.reduce((newDelta, op) => {
    if (op.attributes && op.attributes[format]) {
      return newDelta.push(op);
    }
    return newDelta.insert(
      op.insert,
      extend({}, { [format]: value }, op.attributes),
    );
  }, new Delta());
}

function deltaEndsWith(delta, text) {
  let endText = '';
  for (
    let i = delta.ops.length - 1;
    i >= 0 && endText.length < text.length;
    --i // eslint-disable-line no-plusplus
  ) {
    const op = delta.ops[i];
    if (typeof op.insert !== 'string') break;
    endText = op.insert + endText;
  }
  return endText.slice(-1 * text.length) === text;
}

function isLine(node) {
  if (node.childNodes.length === 0) return false; // Exclude embed blocks
  return [
    'address',
    'article',
    'blockquote',
    'canvas',
    'dd',
    'div',
    'dl',
    'dt',
    'fieldset',
    'figcaption',
    'figure',
    'footer',
    'form',
    'h1',
    'h2',
    'h3',
    'h4',
    'h5',
    'h6',
    'header',
    'iframe',
    'li',
    'main',
    'nav',
    'ol',
    'output',
    'p',
    'pre',
    'section',
    'table',
    'td',
    'tr',
    'ul',
    'video',
  ].includes(node.tagName.toLowerCase());
}

const preNodes = new WeakMap();
function isPre(node) {
  if (node == null) return false;
  if (!preNodes.has(node)) {
    if (node.tagName === 'PRE') {
      preNodes.set(node, true);
    } else {
      preNodes.set(node, isPre(node.parentNode));
    }
  }
  return preNodes.get(node);
}

function traverse(scroll, node, elementMatchers, textMatchers, nodeMatches) {
  // Post-order
  if (node.nodeType === node.TEXT_NODE) {
    return textMatchers.reduce((delta, matcher) => {
      return matcher(node, delta, scroll);
    }, new Delta());
  } else if (node.nodeType === node.ELEMENT_NODE) {
    return Array.from(node.childNodes || []).reduce((delta, childNode) => {
      let childrenDelta = traverse(
        scroll,
        childNode,
        elementMatchers,
        textMatchers,
        nodeMatches,
      );
      if (childNode.nodeType === node.ELEMENT_NODE) {
        childrenDelta = elementMatchers.reduce((reducedDelta, matcher) => {
          return matcher(childNode, reducedDelta, scroll);
        }, childrenDelta);
        childrenDelta = (nodeMatches.get(childNode) || []).reduce(
          (reducedDelta, matcher) => {
            return matcher(childNode, reducedDelta, scroll);
          },
          childrenDelta,
        );
      }
      return delta.concat(childrenDelta);
    }, new Delta());
  }
  return new Delta();
}

function matchAlias(format, node, delta) {
  return applyFormat(delta, format, true);
}

function matchAttributor(node, delta, scroll) {
  const attributes = Attributor.keys(node);
  const classes = ClassAttributor.keys(node);
  const styles = StyleAttributor.keys(node);
  const formats = {};
  attributes
    .concat(classes)
    .concat(styles)
    .forEach(name => {
      let attr = scroll.query(name, Scope.ATTRIBUTE);
      if (attr != null) {
        formats[attr.attrName] = attr.value(node);
        if (formats[attr.attrName]) return;
      }
      attr = ATTRIBUTE_ATTRIBUTORS[name];
      if (attr != null && (attr.attrName === name || attr.keyName === name)) {
        formats[attr.attrName] = attr.value(node) || undefined;
      }
      attr = STYLE_ATTRIBUTORS[name];
      if (attr != null && (attr.attrName === name || attr.keyName === name)) {
        attr = STYLE_ATTRIBUTORS[name];
        formats[attr.attrName] = attr.value(node) || undefined;
      }
    });
  if (Object.keys(formats).length > 0) {
    return applyFormat(delta, formats);
  }
  return delta;
}

function matchBlot(node, delta, scroll) {
  const match = scroll.query(node);
  if (match == null) return delta;
  if (match.prototype instanceof EmbedBlot) {
    const embed = {};
    const value = match.value(node);
    if (value != null) {
      embed[match.blotName] = value;
      return new Delta().insert(embed, match.formats(node, scroll));
    }
  } else if (typeof match.formats === 'function') {
    return applyFormat(delta, match.blotName, match.formats(node, scroll));
  }
  return delta;
}

function matchBreak(node, delta) {
  if (!deltaEndsWith(delta, '\n')) {
    delta.insert('\n');
  }
  return delta;
}

function matchCodeBlock(node, delta, scroll) {
  const match = scroll.query('code-block');
  const language = match ? match.formats(node, scroll) : true;
  return applyFormat(delta, 'code-block', language);
}

function matchIgnore() {
  return new Delta();
}

function matchIndent(node, delta, scroll) {
  const match = scroll.query(node);
  if (
    match == null ||
    match.blotName !== 'list' ||
    !deltaEndsWith(delta, '\n')
  ) {
    return delta;
  }
  let indent = -1;
  let parent = node.parentNode;
  while (parent != null) {
    if (['OL', 'UL'].includes(parent.tagName)) {
      indent += 1;
    }
    parent = parent.parentNode;
  }
  if (indent <= 0) return delta;
  return delta.compose(
    new Delta().retain(delta.length() - 1).retain(1, { indent }),
  );
}

function matchList(node, delta) {
  const list = node.tagName === 'OL' ? 'ordered' : 'bullet';
  return applyFormat(delta, 'list', list);
}

function matchNewline(node, delta) {
  if (!deltaEndsWith(delta, '\n')) {
    if (
      isLine(node) ||
      (delta.length() > 0 && node.nextSibling && isLine(node.nextSibling))
    ) {
      delta.insert('\n');
    }
  }
  return delta;
}

function matchStyles(node, delta) {
  const formats = {};
  const style = node.style || {};
  if (style.fontStyle === 'italic') {
    formats.italic = true;
  }
  if (
    style.fontWeight.startsWith('bold') ||
    parseInt(style.fontWeight, 10) >= 700
  ) {
    formats.bold = true;
  }
  if (Object.keys(formats).length > 0) {
    delta = applyFormat(delta, formats);
  }
  if (parseFloat(style.textIndent || 0) > 0) {
    // Could be 0.5in
    return new Delta().insert('\t').concat(delta);
  }
  return delta;
}

function matchTable(node, delta) {
  const table =
    node.parentNode.tagName === 'TABLE'
      ? node.parentNode
      : node.parentNode.parentNode;
  const rows = Array.from(table.querySelectorAll('tr'));
  const row = rows.indexOf(node) + 1;
  return applyFormat(delta, 'table', row);
}

function matchText(node, delta) {
  let text = node.data;
  // Word represents empty line with <o:p> </o:p>
  if (node.parentNode.tagName === 'O:P') {
    return delta.insert(text.trim());
  }
  if (text.trim().length === 0 && node.parentNode == null) {
    return delta;
  }
  if (!isPre(node)) {
    const replacer = (collapse, match) => {
      const replaced = match.replace(/[^\u00a0]/g, ''); // \u00a0 is nbsp;
      return replaced.length < 1 && collapse ? ' ' : replaced;
    };
    text = text.replace(/\r\n/g, ' ').replace(/\n/g, ' ');
    text = text.replace(/\s\s+/g, replacer.bind(replacer, true)); // collapse whitespace
    if (
      (node.previousSibling == null && isLine(node.parentNode)) ||
      (node.previousSibling != null && isLine(node.previousSibling))
    ) {
      text = text.replace(/^\s+/, replacer.bind(replacer, false));
    }
    if (
      (node.nextSibling == null && isLine(node.parentNode)) ||
      (node.nextSibling != null && isLine(node.nextSibling))
    ) {
      text = text.replace(/\s+$/, replacer.bind(replacer, false));
    }
  }
  return delta.insert(text);
}

export {
  Clipboard as default,
  matchAttributor,
  matchBlot,
  matchNewline,
  matchText,
  traverse,
};
<|endoftext|>