72 lines
246 KiB
JavaScript
72 lines
246 KiB
JavaScript
(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module){"use strict";var _Mathmin=Math.min,_Mathmax=Math.max;const Drawer=require("./src/Drawer"),Parser=require("./src/Parser"),ReactionParser=require("./src/ReactionParser"),SvgDrawer=require("./src/SvgDrawer"),ReactionDrawer=require("./src/ReactionDrawer"),SmiDrawer=require("./src/SmilesDrawer"),GaussDrawer=require("./src/GaussDrawer");var canUseDOM=!!("undefined"!=typeof window&&window.document&&window.document.createElement),SmilesDrawer={Version:"1.0.0"};SmilesDrawer.Drawer=Drawer,SmilesDrawer.Parser=Parser,SmilesDrawer.SvgDrawer=SvgDrawer,SmilesDrawer.ReactionDrawer=ReactionDrawer,SmilesDrawer.ReactionParser=ReactionParser,SmilesDrawer.GaussDrawer=GaussDrawer,SmilesDrawer.clean=function(smiles){return smiles.replace(/[^A-Za-z0-9@\.\+\-\?!\(\)\[\]\{\}/\\=#\$:\*]/g,"")},SmilesDrawer.apply=function(options,selector="canvas[data-smiles]",themeName="light",onError=null){let smilesDrawer=new Drawer(options),elements=document.querySelectorAll(selector);for(var i=0;i<elements.length;i++){let element=elements[i];SmilesDrawer.parse(element.getAttribute("data-smiles"),function(tree){smilesDrawer.draw(tree,element,themeName,!1)},function(err){onError&&onError(err)})}},SmilesDrawer.parse=function(smiles,successCallback,errorCallback){try{successCallback&&successCallback(Parser.parse(smiles))}catch(err){errorCallback&&errorCallback(err)}},SmilesDrawer.parseReaction=function(reactionSmiles,successCallback,errorCallback){try{successCallback&&successCallback(ReactionParser.parse(reactionSmiles))}catch(err){errorCallback&&errorCallback(err)}},canUseDOM&&(window.SmilesDrawer=SmilesDrawer,window.SmiDrawer=SmiDrawer),SmilesDrawer.SmiDrawer=SmiDrawer,Array.prototype.fill||Object.defineProperty(Array.prototype,"fill",{value:function(value){if(null==this)throw new TypeError("this is null or not defined");for(var O=Object(this),len=O.length>>>0,start=arguments[1],relativeStart=start>>0,k=0>relativeStart?_Mathmax(len+relativeStart,0):_Mathmin(relativeStart,len),end=arguments[2],relativeEnd=void 0===end?len:end>>0,final=0>relativeEnd?_Mathmax(len+relativeEnd,0):_Mathmin(relativeEnd,len);k<final;)O[k]=value,k++;return O}}),module.exports=SmilesDrawer},{"./src/Drawer":6,"./src/GaussDrawer":10,"./src/Parser":15,"./src/ReactionDrawer":18,"./src/ReactionParser":19,"./src/SmilesDrawer":23,"./src/SvgDrawer":24}],2:[function(require,module,exports){var _NumberMAX_VALUE=Number.MAX_VALUE,_Mathsin=Math.sin,_Mathatan=Math.atan2,_Mathpow=Math.pow,_Mathcos=Math.cos,_Mathsqrt=Math.sqrt,_Mathfloor=Math.floor,_Mathround=Math.round,_MathPI=Math.PI,_Mathabs=Math.abs,_Mathmin2=Math.min,_Mathmax2=Math.max;/**
|
|
* chroma.js - JavaScript library for color conversions
|
|
*
|
|
* Copyright (c) 2011-2019, Gregor Aisch
|
|
* All rights reserved.
|
|
*
|
|
* Redistribution and use in source and binary forms, with or without
|
|
* modification, are permitted provided that the following conditions are met:
|
|
*
|
|
* 1. Redistributions of source code must retain the above copyright notice, this
|
|
* list of conditions and the following disclaimer.
|
|
*
|
|
* 2. Redistributions in binary form must reproduce the above copyright notice,
|
|
* this list of conditions and the following disclaimer in the documentation
|
|
* and/or other materials provided with the distribution.
|
|
*
|
|
* 3. The name Gregor Aisch may not be used to endorse or promote products
|
|
* derived from this software without specific prior written permission.
|
|
*
|
|
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
|
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
* DISCLAIMED. IN NO EVENT SHALL GREGOR AISCH OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
|
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
|
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
|
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
|
|
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
|
|
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
|
|
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
*
|
|
* -------------------------------------------------------
|
|
*
|
|
* chroma.js includes colors from colorbrewer2.org, which are released under
|
|
* the following license:
|
|
*
|
|
* Copyright (c) 2002 Cynthia Brewer, Mark Harrower,
|
|
* and The Pennsylvania State University.
|
|
*
|
|
* 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.
|
|
*
|
|
* ------------------------------------------------------
|
|
*
|
|
* Named colors are taken from X11 Color Names.
|
|
* http://www.w3.org/TR/css3-color/#svg-color
|
|
*
|
|
* @preserve
|
|
*/(function(global,factory){"object"==typeof exports&&"undefined"!=typeof module?module.exports=factory():"function"==typeof define&&define.amd?define(factory):(global="undefined"==typeof globalThis?global||self:globalThis,global.chroma=factory())})(this,function(){'use strict';var _Mathsign=Math.sign,_Mathlog=Math.log,_NumberNaN=Number.NaN;function rgb2lrgb(c){var abs=_Mathabs(c);return .04045>abs?c/12.92:(sign$1(c)||1)*pow$8((abs+.055)/1.055,2.4)}function lrgb2rgb(c){var abs=_Mathabs(c);return .0031308<abs?(sign(c)||1)*(1.055*pow$7(abs,1/2.4)-.055):12.92*c}function __range__(left,right,inclusive){for(var range=[],ascending=left<right,end=inclusive?ascending?right+1:right-1:right,i=left;ascending?i<end:i>end;ascending?i++:i--)range.push(i);return range}for(var limit$2=function(x,min,max){return void 0===min&&(min=0),void 0===max&&(max=1),x<min?min:x>max?max:x},limit$1=limit$2,clip_rgb$3=function(rgb){rgb._clipped=!1,rgb._unclipped=rgb.slice(0);for(var i=0;3>=i;i++)3>i?((0>rgb[i]||255<rgb[i])&&(rgb._clipped=!0),rgb[i]=limit$1(rgb[i],0,255)):3===i&&(rgb[i]=limit$1(rgb[i],0,1));return rgb},classToType={},i$1=0,list$1=["Boolean","Number","String","Function","Array","Date","RegExp","Undefined","Null"],name;i$1<list$1.length;i$1+=1)name=list$1[i$1],classToType["[object "+name+"]"]=name.toLowerCase();var type$p=function(obj){return classToType[Object.prototype.toString.call(obj)]||"object"},PI$2=_MathPI,utils={clip_rgb:clip_rgb$3,limit:limit$2,type:type$p,unpack:function(args,keyOrder){return void 0===keyOrder&&(keyOrder=null),3<=args.length?Array.prototype.slice.call(args):"object"==type$p(args[0])&&keyOrder?keyOrder.split("").filter(function(k){return void 0!==args[0][k]}).map(function(k){return args[0][k]}):args[0]},last:function(args){if(2>args.length)return null;var l=args.length-1;return"string"==type$p(args[l])?args[l].toLowerCase():null},PI:PI$2,TWOPI:2*PI$2,PITHIRD:PI$2/3,DEG2RAD:PI$2/180,RAD2DEG:180/PI$2},input$h={format:{},autodetect:[]},last$3=utils.last,clip_rgb$2=utils.clip_rgb,type$m=utils.type,_input=input$h,Color$D=function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];var me=this;if("object"===type$m(args[0])&&args[0].constructor&&args[0].constructor===this.constructor)return args[0];var mode=last$3(args),autodetect=!1;if(!mode){autodetect=!0,_input.sorted||(_input.autodetect=_input.autodetect.sort(function(a,b){return b.p-a.p}),_input.sorted=!0);for(var i=0,list=_input.autodetect,chk;i<list.length&&(chk=list[i],mode=chk.test.apply(chk,args),!mode);i+=1);}if(_input.format[mode]){var rgb=_input.format[mode].apply(null,autodetect?args:args.slice(0,-1));me._rgb=clip_rgb$2(rgb)}else throw new Error("unknown format: "+args);3===me._rgb.length&&me._rgb.push(1)};Color$D.prototype.toString=function(){return"function"==type$m(this.hex)?this.hex():"["+this._rgb.join(",")+"]"};var Color_1=Color$D,chroma$k=function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];return new(Function.prototype.bind.apply(chroma$k.Color,[null].concat(args)))};chroma$k.Color=Color_1,chroma$k.version="2.4.2";var chroma_1=chroma$k,unpack$A=utils.unpack,max$2=_Mathmax2,unpack$z=utils.unpack,Color$C=Color_1,input$g=input$h,unpack$y=utils.unpack,type$l=utils.type,rgb2cmyk=function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];var ref=unpack$A(args,"rgb"),r=ref[0],g=ref[1],b=ref[2];r/=255,g/=255,b/=255;var k=1-max$2(r,max$2(g,b)),f=1>k?1/(1-k):0,c=(1-r-k)*f,m=(1-g-k)*f,y=(1-b-k)*f;return[c,m,y,k]};Color$C.prototype.cmyk=function(){return rgb2cmyk(this._rgb)},chroma_1.cmyk=function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];return new(Function.prototype.bind.apply(Color$C,[null].concat(args,["cmyk"])))},input$g.format.cmyk=function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];args=unpack$z(args,"cmyk");var c=args[0],m=args[1],y=args[2],k=args[3],alpha=4<args.length?args[4]:1;return 1===k?[0,0,0,alpha]:[1<=c?0:255*(1-c)*(1-k),1<=m?0:255*(1-m)*(1-k),1<=y?0:255*(1-y)*(1-k),alpha]},input$g.autodetect.push({p:2,test:function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];if(args=unpack$y(args,"cmyk"),"array"===type$l(args)&&4===args.length)return"cmyk"}});var unpack$x=utils.unpack,last$2=utils.last,rnd=function(a){return _Mathround(100*a)/100},unpack$w=utils.unpack,rgb2hsl_1=function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];args=unpack$w(args,"rgba");var r=args[0],g=args[1],b=args[2];r/=255,g/=255,b/=255;var min=_Mathmin2(r,g,b),max=_Mathmax2(r,g,b),l=(max+min)/2,s,h;return max===min?(s=0,h=_NumberNaN):s=.5>l?(max-min)/(max+min):(max-min)/(2-max-min),r==max?h=(g-b)/(max-min):g==max?h=2+(b-r)/(max-min):b==max&&(h=4+(r-g)/(max-min)),h*=60,0>h&&(h+=360),3<args.length&&void 0!==args[3]?[h,s,l,args[3]]:[h,s,l]},unpack$v=utils.unpack,last$1=utils.last,hsl2css=function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];var hsla=unpack$x(args,"hsla"),mode=last$2(args)||"lsa";return hsla[0]=rnd(hsla[0]||0),hsla[1]=rnd(100*hsla[1])+"%",hsla[2]=rnd(100*hsla[2])+"%","hsla"===mode||3<hsla.length&&1>hsla[3]?(hsla[3]=3<hsla.length?hsla[3]:1,mode="hsla"):hsla.length=3,mode+"("+hsla.join(",")+")"},round$6=_Mathround,unpack$u=utils.unpack,round$5=_Mathround,hsl2rgb$1=function(){for(var args=[],len=arguments.length,assign;len--;)args[len]=arguments[len];args=unpack$u(args,"hsl");var h=args[0],s=args[1],l=args[2],r,g,b;if(0===s)r=g=b=255*l;else{var t3=[0,0,0],c=[0,0,0],t2=.5>l?l*(1+s):l+s-l*s,t1=2*l-t2,h_=h/360;t3[0]=h_+1/3,t3[1]=h_,t3[2]=h_-1/3;for(var i=0;3>i;i++)0>t3[i]&&(t3[i]+=1),1<t3[i]&&(t3[i]-=1),c[i]=1>6*t3[i]?t1+6*(t2-t1)*t3[i]:1>2*t3[i]?t2:2>3*t3[i]?t1+6*((t2-t1)*(2/3-t3[i])):t1;assign=[round$5(255*c[0]),round$5(255*c[1]),round$5(255*c[2])],r=assign[0],g=assign[1],b=assign[2]}return 3<args.length?[r,g,b,args[3]]:[r,g,b,1]},hsl2rgb_1=hsl2rgb$1,hsl2rgb=hsl2rgb_1,input$f=input$h,RE_RGB=/^rgb\(\s*(-?\d+),\s*(-?\d+)\s*,\s*(-?\d+)\s*\)$/,RE_RGBA=/^rgba\(\s*(-?\d+),\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*([01]|[01]?\.\d+)\)$/,RE_RGB_PCT=/^rgb\(\s*(-?\d+(?:\.\d+)?)%,\s*(-?\d+(?:\.\d+)?)%\s*,\s*(-?\d+(?:\.\d+)?)%\s*\)$/,RE_RGBA_PCT=/^rgba\(\s*(-?\d+(?:\.\d+)?)%,\s*(-?\d+(?:\.\d+)?)%\s*,\s*(-?\d+(?:\.\d+)?)%\s*,\s*([01]|[01]?\.\d+)\)$/,RE_HSL=/^hsl\(\s*(-?\d+(?:\.\d+)?),\s*(-?\d+(?:\.\d+)?)%\s*,\s*(-?\d+(?:\.\d+)?)%\s*\)$/,RE_HSLA=/^hsla\(\s*(-?\d+(?:\.\d+)?),\s*(-?\d+(?:\.\d+)?)%\s*,\s*(-?\d+(?:\.\d+)?)%\s*,\s*([01]|[01]?\.\d+)\)$/,round$4=_Mathround,css2rgb$1=function(css){css=css.toLowerCase().trim();var m;if(input$f.format.named)try{return input$f.format.named(css)}catch(e){}if(m=css.match(RE_RGB)){for(var rgb=m.slice(1,4),i=0;3>i;i++)rgb[i]=+rgb[i];return rgb[3]=1,rgb}if(m=css.match(RE_RGBA)){for(var rgb$1=m.slice(1,5),i$1=0;4>i$1;i$1++)rgb$1[i$1]=+rgb$1[i$1];return rgb$1}if(m=css.match(RE_RGB_PCT)){for(var rgb$2=m.slice(1,4),i$2=0;3>i$2;i$2++)rgb$2[i$2]=round$4(2.55*rgb$2[i$2]);return rgb$2[3]=1,rgb$2}if(m=css.match(RE_RGBA_PCT)){for(var rgb$3=m.slice(1,5),i$3=0;3>i$3;i$3++)rgb$3[i$3]=round$4(2.55*rgb$3[i$3]);return rgb$3[3]=+rgb$3[3],rgb$3}if(m=css.match(RE_HSL)){var hsl=m.slice(1,4);hsl[1]*=.01,hsl[2]*=.01;var rgb$4=hsl2rgb(hsl);return rgb$4[3]=1,rgb$4}if(m=css.match(RE_HSLA)){var hsl$1=m.slice(1,4);hsl$1[1]*=.01,hsl$1[2]*=.01;var rgb$5=hsl2rgb(hsl$1);return rgb$5[3]=+m[4],rgb$5}};css2rgb$1.test=function(s){return RE_RGB.test(s)||RE_RGBA.test(s)||RE_RGB_PCT.test(s)||RE_RGBA_PCT.test(s)||RE_HSL.test(s)||RE_HSLA.test(s)};var Color$B=Color_1,input$e=input$h,type$k=utils.type,rgb2css=function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];var rgba=unpack$v(args,"rgba"),mode=last$1(args)||"rgb";return"hsl"==mode.substr(0,3)?hsl2css(rgb2hsl_1(rgba),mode):(rgba[0]=round$6(rgba[0]),rgba[1]=round$6(rgba[1]),rgba[2]=round$6(rgba[2]),("rgba"===mode||3<rgba.length&&1>rgba[3])&&(rgba[3]=3<rgba.length?rgba[3]:1,mode="rgba"),mode+"("+rgba.slice(0,"rgb"===mode?3:4).join(",")+")")},css2rgb=css2rgb$1;Color$B.prototype.css=function(mode){return rgb2css(this._rgb,mode)},chroma_1.css=function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];return new(Function.prototype.bind.apply(Color$B,[null].concat(args,["css"])))},input$e.format.css=css2rgb,input$e.autodetect.push({p:5,test:function(h){for(var rest=[],len=arguments.length-1;0<len--;)rest[len]=arguments[len+1];if(!rest.length&&"string"===type$k(h)&&css2rgb.test(h))return"css"}});var Color$A=Color_1,unpack$t=utils.unpack;input$h.format.gl=function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];var rgb=unpack$t(args,"rgba");return rgb[0]*=255,rgb[1]*=255,rgb[2]*=255,rgb},chroma_1.gl=function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];return new(Function.prototype.bind.apply(Color$A,[null].concat(args,["gl"])))},Color$A.prototype.gl=function(){var rgb=this._rgb;return[rgb[0]/255,rgb[1]/255,rgb[2]/255,rgb[3]]};var unpack$s=utils.unpack,unpack$r=utils.unpack,hcg2rgb=function(){for(var args=[],len=arguments.length,assign,assign$1,assign$2,assign$3,assign$4,assign$5;len--;)args[len]=arguments[len];args=unpack$r(args,"hcg");var h=args[0],c=args[1],_g=args[2],r,g,b;_g*=255;var _c=255*c;if(0===c)r=g=b=_g;else{360===h&&(h=0),360<h&&(h-=360),0>h&&(h+=360),h/=60;var i=_Mathfloor(h),f=h-i,p=_g*(1-c),q=p+_c*(1-f),t=p+_c*f,v=p+_c;0===i?(assign=[v,t,p],r=assign[0],g=assign[1],b=assign[2]):1===i?(assign$1=[q,v,p],r=assign$1[0],g=assign$1[1],b=assign$1[2]):2===i?(assign$2=[p,v,t],r=assign$2[0],g=assign$2[1],b=assign$2[2]):3===i?(assign$3=[p,q,v],r=assign$3[0],g=assign$3[1],b=assign$3[2]):4===i?(assign$4=[t,p,v],r=assign$4[0],g=assign$4[1],b=assign$4[2]):5===i?(assign$5=[v,p,q],r=assign$5[0],g=assign$5[1],b=assign$5[2]):void 0}return[r,g,b,3<args.length?args[3]:1]},unpack$q=utils.unpack,type$j=utils.type,Color$z=Color_1,input$c=input$h,rgb2hcg=function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];var ref=unpack$s(args,"rgb"),r=ref[0],g=ref[1],b=ref[2],min=_Mathmin2(r,g,b),max=_Mathmax2(r,g,b),delta=max-min,h;return 0===delta?h=_NumberNaN:(r===max&&(h=(g-b)/delta),g===max&&(h=2+(b-r)/delta),b===max&&(h=4+(r-g)/delta),h*=60,0>h&&(h+=360)),[h,100*delta/255,100*(min/(255-delta))]};Color$z.prototype.hcg=function(){return rgb2hcg(this._rgb)},chroma_1.hcg=function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];return new(Function.prototype.bind.apply(Color$z,[null].concat(args,["hcg"])))},input$c.format.hcg=hcg2rgb,input$c.autodetect.push({p:1,test:function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];if(args=unpack$q(args,"hcg"),"array"===type$j(args)&&3===args.length)return"hcg"}});var unpack$p=utils.unpack,last=utils.last,round$3=_Mathround,rgb2hex_1=function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];var ref=unpack$p(args,"rgba"),r=ref[0],g=ref[1],b=ref[2],a=ref[3],mode=last(args)||"auto";void 0===a&&(a=1),"auto"===mode&&(mode=1>a?"rgba":"rgb"),r=round$3(r),g=round$3(g),b=round$3(b);var u=r<<16|g<<8|b,str="000000"+u.toString(16);str=str.substr(str.length-6);var hxa="0"+round$3(255*a).toString(16);switch(hxa=hxa.substr(hxa.length-2),mode.toLowerCase()){case"rgba":return"#"+str+hxa;case"argb":return"#"+hxa+str;default:return"#"+str;}},RE_HEX=/^#?([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/,RE_HEXA=/^#?([A-Fa-f0-9]{8}|[A-Fa-f0-9]{4})$/,hex2rgb_1=function(hex){if(hex.match(RE_HEX)){(4===hex.length||7===hex.length)&&(hex=hex.substr(1)),3===hex.length&&(hex=hex.split(""),hex=hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2]);var u=parseInt(hex,16);return[u>>16,255&u>>8,255&u,1]}if(hex.match(RE_HEXA)){(5===hex.length||9===hex.length)&&(hex=hex.substr(1)),4===hex.length&&(hex=hex.split(""),hex=hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2]+hex[3]+hex[3]);var u$1=parseInt(hex,16),a=_Mathround(100*((255&u$1)/255))/100;return[255&u$1>>24,255&u$1>>16,255&u$1>>8,a]}throw new Error("unknown hex color: "+hex)},Color$y=Color_1,type$i=utils.type,input$b=input$h;Color$y.prototype.hex=function(mode){return rgb2hex_1(this._rgb,mode)},chroma_1.hex=function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];return new(Function.prototype.bind.apply(Color$y,[null].concat(args,["hex"])))},input$b.format.hex=hex2rgb_1,input$b.autodetect.push({p:4,test:function(h){for(var rest=[],len=arguments.length-1;0<len--;)rest[len]=arguments[len+1];if(!rest.length&&"string"===type$i(h)&&0<=[3,4,5,6,7,8,9].indexOf(h.length))return"hex"}});var unpack$o=utils.unpack,TWOPI$2=utils.TWOPI,acos=Math.acos,rgb2hsi$1=function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];var ref=unpack$o(args,"rgb"),r=ref[0],g=ref[1],b=ref[2];r/=255,g/=255,b/=255;var min_=_Mathmin2(r,g,b),i=(r+g+b)/3,s=0<i?1-min_/i:0,h;return 0===s?h=NaN:(h=(r-g+(r-b))/2,h/=_Mathsqrt((r-g)*(r-g)+(r-b)*(g-b)),h=acos(h),b>g&&(h=TWOPI$2-h),h/=TWOPI$2),[360*h,s,i]},unpack$n=utils.unpack,limit=utils.limit,TWOPI$1=utils.TWOPI,PITHIRD=utils.PITHIRD,cos$4=_Mathcos,hsi2rgb=function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];args=unpack$n(args,"hsi");var h=args[0],s=args[1],i=args[2],r,g,b;return isNaN(h)&&(h=0),isNaN(s)&&(s=0),360<h&&(h-=360),0>h&&(h+=360),h/=360,h<1/3?(b=(1-s)/3,r=(1+s*cos$4(TWOPI$1*h)/cos$4(PITHIRD-TWOPI$1*h))/3,g=1-(b+r)):h<2/3?(h-=1/3,r=(1-s)/3,g=(1+s*cos$4(TWOPI$1*h)/cos$4(PITHIRD-TWOPI$1*h))/3,b=1-(r+g)):(h-=2/3,g=(1-s)/3,b=(1+s*cos$4(TWOPI$1*h)/cos$4(PITHIRD-TWOPI$1*h))/3,r=1-(g+b)),r=limit(3*(i*r)),g=limit(3*(i*g)),b=limit(3*(i*b)),[255*r,255*g,255*b,3<args.length?args[3]:1]},unpack$m=utils.unpack,type$h=utils.type,Color$x=Color_1,input$a=input$h;Color$x.prototype.hsi=function(){return rgb2hsi$1(this._rgb)},chroma_1.hsi=function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];return new(Function.prototype.bind.apply(Color$x,[null].concat(args,["hsi"])))},input$a.format.hsi=hsi2rgb,input$a.autodetect.push({p:2,test:function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];if(args=unpack$m(args,"hsi"),"array"===type$h(args)&&3===args.length)return"hsi"}});var unpack$l=utils.unpack,type$g=utils.type,Color$w=Color_1,input$9=input$h;Color$w.prototype.hsl=function(){return rgb2hsl_1(this._rgb)},chroma_1.hsl=function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];return new(Function.prototype.bind.apply(Color$w,[null].concat(args,["hsl"])))},input$9.format.hsl=hsl2rgb_1,input$9.autodetect.push({p:2,test:function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];if(args=unpack$l(args,"hsl"),"array"===type$g(args)&&3===args.length)return"hsl"}});var unpack$k=utils.unpack,unpack$j=utils.unpack,hsv2rgb=function(){for(var args=[],len=arguments.length,assign,assign$1,assign$2,assign$3,assign$4,assign$5;len--;)args[len]=arguments[len];args=unpack$j(args,"hsv");var h=args[0],s=args[1],v=args[2],r,g,b;if(v*=255,0===s)r=g=b=v;else{360===h&&(h=0),360<h&&(h-=360),0>h&&(h+=360),h/=60;var i=_Mathfloor(h),f=h-i,p=v*(1-s),q=v*(1-s*f),t=v*(1-s*(1-f));0===i?(assign=[v,t,p],r=assign[0],g=assign[1],b=assign[2]):1===i?(assign$1=[q,v,p],r=assign$1[0],g=assign$1[1],b=assign$1[2]):2===i?(assign$2=[p,v,t],r=assign$2[0],g=assign$2[1],b=assign$2[2]):3===i?(assign$3=[p,q,v],r=assign$3[0],g=assign$3[1],b=assign$3[2]):4===i?(assign$4=[t,p,v],r=assign$4[0],g=assign$4[1],b=assign$4[2]):5===i?(assign$5=[v,p,q],r=assign$5[0],g=assign$5[1],b=assign$5[2]):void 0}return[r,g,b,3<args.length?args[3]:1]},unpack$i=utils.unpack,type$f=utils.type,Color$v=Color_1,input$8=input$h,rgb2hsv=function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];args=unpack$k(args,"rgb");var r=args[0],g=args[1],b=args[2],min_=_Mathmin2(r,g,b),max_=_Mathmax2(r,g,b),delta=max_-min_,h,s,v;return v=max_/255,0===max_?(h=_NumberNaN,s=0):(s=delta/max_,r===max_&&(h=(g-b)/delta),g===max_&&(h=2+(b-r)/delta),b===max_&&(h=4+(r-g)/delta),h*=60,0>h&&(h+=360)),[h,s,v]};Color$v.prototype.hsv=function(){return rgb2hsv(this._rgb)},chroma_1.hsv=function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];return new(Function.prototype.bind.apply(Color$v,[null].concat(args,["hsv"])))},input$8.format.hsv=hsv2rgb,input$8.autodetect.push({p:2,test:function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];if(args=unpack$i(args,"hsv"),"array"===type$f(args)&&3===args.length)return"hsv"}});var labConstants={Kn:18,Xn:.95047,Yn:1,Zn:1.08883,t0:.137931034,t1:.206896552,t2:.12841855,t3:.008856452},LAB_CONSTANTS$3=labConstants,unpack$h=utils.unpack,pow$a=_Mathpow,rgb_xyz=function(r){return .04045>=(r/=255)?r/12.92:pow$a((r+.055)/1.055,2.4)},xyz_lab=function(t){return t>LAB_CONSTANTS$3.t3?pow$a(t,1/3):t/LAB_CONSTANTS$3.t2+LAB_CONSTANTS$3.t0},rgb2xyz=function(r,g,b){r=rgb_xyz(r),g=rgb_xyz(g),b=rgb_xyz(b);var x=xyz_lab((.4124564*r+.3575761*g+.1804375*b)/LAB_CONSTANTS$3.Xn),y=xyz_lab((.2126729*r+.7151522*g+.072175*b)/LAB_CONSTANTS$3.Yn),z=xyz_lab((.0193339*r+.119192*g+.9503041*b)/LAB_CONSTANTS$3.Zn);return[x,y,z]},rgb2lab_1=function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];var ref=unpack$h(args,"rgb"),r=ref[0],g=ref[1],b=ref[2],ref$1=rgb2xyz(r,g,b),x=ref$1[0],y=ref$1[1],z=ref$1[2],l=116*y-16;return[0>l?0:l,500*(x-y),200*(y-z)]},LAB_CONSTANTS$2=labConstants,unpack$g=utils.unpack,xyz_rgb=function(r){return 255*(.00304>=r?12.92*r:1.055*_Mathpow(r,1/2.4)-.055)},lab_xyz=function(t){return t>LAB_CONSTANTS$2.t1?t*t*t:LAB_CONSTANTS$2.t2*(t-LAB_CONSTANTS$2.t0)},lab2rgb_1=function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];args=unpack$g(args,"lab");var l=args[0],a=args[1],b=args[2],x,y,z,r,g,b_;return y=(l+16)/116,x=isNaN(a)?y:y+a/500,z=isNaN(b)?y:y-b/200,y=LAB_CONSTANTS$2.Yn*lab_xyz(y),x=LAB_CONSTANTS$2.Xn*lab_xyz(x),z=LAB_CONSTANTS$2.Zn*lab_xyz(z),r=xyz_rgb(3.2404542*x-1.5371385*y-.4985314*z),g=xyz_rgb(-.969266*x+1.8760108*y+.041556*z),b_=xyz_rgb(.0556434*x-.2040259*y+1.0572252*z),[r,g,b_,3<args.length?args[3]:1]},unpack$f=utils.unpack,type$e=utils.type,Color$u=Color_1,input$7=input$h;Color$u.prototype.lab=function(){return rgb2lab_1(this._rgb)},chroma_1.lab=function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];return new(Function.prototype.bind.apply(Color$u,[null].concat(args,["lab"])))},input$7.format.lab=lab2rgb_1,input$7.autodetect.push({p:2,test:function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];if(args=unpack$f(args,"lab"),"array"===type$e(args)&&3===args.length)return"lab"}});var unpack$e=utils.unpack,RAD2DEG=utils.RAD2DEG,lab2lch_1=function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];var ref=unpack$e(args,"lab"),l=ref[0],a=ref[1],b=ref[2],c=_Mathsqrt(a*a+b*b),h=(_Mathatan(b,a)*RAD2DEG+360)%360;return 0===_Mathround(1e4*c)&&(h=_NumberNaN),[l,c,h]},unpack$d=utils.unpack,unpack$c=utils.unpack,DEG2RAD=utils.DEG2RAD,lch2lab_1=function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];var ref=unpack$c(args,"lch"),l=ref[0],c=ref[1],h=ref[2];return isNaN(h)&&(h=0),h*=DEG2RAD,[l,_Mathcos(h)*c,_Mathsin(h)*c]},unpack$b=utils.unpack,lch2rgb_1=function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];args=unpack$b(args,"lch");var l=args[0],c=args[1],h=args[2],ref=lch2lab_1(l,c,h),L=ref[0],a=ref[1],b_=ref[2],ref$1=lab2rgb_1(L,a,b_),r=ref$1[0],g=ref$1[1],b=ref$1[2];return[r,g,b,3<args.length?args[3]:1]},unpack$a=utils.unpack,unpack$9=utils.unpack,type$d=utils.type,chroma$a=chroma_1,Color$t=Color_1,input$6=input$h,rgb2lch=function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];var ref=unpack$d(args,"rgb"),r=ref[0],g=ref[1],b=ref[2],ref$1=rgb2lab_1(r,g,b),l=ref$1[0],a=ref$1[1],b_=ref$1[2];return lab2lch_1(l,a,b_)};Color$t.prototype.lch=function(){return rgb2lch(this._rgb)},Color$t.prototype.hcl=function(){return rgb2lch(this._rgb).reverse()},chroma$a.lch=function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];return new(Function.prototype.bind.apply(Color$t,[null].concat(args,["lch"])))},chroma$a.hcl=function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];return new(Function.prototype.bind.apply(Color$t,[null].concat(args,["hcl"])))},input$6.format.lch=lch2rgb_1,input$6.format.hcl=function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];var hcl=unpack$a(args,"hcl").reverse();return lch2rgb_1.apply(void 0,hcl)},["lch","hcl"].forEach(function(m){return input$6.autodetect.push({p:2,test:function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];if(args=unpack$9(args,m),"array"===type$d(args)&&3===args.length)return m}})});var w3cx11_1={aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000000",blanchedalmond:"#ffebcd",blue:"#0000ff",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflower:"#6495ed",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#ff00ff",gainsboro:"#dcdcdc",ghostwhite:"#f8f8ff",gold:"#ffd700",goldenrod:"#daa520",gray:"#808080",green:"#008000",greenyellow:"#adff2f",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",indianred:"#cd5c5c",indigo:"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",laserlemon:"#ffff54",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrod:"#fafad2",lightgoldenrodyellow:"#fafad2",lightgray:"#d3d3d3",lightgreen:"#90ee90",lightgrey:"#d3d3d3",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightslategrey:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#00ff00",limegreen:"#32cd32",linen:"#faf0e6",magenta:"#ff00ff",maroon:"#800000",maroon2:"#7f0000",maroon3:"#b03060",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370db",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#db7093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",purple2:"#7f007f",purple3:"#a020f0",rebeccapurple:"#663399",red:"#ff0000",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",slategrey:"#708090",snow:"#fffafa",springgreen:"#00ff7f",steelblue:"#4682b4",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",violet:"#ee82ee",wheat:"#f5deb3",white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32"},input$5=input$h,type$c=utils.type,w3cx11=w3cx11_1;Color_1.prototype.name=function(){for(var hex=rgb2hex_1(this._rgb,"rgb"),i=0,list=Object.keys(w3cx11),n;i<list.length;i+=1)if(n=list[i],w3cx11[n]===hex)return n.toLowerCase();return hex},input$5.format.named=function(name){if(name=name.toLowerCase(),w3cx11[name])return hex2rgb_1(w3cx11[name]);throw new Error("unknown color name: "+name)},input$5.autodetect.push({p:5,test:function(h){for(var rest=[],len=arguments.length-1;0<len--;)rest[len]=arguments[len+1];if(!rest.length&&"string"===type$c(h)&&w3cx11[h.toLowerCase()])return"named"}});var unpack$8=utils.unpack,type$b=utils.type,Color$r=Color_1,input$4=input$h,type$a=utils.type,rgb2num=function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];var ref=unpack$8(args,"rgb"),r=ref[0],g=ref[1],b=ref[2];return(r<<16)+(g<<8)+b};Color$r.prototype.num=function(){return rgb2num(this._rgb)},chroma_1.num=function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];return new(Function.prototype.bind.apply(Color$r,[null].concat(args,["num"])))},input$4.format.num=function(num){if("number"==type$b(num)&&0<=num&&16777215>=num){return[num>>16,255&num>>8,255&num,1]}throw new Error("unknown num color: "+num)},input$4.autodetect.push({p:5,test:function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];if(1===args.length&&"number"===type$a(args[0])&&0<=args[0]&&16777215>=args[0])return"num"}});var Color$q=Color_1,input$3=input$h,unpack$7=utils.unpack,type$9=utils.type,round$1=_Mathround;Color$q.prototype.rgb=function(rnd){return void 0===rnd&&(rnd=!0),!1===rnd?this._rgb.slice(0,3):this._rgb.slice(0,3).map(round$1)},Color$q.prototype.rgba=function(rnd){return void 0===rnd&&(rnd=!0),this._rgb.slice(0,4).map(function(v,i){return 3>i?!1===rnd?v:round$1(v):v})},chroma_1.rgb=function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];return new(Function.prototype.bind.apply(Color$q,[null].concat(args,["rgb"])))},input$3.format.rgb=function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];var rgba=unpack$7(args,"rgba");return void 0===rgba[3]&&(rgba[3]=1),rgba},input$3.autodetect.push({p:3,test:function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];if(args=unpack$7(args,"rgba"),"array"===type$9(args)&&(3===args.length||4===args.length&&"number"==type$9(args[3])&&0<=args[3]&&1>=args[3]))return"rgb"}});var log$1=_Mathlog,temperature2rgb_1=function(kelvin){var temp=kelvin/100,r,g,b;return 66>temp?(r=255,g=6>temp?0:-155.25485562709179-.44596950469579133*(g=temp-2)+104.49216199393888*log$1(g),b=20>temp?0:-254.76935184120902+.8274096064007395*(b=temp-10)+115.67994401066147*log$1(b)):(r=351.97690566805693+.114206453784165*(r=temp-55)-40.25366309332127*log$1(r),g=325.4494125711974+.07943456536662342*(g=temp-50)-28.0852963507957*log$1(g),b=255),[r,g,b,1]},unpack$6=utils.unpack,chroma$7=chroma_1,Color$p=Color_1,input$2=input$h,rgb2temperature=function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];for(var rgb=unpack$6(args,"rgb"),r=rgb[0],b=rgb[2],minTemp=1e3,maxTemp=4e4,temp;maxTemp-minTemp>.4;){temp=.5*(maxTemp+minTemp);var rgb$1=temperature2rgb_1(temp);rgb$1[2]/rgb$1[0]>=b/r?maxTemp=temp:minTemp=temp}return _Mathround(temp)};Color$p.prototype.temp=Color$p.prototype.kelvin=Color$p.prototype.temperature=function(){return rgb2temperature(this._rgb)},chroma$7.temp=chroma$7.kelvin=chroma$7.temperature=function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];return new(Function.prototype.bind.apply(Color$p,[null].concat(args,["temp"])))},input$2.format.temp=input$2.format.kelvin=input$2.format.temperature=temperature2rgb_1;var unpack$5=utils.unpack,cbrt=Math.cbrt,pow$8=_Mathpow,sign$1=_Mathsign,rgb2oklab_1=function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];var ref=unpack$5(args,"rgb"),r=ref[0],g=ref[1],b=ref[2],ref$1=[rgb2lrgb(r/255),rgb2lrgb(g/255),rgb2lrgb(b/255)],lr=ref$1[0],lg=ref$1[1],lb=ref$1[2],l=cbrt(.4122214708*lr+.5363325363*lg+.0514459929*lb),m=cbrt(.2119034982*lr+.6806995451*lg+.1073969566*lb),s=cbrt(.0883024619*lr+.2817188376*lg+.6299787005*lb);return[.2104542553*l+.793617785*m-.0040720468*s,1.9779984951*l-2.428592205*m+.4505937099*s,.0259040371*l+.7827717662*m-.808675766*s]},unpack$4=utils.unpack,pow$7=_Mathpow,sign=_Mathsign,oklab2rgb_1=function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];args=unpack$4(args,"lab");var L=args[0],a=args[1],b=args[2],l=pow$7(L+.3963377774*a+.2158037573*b,3),m=pow$7(L-.1055613458*a-.0638541728*b,3),s=pow$7(L-.0894841775*a-1.291485548*b,3);return[255*lrgb2rgb(+4.0767416621*l-3.3077115913*m+.2309699292*s),255*lrgb2rgb(-1.2684380046*l+2.6097574011*m-.3413193965*s),255*lrgb2rgb(-.0041960863*l-.7034186147*m+1.707614701*s),3<args.length?args[3]:1]},unpack$3=utils.unpack,type$8=utils.type,Color$o=Color_1,input$1=input$h;Color$o.prototype.oklab=function(){return rgb2oklab_1(this._rgb)},chroma_1.oklab=function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];return new(Function.prototype.bind.apply(Color$o,[null].concat(args,["oklab"])))},input$1.format.oklab=oklab2rgb_1,input$1.autodetect.push({p:3,test:function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];if(args=unpack$3(args,"oklab"),"array"===type$8(args)&&3===args.length)return"oklab"}});var unpack$2=utils.unpack,unpack$1=utils.unpack,unpack=utils.unpack,type$7=utils.type,Color$n=Color_1,input=input$h,rgb2oklch=function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];var ref=unpack$2(args,"rgb"),r=ref[0],g=ref[1],b=ref[2],ref$1=rgb2oklab_1(r,g,b),l=ref$1[0],a=ref$1[1],b_=ref$1[2];return lab2lch_1(l,a,b_)};Color$n.prototype.oklch=function(){return rgb2oklch(this._rgb)},chroma_1.oklch=function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];return new(Function.prototype.bind.apply(Color$n,[null].concat(args,["oklch"])))},input.format.oklch=function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];args=unpack$1(args,"lch");var l=args[0],c=args[1],h=args[2],ref=lch2lab_1(l,c,h),L=ref[0],a=ref[1],b_=ref[2],ref$1=oklab2rgb_1(L,a,b_),r=ref$1[0],g=ref$1[1],b=ref$1[2];return[r,g,b,3<args.length?args[3]:1]},input.autodetect.push({p:3,test:function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];if(args=unpack(args,"oklch"),"array"===type$7(args)&&3===args.length)return"oklch"}});var Color$m=Color_1,type$6=utils.type;Color$m.prototype.alpha=function(a,mutate){return void 0===mutate&&(mutate=!1),void 0!==a&&"number"===type$6(a)?mutate?(this._rgb[3]=a,this):new Color$m([this._rgb[0],this._rgb[1],this._rgb[2],a],"rgb"):this._rgb[3]};Color_1.prototype.clipped=function(){return this._rgb._clipped||!1};var Color$k=Color_1;Color$k.prototype.darken=function(amount){void 0===amount&&(amount=1);var me=this,lab=me.lab();return lab[0]-=labConstants.Kn*amount,new Color$k(lab,"lab").alpha(me.alpha(),!0)},Color$k.prototype.brighten=function(amount){return void 0===amount&&(amount=1),this.darken(-amount)},Color$k.prototype.darker=Color$k.prototype.darken,Color$k.prototype.brighter=Color$k.prototype.brighten;Color_1.prototype.get=function(mc){var ref=mc.split("."),mode=ref[0],channel=ref[1],src=this[mode]();if(channel){var i=mode.indexOf(channel)-("ok"===mode.substr(0,2)?2:0);if(-1<i)return src[i];throw new Error("unknown channel "+channel+" in mode "+mode)}else return src};var Color$i=Color_1,type$5=utils.type;Color$i.prototype.luminance=function(lum){if(lum!==void 0&&"number"===type$5(lum)){if(0===lum)return new Color$i([0,0,0,this._rgb[3]],"rgb");if(1===lum)return new Color$i([255,255,255,this._rgb[3]],"rgb");var cur_lum=this.luminance(),max_iter=20,test=function(low,high){var mid=low.interpolate(high,.5,"rgb"),lm=mid.luminance();return _Mathabs(lum-lm)<1e-7||!max_iter--?mid:lm>lum?test(low,mid):test(mid,high)},rgb=(cur_lum>lum?test(new Color$i([0,0,0]),this):test(this,new Color$i([255,255,255]))).rgb();return new Color$i(rgb.concat([this._rgb[3]]))}return rgb2luminance.apply(void 0,this._rgb.slice(0,3))};var rgb2luminance=function(r,g,b){return r=luminance_x(r),g=luminance_x(g),b=luminance_x(b),.2126*r+.7152*g+.0722*b},luminance_x=function(x){return x/=255,.03928>=x?x/12.92:_Mathpow((x+.055)/1.055,2.4)},interpolator$1={},Color$h=Color_1,type$4=utils.type,interpolator=interpolator$1,mix$1=function(col1,col2,f){void 0===f&&(f=.5);for(var rest=[],len=arguments.length-3;0<len--;)rest[len]=arguments[len+3];var mode=rest[0]||"lrgb";if(interpolator[mode]||rest.length||(mode=Object.keys(interpolator)[0]),!interpolator[mode])throw new Error("interpolation mode "+mode+" is not defined");return"object"!==type$4(col1)&&(col1=new Color$h(col1)),"object"!==type$4(col2)&&(col2=new Color$h(col2)),interpolator[mode](col1,col2,f).alpha(col1.alpha()+f*(col2.alpha()-col1.alpha()))},Color$g=Color_1;Color$g.prototype.mix=Color$g.prototype.interpolate=function(col2,f){void 0===f&&(f=.5);for(var rest=[],len=arguments.length-2;0<len--;)rest[len]=arguments[len+2];return mix$1.apply(void 0,[this,col2,f].concat(rest))};var Color$f=Color_1;Color$f.prototype.premultiply=function(mutate){void 0===mutate&&(mutate=!1);var rgb=this._rgb,a=rgb[3];return mutate?(this._rgb=[rgb[0]*a,rgb[1]*a,rgb[2]*a,a],this):new Color$f([rgb[0]*a,rgb[1]*a,rgb[2]*a,a],"rgb")};var Color$e=Color_1;Color$e.prototype.saturate=function(amount){void 0===amount&&(amount=1);var me=this,lch=me.lch();return lch[1]+=labConstants.Kn*amount,0>lch[1]&&(lch[1]=0),new Color$e(lch,"lch").alpha(me.alpha(),!0)},Color$e.prototype.desaturate=function(amount){return void 0===amount&&(amount=1),this.saturate(-amount)};var Color$d=Color_1,type$3=utils.type;Color$d.prototype.set=function(mc,value,mutate){void 0===mutate&&(mutate=!1);var ref=mc.split("."),mode=ref[0],channel=ref[1],src=this[mode]();if(channel){var i=mode.indexOf(channel)-("ok"===mode.substr(0,2)?2:0);if(-1<i){if("string"==type$3(value))switch(value.charAt(0)){case"+":src[i]+=+value;break;case"-":src[i]+=+value;break;case"*":src[i]*=+value.substr(1);break;case"/":src[i]/=+value.substr(1);break;default:src[i]=+value;}else if("number"===type$3(value))src[i]=value;else throw new Error("unsupported value for Color.set");var out=new Color$d(src,mode);return mutate?(this._rgb=out._rgb,this):out}throw new Error("unknown channel "+channel+" in mode "+mode)}else return src};interpolator$1.rgb=function(col1,col2,f){var xyz0=col1._rgb,xyz1=col2._rgb;return new Color_1(xyz0[0]+f*(xyz1[0]-xyz0[0]),xyz0[1]+f*(xyz1[1]-xyz0[1]),xyz0[2]+f*(xyz1[2]-xyz0[2]),"rgb")};var sqrt$2=_Mathsqrt,pow$5=_Mathpow;interpolator$1.lrgb=function(col1,col2,f){var ref=col1._rgb,x1=ref[0],y1=ref[1],z1=ref[2],ref$1=col2._rgb,x2=ref$1[0],y2=ref$1[1],z2=ref$1[2];return new Color_1(sqrt$2(pow$5(x1,2)*(1-f)+pow$5(x2,2)*f),sqrt$2(pow$5(y1,2)*(1-f)+pow$5(y2,2)*f),sqrt$2(pow$5(z1,2)*(1-f)+pow$5(z2,2)*f),"rgb")};interpolator$1.lab=function(col1,col2,f){var xyz0=col1.lab(),xyz1=col2.lab();return new Color_1(xyz0[0]+f*(xyz1[0]-xyz0[0]),xyz0[1]+f*(xyz1[1]-xyz0[1]),xyz0[2]+f*(xyz1[2]-xyz0[2]),"lab")};var Color$9=Color_1,_hsx=function(col1,col2,f,m){var assign,assign$1,xyz0,xyz1;"hsl"===m?(xyz0=col1.hsl(),xyz1=col2.hsl()):"hsv"===m?(xyz0=col1.hsv(),xyz1=col2.hsv()):"hcg"===m?(xyz0=col1.hcg(),xyz1=col2.hcg()):"hsi"===m?(xyz0=col1.hsi(),xyz1=col2.hsi()):"lch"===m||"hcl"===m?(m="hcl",xyz0=col1.hcl(),xyz1=col2.hcl()):"oklch"===m&&(xyz0=col1.oklch().reverse(),xyz1=col2.oklch().reverse());var hue0,hue1,sat0,sat1,lbv0,lbv1;("h"===m.substr(0,1)||"oklch"===m)&&(assign=xyz0,hue0=assign[0],sat0=assign[1],lbv0=assign[2],assign$1=xyz1,hue1=assign$1[0],sat1=assign$1[1],lbv1=assign$1[2]);var sat,hue,lbv,dh;return isNaN(hue0)||isNaN(hue1)?isNaN(hue0)?isNaN(hue1)?hue=_NumberNaN:(hue=hue1,(1==lbv0||0==lbv0)&&"hsv"!=m&&(sat=sat1)):(hue=hue0,(1==lbv1||0==lbv1)&&"hsv"!=m&&(sat=sat0)):(dh=hue1>hue0&&180<hue1-hue0?hue1-(hue0+360):hue1<hue0&&180<hue0-hue1?hue1+360-hue0:hue1-hue0,hue=hue0+f*dh),void 0===sat&&(sat=sat0+f*(sat1-sat0)),lbv=lbv0+f*(lbv1-lbv0),"oklch"===m?new Color$9([lbv,sat,hue],m):new Color$9([hue,sat,lbv],m)},lch=function(col1,col2,f){return _hsx(col1,col2,f,"lch")};interpolator$1.lch=lch,interpolator$1.hcl=lch;interpolator$1.num=function(col1,col2,f){var c1=col1.num(),c2=col2.num();return new Color_1(c1+f*(c2-c1),"num")};interpolator$1.hcg=function(col1,col2,f){return _hsx(col1,col2,f,"hcg")};interpolator$1.hsi=function(col1,col2,f){return _hsx(col1,col2,f,"hsi")};interpolator$1.hsl=function(col1,col2,f){return _hsx(col1,col2,f,"hsl")};interpolator$1.hsv=function(col1,col2,f){return _hsx(col1,col2,f,"hsv")};interpolator$1.oklab=function(col1,col2,f){var xyz0=col1.oklab(),xyz1=col2.oklab();return new Color_1(xyz0[0]+f*(xyz1[0]-xyz0[0]),xyz0[1]+f*(xyz1[1]-xyz0[1]),xyz0[2]+f*(xyz1[2]-xyz0[2]),"oklab")};interpolator$1.oklch=function(col1,col2,f){return _hsx(col1,col2,f,"oklch")};var Color$6=Color_1,clip_rgb$1=utils.clip_rgb,pow$4=_Mathpow,sqrt$1=_Mathsqrt,PI$1=_MathPI,cos$2=_Mathcos,sin$2=_Mathsin,average=function(colors,mode,weights){void 0===mode&&(mode="lrgb"),void 0===weights&&(weights=null);var l=colors.length;weights||(weights=Array.from(Array(l)).map(function(){return 1}));var k=l/weights.reduce(function(a,b){return a+b});if(weights.forEach(function(w,i){weights[i]*=k}),colors=colors.map(function(c){return new Color$6(c)}),"lrgb"===mode)return _average_lrgb(colors,weights);for(var first=colors.shift(),xyz=first.get(mode),cnt=[],dx=0,dy=0,i=0;i<xyz.length;i++)if(xyz[i]=(xyz[i]||0)*weights[0],cnt.push(isNaN(xyz[i])?0:weights[0]),"h"===mode.charAt(i)&&!isNaN(xyz[i])){var A=xyz[i]/180*PI$1;dx+=cos$2(A)*weights[0],dy+=sin$2(A)*weights[0]}var alpha=first.alpha()*weights[0];colors.forEach(function(c,ci){var xyz2=c.get(mode);alpha+=c.alpha()*weights[ci+1];for(var i=0;i<xyz.length;i++)if(!isNaN(xyz2[i]))if(cnt[i]+=weights[ci+1],"h"===mode.charAt(i)){var A=xyz2[i]/180*PI$1;dx+=cos$2(A)*weights[ci+1],dy+=sin$2(A)*weights[ci+1]}else xyz[i]+=xyz2[i]*weights[ci+1]});for(var i$1=0;i$1<xyz.length;i$1++)if("h"===mode.charAt(i$1)){for(var A$1=180*(_Mathatan(dy/cnt[i$1],dx/cnt[i$1])/PI$1);0>A$1;)A$1+=360;for(;360<=A$1;)A$1-=360;xyz[i$1]=A$1}else xyz[i$1]/=cnt[i$1];return alpha/=l,new Color$6(xyz,mode).alpha(.99999<alpha?1:alpha,!0)},_average_lrgb=function(colors,weights){for(var l=colors.length,xyz=[0,0,0,0],i=0;i<colors.length;i++){var col=colors[i],f=weights[i]/l,rgb=col._rgb;xyz[0]+=pow$4(rgb[0],2)*f,xyz[1]+=pow$4(rgb[1],2)*f,xyz[2]+=pow$4(rgb[2],2)*f,xyz[3]+=rgb[3]*f}return xyz[0]=sqrt$1(xyz[0]),xyz[1]=sqrt$1(xyz[1]),xyz[2]=sqrt$1(xyz[2]),.9999999<xyz[3]&&(xyz[3]=1),new Color$6(clip_rgb$1(xyz))},chroma$4=chroma_1,type$2=utils.type,scale$2=function(colors){var _mode="rgb",_nacol=chroma$4("#ccc"),_spread=0,_domain=[0,1],_pos=[],_padding=[0,0],_classes=!1,_colors=[],_out=!1,_min=0,_max=1,_correctLightness=!1,_colorCache={},_useCache=!0,_gamma=1,setColors=function(colors){if(colors=colors||["#fff","#000"],colors&&"string"===type$2(colors)&&chroma$4.brewer&&chroma$4.brewer[colors.toLowerCase()]&&(colors=chroma$4.brewer[colors.toLowerCase()]),"array"===type$2(colors)){1===colors.length&&(colors=[colors[0],colors[0]]),colors=colors.slice(0);for(var c=0;c<colors.length;c++)colors[c]=chroma$4(colors[c]);_pos.length=0;for(var c$1=0;c$1<colors.length;c$1++)_pos.push(c$1/(colors.length-1))}return resetCache(),_colors=colors},getClass=function(value){if(null!=_classes){for(var n=_classes.length-1,i=0;i<n&&value>=_classes[i];)i++;return i-1}return 0},tMapLightness=function(t){return t},tMapDomain=function(t){return t},getColor=function(val,bypassMap){var col,t;if(null==bypassMap&&(bypassMap=!1),isNaN(val)||null===val)return _nacol;if(!!bypassMap)t=val;else if(_classes&&2<_classes.length){var c=getClass(val);t=c/(_classes.length-2)}else t=_max===_min?1:(val-_min)/(_max-_min);t=tMapDomain(t),bypassMap||(t=tMapLightness(t)),1!==_gamma&&(t=_Mathpow(t,_gamma)),t=_padding[0]+t*(1-_padding[0]-_padding[1]),t=_Mathmin2(1,_Mathmax2(0,t));var k=_Mathfloor(1e4*t);if(_useCache&&_colorCache[k])col=_colorCache[k];else{if("array"===type$2(_colors))for(var i=0,p;i<_pos.length;i++){if(p=_pos[i],t<=p){col=_colors[i];break}if(t>=p&&i===_pos.length-1){col=_colors[i];break}if(t>p&&t<_pos[i+1]){t=(t-p)/(_pos[i+1]-p),col=chroma$4.interpolate(_colors[i],_colors[i+1],t,_mode);break}}else"function"===type$2(_colors)&&(col=_colors(t));_useCache&&(_colorCache[k]=col)}return col},resetCache=function(){return _colorCache={}};setColors(colors);var f=function(v){var c=chroma$4(getColor(v));return _out&&c[_out]?c[_out]():c};return f.classes=function(classes){if(null!=classes){if("array"===type$2(classes))_classes=classes,_domain=[classes[0],classes[classes.length-1]];else{var d=chroma$4.analyze(_domain);_classes=0===classes?[d.min,d.max]:chroma$4.limits(d,"e",classes)}return f}return _classes},f.domain=function(domain){if(!arguments.length)return _domain;_min=domain[0],_max=domain[domain.length-1],_pos=[];var k=_colors.length;if(domain.length===k&&_min!==_max)for(var i=0,list=Array.from(domain),d;i<list.length;i+=1)d=list[i],_pos.push((d-_min)/(_max-_min));else{for(var c=0;c<k;c++)_pos.push(c/(k-1));if(2<domain.length){var tOut=domain.map(function(d,i){return i/(domain.length-1)}),tBreaks=domain.map(function(d){return(d-_min)/(_max-_min)});tBreaks.every(function(val,i){return tOut[i]===val})||(tMapDomain=function(t){if(0>=t||1<=t)return t;for(var i=0;t>=tBreaks[i+1];)i++;var f=(t-tBreaks[i])/(tBreaks[i+1]-tBreaks[i]),out=tOut[i]+f*(tOut[i+1]-tOut[i]);return out})}}return _domain=[_min,_max],f},f.mode=function(_m){return arguments.length?(_mode=_m,resetCache(),f):_mode},f.range=function(colors){return setColors(colors),f},f.out=function(_o){return _out=_o,f},f.spread=function(val){return arguments.length?(_spread=val,f):_spread},f.correctLightness=function(v){return null==v&&(v=!0),_correctLightness=v,resetCache(),tMapLightness=_correctLightness?function(t){for(var L0=getColor(0,!0).lab()[0],L1=getColor(1,!0).lab()[0],L_actual=getColor(t,!0).lab()[0],L_ideal=L0+(L1-L0)*t,L_diff=L_actual-L_ideal,t0=0,t1=1,max_iter=20;.01<_Mathabs(L_diff)&&0<max_iter--;)(function(){return L0>L1&&(L_diff*=-1),0>L_diff?(t0=t,t+=.5*(t1-t)):(t1=t,t+=.5*(t0-t)),L_actual=getColor(t,!0).lab()[0],L_diff=L_actual-L_ideal})();return t}:function(t){return t},f},f.padding=function(p){return null==p?_padding:("number"===type$2(p)&&(p=[p,p]),_padding=p,f)},f.colors=function(numColors,out){2>arguments.length&&(out="hex");var result=[];if(0===arguments.length)result=_colors.slice(0);else if(1===numColors)result=[f(.5)];else if(1<numColors){var dm=_domain[0],dd=_domain[1]-dm;result=__range__(0,numColors,!1).map(function(i){return f(dm+i/(numColors-1)*dd)})}else{colors=[];var samples=[];if(_classes&&2<_classes.length)for(var i=1,end=_classes.length,asc=1<=end;asc?i<end:i>end;asc?i++:i--)samples.push(.5*(_classes[i-1]+_classes[i]));else samples=_domain;result=samples.map(function(v){return f(v)})}return chroma$4[out]&&(result=result.map(function(c){return c[out]()})),result},f.cache=function(c){return null==c?_useCache:(_useCache=c,f)},f.gamma=function(g){return null==g?_gamma:(_gamma=g,f)},f.nodata=function(d){return null==d?_nacol:(_nacol=chroma$4(d),f)},f},Color$5=Color_1,binom_row=function(n){for(var row=[1,1],i=1,newrow;i<n;i++){newrow=[1];for(var j=1;j<=row.length;j++)newrow[j]=(row[j]||0)+row[j-1];row=newrow}return row},bezier=function(colors){var assign,assign$1,assign$2,I,lab0,lab1,lab2;if(colors=colors.map(function(c){return new Color$5(c)}),2===colors.length)assign=colors.map(function(c){return c.lab()}),lab0=assign[0],lab1=assign[1],I=function(t){var lab=[0,1,2].map(function(i){return lab0[i]+t*(lab1[i]-lab0[i])});return new Color$5(lab,"lab")};else if(3===colors.length)assign$1=colors.map(function(c){return c.lab()}),lab0=assign$1[0],lab1=assign$1[1],lab2=assign$1[2],I=function(t){var lab=[0,1,2].map(function(i){return(1-t)*(1-t)*lab0[i]+2*(1-t)*t*lab1[i]+t*t*lab2[i]});return new Color$5(lab,"lab")};else if(4===colors.length){var lab3;assign$2=colors.map(function(c){return c.lab()}),lab0=assign$2[0],lab1=assign$2[1],lab2=assign$2[2],lab3=assign$2[3],I=function(t){var lab=[0,1,2].map(function(i){return(1-t)*(1-t)*(1-t)*lab0[i]+3*(1-t)*(1-t)*t*lab1[i]+3*(1-t)*t*t*lab2[i]+t*t*t*lab3[i]});return new Color$5(lab,"lab")}}else if(5<=colors.length){var labs,row,n;labs=colors.map(function(c){return c.lab()}),n=colors.length-1,row=binom_row(n),I=function(t){var lab=[0,1,2].map(function(i){return labs.reduce(function(sum,el,j){return sum+row[j]*_Mathpow(1-t,n-j)*_Mathpow(t,j)*el[i]},0)});return new Color$5(lab,"lab")}}else throw new RangeError("No point in running bezier with only one color.");return I},chroma$3=chroma_1,blend=function(bottom,top,mode){if(!blend[mode])throw new Error("unknown blend mode "+mode);return blend[mode](bottom,top)},blend_f=function(f){return function(bottom,top){var c0=chroma$3(top).rgb(),c1=chroma$3(bottom).rgb();return chroma$3.rgb(f(c0,c1))}},each=function(f){return function(c0,c1){var out=[];return out[0]=f(c0[0],c1[0]),out[1]=f(c0[1],c1[1]),out[2]=f(c0[2],c1[2]),out}};blend.normal=blend_f(each(function(a){return a})),blend.multiply=blend_f(each(function(a,b){return a*b/255})),blend.screen=blend_f(each(function(a,b){return 255*(1-(1-a/255)*(1-b/255))})),blend.overlay=blend_f(each(function(a,b){return 128>b?2*a*b/255:255*(1-2*(1-a/255)*(1-b/255))})),blend.darken=blend_f(each(function(a,b){return a>b?b:a})),blend.lighten=blend_f(each(function(a,b){return a>b?a:b})),blend.dodge=blend_f(each(function(a,b){return 255===a?255:(a=255*(b/255)/(1-a/255),255<a?255:a)})),blend.burn=blend_f(each(function(a,b){return 255*(1-(1-b/255)/(a/255))}));for(var blend_1=blend,type$1=utils.type,clip_rgb=utils.clip_rgb,TWOPI=utils.TWOPI,chroma$2=chroma_1,cubehelix=function(start,rotations,hue,gamma,lightness){void 0===start&&(start=300),void 0===rotations&&(rotations=-1.5),void 0===hue&&(hue=1),void 0===gamma&&(gamma=1),void 0===lightness&&(lightness=[0,1]);var dh=0,dl;"array"===type$1(lightness)?dl=lightness[1]-lightness[0]:(dl=0,lightness=[lightness,lightness]);var f=function(fract){var a=TWOPI*((start+120)/360+rotations*fract),l=_Mathpow(lightness[0]+dl*fract,gamma),h=0===dh?hue:hue[0]+fract*dh,amp=h*l*(1-l)/2,cos_a=_Mathcos(a),sin_a=_Mathsin(a);return chroma$2(clip_rgb([255*(l+amp*(-.14861*cos_a+1.78277*sin_a)),255*(l+amp*(-.29227*cos_a-.90649*sin_a)),255*(l+amp*(+1.97294*cos_a)),1]))};return f.start=function(s){return null==s?start:(start=s,f)},f.rotations=function(r){return null==r?rotations:(rotations=r,f)},f.gamma=function(g){return null==g?gamma:(gamma=g,f)},f.hue=function(h){return null==h?hue:(hue=h,"array"===type$1(hue)?(dh=hue[1]-hue[0],0===dh&&(hue=hue[1])):dh=0,f)},f.lightness=function(h){return null==h?lightness:("array"===type$1(h)?(lightness=h,dl=h[1]-h[0]):(lightness=[h,h],dl=0),f)},f.scale=function(){return chroma$2.scale(f)},f.hue(hue),f},random=Math.random,random_1=function(){for(var code="#",i=0;6>i;i++)code+="0123456789abcdef".charAt(_Mathfloor(16*random()));return new Color_1(code,"hex")},type=type$p,log=_Mathlog,analyze=function(data,key){void 0===key&&(key=null);var r={min:_NumberMAX_VALUE,max:-1*_NumberMAX_VALUE,sum:0,values:[],count:0};return"object"===type(data)&&(data=Object.values(data)),data.forEach(function(val){key&&"object"===type(val)&&(val=val[key]),void 0===val||null===val||isNaN(val)||(r.values.push(val),r.sum+=val,val<r.min&&(r.min=val),val>r.max&&(r.max=val),r.count+=1)}),r.domain=[r.min,r.max],r.limits=function(mode,num){return limits(r,mode,num)},r},limits=function(data,mode,num){var _MathLOG10E=Math.LOG10E;void 0===mode&&(mode="equal"),void 0===num&&(num=7),"array"==type(data)&&(data=analyze(data));var min=data.min,max=data.max,values=data.values.sort(function(a,b){return a-b});if(1===num)return[min,max];var limits=[];if("c"===mode.substr(0,1)&&(limits.push(min),limits.push(max)),"e"===mode.substr(0,1)){limits.push(min);for(var i=1;i<num;i++)limits.push(min+i/num*(max-min));limits.push(max)}else if("l"===mode.substr(0,1)){if(0>=min)throw new Error("Logarithmic scales are only possible for values > 0");var min_log=_MathLOG10E*log(min),max_log=_MathLOG10E*log(max);limits.push(min);for(var i$1=1;i$1<num;i$1++)limits.push(_Mathpow(10,min_log+i$1/num*(max_log-min_log)));limits.push(max)}else if("q"===mode.substr(0,1)){limits.push(min);for(var i$2=1;i$2<num;i$2++){var p=(values.length-1)*i$2/num,pb=_Mathfloor(p);if(pb===p)limits.push(values[pb]);else{var pr=p-pb;limits.push(values[pb]*(1-pr)+values[pb+1]*pr)}}limits.push(max)}else if("k"===mode.substr(0,1)){var n=values.length,assignments=Array(n),clusterSizes=Array(num),repeat=!0,nb_iters=0,centroids=null,cluster;centroids=[],centroids.push(min);for(var i$3=1;i$3<num;i$3++)centroids.push(min+i$3/num*(max-min));for(centroids.push(max);repeat;){for(var j=0;j<num;j++)clusterSizes[j]=0;for(var i$4=0;i$4<n;i$4++)for(var value=values[i$4],mindist=_NumberMAX_VALUE,best=void 0,j$1=0,dist;j$1<num;j$1++)dist=_Mathabs(centroids[j$1]-value),dist<mindist&&(mindist=dist,best=j$1),clusterSizes[best]++,assignments[i$4]=best;for(var newCentroids=Array(num),j$2=0;j$2<num;j$2++)newCentroids[j$2]=null;for(var i$5=0;i$5<n;i$5++)cluster=assignments[i$5],null===newCentroids[cluster]?newCentroids[cluster]=values[i$5]:newCentroids[cluster]+=values[i$5];for(var j$3=0;j$3<num;j$3++)newCentroids[j$3]*=1/clusterSizes[j$3];repeat=!1;for(var j$4=0;j$4<num;j$4++)if(newCentroids[j$4]!==centroids[j$4]){repeat=!0;break}centroids=newCentroids,nb_iters++,200<nb_iters&&(repeat=!1)}for(var kClusters={},j$5=0;j$5<num;j$5++)kClusters[j$5]=[];for(var i$6=0;i$6<n;i$6++)cluster=assignments[i$6],kClusters[cluster].push(values[i$6]);for(var tmpKMeansBreaks=[],j$6=0;j$6<num;j$6++)tmpKMeansBreaks.push(kClusters[j$6][0]),tmpKMeansBreaks.push(kClusters[j$6][kClusters[j$6].length-1]);tmpKMeansBreaks=tmpKMeansBreaks.sort(function(a,b){return a-b}),limits.push(tmpKMeansBreaks[0]);for(var i$7=1,v;i$7<tmpKMeansBreaks.length;i$7+=2)v=tmpKMeansBreaks[i$7],isNaN(v)||-1!==limits.indexOf(v)||limits.push(v)}return limits},analyze_1={analyze:analyze,limits:limits},Color$3=Color_1,contrast=function(a,b){a=new Color$3(a),b=new Color$3(b);var l1=a.luminance(),l2=b.luminance();return l1>l2?(l1+.05)/(l2+.05):(l2+.05)/(l1+.05)},Color$2=Color_1,sqrt=_Mathsqrt,pow=_Mathpow,atan2=_Mathatan,abs=_Mathabs,cos=_Mathcos,sin=_Mathsin,exp=Math.exp,PI=_MathPI,deltaE=function(a,b,Kl,Kc,Kh){void 0===Kl&&(Kl=1),void 0===Kc&&(Kc=1),void 0===Kh&&(Kh=1);var rad2deg=function(rad){return 360*rad/(2*PI)},deg2rad=function(deg){return 2*PI*deg/360};a=new Color$2(a),b=new Color$2(b);var ref=Array.from(a.lab()),L1=ref[0],a1=ref[1],b1=ref[2],ref$1=Array.from(b.lab()),L2=ref$1[0],a2=ref$1[1],b2=ref$1[2],avgL=(L1+L2)/2,C1=sqrt(pow(a1,2)+pow(b1,2)),C2=sqrt(pow(a2,2)+pow(b2,2)),avgC=(C1+C2)/2,G=.5*(1-sqrt(pow(avgC,7)/(pow(avgC,7)+pow(25,7)))),a1p=a1*(1+G),a2p=a2*(1+G),C1p=sqrt(pow(a1p,2)+pow(b1,2)),C2p=sqrt(pow(a2p,2)+pow(b2,2)),avgCp=(C1p+C2p)/2,arctan1=rad2deg(atan2(b1,a1p)),arctan2=rad2deg(atan2(b2,a2p)),h1p=0<=arctan1?arctan1:arctan1+360,h2p=0<=arctan2?arctan2:arctan2+360,avgHp=180<abs(h1p-h2p)?(h1p+h2p+360)/2:(h1p+h2p)/2,T=1-.17*cos(deg2rad(avgHp-30))+.24*cos(deg2rad(2*avgHp))+.32*cos(deg2rad(3*avgHp+6))-.2*cos(deg2rad(4*avgHp-63)),deltaHp=h2p-h1p;deltaHp=180>=abs(deltaHp)?deltaHp:h2p<=h1p?deltaHp+360:deltaHp-360,deltaHp=2*sqrt(C1p*C2p)*sin(deg2rad(deltaHp)/2);var deltaCp=C2p-C1p,sl=1+.015*pow(avgL-50,2)/sqrt(20+pow(avgL-50,2)),sc=1+.045*avgCp,sh=1+.015*avgCp*T,deltaTheta=30*exp(-pow((avgHp-275)/25,2)),Rc=2*sqrt(pow(avgCp,7)/(pow(avgCp,7)+pow(25,7))),Rt=-Rc*sin(2*deg2rad(deltaTheta)),result=sqrt(pow((L2-L1)/(Kl*sl),2)+pow(deltaCp/(Kc*sc),2)+pow(deltaHp/(Kh*sh),2)+Rt*(deltaCp/(Kc*sc))*(deltaHp/(Kh*sh)));return _Mathmax2(0,_Mathmin2(100,result))},Color$1=Color_1,distance=function(a,b,mode){void 0===mode&&(mode="lab"),a=new Color$1(a),b=new Color$1(b);var l1=a.get(mode),l2=b.get(mode),sum_sq=0;for(var i in l1){var d=(l1[i]||0)-(l2[i]||0);sum_sq+=d*d}return _Mathsqrt(sum_sq)},valid=function(){for(var args=[],len=arguments.length;len--;)args[len]=arguments[len];try{return new(Function.prototype.bind.apply(Color_1,[null].concat(args))),!0}catch(e){return!1}},chroma$1=chroma_1,scale=scale$2,scales={cool:function(){return scale([chroma$1.hsl(180,1,.9),chroma$1.hsl(250,.7,.4)])},hot:function(){return scale(["#000","#f00","#ff0","#fff"]).mode("rgb")}},colorbrewer={OrRd:["#fff7ec","#fee8c8","#fdd49e","#fdbb84","#fc8d59","#ef6548","#d7301f","#b30000","#7f0000"],PuBu:["#fff7fb","#ece7f2","#d0d1e6","#a6bddb","#74a9cf","#3690c0","#0570b0","#045a8d","#023858"],BuPu:["#f7fcfd","#e0ecf4","#bfd3e6","#9ebcda","#8c96c6","#8c6bb1","#88419d","#810f7c","#4d004b"],Oranges:["#fff5eb","#fee6ce","#fdd0a2","#fdae6b","#fd8d3c","#f16913","#d94801","#a63603","#7f2704"],BuGn:["#f7fcfd","#e5f5f9","#ccece6","#99d8c9","#66c2a4","#41ae76","#238b45","#006d2c","#00441b"],YlOrBr:["#ffffe5","#fff7bc","#fee391","#fec44f","#fe9929","#ec7014","#cc4c02","#993404","#662506"],YlGn:["#ffffe5","#f7fcb9","#d9f0a3","#addd8e","#78c679","#41ab5d","#238443","#006837","#004529"],Reds:["#fff5f0","#fee0d2","#fcbba1","#fc9272","#fb6a4a","#ef3b2c","#cb181d","#a50f15","#67000d"],RdPu:["#fff7f3","#fde0dd","#fcc5c0","#fa9fb5","#f768a1","#dd3497","#ae017e","#7a0177","#49006a"],Greens:["#f7fcf5","#e5f5e0","#c7e9c0","#a1d99b","#74c476","#41ab5d","#238b45","#006d2c","#00441b"],YlGnBu:["#ffffd9","#edf8b1","#c7e9b4","#7fcdbb","#41b6c4","#1d91c0","#225ea8","#253494","#081d58"],Purples:["#fcfbfd","#efedf5","#dadaeb","#bcbddc","#9e9ac8","#807dba","#6a51a3","#54278f","#3f007d"],GnBu:["#f7fcf0","#e0f3db","#ccebc5","#a8ddb5","#7bccc4","#4eb3d3","#2b8cbe","#0868ac","#084081"],Greys:["#ffffff","#f0f0f0","#d9d9d9","#bdbdbd","#969696","#737373","#525252","#252525","#000000"],YlOrRd:["#ffffcc","#ffeda0","#fed976","#feb24c","#fd8d3c","#fc4e2a","#e31a1c","#bd0026","#800026"],PuRd:["#f7f4f9","#e7e1ef","#d4b9da","#c994c7","#df65b0","#e7298a","#ce1256","#980043","#67001f"],Blues:["#f7fbff","#deebf7","#c6dbef","#9ecae1","#6baed6","#4292c6","#2171b5","#08519c","#08306b"],PuBuGn:["#fff7fb","#ece2f0","#d0d1e6","#a6bddb","#67a9cf","#3690c0","#02818a","#016c59","#014636"],Viridis:["#440154","#482777","#3f4a8a","#31678e","#26838f","#1f9d8a","#6cce5a","#b6de2b","#fee825"],Spectral:["#9e0142","#d53e4f","#f46d43","#fdae61","#fee08b","#ffffbf","#e6f598","#abdda4","#66c2a5","#3288bd","#5e4fa2"],RdYlGn:["#a50026","#d73027","#f46d43","#fdae61","#fee08b","#ffffbf","#d9ef8b","#a6d96a","#66bd63","#1a9850","#006837"],RdBu:["#67001f","#b2182b","#d6604d","#f4a582","#fddbc7","#f7f7f7","#d1e5f0","#92c5de","#4393c3","#2166ac","#053061"],PiYG:["#8e0152","#c51b7d","#de77ae","#f1b6da","#fde0ef","#f7f7f7","#e6f5d0","#b8e186","#7fbc41","#4d9221","#276419"],PRGn:["#40004b","#762a83","#9970ab","#c2a5cf","#e7d4e8","#f7f7f7","#d9f0d3","#a6dba0","#5aae61","#1b7837","#00441b"],RdYlBu:["#a50026","#d73027","#f46d43","#fdae61","#fee090","#ffffbf","#e0f3f8","#abd9e9","#74add1","#4575b4","#313695"],BrBG:["#543005","#8c510a","#bf812d","#dfc27d","#f6e8c3","#f5f5f5","#c7eae5","#80cdc1","#35978f","#01665e","#003c30"],RdGy:["#67001f","#b2182b","#d6604d","#f4a582","#fddbc7","#ffffff","#e0e0e0","#bababa","#878787","#4d4d4d","#1a1a1a"],PuOr:["#7f3b08","#b35806","#e08214","#fdb863","#fee0b6","#f7f7f7","#d8daeb","#b2abd2","#8073ac","#542788","#2d004b"],Set2:["#66c2a5","#fc8d62","#8da0cb","#e78ac3","#a6d854","#ffd92f","#e5c494","#b3b3b3"],Accent:["#7fc97f","#beaed4","#fdc086","#ffff99","#386cb0","#f0027f","#bf5b17","#666666"],Set1:["#e41a1c","#377eb8","#4daf4a","#984ea3","#ff7f00","#ffff33","#a65628","#f781bf","#999999"],Set3:["#8dd3c7","#ffffb3","#bebada","#fb8072","#80b1d3","#fdb462","#b3de69","#fccde5","#d9d9d9","#bc80bd","#ccebc5","#ffed6f"],Dark2:["#1b9e77","#d95f02","#7570b3","#e7298a","#66a61e","#e6ab02","#a6761d","#666666"],Paired:["#a6cee3","#1f78b4","#b2df8a","#33a02c","#fb9a99","#e31a1c","#fdbf6f","#ff7f00","#cab2d6","#6a3d9a","#ffff99","#b15928"],Pastel2:["#b3e2cd","#fdcdac","#cbd5e8","#f4cae4","#e6f5c9","#fff2ae","#f1e2cc","#cccccc"],Pastel1:["#fbb4ae","#b3cde3","#ccebc5","#decbe4","#fed9a6","#ffffcc","#e5d8bd","#fddaec","#f2f2f2"]},i=0,list=Object.keys(colorbrewer),key;i<list.length;i+=1)key=list[i],colorbrewer[key.toLowerCase()]=colorbrewer[key];var chroma=chroma_1;chroma.average=average,chroma.bezier=function(colors){var f=bezier(colors);return f.scale=function(){return scale$2(f)},f},chroma.blend=blend_1,chroma.cubehelix=cubehelix,chroma.mix=chroma.interpolate=mix$1,chroma.random=random_1,chroma.scale=scale$2,chroma.analyze=analyze_1.analyze,chroma.contrast=contrast,chroma.deltaE=deltaE,chroma.distance=distance,chroma.limits=analyze_1.limits,chroma.valid=valid,chroma.scales=scales,chroma.colors=w3cx11_1,chroma.brewer=colorbrewer;return chroma})},{}],3:[function(require,module){"use strict";var _Mathmin3=Math.min;class ArrayHelper{static clone(arr){let out=Array.isArray(arr)?[]:{};for(let key in arr){let value=arr[key];out[key]="function"==typeof value.clone?value.clone():"object"==typeof value?ArrayHelper.clone(value):value}return out}static equals(arrA,arrB){if(arrA.length!==arrB.length)return!1;let tmpA=arrA.slice().sort(),tmpB=arrB.slice().sort();for(var i=0;i<tmpA.length;i++)if(tmpA[i]!==tmpB[i])return!1;return!0}static print(arr){if(0==arr.length)return"";let s="(";for(let i=0;i<arr.length;i++)s+=arr[i].id?arr[i].id+", ":arr[i]+", ";return s=s.substring(0,s.length-2),s+")"}static each(arr,callback){for(let i=0;i<arr.length;i++)callback(arr[i])}static get(arr,property,value){for(let i=0;i<arr.length;i++)if(arr[i][property]==value)return arr[i]}static contains(arr,options){if(!options.property&&!options.func){for(let i=0;i<arr.length;i++)if(arr[i]==options.value)return!0;}else if(options.func){for(let i=0;i<arr.length;i++)if(options.func(arr[i]))return!0;}else for(let i=0;i<arr.length;i++)if(arr[i][options.property]==options.value)return!0;return!1}static intersection(arrA,arrB){let intersection=[];for(let i=0;i<arrA.length;i++)for(let j=0;j<arrB.length;j++)arrA[i]===arrB[j]&&intersection.push(arrA[i]);return intersection}static unique(arr){let contains={};return arr.filter(function(i){return!(contains[i]!==void 0)&&(contains[i]=!0)})}static count(arr,value){let count=0;for(let i=0;i<arr.length;i++)arr[i]===value&&count++;return count}static toggle(arr,value){let newArr=[],removed=!1;for(let i=0;i<arr.length;i++)arr[i]===value?removed=!0:newArr.push(arr[i]);return removed||newArr.push(value),newArr}static remove(arr,value){let tmp=[];for(let i=0;i<arr.length;i++)arr[i]!==value&&tmp.push(arr[i]);return tmp}static removeUnique(arr,value){let index=arr.indexOf(value);return-1<index&&arr.splice(index,1),arr}static removeAll(arrA,arrB){return arrA.filter(function(item){return-1===arrB.indexOf(item)})}static merge(arrA,arrB){let arr=Array(arrA.length+arrB.length);for(let i=0;i<arrA.length;i++)arr[i]=arrA[i];for(let i=0;i<arrB.length;i++)arr[arrA.length+i]=arrB[i];return arr}static containsAll(arrA,arrB){let containing=0;for(let i=0;i<arrA.length;i++)for(let j=0;j<arrB.length;j++)arrA[i]===arrB[j]&&containing++;return containing===arrB.length}static sortByAtomicNumberDesc(arr){let map=arr.map(function(e,i){return{index:i,value:e.atomicNumber.split(".").map(Number)}});return map.sort(function(a,b){let min=_Mathmin3(b.value.length,a.value.length),i=0;for(;i<min&&b.value[i]===a.value[i];)i++;return i===min?b.value.length-a.value.length:b.value[i]-a.value[i]}),map.map(function(e){return arr[e.index]})}static deepCopy(arr){let newArr=[];for(let i=0,item;i<arr.length;i++)item=arr[i],newArr[i]=item instanceof Array?ArrayHelper.deepCopy(item):item;return newArr}}module.exports=ArrayHelper},{}],4:[function(require,module){"use strict";const ArrayHelper=require("./ArrayHelper"),Vertex=require("./Vertex"),Ring=require("./Ring");class Atom{constructor(element,bondType="-"){this.idx=null,this.element=1===element.length?element.toUpperCase():element,this.drawExplicit=!1,this.ringbonds=[],this.rings=[],this.bondType=bondType,this.branchBond=null,this.isBridge=!1,this.isBridgeNode=!1,this.originalRings=[],this.bridgedRing=null,this.anchoredRings=[],this.bracket=null,this.plane=0,this.attachedPseudoElements={},this.hasAttachedPseudoElements=!1,this.isDrawn=!0,this.isConnectedToRing=!1,this.neighbouringElements=[],this.isPartOfAromaticRing=element!==this.element,this.bondCount=0,this.chirality="",this.isStereoCenter=!1,this.priority=0,this.mainChain=!1,this.hydrogenDirection="down",this.subtreeDepth=1,this.hasHydrogen=!1,this.class=void 0}addNeighbouringElement(element){this.neighbouringElements.push(element)}attachPseudoElement(element,previousElement,hydrogenCount=0,charge=0){null===hydrogenCount&&(hydrogenCount=0),null===charge&&(charge=0);let key=hydrogenCount+element+charge;this.attachedPseudoElements[key]?this.attachedPseudoElements[key].count+=1:this.attachedPseudoElements[key]={element:element,count:1,hydrogenCount:hydrogenCount,previousElement:previousElement,charge:charge},this.hasAttachedPseudoElements=!0}getAttachedPseudoElements(){let ordered={},that=this;return Object.keys(this.attachedPseudoElements).sort().forEach(function(key){ordered[key]=that.attachedPseudoElements[key]}),ordered}getAttachedPseudoElementsCount(){return Object.keys(this.attachedPseudoElements).length}isHeteroAtom(){return"C"!==this.element&&"H"!==this.element}addAnchoredRing(ringId){ArrayHelper.contains(this.anchoredRings,{value:ringId})||this.anchoredRings.push(ringId)}getRingbondCount(){return this.ringbonds.length}backupRings(){this.originalRings=Array(this.rings.length);for(let i=0;i<this.rings.length;i++)this.originalRings[i]=this.rings[i]}restoreRings(){this.rings=Array(this.originalRings.length);for(let i=0;i<this.originalRings.length;i++)this.rings[i]=this.originalRings[i]}haveCommonRingbond(atomA,atomB){for(let i=0;i<atomA.ringbonds.length;i++)for(let j=0;j<atomB.ringbonds.length;j++)if(atomA.ringbonds[i].id==atomB.ringbonds[j].id)return!0;return!1}neighbouringElementsEqual(arr){if(arr.length!==this.neighbouringElements.length)return!1;arr.sort(),this.neighbouringElements.sort();for(var i=0;i<this.neighbouringElements.length;i++)if(arr[i]!==this.neighbouringElements[i])return!1;return!0}getAtomicNumber(){return Atom.atomicNumbers[this.element]}getMaxBonds(){return Atom.maxBonds[this.element]}static get maxBonds(){return{H:1,C:4,N:3,O:2,P:3,S:2,B:3,F:1,I:1,Cl:1,Br:1}}static get atomicNumbers(){return{H:1,He:2,Li:3,Be:4,B:5,b:5,C:6,c:6,N:7,n:7,O:8,o:8,F:9,Ne:10,Na:11,Mg:12,Al:13,Si:14,P:15,p:15,S:16,s:16,Cl:17,Ar:18,K:19,Ca:20,Sc:21,Ti:22,V:23,Cr:24,Mn:25,Fe:26,Co:27,Ni:28,Cu:29,Zn:30,Ga:31,Ge:32,As:33,Se:34,Br:35,Kr:36,Rb:37,Sr:38,Y:39,Zr:40,Nb:41,Mo:42,Tc:43,Ru:44,Rh:45,Pd:46,Ag:47,Cd:48,In:49,Sn:50,Sb:51,Te:52,I:53,Xe:54,Cs:55,Ba:56,La:57,Ce:58,Pr:59,Nd:60,Pm:61,Sm:62,Eu:63,Gd:64,Tb:65,Dy:66,Ho:67,Er:68,Tm:69,Yb:70,Lu:71,Hf:72,Ta:73,W:74,Re:75,Os:76,Ir:77,Pt:78,Au:79,Hg:80,Tl:81,Pb:82,Bi:83,Po:84,At:85,Rn:86,Fr:87,Ra:88,Ac:89,Th:90,Pa:91,U:92,Np:93,Pu:94,Am:95,Cm:96,Bk:97,Cf:98,Es:99,Fm:100,Md:101,No:102,Lr:103,Rf:104,Db:105,Sg:106,Bh:107,Hs:108,Mt:109,Ds:110,Rg:111,Cn:112,Uut:113,Uuq:114,Uup:115,Uuh:116,Uus:117,Uuo:118}}static get mass(){return{H:1,He:2,Li:3,Be:4,B:5,b:5,C:6,c:6,N:7,n:7,O:8,o:8,F:9,Ne:10,Na:11,Mg:12,Al:13,Si:14,P:15,p:15,S:16,s:16,Cl:17,Ar:18,K:19,Ca:20,Sc:21,Ti:22,V:23,Cr:24,Mn:25,Fe:26,Co:27,Ni:28,Cu:29,Zn:30,Ga:31,Ge:32,As:33,Se:34,Br:35,Kr:36,Rb:37,Sr:38,Y:39,Zr:40,Nb:41,Mo:42,Tc:43,Ru:44,Rh:45,Pd:46,Ag:47,Cd:48,In:49,Sn:50,Sb:51,Te:52,I:53,Xe:54,Cs:55,Ba:56,La:57,Ce:58,Pr:59,Nd:60,Pm:61,Sm:62,Eu:63,Gd:64,Tb:65,Dy:66,Ho:67,Er:68,Tm:69,Yb:70,Lu:71,Hf:72,Ta:73,W:74,Re:75,Os:76,Ir:77,Pt:78,Au:79,Hg:80,Tl:81,Pb:82,Bi:83,Po:84,At:85,Rn:86,Fr:87,Ra:88,Ac:89,Th:90,Pa:91,U:92,Np:93,Pu:94,Am:95,Cm:96,Bk:97,Cf:98,Es:99,Fm:100,Md:101,No:102,Lr:103,Rf:104,Db:105,Sg:106,Bh:107,Hs:108,Mt:109,Ds:110,Rg:111,Cn:112,Uut:113,Uuq:114,Uup:115,Uuh:116,Uus:117,Uuo:118}}}module.exports=Atom},{"./ArrayHelper":3,"./Ring":20,"./Vertex":29}],5:[function(require,module){"use strict";var _NumberMAX_VALUE2=Number.MAX_VALUE;const MathHelper=require("./MathHelper"),Vector2=require("./Vector2"),Line=require("./Line"),Vertex=require("./Vertex"),Ring=require("./Ring"),{getChargeText}=require("./UtilityFunctions");module.exports=class{constructor(target,themeManager,options){this.canvas="string"==typeof target||target instanceof String?document.getElementById(target):target,this.ctx=this.canvas.getContext("2d"),this.themeManager=themeManager,this.opts=options,this.drawingWidth=0,this.drawingHeight=0,this.offsetX=0,this.offsetY=0,this.fontLarge=this.opts.fontSizeLarge+"pt Helvetica, Arial, sans-serif",this.fontSmall=this.opts.fontSizeSmall+"pt Helvetica, Arial, sans-serif",this.updateSize(this.opts.width,this.opts.height),this.ctx.font=this.fontLarge,this.hydrogenWidth=this.ctx.measureText("H").width,this.halfHydrogenWidth=this.hydrogenWidth/2,this.halfBondThickness=this.opts.bondThickness/2}updateSize(width,height){this.devicePixelRatio=window.devicePixelRatio||1,this.backingStoreRatio=this.ctx.webkitBackingStorePixelRatio||this.ctx.mozBackingStorePixelRatio||this.ctx.msBackingStorePixelRatio||this.ctx.oBackingStorePixelRatio||this.ctx.backingStorePixelRatio||1,this.ratio=this.devicePixelRatio/this.backingStoreRatio,1===this.ratio?(this.canvas.width=width*this.ratio,this.canvas.height=height*this.ratio):(this.canvas.width=width*this.ratio,this.canvas.height=height*this.ratio,this.canvas.style.width=width+"px",this.canvas.style.height=height+"px",this.ctx.setTransform(this.ratio,0,0,this.ratio,0,0))}setTheme(theme){this.colors=theme}scale(vertices){let maxX=-_NumberMAX_VALUE2,maxY=-_NumberMAX_VALUE2,minX=_NumberMAX_VALUE2,minY=_NumberMAX_VALUE2;for(var i=0;i<vertices.length;i++){if(!vertices[i].value.isDrawn)continue;let p=vertices[i].position;maxX<p.x&&(maxX=p.x),maxY<p.y&&(maxY=p.y),minX>p.x&&(minX=p.x),minY>p.y&&(minY=p.y)}var padding=this.opts.padding;maxX+=padding,maxY+=padding,minX-=padding,minY-=padding,this.drawingWidth=maxX-minX,this.drawingHeight=maxY-minY;var scaleX=this.canvas.offsetWidth/this.drawingWidth,scaleY=this.canvas.offsetHeight/this.drawingHeight,scale=scaleX<scaleY?scaleX:scaleY;this.ctx.scale(scale,scale),this.offsetX=-minX,this.offsetY=-minY,scaleX<scaleY?this.offsetY+=this.canvas.offsetHeight/(2*scale)-this.drawingHeight/2:this.offsetX+=this.canvas.offsetWidth/(2*scale)-this.drawingWidth/2}reset(){this.ctx.setTransform(1,0,0,1,0,0)}getColor(key){return key=key.toUpperCase(),key in this.colors?this.colors[key]:this.colors.C}drawCircle(x,y,radius,color,fill=!0,debug=!1,debugText=""){let ctx=this.ctx,offsetX=this.offsetX,offsetY=this.offsetY;ctx.save(),ctx.lineWidth=1.5,ctx.beginPath(),ctx.arc(x+offsetX,y+offsetY,radius,0,MathHelper.twoPI,!0),ctx.closePath(),debug?(fill?(ctx.fillStyle="#f00",ctx.fill()):(ctx.strokeStyle="#f00",ctx.stroke()),this.drawDebugText(x,y,debugText)):fill?(ctx.fillStyle=color,ctx.fill()):(ctx.strokeStyle=color,ctx.stroke()),ctx.restore()}drawLine(line,dashed=!1,alpha=1){let ctx=this.ctx,offsetX=this.offsetX,offsetY=this.offsetY,shortLine=line.clone().shorten(4),l=shortLine.getLeftVector().clone(),r=shortLine.getRightVector().clone();l.x+=offsetX,l.y+=offsetY,r.x+=offsetX,r.y+=offsetY,dashed||(ctx.save(),ctx.globalCompositeOperation="destination-out",ctx.beginPath(),ctx.moveTo(l.x,l.y),ctx.lineTo(r.x,r.y),ctx.lineCap="round",ctx.lineWidth=this.opts.bondThickness+1.2,ctx.strokeStyle=this.themeManager.getColor("BACKGROUND"),ctx.stroke(),ctx.globalCompositeOperation="source-over",ctx.restore()),l=line.getLeftVector().clone(),r=line.getRightVector().clone(),l.x+=offsetX,l.y+=offsetY,r.x+=offsetX,r.y+=offsetY,ctx.save(),ctx.beginPath(),ctx.moveTo(l.x,l.y),ctx.lineTo(r.x,r.y),ctx.lineCap="round",ctx.lineWidth=this.opts.bondThickness;let gradient=this.ctx.createLinearGradient(l.x,l.y,r.x,r.y);gradient.addColorStop(.4,this.themeManager.getColor(line.getLeftElement())||this.themeManager.getColor("C")),gradient.addColorStop(.6,this.themeManager.getColor(line.getRightElement())||this.themeManager.getColor("C")),dashed&&(ctx.setLineDash([1,1.5]),ctx.lineWidth=this.opts.bondThickness/1.5),1>alpha&&(ctx.globalAlpha=alpha),ctx.strokeStyle=gradient,ctx.stroke(),ctx.restore()}drawWedge(line,width=1){if(isNaN(line.from.x)||isNaN(line.from.y)||isNaN(line.to.x)||isNaN(line.to.y))return;let ctx=this.ctx,offsetX=this.offsetX,offsetY=this.offsetY,shortLine=line.clone().shorten(5),l=shortLine.getLeftVector().clone(),r=shortLine.getRightVector().clone();l.x+=offsetX,l.y+=offsetY,r.x+=offsetX,r.y+=offsetY,l=line.getLeftVector().clone(),r=line.getRightVector().clone(),l.x+=offsetX,l.y+=offsetY,r.x+=offsetX,r.y+=offsetY,ctx.save();let normals=Vector2.normals(l,r);normals[0].normalize(),normals[1].normalize();let isRightChiralCenter=line.getRightChiral(),start=l,end=r;isRightChiralCenter&&(start=r,end=l);let t=Vector2.add(start,Vector2.multiplyScalar(normals[0],this.halfBondThickness)),u=Vector2.add(end,Vector2.multiplyScalar(normals[0],1.5+this.halfBondThickness)),v=Vector2.add(end,Vector2.multiplyScalar(normals[1],1.5+this.halfBondThickness)),w=Vector2.add(start,Vector2.multiplyScalar(normals[1],this.halfBondThickness));ctx.beginPath(),ctx.moveTo(t.x,t.y),ctx.lineTo(u.x,u.y),ctx.lineTo(v.x,v.y),ctx.lineTo(w.x,w.y);let gradient=this.ctx.createRadialGradient(r.x,r.y,this.opts.bondLength,r.x,r.y,0);gradient.addColorStop(.4,this.themeManager.getColor(line.getLeftElement())||this.themeManager.getColor("C")),gradient.addColorStop(.6,this.themeManager.getColor(line.getRightElement())||this.themeManager.getColor("C")),ctx.fillStyle=gradient,ctx.fill(),ctx.restore()}drawDashedWedge(line){if(isNaN(line.from.x)||isNaN(line.from.y)||isNaN(line.to.x)||isNaN(line.to.y))return;let ctx=this.ctx,offsetX=this.offsetX,offsetY=this.offsetY,l=line.getLeftVector().clone(),r=line.getRightVector().clone();l.x+=offsetX,l.y+=offsetY,r.x+=offsetX,r.y+=offsetY,ctx.save();let normals=Vector2.normals(l,r);normals[0].normalize(),normals[1].normalize();let isRightChiralCenter=line.getRightChiral(),shortLine=line.clone(),start,end,sStart,sEnd;isRightChiralCenter?(start=r,end=l,shortLine.shortenRight(1),sStart=shortLine.getRightVector().clone(),sEnd=shortLine.getLeftVector().clone()):(start=l,end=r,shortLine.shortenLeft(1),sStart=shortLine.getLeftVector().clone(),sEnd=shortLine.getRightVector().clone()),sStart.x+=offsetX,sStart.y+=offsetY,sEnd.x+=offsetX,sEnd.y+=offsetY;let dir=Vector2.subtract(end,start).normalize();ctx.strokeStyle=this.themeManager.getColor("C"),ctx.lineCap="round",ctx.lineWidth=this.opts.bondThickness,ctx.beginPath();let length=line.getLength(),step=1.25/(length/(3*this.opts.bondThickness)),changed=!1;for(var t=0;1>t;t+=step){let to=Vector2.multiplyScalar(dir,t*length),startDash=Vector2.add(start,to),width=1.5*t,dashOffset=Vector2.multiplyScalar(normals[0],width);!changed&&.5<t&&(ctx.stroke(),ctx.beginPath(),ctx.strokeStyle=this.themeManager.getColor(line.getRightElement())||this.themeManager.getColor("C"),changed=!0),startDash.subtract(dashOffset),ctx.moveTo(startDash.x,startDash.y),startDash.add(Vector2.multiplyScalar(dashOffset,2)),ctx.lineTo(startDash.x,startDash.y)}ctx.stroke(),ctx.restore()}drawDebugText(x,y,text){let ctx=this.ctx;ctx.save(),ctx.font="5px Droid Sans, sans-serif",ctx.textAlign="start",ctx.textBaseline="top",ctx.fillStyle="#ff0000",ctx.fillText(text,x+this.offsetX,y+this.offsetY),ctx.restore()}drawBall(x,y,elementName){let ctx=this.ctx;ctx.save(),ctx.beginPath(),ctx.arc(x+this.offsetX,y+this.offsetY,this.opts.bondLength/4.5,0,MathHelper.twoPI,!1),ctx.fillStyle=this.themeManager.getColor(elementName),ctx.fill(),ctx.restore()}drawPoint(x,y,elementName){let ctx=this.ctx,offsetX=this.offsetX,offsetY=this.offsetY;ctx.save(),ctx.globalCompositeOperation="destination-out",ctx.beginPath(),ctx.arc(x+offsetX,y+offsetY,1.5,0,MathHelper.twoPI,!0),ctx.closePath(),ctx.fill(),ctx.globalCompositeOperation="source-over",ctx.beginPath(),ctx.arc(x+this.offsetX,y+this.offsetY,.75,0,MathHelper.twoPI,!1),ctx.fillStyle=this.themeManager.getColor(elementName),ctx.fill(),ctx.restore()}drawText(x,y,elementName,hydrogens,direction,isTerminal,charge,isotope,vertexCount,attachedPseudoElement={}){let ctx=this.ctx,offsetX=this.offsetX,offsetY=this.offsetY;ctx.save(),ctx.textAlign="start",ctx.textBaseline="alphabetic";let chargeText="",chargeWidth=0;charge&&(chargeText=getChargeText(charge),ctx.font=this.fontSmall,chargeWidth=ctx.measureText(chargeText).width);let isotopeText="0",isotopeWidth=0;0<isotope&&(isotopeText=isotope.toString(),ctx.font=this.fontSmall,isotopeWidth=ctx.measureText(isotopeText).width),1===charge&&"N"===elementName&&attachedPseudoElement.hasOwnProperty("0O")&&attachedPseudoElement.hasOwnProperty("0O-1")&&(attachedPseudoElement={"0O":{element:"O",count:2,hydrogenCount:0,previousElement:"C",charge:""}},charge=0),ctx.font=this.fontLarge,ctx.fillStyle=this.themeManager.getColor("BACKGROUND");let dim=ctx.measureText(elementName);dim.totalWidth=dim.width+chargeWidth,dim.height=parseInt(this.fontLarge,10);let r=dim.width>this.opts.fontSizeLarge?dim.width:this.opts.fontSizeLarge;r/=1.5,ctx.globalCompositeOperation="destination-out",ctx.beginPath(),ctx.arc(x+offsetX,y+offsetY,r,0,MathHelper.twoPI,!0),ctx.closePath(),ctx.fill(),ctx.globalCompositeOperation="source-over";let cursorPos=-dim.width/2,cursorPosLeft=-dim.width/2;ctx.fillStyle=this.themeManager.getColor(elementName),ctx.fillText(elementName,x+offsetX+cursorPos,y+this.opts.halfFontSizeLarge+offsetY),cursorPos+=dim.width,charge&&(ctx.font=this.fontSmall,ctx.fillText(chargeText,x+offsetX+cursorPos,y-this.opts.fifthFontSizeSmall+offsetY),cursorPos+=chargeWidth),0<isotope&&(ctx.font=this.fontSmall,ctx.fillText(isotopeText,x+offsetX+cursorPosLeft-isotopeWidth,y-this.opts.fifthFontSizeSmall+offsetY),cursorPosLeft-=isotopeWidth),ctx.font=this.fontLarge;let hydrogenWidth=0,hydrogenCountWidth=0;if(1===hydrogens){let hx=x+offsetX,hy=y+offsetY+this.opts.halfFontSizeLarge;hydrogenWidth=this.hydrogenWidth,cursorPosLeft-=hydrogenWidth,"left"===direction?hx+=cursorPosLeft:"right"===direction?hx+=cursorPos:"up"===direction&&isTerminal?hx+=cursorPos:"down"===direction&&isTerminal?hx+=cursorPos:"up"!==direction||isTerminal?"down"===direction&&!isTerminal&&(hy+=this.opts.fontSizeLarge+this.opts.quarterFontSizeLarge,hx-=this.halfHydrogenWidth):(hy-=this.opts.fontSizeLarge+this.opts.quarterFontSizeLarge,hx-=this.halfHydrogenWidth),ctx.fillText("H",hx,hy),cursorPos+=hydrogenWidth}else if(1<hydrogens){let hx=x+offsetX,hy=y+offsetY+this.opts.halfFontSizeLarge;hydrogenWidth=this.hydrogenWidth,ctx.font=this.fontSmall,hydrogenCountWidth=ctx.measureText(hydrogens).width,cursorPosLeft-=hydrogenWidth+hydrogenCountWidth,"left"===direction?hx+=cursorPosLeft:"right"===direction?hx+=cursorPos:"up"===direction&&isTerminal?hx+=cursorPos:"down"===direction&&isTerminal?hx+=cursorPos:"up"!==direction||isTerminal?"down"===direction&&!isTerminal&&(hy+=this.opts.fontSizeLarge+this.opts.quarterFontSizeLarge,hx-=this.halfHydrogenWidth):(hy-=this.opts.fontSizeLarge+this.opts.quarterFontSizeLarge,hx-=this.halfHydrogenWidth),ctx.font=this.fontLarge,ctx.fillText("H",hx,hy),ctx.font=this.fontSmall,ctx.fillText(hydrogens,hx+this.halfHydrogenWidth+hydrogenCountWidth,hy+this.opts.fifthFontSizeSmall),cursorPos+=hydrogenWidth+this.halfHydrogenWidth+hydrogenCountWidth}for(let key in attachedPseudoElement){if(!attachedPseudoElement.hasOwnProperty(key))continue;let openParenthesisWidth=0,closeParenthesisWidth=0,element=attachedPseudoElement[key].element,elementCount=attachedPseudoElement[key].count,hydrogenCount=attachedPseudoElement[key].hydrogenCount,elementCharge=attachedPseudoElement[key].charge;ctx.font=this.fontLarge,1<elementCount&&0<hydrogenCount&&(openParenthesisWidth=ctx.measureText("(").width,closeParenthesisWidth=ctx.measureText(")").width);let elementWidth=ctx.measureText(element).width,elementCountWidth=0,elementChargeText="",elementChargeWidth=0;hydrogenWidth=0,0<hydrogenCount&&(hydrogenWidth=this.hydrogenWidth),ctx.font=this.fontSmall,1<elementCount&&(elementCountWidth=ctx.measureText(elementCount).width),0!==elementCharge&&(elementChargeText=getChargeText(elementCharge),elementChargeWidth=ctx.measureText(elementChargeText).width),hydrogenCountWidth=0,1<hydrogenCount&&(hydrogenCountWidth=ctx.measureText(hydrogenCount).width),ctx.font=this.fontLarge;let hx=x+offsetX,hy=y+offsetY+this.opts.halfFontSizeLarge;ctx.fillStyle=this.themeManager.getColor(element),0<elementCount&&(cursorPosLeft-=elementCountWidth),1<elementCount&&0<hydrogenCount&&("left"===direction?(cursorPosLeft-=closeParenthesisWidth,ctx.fillText(")",hx+cursorPosLeft,hy)):(ctx.fillText("(",hx+cursorPos,hy),cursorPos+=openParenthesisWidth)),"left"===direction?(cursorPosLeft-=elementWidth,ctx.fillText(element,hx+cursorPosLeft,hy)):(ctx.fillText(element,hx+cursorPos,hy),cursorPos+=elementWidth),0<hydrogenCount&&("left"===direction?(cursorPosLeft-=hydrogenWidth+hydrogenCountWidth,ctx.fillText("H",hx+cursorPosLeft,hy),1<hydrogenCount&&(ctx.font=this.fontSmall,ctx.fillText(hydrogenCount,hx+cursorPosLeft+hydrogenWidth,hy+this.opts.fifthFontSizeSmall))):(ctx.fillText("H",hx+cursorPos,hy),cursorPos+=hydrogenWidth,1<hydrogenCount&&(ctx.font=this.fontSmall,ctx.fillText(hydrogenCount,hx+cursorPos,hy+this.opts.fifthFontSizeSmall),cursorPos+=hydrogenCountWidth))),ctx.font=this.fontLarge,1<elementCount&&0<hydrogenCount&&("left"===direction?(cursorPosLeft-=openParenthesisWidth,ctx.fillText("(",hx+cursorPosLeft,hy)):(ctx.fillText(")",hx+cursorPos,hy),cursorPos+=closeParenthesisWidth)),ctx.font=this.fontSmall,1<elementCount&&("left"===direction?ctx.fillText(elementCount,hx+cursorPosLeft+openParenthesisWidth+closeParenthesisWidth+hydrogenWidth+hydrogenCountWidth+elementWidth,hy+this.opts.fifthFontSizeSmall):(ctx.fillText(elementCount,hx+cursorPos,hy+this.opts.fifthFontSizeSmall),cursorPos+=elementCountWidth)),0!==elementCharge&&("left"===direction?ctx.fillText(elementChargeText,hx+cursorPosLeft+openParenthesisWidth+closeParenthesisWidth+hydrogenWidth+hydrogenCountWidth+elementWidth,y-this.opts.fifthFontSizeSmall+offsetY):(ctx.fillText(elementChargeText,hx+cursorPos,y-this.opts.fifthFontSizeSmall+offsetY),cursorPos+=elementChargeWidth))}ctx.restore()}getChargeText(charge){return 1===charge?"+":2===charge?"2+":-1===charge?"-":-2===charge?"2-":""}drawDebugPoint(x,y,debugText="",color="#f00"){this.drawCircle(x,y,2,color,!0,!0,debugText)}drawAromaticityRing(ring){let ctx=this.ctx,radius=MathHelper.apothemFromSideLength(this.opts.bondLength,ring.getSize());ctx.save(),ctx.strokeStyle=this.themeManager.getColor("C"),ctx.lineWidth=this.opts.bondThickness,ctx.beginPath(),ctx.arc(ring.center.x+this.offsetX,ring.center.y+this.offsetY,radius-this.opts.bondSpacing,0,2*Math.PI,!0),ctx.closePath(),ctx.stroke(),ctx.restore()}clear(){this.ctx.clearRect(0,0,this.canvas.offsetWidth,this.canvas.offsetHeight)}}},{"./Line":12,"./MathHelper":13,"./Ring":20,"./UtilityFunctions":27,"./Vector2":28,"./Vertex":29}],6:[function(require,module){"use strict";const SvgDrawer=require("./SvgDrawer");module.exports=class{constructor(options){this.svgDrawer=new SvgDrawer(options)}draw(data,target,themeName="light",infoOnly=!1,highlight_atoms=[]){let canvas=null;canvas="string"==typeof target||target instanceof String?document.getElementById(target):target;let svg=document.createElementNS("http://www.w3.org/2000/svg","svg");svg.setAttribute("xmlns","http://www.w3.org/2000/svg"),svg.setAttributeNS(null,"viewBox","0 0 "+this.svgDrawer.opts.width+" "+this.svgDrawer.opts.height),svg.setAttributeNS(null,"width",this.svgDrawer.opts.width+""),svg.setAttributeNS(null,"height",this.svgDrawer.opts.height+""),this.svgDrawer.draw(data,svg,themeName,infoOnly,highlight_atoms),this.svgDrawer.svgWrapper.toCanvas(canvas,this.svgDrawer.opts.width,this.svgDrawer.opts.height)}getTotalOverlapScore(){return this.svgDrawer.getTotalOverlapScore()}getMolecularFormula(){this.svgDrawer.getMolecularFormula()}}},{"./SvgDrawer":24}],7:[function(require,module){"use strict";var _Mathsin2=Math.sin,_Mathcos2=Math.cos,_Mathsqrt2=Math.sqrt,_MathPI2=Math.PI,_Mathabs2=Math.abs,_Mathmin4=Math.min,_Mathmax3=Math.max;const MathHelper=require("./MathHelper"),ArrayHelper=require("./ArrayHelper"),Vector2=require("./Vector2"),Line=require("./Line"),Vertex=require("./Vertex"),Edge=require("./Edge"),Atom=require("./Atom"),Ring=require("./Ring"),RingConnection=require("./RingConnection"),CanvasWrapper=require("./CanvasWrapper"),Graph=require("./Graph"),SSSR=require("./SSSR"),ThemeManager=require("./ThemeManager"),Options=require("./Options");module.exports=class{constructor(options){this.graph=null,this.doubleBondConfigCount=0,this.doubleBondConfig=null,this.ringIdCounter=0,this.ringConnectionIdCounter=0,this.canvasWrapper=null,this.totalOverlapScore=0,this.defaultOptions={width:500,height:500,scale:0,bondThickness:1,bondLength:30,shortBondLength:.8,bondSpacing:30*.17,atomVisualization:"default",isomeric:!0,debug:!1,terminalCarbons:!1,explicitHydrogens:!0,overlapSensitivity:.42,overlapResolutionIterations:1,compactDrawing:!0,fontFamily:"Arial, Helvetica, sans-serif",fontSizeLarge:11,fontSizeSmall:3,padding:10,experimentalSSSR:!1,kkThreshold:.1,kkInnerThreshold:.1,kkMaxIteration:2e4,kkMaxInnerIteration:50,kkMaxEnergy:1e9,weights:{colormap:null,additionalPadding:20,sigma:10,interval:0,opacity:1},themes:{dark:{C:"#fff",O:"#e74c3c",N:"#3498db",F:"#27ae60",CL:"#16a085",BR:"#d35400",I:"#8e44ad",P:"#d35400",S:"#f1c40f",B:"#e67e22",SI:"#e67e22",H:"#aaa",BACKGROUND:"#141414"},light:{C:"#222",O:"#e74c3c",N:"#3498db",F:"#27ae60",CL:"#16a085",BR:"#d35400",I:"#8e44ad",P:"#d35400",S:"#f1c40f",B:"#e67e22",SI:"#e67e22",H:"#666",BACKGROUND:"#fff"},oldschool:{C:"#000",O:"#000",N:"#000",F:"#000",CL:"#000",BR:"#000",I:"#000",P:"#000",S:"#000",B:"#000",SI:"#000",H:"#000",BACKGROUND:"#fff"},solarized:{C:"#586e75",O:"#dc322f",N:"#268bd2",F:"#859900",CL:"#16a085",BR:"#cb4b16",I:"#6c71c4",P:"#d33682",S:"#b58900",B:"#2aa198",SI:"#2aa198",H:"#657b83",BACKGROUND:"#fff"},"solarized-dark":{C:"#93a1a1",O:"#dc322f",N:"#268bd2",F:"#859900",CL:"#16a085",BR:"#cb4b16",I:"#6c71c4",P:"#d33682",S:"#b58900",B:"#2aa198",SI:"#2aa198",H:"#839496",BACKGROUND:"#fff"},matrix:{C:"#678c61",O:"#2fc079",N:"#4f7e7e",F:"#90d762",CL:"#82d967",BR:"#23755a",I:"#409931",P:"#c1ff8a",S:"#faff00",B:"#50b45a",SI:"#409931",H:"#426644",BACKGROUND:"#fff"},github:{C:"#24292f",O:"#cf222e",N:"#0969da",F:"#2da44e",CL:"#6fdd8b",BR:"#bc4c00",I:"#8250df",P:"#bf3989",S:"#d4a72c",B:"#fb8f44",SI:"#bc4c00",H:"#57606a",BACKGROUND:"#fff"},carbon:{C:"#161616",O:"#da1e28",N:"#0f62fe",F:"#198038",CL:"#007d79",BR:"#fa4d56",I:"#8a3ffc",P:"#ff832b",S:"#f1c21b",B:"#8a3800",SI:"#e67e22",H:"#525252",BACKGROUND:"#fff"},cyberpunk:{C:"#ea00d9",O:"#ff3131",N:"#0abdc6",F:"#00ff9f",CL:"#00fe00",BR:"#fe9f20",I:"#ff00ff",P:"#fe7f00",S:"#fcee0c",B:"#ff00ff",SI:"#ffffff",H:"#913cb1",BACKGROUND:"#fff"},gruvbox:{C:"#665c54",O:"#cc241d",N:"#458588",F:"#98971a",CL:"#79740e",BR:"#d65d0e",I:"#b16286",P:"#af3a03",S:"#d79921",B:"#689d6a",SI:"#427b58",H:"#7c6f64",BACKGROUND:"#fbf1c7"},"gruvbox-dark":{C:"#ebdbb2",O:"#cc241d",N:"#458588",F:"#98971a",CL:"#b8bb26",BR:"#d65d0e",I:"#b16286",P:"#fe8019",S:"#d79921",B:"#8ec07c",SI:"#83a598",H:"#bdae93",BACKGROUND:"#282828"},custom:{C:"#222",O:"#e74c3c",N:"#3498db",F:"#27ae60",CL:"#16a085",BR:"#d35400",I:"#8e44ad",P:"#d35400",S:"#f1c40f",B:"#e67e22",SI:"#e67e22",H:"#666",BACKGROUND:"#fff"}}},this.opts=Options.extend(!0,this.defaultOptions,options),this.opts.halfBondSpacing=this.opts.bondSpacing/2,this.opts.bondLengthSq=this.opts.bondLength*this.opts.bondLength,this.opts.halfFontSizeLarge=this.opts.fontSizeLarge/2,this.opts.quarterFontSizeLarge=this.opts.fontSizeLarge/4,this.opts.fifthFontSizeSmall=this.opts.fontSizeSmall/5,this.theme=this.opts.themes.dark}draw(data,target,themeName="light",infoOnly=!1){this.initDraw(data,themeName,infoOnly),this.infoOnly||(this.themeManager=new ThemeManager(this.opts.themes,themeName),this.canvasWrapper=new CanvasWrapper(target,this.themeManager,this.opts)),infoOnly||(this.processGraph(),this.canvasWrapper.scale(this.graph.vertices),this.drawEdges(this.opts.debug),this.drawVertices(this.opts.debug),this.canvasWrapper.reset(),this.opts.debug&&(console.log(this.graph),console.log(this.rings),console.log(this.ringConnections)))}edgeRingCount(edgeId){let edge=this.graph.edges[edgeId],a=this.graph.vertices[edge.sourceId],b=this.graph.vertices[edge.targetId];return _Mathmin4(a.value.rings.length,b.value.rings.length)}getBridgedRings(){let bridgedRings=[];for(var i=0;i<this.rings.length;i++)this.rings[i].isBridged&&bridgedRings.push(this.rings[i]);return bridgedRings}getFusedRings(){let fusedRings=[];for(var i=0;i<this.rings.length;i++)this.rings[i].isFused&&fusedRings.push(this.rings[i]);return fusedRings}getSpiros(){let spiros=[];for(var i=0;i<this.rings.length;i++)this.rings[i].isSpiro&&spiros.push(this.rings[i]);return spiros}printRingInfo(){let result="";for(var i=0;i<this.rings.length;i++){const ring=this.rings[i];result+=ring.id+";",result+=ring.members.length+";",result+=ring.neighbours.length+";",result+=ring.isSpiro?"true;":"false;",result+=ring.isFused?"true;":"false;",result+=ring.isBridged?"true;":"false;",result+=ring.rings.length+";",result+="\n"}return result}rotateDrawing(){let a=0,b=0,maxDist=0;for(var i=0;i<this.graph.vertices.length;i++){let vertexA=this.graph.vertices[i];if(vertexA.value.isDrawn)for(var j=i+1;j<this.graph.vertices.length;j++){let vertexB=this.graph.vertices[j];if(!vertexB.value.isDrawn)continue;let dist=vertexA.position.distanceSq(vertexB.position);dist>maxDist&&(maxDist=dist,a=i,b=j)}}let angle=-Vector2.subtract(this.graph.vertices[a].position,this.graph.vertices[b].position).angle();if(!isNaN(angle)){let remainder=angle%.523599;.2617995>remainder?angle-=remainder:angle+=.523599-remainder;for(var i=0;i<this.graph.vertices.length;i++)i!==b&&this.graph.vertices[i].position.rotateAround(angle,this.graph.vertices[b].position);for(var i=0;i<this.rings.length;i++)this.rings[i].center.rotateAround(angle,this.graph.vertices[b].position)}}getTotalOverlapScore(){return this.totalOverlapScore}getRingCount(){return this.rings.length}hasBridgedRing(){return this.bridgedRing}getHeavyAtomCount(){let hac=0;for(var i=0;i<this.graph.vertices.length;i++)"H"!==this.graph.vertices[i].value.element&&hac++;return hac}getMolecularFormula(data=null){let molecularFormula="",counts=new Map,graph=null===data?this.graph:new Graph(data,this.opts.isomeric);for(var i=0;i<graph.vertices.length;i++){let atom=graph.vertices[i].value;if(counts.has(atom.element)?counts.set(atom.element,counts.get(atom.element)+1):counts.set(atom.element,1),atom.bracket&&!atom.bracket.chirality&&(counts.has("H")?counts.set("H",counts.get("H")+atom.bracket.hcount):counts.set("H",atom.bracket.hcount)),!atom.bracket){let nHydrogens=Atom.maxBonds[atom.element]-atom.bondCount;atom.isPartOfAromaticRing&&nHydrogens--,counts.has("H")?counts.set("H",counts.get("H")+nHydrogens):counts.set("H",nHydrogens)}}if(counts.has("C")){let count=counts.get("C");molecularFormula+="C"+(1<count?count:""),counts.delete("C")}if(counts.has("H")){let count=counts.get("H");molecularFormula+="H"+(1<count?count:""),counts.delete("H")}let elements=Object.keys(Atom.atomicNumbers).sort();return elements.map(e=>{if(counts.has(e)){let count=counts.get(e);molecularFormula+=e+(1<count?count:"")}}),molecularFormula}getRingbondType(vertexA,vertexB){if(1>vertexA.value.getRingbondCount()||1>vertexB.value.getRingbondCount())return null;for(var i=0;i<vertexA.value.ringbonds.length;i++)for(var j=0;j<vertexB.value.ringbonds.length;j++)if(vertexA.value.ringbonds[i].id===vertexB.value.ringbonds[j].id)return"-"===vertexA.value.ringbonds[i].bondType?vertexB.value.ringbonds[j].bond:vertexA.value.ringbonds[i].bond;return null}initDraw(data,themeName,infoOnly,highlight_atoms){this.data=data,this.infoOnly=infoOnly,this.ringIdCounter=0,this.ringConnectionIdCounter=0,this.graph=new Graph(data,this.opts.isomeric),this.rings=[],this.ringConnections=[],this.originalRings=[],this.originalRingConnections=[],this.bridgedRing=!1,this.doubleBondConfigCount=null,this.doubleBondConfig=null,this.highlight_atoms=highlight_atoms,this.initRings(),this.initHydrogens()}processGraph(){this.position(),this.restoreRingInformation(),this.resolvePrimaryOverlaps();let overlapScore=this.getOverlapScore();this.totalOverlapScore=this.getOverlapScore().total;for(var o=0;o<this.opts.overlapResolutionIterations;o++)for(var i=0;i<this.graph.edges.length;i++){let edge=this.graph.edges[i];if(this.isEdgeRotatable(edge)){let subTreeDepthA=this.graph.getTreeDepth(edge.sourceId,edge.targetId),subTreeDepthB=this.graph.getTreeDepth(edge.targetId,edge.sourceId),a=edge.targetId,b=edge.sourceId;subTreeDepthA>subTreeDepthB&&(a=edge.sourceId,b=edge.targetId);let subTreeOverlap=this.getSubtreeOverlapScore(b,a,overlapScore.vertexScores);if(subTreeOverlap.value>this.opts.overlapSensitivity){let vertexA=this.graph.vertices[a],vertexB=this.graph.vertices[b],neighboursB=vertexB.getNeighbours(a);if(1===neighboursB.length){let neighbour=this.graph.vertices[neighboursB[0]],angle=neighbour.position.getRotateAwayFromAngle(vertexA.position,vertexB.position,MathHelper.toRad(120));this.rotateSubtree(neighbour.id,vertexB.id,angle,vertexB.position);let newTotalOverlapScore=this.getOverlapScore().total;newTotalOverlapScore>this.totalOverlapScore?this.rotateSubtree(neighbour.id,vertexB.id,-angle,vertexB.position):this.totalOverlapScore=newTotalOverlapScore}else if(2===neighboursB.length){if(0!==vertexB.value.rings.length&&0!==vertexA.value.rings.length)continue;let neighbourA=this.graph.vertices[neighboursB[0]],neighbourB=this.graph.vertices[neighboursB[1]];if(1===neighbourA.value.rings.length&&1===neighbourB.value.rings.length){if(neighbourA.value.rings[0]!==neighbourB.value.rings[0])continue;}else if(0!==neighbourA.value.rings.length||0!==neighbourB.value.rings.length)continue;else{let angleA=neighbourA.position.getRotateAwayFromAngle(vertexA.position,vertexB.position,MathHelper.toRad(120)),angleB=neighbourB.position.getRotateAwayFromAngle(vertexA.position,vertexB.position,MathHelper.toRad(120));this.rotateSubtree(neighbourA.id,vertexB.id,angleA,vertexB.position),this.rotateSubtree(neighbourB.id,vertexB.id,angleB,vertexB.position);let newTotalOverlapScore=this.getOverlapScore().total;newTotalOverlapScore>this.totalOverlapScore?(this.rotateSubtree(neighbourA.id,vertexB.id,-angleA,vertexB.position),this.rotateSubtree(neighbourB.id,vertexB.id,-angleB,vertexB.position)):this.totalOverlapScore=newTotalOverlapScore}}overlapScore=this.getOverlapScore()}}}this.resolveSecondaryOverlaps(overlapScore.scores),this.opts.isomeric&&this.annotateStereochemistry(),this.opts.compactDrawing&&"default"===this.opts.atomVisualization&&this.initPseudoElements(),this.rotateDrawing()}initRings(){let openBonds=new Map;for(var i=this.graph.vertices.length-1;0<=i;i--){let vertex=this.graph.vertices[i];if(0!==vertex.value.ringbonds.length)for(var j=0;j<vertex.value.ringbonds.length;j++){let ringbondId=vertex.value.ringbonds[j].id,ringbondBond=vertex.value.ringbonds[j].bond;if(!openBonds.has(ringbondId))openBonds.set(ringbondId,[vertex.id,ringbondBond]);else{let sourceVertexId=vertex.id,targetVertexId=openBonds.get(ringbondId)[0],targetRingbondBond=openBonds.get(ringbondId)[1],edge=new Edge(sourceVertexId,targetVertexId,1);edge.setBondType(targetRingbondBond||ringbondBond||"-");let edgeId=this.graph.addEdge(edge),targetVertex=this.graph.vertices[targetVertexId];vertex.addRingbondChild(targetVertexId,j),vertex.value.addNeighbouringElement(targetVertex.value.element),targetVertex.addRingbondChild(sourceVertexId,j),targetVertex.value.addNeighbouringElement(vertex.value.element),vertex.edges.push(edgeId),targetVertex.edges.push(edgeId),openBonds.delete(ringbondId)}}}let rings=SSSR.getRings(this.graph,this.opts.experimentalSSSR);if(null!==rings){for(var i=0;i<rings.length;i++){let ringVertices=[...rings[i]],ringId=this.addRing(new Ring(ringVertices));for(var j=0;j<ringVertices.length;j++)this.graph.vertices[ringVertices[j]].value.rings.push(ringId)}for(var i=0;i<this.rings.length-1;i++)for(var j=i+1;j<this.rings.length;j++){let a=this.rings[i],b=this.rings[j],ringConnection=new RingConnection(a,b);0<ringConnection.vertices.size&&this.addRingConnection(ringConnection)}for(var i=0;i<this.rings.length;i++){let ring=this.rings[i];ring.neighbours=RingConnection.getNeighbours(this.ringConnections,ring.id)}for(var i=0;i<this.rings.length;i++){let ring=this.rings[i];this.graph.vertices[ring.members[0]].value.addAnchoredRing(ring.id)}for(this.backupRingInformation();0<this.rings.length;){let id=-1;for(var i=0;i<this.rings.length;i++){let ring=this.rings[i];this.isPartOfBridgedRing(ring.id)&&!ring.isBridged&&(id=ring.id)}if(-1===id)break;let ring=this.getRing(id),involvedRings=this.getBridgedRingRings(ring.id);this.bridgedRing=!0,this.createBridgedRing(involvedRings,ring.members[0]);for(var i=0;i<involvedRings.length;i++)this.removeRing(involvedRings[i])}}}initHydrogens(){if(!this.opts.explicitHydrogens)for(var i=0;i<this.graph.vertices.length;i++){let vertex=this.graph.vertices[i];if("H"!==vertex.value.element)continue;let neighbour=this.graph.vertices[vertex.neighbours[0]];neighbour.value.hasHydrogen=!0,(!neighbour.value.isStereoCenter||2>neighbour.value.rings.length&&!neighbour.value.bridgedRing||neighbour.value.bridgedRing&&2>neighbour.value.originalRings.length)&&(vertex.value.isDrawn=!1)}}getBridgedRingRings(ringId){let involvedRings=[],that=this,recurse=function(r){let ring=that.getRing(r);involvedRings.push(r);for(var i=0;i<ring.neighbours.length;i++){let n=ring.neighbours[i];-1===involvedRings.indexOf(n)&&n!==r&&RingConnection.isBridge(that.ringConnections,that.graph.vertices,r,n)&&recurse(n)}};return recurse(ringId),ArrayHelper.unique(involvedRings)}isPartOfBridgedRing(ringId){for(var i=0;i<this.ringConnections.length;i++)if(this.ringConnections[i].containsRing(ringId)&&this.ringConnections[i].isBridge(this.graph.vertices))return!0;return!1}createBridgedRing(ringIds,sourceVertexId){let ringMembers=new Set,vertices=new Set,neighbours=new Set;for(var i=0;i<ringIds.length;i++){let ring=this.getRing(ringIds[i]);ring.isPartOfBridged=!0;for(var j=0;j<ring.members.length;j++)vertices.add(ring.members[j]);for(var j=0;j<ring.neighbours.length;j++){let id=ring.neighbours[j];-1===ringIds.indexOf(id)&&neighbours.add(ring.neighbours[j])}}let leftovers=new Set;for(let id of vertices){let vertex=this.graph.vertices[id],intersection=ArrayHelper.intersection(ringIds,vertex.value.rings);1===vertex.value.rings.length||1===intersection.length?ringMembers.add(vertex.id):leftovers.add(vertex.id)}let insideRing=[];for(let id of leftovers){let vertex=this.graph.vertices[id],onRing=!1;for(let j=0;j<vertex.edges.length;j++)1===this.edgeRingCount(vertex.edges[j])&&(onRing=!0);onRing?(vertex.value.isBridgeNode=!0,ringMembers.add(vertex.id)):(vertex.value.isBridge=!0,ringMembers.add(vertex.id))}let ring=new Ring([...ringMembers]);this.addRing(ring),ring.isBridged=!0,ring.neighbours=[...neighbours];for(var i=0;i<ringIds.length;i++)ring.rings.push(this.getRing(ringIds[i]).clone());for(var i=0;i<ring.members.length;i++)this.graph.vertices[ring.members[i]].value.bridgedRing=ring.id;for(var i=0;i<insideRing.length;i++){let vertex=this.graph.vertices[insideRing[i]];vertex.value.rings=[]}for(let id of ringMembers){let vertex=this.graph.vertices[id];vertex.value.rings=ArrayHelper.removeAll(vertex.value.rings,ringIds),vertex.value.rings.push(ring.id)}for(var i=0;i<ringIds.length;i++)for(var j=i+1;j<ringIds.length;j++)this.removeRingConnectionsBetween(ringIds[i],ringIds[j]);for(let id of neighbours){let connections=this.getRingConnections(id,ringIds);for(var j=0;j<connections.length;j++)this.getRingConnection(connections[j]).updateOther(ring.id,id);this.getRing(id).neighbours.push(ring.id)}return ring}areVerticesInSameRing(vertexA,vertexB){for(var i=0;i<vertexA.value.rings.length;i++)for(var j=0;j<vertexB.value.rings.length;j++)if(vertexA.value.rings[i]===vertexB.value.rings[j])return!0;return!1}getCommonRings(vertexA,vertexB){let commonRings=[];for(var i=0;i<vertexA.value.rings.length;i++)for(var j=0;j<vertexB.value.rings.length;j++)vertexA.value.rings[i]==vertexB.value.rings[j]&&commonRings.push(vertexA.value.rings[i]);return commonRings}getLargestOrAromaticCommonRing(vertexA,vertexB){let commonRings=this.getCommonRings(vertexA,vertexB),maxSize=0,largestCommonRing=null;for(var i=0;i<commonRings.length;i++){let ring=this.getRing(commonRings[i]),size=ring.getSize();if(ring.isBenzeneLike(this.graph.vertices))return ring;size>maxSize&&(maxSize=size,largestCommonRing=ring)}return largestCommonRing}getVerticesAt(position,radius,excludeVertexId){let locals=[];for(var i=0;i<this.graph.vertices.length;i++){let vertex=this.graph.vertices[i];if(vertex.id===excludeVertexId||!vertex.positioned)continue;let distance=position.distanceSq(vertex.position);distance<=radius*radius&&locals.push(vertex.id)}return locals}getClosestVertex(vertex){let minDist=99999,minVertex=null;for(var i=0;i<this.graph.vertices.length;i++){let v=this.graph.vertices[i];if(v.id===vertex.id)continue;let distSq=vertex.position.distanceSq(v.position);distSq<minDist&&(minDist=distSq,minVertex=v)}return minVertex}addRing(ring){return ring.id=this.ringIdCounter++,this.rings.push(ring),ring.id}removeRing(ringId){this.rings=this.rings.filter(function(item){return item.id!==ringId}),this.ringConnections=this.ringConnections.filter(function(item){return item.firstRingId!==ringId&&item.secondRingId!==ringId});for(var i=0;i<this.rings.length;i++){let r=this.rings[i];r.neighbours=r.neighbours.filter(function(item){return item!==ringId})}}getRing(ringId){for(var i=0;i<this.rings.length;i++)if(this.rings[i].id==ringId)return this.rings[i]}addRingConnection(ringConnection){return ringConnection.id=this.ringConnectionIdCounter++,this.ringConnections.push(ringConnection),ringConnection.id}removeRingConnection(ringConnectionId){this.ringConnections=this.ringConnections.filter(function(item){return item.id!==ringConnectionId})}removeRingConnectionsBetween(vertexIdA,vertexIdB){let toRemove=[];for(var i=0;i<this.ringConnections.length;i++){let ringConnection=this.ringConnections[i];(ringConnection.firstRingId===vertexIdA&&ringConnection.secondRingId===vertexIdB||ringConnection.firstRingId===vertexIdB&&ringConnection.secondRingId===vertexIdA)&&toRemove.push(ringConnection.id)}for(var i=0;i<toRemove.length;i++)this.removeRingConnection(toRemove[i])}getRingConnection(id){for(var i=0;i<this.ringConnections.length;i++)if(this.ringConnections[i].id==id)return this.ringConnections[i]}getRingConnections(ringId,ringIds){let ringConnections=[];for(var i=0;i<this.ringConnections.length;i++){let rc=this.ringConnections[i];for(var j=0;j<ringIds.length;j++){let id=ringIds[j];(rc.firstRingId===ringId&&rc.secondRingId===id||rc.firstRingId===id&&rc.secondRingId===ringId)&&ringConnections.push(rc.id)}}return ringConnections}getOverlapScore(){let total=0,overlapScores=new Float32Array(this.graph.vertices.length);for(var i=0;i<this.graph.vertices.length;i++)overlapScores[i]=0;for(var i=0,j;i<this.graph.vertices.length;i++)for(j=this.graph.vertices.length;--j>i;){let a=this.graph.vertices[i],b=this.graph.vertices[j];if(!a.value.isDrawn||!b.value.isDrawn)continue;let dist=Vector2.subtract(a.position,b.position).lengthSq();if(dist<this.opts.bondLengthSq){let weighted=(this.opts.bondLength-_Mathsqrt2(dist))/this.opts.bondLength;total+=weighted,overlapScores[i]+=weighted,overlapScores[j]+=weighted}}let sortable=[];for(var i=0;i<this.graph.vertices.length;i++)sortable.push({id:i,score:overlapScores[i]});return sortable.sort(function(a,b){return b.score-a.score}),{total:total,scores:sortable,vertexScores:overlapScores}}chooseSide(vertexA,vertexB,sides){let an=vertexA.getNeighbours(vertexB.id),bn=vertexB.getNeighbours(vertexA.id),anCount=an.length,bnCount=bn.length,tn=ArrayHelper.merge(an,bn),sideCount=[0,0];for(var i=0;i<tn.length;i++){let v=this.graph.vertices[tn[i]].position;v.sameSideAs(vertexA.position,vertexB.position,sides[0])?sideCount[0]++:sideCount[1]++}let totalSideCount=[0,0];for(var i=0;i<this.graph.vertices.length;i++){let v=this.graph.vertices[i].position;v.sameSideAs(vertexA.position,vertexB.position,sides[0])?totalSideCount[0]++:totalSideCount[1]++}return{totalSideCount:totalSideCount,totalPosition:totalSideCount[0]>totalSideCount[1]?0:1,sideCount:sideCount,position:sideCount[0]>sideCount[1]?0:1,anCount:anCount,bnCount:bnCount}}setRingCenter(ring){let ringSize=ring.getSize(),total=new Vector2(0,0);for(var i=0;i<ringSize;i++)total.add(this.graph.vertices[ring.members[i]].position);ring.center=total.divide(ringSize)}getSubringCenter(ring,vertex){let rings=vertex.value.originalRings,center=ring.center,smallest=Number.MAX_VALUE;for(var i=0;i<rings.length;i++)for(var j=0;j<ring.rings.length;j++)rings[i]===ring.rings[j].id&&ring.rings[j].getSize()<smallest&&(center=ring.rings[j].center,smallest=ring.rings[j].getSize());return center}drawEdges(debug){let that=this,drawn=Array(this.graph.edges.length);if(drawn.fill(!1),this.graph.traverseBF(0,function(vertex){let edges=that.graph.getEdges(vertex.id);for(var i=0;i<edges.length;i++){let edgeId=edges[i];drawn[edgeId]||(drawn[edgeId]=!0,that.drawEdge(edgeId,debug))}}),!this.bridgedRing)for(var i=0;i<this.rings.length;i++){let ring=this.rings[i];this.isRingAromatic(ring)&&this.canvasWrapper.drawAromaticityRing(ring)}}drawEdge(edgeId,debug){let that=this,edge=this.graph.edges[edgeId],vertexA=this.graph.vertices[edge.sourceId],vertexB=this.graph.vertices[edge.targetId],elementA=vertexA.value.element,elementB=vertexB.value.element;if((!vertexA.value.isDrawn||!vertexB.value.isDrawn)&&"default"===this.opts.atomVisualization)return;let a=vertexA.position,b=vertexB.position,normals=this.getEdgeNormals(edge),sides=ArrayHelper.clone(normals);if(sides[0].multiplyScalar(10).add(a),sides[1].multiplyScalar(10).add(a),"="===edge.bondType||"="===this.getRingbondType(vertexA,vertexB)||edge.isPartOfAromaticRing&&this.bridgedRing){let inRing=this.areVerticesInSameRing(vertexA,vertexB),s=this.chooseSide(vertexA,vertexB,sides);if(inRing){let lcr=this.getLargestOrAromaticCommonRing(vertexA,vertexB),center=lcr.center;normals[0].multiplyScalar(that.opts.bondSpacing),normals[1].multiplyScalar(that.opts.bondSpacing);let line=null;line=center.sameSideAs(vertexA.position,vertexB.position,Vector2.add(a,normals[0]))?new Line(Vector2.add(a,normals[0]),Vector2.add(b,normals[0]),elementA,elementB):new Line(Vector2.add(a,normals[1]),Vector2.add(b,normals[1]),elementA,elementB),line.shorten(this.opts.bondLength-this.opts.shortBondLength*this.opts.bondLength),edge.isPartOfAromaticRing?this.canvasWrapper.drawLine(line,!0):this.canvasWrapper.drawLine(line),this.canvasWrapper.drawLine(new Line(a,b,elementA,elementB))}else if(edge.center||vertexA.isTerminal()&&vertexB.isTerminal()){normals[0].multiplyScalar(that.opts.halfBondSpacing),normals[1].multiplyScalar(that.opts.halfBondSpacing);let lineA=new Line(Vector2.add(a,normals[0]),Vector2.add(b,normals[0]),elementA,elementB),lineB=new Line(Vector2.add(a,normals[1]),Vector2.add(b,normals[1]),elementA,elementB);this.canvasWrapper.drawLine(lineA),this.canvasWrapper.drawLine(lineB)}else if(0==s.anCount&&1<s.bnCount||0==s.bnCount&&1<s.anCount){normals[0].multiplyScalar(that.opts.halfBondSpacing),normals[1].multiplyScalar(that.opts.halfBondSpacing);let lineA=new Line(Vector2.add(a,normals[0]),Vector2.add(b,normals[0]),elementA,elementB),lineB=new Line(Vector2.add(a,normals[1]),Vector2.add(b,normals[1]),elementA,elementB);this.canvasWrapper.drawLine(lineA),this.canvasWrapper.drawLine(lineB)}else if(s.sideCount[0]>s.sideCount[1]){normals[0].multiplyScalar(that.opts.bondSpacing),normals[1].multiplyScalar(that.opts.bondSpacing);let line=new Line(Vector2.add(a,normals[0]),Vector2.add(b,normals[0]),elementA,elementB);line.shorten(this.opts.bondLength-this.opts.shortBondLength*this.opts.bondLength),this.canvasWrapper.drawLine(line),this.canvasWrapper.drawLine(new Line(a,b,elementA,elementB))}else if(s.sideCount[0]<s.sideCount[1]){normals[0].multiplyScalar(that.opts.bondSpacing),normals[1].multiplyScalar(that.opts.bondSpacing);let line=new Line(Vector2.add(a,normals[1]),Vector2.add(b,normals[1]),elementA,elementB);line.shorten(this.opts.bondLength-this.opts.shortBondLength*this.opts.bondLength),this.canvasWrapper.drawLine(line),this.canvasWrapper.drawLine(new Line(a,b,elementA,elementB))}else if(s.totalSideCount[0]>s.totalSideCount[1]){normals[0].multiplyScalar(that.opts.bondSpacing),normals[1].multiplyScalar(that.opts.bondSpacing);let line=new Line(Vector2.add(a,normals[0]),Vector2.add(b,normals[0]),elementA,elementB);line.shorten(this.opts.bondLength-this.opts.shortBondLength*this.opts.bondLength),this.canvasWrapper.drawLine(line),this.canvasWrapper.drawLine(new Line(a,b,elementA,elementB))}else if(s.totalSideCount[0]<=s.totalSideCount[1]){normals[0].multiplyScalar(that.opts.bondSpacing),normals[1].multiplyScalar(that.opts.bondSpacing);let line=new Line(Vector2.add(a,normals[1]),Vector2.add(b,normals[1]),elementA,elementB);line.shorten(this.opts.bondLength-this.opts.shortBondLength*this.opts.bondLength),this.canvasWrapper.drawLine(line),this.canvasWrapper.drawLine(new Line(a,b,elementA,elementB))}else;}else if("#"===edge.bondType){normals[0].multiplyScalar(that.opts.bondSpacing/1.5),normals[1].multiplyScalar(that.opts.bondSpacing/1.5);let lineA=new Line(Vector2.add(a,normals[0]),Vector2.add(b,normals[0]),elementA,elementB),lineB=new Line(Vector2.add(a,normals[1]),Vector2.add(b,normals[1]),elementA,elementB);this.canvasWrapper.drawLine(lineA),this.canvasWrapper.drawLine(lineB),this.canvasWrapper.drawLine(new Line(a,b,elementA,elementB))}else if("."===edge.bondType);else{let isChiralCenterA=vertexA.value.isStereoCenter,isChiralCenterB=vertexB.value.isStereoCenter;"up"===edge.wedge?this.canvasWrapper.drawWedge(new Line(a,b,elementA,elementB,isChiralCenterA,isChiralCenterB)):"down"===edge.wedge?this.canvasWrapper.drawDashedWedge(new Line(a,b,elementA,elementB,isChiralCenterA,isChiralCenterB)):this.canvasWrapper.drawLine(new Line(a,b,elementA,elementB,isChiralCenterA,isChiralCenterB))}if(debug){let midpoint=Vector2.midpoint(a,b);this.canvasWrapper.drawDebugText(midpoint.x,midpoint.y,"e: "+edgeId)}}drawVertices(debug){for(var i=this.graph.vertices.length,i=0;i<this.graph.vertices.length;i++){let vertex=this.graph.vertices[i],atom=vertex.value,charge=0,isotope=0,bondCount=vertex.value.bondCount,element=atom.element,hydrogens=Atom.maxBonds[element]-bondCount,dir=vertex.getTextDirection(this.graph.vertices),isTerminal=!!(this.opts.terminalCarbons||"C"!==element||atom.hasAttachedPseudoElements)&&vertex.isTerminal(),isCarbon="C"===atom.element;if("N"===atom.element&&atom.isPartOfAromaticRing&&(hydrogens=0),atom.bracket&&(hydrogens=atom.bracket.hcount,charge=atom.bracket.charge,isotope=atom.bracket.isotope),"allballs"===this.opts.atomVisualization)this.canvasWrapper.drawBall(vertex.position.x,vertex.position.y,element);else if(atom.isDrawn&&(!isCarbon||atom.drawExplicit||isTerminal||atom.hasAttachedPseudoElements)||1===this.graph.vertices.length)"default"===this.opts.atomVisualization?this.canvasWrapper.drawText(vertex.position.x,vertex.position.y,element,hydrogens,dir,isTerminal,charge,isotope,this.graph.vertices.length,atom.getAttachedPseudoElements()):"balls"===this.opts.atomVisualization&&this.canvasWrapper.drawBall(vertex.position.x,vertex.position.y,element);else if(2===vertex.getNeighbourCount()&&!0==vertex.forcePositioned){let a=this.graph.vertices[vertex.neighbours[0]].position,b=this.graph.vertices[vertex.neighbours[1]].position,angle=Vector2.threePointangle(vertex.position,a,b);.1>_Mathabs2(_MathPI2-angle)&&this.canvasWrapper.drawPoint(vertex.position.x,vertex.position.y,element)}if(debug){let value="v: "+vertex.id+" "+ArrayHelper.print(atom.ringbonds);this.canvasWrapper.drawDebugText(vertex.position.x,vertex.position.y,value)}else;}if(this.opts.debug)for(var i=0;i<this.rings.length;i++){let center=this.rings[i].center;this.canvasWrapper.drawDebugPoint(center.x,center.y,"r: "+this.rings[i].id)}}position(){let startVertex=null;for(var i=0;i<this.graph.vertices.length;i++)if(null!==this.graph.vertices[i].value.bridgedRing){startVertex=this.graph.vertices[i];break}for(var i=0;i<this.rings.length;i++)this.rings[i].isBridged&&(startVertex=this.graph.vertices[this.rings[i].members[0]]);0<this.rings.length&&null===startVertex&&(startVertex=this.graph.vertices[this.rings[0].members[0]]),null===startVertex&&(startVertex=this.graph.vertices[0]),this.createNextBond(startVertex,null,0)}backupRingInformation(){this.originalRings=[],this.originalRingConnections=[];for(var i=0;i<this.rings.length;i++)this.originalRings.push(this.rings[i]);for(var i=0;i<this.ringConnections.length;i++)this.originalRingConnections.push(this.ringConnections[i]);for(var i=0;i<this.graph.vertices.length;i++)this.graph.vertices[i].value.backupRings()}restoreRingInformation(){let bridgedRings=this.getBridgedRings();this.rings=[],this.ringConnections=[];for(var i=0;i<bridgedRings.length;i++){let bridgedRing=bridgedRings[i];for(var j=0;j<bridgedRing.rings.length;j++){let ring=bridgedRing.rings[j];this.originalRings[ring.id].center=ring.center}}for(var i=0;i<this.originalRings.length;i++)this.rings.push(this.originalRings[i]);for(var i=0;i<this.originalRingConnections.length;i++)this.ringConnections.push(this.originalRingConnections[i]);for(var i=0;i<this.graph.vertices.length;i++)this.graph.vertices[i].value.restoreRings()}createRing(ring,center=null,startVertex=null,previousVertex=null){if(ring.positioned)return;center=center?center:new Vector2(0,0);let orderedNeighbours=ring.getOrderedNeighbours(this.ringConnections),startingAngle=startVertex?Vector2.subtract(startVertex.position,center).angle():0,radius=MathHelper.polyCircumradius(this.opts.bondLength,ring.getSize()),angle=MathHelper.centralAngle(ring.getSize());ring.centralAngle=angle;let a=startingAngle,that=this,startVertexId=startVertex?startVertex.id:null;if(-1===ring.members.indexOf(startVertexId)&&(startVertex&&(startVertex.positioned=!1),startVertexId=ring.members[0]),ring.isBridged){this.graph.kkLayout(ring.members.slice(),center,startVertex.id,ring,this.opts.bondLength,this.opts.kkThreshold,this.opts.kkInnerThreshold,this.opts.kkMaxIteration,this.opts.kkMaxInnerIteration,this.opts.kkMaxEnergy),ring.positioned=!0,this.setRingCenter(ring),center=ring.center;for(var i=0;i<ring.rings.length;i++)this.setRingCenter(ring.rings[i])}else ring.eachMember(this.graph.vertices,function(v){let vertex=that.graph.vertices[v];vertex.positioned||vertex.setPosition(center.x+_Mathcos2(a)*radius,center.y+_Mathsin2(a)*radius),a+=angle,(!ring.isBridged||3>ring.rings.length)&&(vertex.angle=a,vertex.positioned=!0)},startVertexId,previousVertex?previousVertex.id:null);ring.positioned=!0,ring.center=center;for(var i=0;i<orderedNeighbours.length;i++){let neighbour=this.getRing(orderedNeighbours[i].neighbour);if(neighbour.positioned)continue;let vertices=RingConnection.getVertices(this.ringConnections,ring.id,neighbour.id);if(2===vertices.length){ring.isFused=!0,neighbour.isFused=!0;let vertexA=this.graph.vertices[vertices[0]],vertexB=this.graph.vertices[vertices[1]],midpoint=Vector2.midpoint(vertexA.position,vertexB.position),normals=Vector2.normals(vertexA.position,vertexB.position);normals[0].normalize(),normals[1].normalize();let r=MathHelper.polyCircumradius(this.opts.bondLength,neighbour.getSize()),apothem=MathHelper.apothem(r,neighbour.getSize());normals[0].multiplyScalar(apothem).add(midpoint),normals[1].multiplyScalar(apothem).add(midpoint);let nextCenter=normals[0];Vector2.subtract(center,normals[1]).lengthSq()>Vector2.subtract(center,normals[0]).lengthSq()&&(nextCenter=normals[1]);let posA=Vector2.subtract(vertexA.position,nextCenter),posB=Vector2.subtract(vertexB.position,nextCenter);-1===posA.clockwise(posB)?!neighbour.positioned&&this.createRing(neighbour,nextCenter,vertexA,vertexB):!neighbour.positioned&&this.createRing(neighbour,nextCenter,vertexB,vertexA)}else if(1===vertices.length){ring.isSpiro=!0,neighbour.isSpiro=!0;let vertexA=this.graph.vertices[vertices[0]],nextCenter=Vector2.subtract(center,vertexA.position);nextCenter.invert(),nextCenter.normalize();let r=MathHelper.polyCircumradius(this.opts.bondLength,neighbour.getSize());nextCenter.multiplyScalar(r),nextCenter.add(vertexA.position),neighbour.positioned||this.createRing(neighbour,nextCenter,vertexA)}}for(var i=0;i<ring.members.length;i++){let ringMember=this.graph.vertices[ring.members[i]],ringMemberNeighbours=ringMember.neighbours;for(var j=0;j<ringMemberNeighbours.length;j++){let v=this.graph.vertices[ringMemberNeighbours[j]];v.positioned||(v.value.isConnectedToRing=!0,this.createNextBond(v,ringMember,0))}}}rotateSubtree(vertexId,parentVertexId,angle,center){let that=this;this.graph.traverseTree(vertexId,parentVertexId,function(vertex){vertex.position.rotateAround(angle,center);for(var i=0;i<vertex.value.anchoredRings.length;i++){let ring=that.rings[vertex.value.anchoredRings[i]];ring&&ring.center.rotateAround(angle,center)}})}getSubtreeOverlapScore(vertexId,parentVertexId,vertexOverlapScores){let that=this,score=0,center=new Vector2(0,0),count=0;return this.graph.traverseTree(vertexId,parentVertexId,function(vertex){if(vertex.value.isDrawn){let s=vertexOverlapScores[vertex.id];s>that.opts.overlapSensitivity&&(score+=s,count++);let position=that.graph.vertices[vertex.id].position.clone();position.multiplyScalar(s),center.add(position)}}),center.divide(score),{value:score/count,center:center}}getCurrentCenterOfMass(){let total=new Vector2(0,0),count=0;for(var i=0;i<this.graph.vertices.length;i++){let vertex=this.graph.vertices[i];vertex.positioned&&(total.add(vertex.position),count++)}return total.divide(count)}getCurrentCenterOfMassInNeigbourhood(vec,r=2*this.opts.bondLength){let total=new Vector2(0,0),count=0;for(var i=0;i<this.graph.vertices.length;i++){let vertex=this.graph.vertices[i];vertex.positioned&&vec.distanceSq(vertex.position)<r*r&&(total.add(vertex.position),count++)}return total.divide(count)}resolvePrimaryOverlaps(){let overlaps=[],done=Array(this.graph.vertices.length);for(var i=0;i<this.rings.length;i++){let ring=this.rings[i];for(var j=0;j<ring.members.length;j++){let vertex=this.graph.vertices[ring.members[j]];if(done[vertex.id])continue;done[vertex.id]=!0;let nonRingNeighbours=this.getNonRingNeighbours(vertex.id);if(1<nonRingNeighbours.length){let rings=[];for(var k=0;k<vertex.value.rings.length;k++)rings.push(vertex.value.rings[k]);overlaps.push({common:vertex,rings:rings,vertices:nonRingNeighbours})}else if(1===nonRingNeighbours.length&&2===vertex.value.rings.length){let rings=[];for(var k=0;k<vertex.value.rings.length;k++)rings.push(vertex.value.rings[k]);overlaps.push({common:vertex,rings:rings,vertices:nonRingNeighbours})}}}for(var i=0;i<overlaps.length;i++){let overlap=overlaps[i];if(2===overlap.vertices.length){let a=overlap.vertices[0],b=overlap.vertices[1];if(!a.value.isDrawn||!b.value.isDrawn)continue;let angle=(2*_MathPI2-this.getRing(overlap.rings[0]).getAngle())/6;this.rotateSubtree(a.id,overlap.common.id,angle,overlap.common.position),this.rotateSubtree(b.id,overlap.common.id,-angle,overlap.common.position);let overlapScore=this.getOverlapScore(),subTreeOverlapA=this.getSubtreeOverlapScore(a.id,overlap.common.id,overlapScore.vertexScores),subTreeOverlapB=this.getSubtreeOverlapScore(b.id,overlap.common.id,overlapScore.vertexScores),total=subTreeOverlapA.value+subTreeOverlapB.value;this.rotateSubtree(a.id,overlap.common.id,-2*angle,overlap.common.position),this.rotateSubtree(b.id,overlap.common.id,2*angle,overlap.common.position),overlapScore=this.getOverlapScore(),subTreeOverlapA=this.getSubtreeOverlapScore(a.id,overlap.common.id,overlapScore.vertexScores),subTreeOverlapB=this.getSubtreeOverlapScore(b.id,overlap.common.id,overlapScore.vertexScores),subTreeOverlapA.value+subTreeOverlapB.value>total&&(this.rotateSubtree(a.id,overlap.common.id,2*angle,overlap.common.position),this.rotateSubtree(b.id,overlap.common.id,-2*angle,overlap.common.position))}else 1!==overlap.vertices.length||2!==overlap.rings.length}}resolveSecondaryOverlaps(scores){for(var i=0;i<scores.length;i++)if(scores[i].score>this.opts.overlapSensitivity){let vertex=this.graph.vertices[scores[i].id];if(vertex.isTerminal()){let closest=this.getClosestVertex(vertex);if(closest){let closestPosition=null;closestPosition=closest.isTerminal()?0===closest.id?this.graph.vertices[1].position:closest.previousPosition:0===closest.id?this.graph.vertices[1].position:closest.position;let vertexPreviousPosition=0===vertex.id?this.graph.vertices[1].position:vertex.previousPosition;vertex.position.rotateAwayFrom(closestPosition,vertexPreviousPosition,MathHelper.toRad(20))}}}}getLastVertexWithAngle(vertexId){let angle=0,vertex=null;for(;!angle&&vertexId;)vertex=this.graph.vertices[vertexId],angle=vertex.angle,vertexId=vertex.parentVertexId;return vertex}createNextBond(vertex,previousVertex=null,angle=0,originShortest=!1,skipPositioning=!1){if(vertex.positioned&&!skipPositioning)return;let doubleBondConfigSet=!1;if(previousVertex){let edge=this.graph.getEdge(vertex.id,previousVertex.id);("/"===edge.bondType||"\\"===edge.bondType)&&1==++this.doubleBondConfigCount%2&&null===this.doubleBondConfig&&(this.doubleBondConfig=edge.bondType,doubleBondConfigSet=!0,null===previousVertex.parentVertexId&&vertex.value.branchBond&&("/"===this.doubleBondConfig?this.doubleBondConfig="\\":"\\"===this.doubleBondConfig&&(this.doubleBondConfig="/")))}if(!skipPositioning)if(!previousVertex){let dummy=new Vector2(this.opts.bondLength,0);dummy.rotate(MathHelper.toRad(-60)),vertex.previousPosition=dummy,vertex.setPosition(this.opts.bondLength,0),vertex.angle=MathHelper.toRad(-60),null===vertex.value.bridgedRing&&(vertex.positioned=!0)}else if(0<previousVertex.value.rings.length){let neighbours=previousVertex.neighbours,joinedVertex=null,pos=new Vector2(0,0);if(null===previousVertex.value.bridgedRing&&1<previousVertex.value.rings.length)for(var i=0;i<neighbours.length;i++){let neighbour=this.graph.vertices[neighbours[i]];if(ArrayHelper.containsAll(neighbour.value.rings,previousVertex.value.rings)){joinedVertex=neighbour;break}}if(null===joinedVertex){for(var i=0;i<neighbours.length;i++){let v=this.graph.vertices[neighbours[i]];v.positioned&&this.areVerticesInSameRing(v,previousVertex)&&pos.add(Vector2.subtract(v.position,previousVertex.position))}pos.invert().normalize().multiplyScalar(this.opts.bondLength).add(previousVertex.position)}else pos=joinedVertex.position.clone().rotateAround(Math.PI,previousVertex.position);vertex.previousPosition=previousVertex.position,vertex.setPositionFromVector(pos),vertex.positioned=!0}else{let v=new Vector2(this.opts.bondLength,0);v.rotate(angle),v.add(previousVertex.position),vertex.setPositionFromVector(v),vertex.previousPosition=previousVertex.position,vertex.positioned=!0}if(null!==vertex.value.bridgedRing){let nextRing=this.getRing(vertex.value.bridgedRing);if(!nextRing.positioned){let nextCenter=Vector2.subtract(vertex.previousPosition,vertex.position);nextCenter.invert(),nextCenter.normalize();let r=MathHelper.polyCircumradius(this.opts.bondLength,nextRing.members.length);nextCenter.multiplyScalar(r),nextCenter.add(vertex.position),this.createRing(nextRing,nextCenter,vertex)}}else if(0<vertex.value.rings.length){let nextRing=this.getRing(vertex.value.rings[0]);if(!nextRing.positioned){let nextCenter=Vector2.subtract(vertex.previousPosition,vertex.position);nextCenter.invert(),nextCenter.normalize();let r=MathHelper.polyCircumradius(this.opts.bondLength,nextRing.getSize());nextCenter.multiplyScalar(r),nextCenter.add(vertex.position),this.createRing(nextRing,nextCenter,vertex)}}else{let isStereoCenter=vertex.value.isStereoCenter,tmpNeighbours=vertex.getNeighbours(),neighbours=[];for(var i=0;i<tmpNeighbours.length;i++)this.graph.vertices[tmpNeighbours[i]].value.isDrawn&&neighbours.push(tmpNeighbours[i]);previousVertex&&(neighbours=ArrayHelper.remove(neighbours,previousVertex.id));let previousAngle=vertex.getAngle();if(1===neighbours.length){let nextVertex=this.graph.vertices[neighbours[0]];if("#"===vertex.value.bondType||previousVertex&&"#"===previousVertex.value.bondType||"="===vertex.value.bondType&&previousVertex&&0===previousVertex.value.rings.length&&"="===previousVertex.value.bondType&&"-"!==vertex.value.branchBond){if(vertex.value.drawExplicit=!1,previousVertex){let straightEdge1=this.graph.getEdge(vertex.id,previousVertex.id);straightEdge1.center=!0}let straightEdge2=this.graph.getEdge(vertex.id,nextVertex.id);straightEdge2.center=!0,("#"===vertex.value.bondType||previousVertex&&"#"===previousVertex.value.bondType)&&(nextVertex.angle=0),nextVertex.drawExplicit=!0,this.createNextBond(nextVertex,vertex,previousAngle+nextVertex.angle)}else if(previousVertex&&0<previousVertex.value.rings.length){let proposedAngleA=MathHelper.toRad(60),proposedAngleB=-proposedAngleA,proposedVectorA=new Vector2(this.opts.bondLength,0),proposedVectorB=new Vector2(this.opts.bondLength,0);proposedVectorA.rotate(proposedAngleA).add(vertex.position),proposedVectorB.rotate(proposedAngleB).add(vertex.position);let centerOfMass=this.getCurrentCenterOfMass(),distanceA=proposedVectorA.distanceSq(centerOfMass),distanceB=proposedVectorB.distanceSq(centerOfMass);nextVertex.angle=distanceA<distanceB?proposedAngleB:proposedAngleA,this.createNextBond(nextVertex,vertex,previousAngle+nextVertex.angle)}else{let a=vertex.angle;if(previousVertex&&3<previousVertex.neighbours.length)a=0<a?_Mathmin4(1.0472,a):0>a?_Mathmax3(-1.0472,a):1.0472;else if(!a){let v=this.getLastVertexWithAngle(vertex.id);a=v.angle,a||(a=1.0472)}if(previousVertex&&!doubleBondConfigSet){let bondType=this.graph.getEdge(vertex.id,nextVertex.id).bondType;"/"===bondType?("/"===this.doubleBondConfig||"\\"===this.doubleBondConfig&&(a=-a),this.doubleBondConfig=null):"\\"===bondType&&("/"===this.doubleBondConfig?a=-a:"\\"===this.doubleBondConfig,this.doubleBondConfig=null)}nextVertex.angle=originShortest?a:-a,this.createNextBond(nextVertex,vertex,previousAngle+nextVertex.angle)}}else if(2===neighbours.length){let a=vertex.angle;a||(a=1.0472);let subTreeDepthA=this.graph.getTreeDepth(neighbours[0],vertex.id),subTreeDepthB=this.graph.getTreeDepth(neighbours[1],vertex.id),l=this.graph.vertices[neighbours[0]],r=this.graph.vertices[neighbours[1]];l.value.subtreeDepth=subTreeDepthA,r.value.subtreeDepth=subTreeDepthB;let subTreeDepthC=this.graph.getTreeDepth(previousVertex?previousVertex.id:null,vertex.id);previousVertex&&(previousVertex.value.subtreeDepth=subTreeDepthC);let cis=0,trans=1;"C"===r.value.element&&"C"!==l.value.element&&1<subTreeDepthB&&5>subTreeDepthA?(cis=1,trans=0):"C"!==r.value.element&&"C"===l.value.element&&1<subTreeDepthA&&5>subTreeDepthB?(cis=0,trans=1):subTreeDepthB>subTreeDepthA&&(cis=1,trans=0);let cisVertex=this.graph.vertices[neighbours[cis]],transVertex=this.graph.vertices[neighbours[trans]],edgeCis=this.graph.getEdge(vertex.id,cisVertex.id),edgeTrans=this.graph.getEdge(vertex.id,transVertex.id),originShortest=!1;subTreeDepthC<subTreeDepthA&&subTreeDepthC<subTreeDepthB&&(originShortest=!0),transVertex.angle=a,cisVertex.angle=-a,"\\"===this.doubleBondConfig?"\\"===transVertex.value.branchBond&&(transVertex.angle=-a,cisVertex.angle=a):"/"===this.doubleBondConfig&&"/"===transVertex.value.branchBond&&(transVertex.angle=-a,cisVertex.angle=a),this.createNextBond(transVertex,vertex,previousAngle+transVertex.angle,originShortest),this.createNextBond(cisVertex,vertex,previousAngle+cisVertex.angle,originShortest)}else if(3===neighbours.length){let d1=this.graph.getTreeDepth(neighbours[0],vertex.id),d2=this.graph.getTreeDepth(neighbours[1],vertex.id),d3=this.graph.getTreeDepth(neighbours[2],vertex.id),s=this.graph.vertices[neighbours[0]],l=this.graph.vertices[neighbours[1]],r=this.graph.vertices[neighbours[2]];s.value.subtreeDepth=d1,l.value.subtreeDepth=d2,r.value.subtreeDepth=d3,d2>d1&&d2>d3?(s=this.graph.vertices[neighbours[1]],l=this.graph.vertices[neighbours[0]],r=this.graph.vertices[neighbours[2]]):d3>d1&&d3>d2&&(s=this.graph.vertices[neighbours[2]],l=this.graph.vertices[neighbours[0]],r=this.graph.vertices[neighbours[1]]),previousVertex&&1>previousVertex.value.rings.length&&1>s.value.rings.length&&1>l.value.rings.length&&1>r.value.rings.length&&1===this.graph.getTreeDepth(l.id,vertex.id)&&1===this.graph.getTreeDepth(r.id,vertex.id)&&1<this.graph.getTreeDepth(s.id,vertex.id)?(s.angle=-vertex.angle,0<=vertex.angle?(l.angle=MathHelper.toRad(30),r.angle=MathHelper.toRad(90)):(l.angle=-MathHelper.toRad(30),r.angle=-MathHelper.toRad(90)),this.createNextBond(s,vertex,previousAngle+s.angle),this.createNextBond(l,vertex,previousAngle+l.angle),this.createNextBond(r,vertex,previousAngle+r.angle)):(s.angle=0,l.angle=MathHelper.toRad(90),r.angle=-MathHelper.toRad(90),this.createNextBond(s,vertex,previousAngle+s.angle),this.createNextBond(l,vertex,previousAngle+l.angle),this.createNextBond(r,vertex,previousAngle+r.angle))}else if(4===neighbours.length){let d1=this.graph.getTreeDepth(neighbours[0],vertex.id),d2=this.graph.getTreeDepth(neighbours[1],vertex.id),d3=this.graph.getTreeDepth(neighbours[2],vertex.id),d4=this.graph.getTreeDepth(neighbours[3],vertex.id),w=this.graph.vertices[neighbours[0]],x=this.graph.vertices[neighbours[1]],y=this.graph.vertices[neighbours[2]],z=this.graph.vertices[neighbours[3]];w.value.subtreeDepth=d1,x.value.subtreeDepth=d2,y.value.subtreeDepth=d3,z.value.subtreeDepth=d4,d2>d1&&d2>d3&&d2>d4?(w=this.graph.vertices[neighbours[1]],x=this.graph.vertices[neighbours[0]],y=this.graph.vertices[neighbours[2]],z=this.graph.vertices[neighbours[3]]):d3>d1&&d3>d2&&d3>d4?(w=this.graph.vertices[neighbours[2]],x=this.graph.vertices[neighbours[0]],y=this.graph.vertices[neighbours[1]],z=this.graph.vertices[neighbours[3]]):d4>d1&&d4>d2&&d4>d3&&(w=this.graph.vertices[neighbours[3]],x=this.graph.vertices[neighbours[0]],y=this.graph.vertices[neighbours[1]],z=this.graph.vertices[neighbours[2]]),w.angle=-MathHelper.toRad(36),x.angle=MathHelper.toRad(36),y.angle=-MathHelper.toRad(108),z.angle=MathHelper.toRad(108),this.createNextBond(w,vertex,previousAngle+w.angle),this.createNextBond(x,vertex,previousAngle+x.angle),this.createNextBond(y,vertex,previousAngle+y.angle),this.createNextBond(z,vertex,previousAngle+z.angle)}}}getCommonRingbondNeighbour(vertex){let neighbours=vertex.neighbours;for(var i=0;i<neighbours.length;i++){let neighbour=this.graph.vertices[neighbours[i]];if(ArrayHelper.containsAll(neighbour.value.rings,vertex.value.rings))return neighbour}return null}isPointInRing(vec){for(var i=0;i<this.rings.length;i++){let ring=this.rings[i];if(!ring.positioned)continue;let radius=MathHelper.polyCircumradius(this.opts.bondLength,ring.getSize());if(vec.distanceSq(ring.center)<radius*radius)return!0}return!1}isEdgeInRing(edge){let source=this.graph.vertices[edge.sourceId],target=this.graph.vertices[edge.targetId];return this.areVerticesInSameRing(source,target)}isEdgeRotatable(edge){let vertexA=this.graph.vertices[edge.sourceId],vertexB=this.graph.vertices[edge.targetId];return!("-"!==edge.bondType)&&!(vertexA.isTerminal()||vertexB.isTerminal())&&!(0<vertexA.value.rings.length&&0<vertexB.value.rings.length&&this.areVerticesInSameRing(vertexA,vertexB))}isRingAromatic(ring){for(var i=0;i<ring.members.length;i++){let vertex=this.graph.vertices[ring.members[i]];if(!vertex.value.isPartOfAromaticRing)return!1}return!0}getEdgeNormals(edge){let v1=this.graph.vertices[edge.sourceId].position,v2=this.graph.vertices[edge.targetId].position,normals=Vector2.units(v1,v2);return normals}getNonRingNeighbours(vertexId){let nrneighbours=[],vertex=this.graph.vertices[vertexId],neighbours=vertex.neighbours;for(var i=0;i<neighbours.length;i++){let neighbour=this.graph.vertices[neighbours[i]],nIntersections=ArrayHelper.intersection(vertex.value.rings,neighbour.value.rings).length;0===nIntersections&&!1==neighbour.value.isBridge&&nrneighbours.push(neighbour)}return nrneighbours}annotateStereochemistry(){for(var i=0;i<this.graph.vertices.length;i++){let vertex=this.graph.vertices[i];if(!vertex.value.isStereoCenter)continue;let neighbours=vertex.getNeighbours(),nNeighbours=neighbours.length,priorities=Array(nNeighbours);for(var j=0;j<nNeighbours;j++){let visited=new Uint8Array(this.graph.vertices.length),priority=[[]];visited[vertex.id]=1,this.visitStereochemistry(neighbours[j],vertex.id,visited,priority,10,0);for(var k=0;k<priority.length;k++)priority[k].sort(function(a,b){return b-a});priorities[j]=[j,priority]}let maxLevels=0,maxEntries=0;for(var j=0;j<priorities.length;j++){priorities[j][1].length>maxLevels&&(maxLevels=priorities[j][1].length);for(var k=0;k<priorities[j][1].length;k++)priorities[j][1][k].length>maxEntries&&(maxEntries=priorities[j][1][k].length)}for(var j=0;j<priorities.length;j++){let diff=maxLevels-priorities[j][1].length;for(var k=0;k<diff;k++)priorities[j][1].push([]);priorities[j][1].push([neighbours[j]]);for(var k=0;k<priorities[j][1].length;k++){let diff=maxEntries-priorities[j][1][k].length;for(var l=0;l<diff;l++)priorities[j][1][k].push(0)}}priorities.sort(function(a,b){for(var j=0;j<a[1].length;j++)for(var k=0;k<a[1][j].length;k++){if(a[1][j][k]>b[1][j][k])return-1;if(a[1][j][k]<b[1][j][k])return 1}return 0});let order=new Uint8Array(nNeighbours);for(var j=0;j<nNeighbours;j++)order[j]=priorities[j][0],vertex.value.priority=j;let posA=this.graph.vertices[neighbours[order[0]]].position,posB=this.graph.vertices[neighbours[order[1]]].position,posC=this.graph.vertices[neighbours[order[2]]].position,cwA=posA.relativeClockwise(posB,vertex.position),cwB=posA.relativeClockwise(posC,vertex.position),isCw=-1===cwA,rotation="@"===vertex.value.bracket.chirality?-1:1,rs=1==MathHelper.parityOfPermutation(order)*rotation?"R":"S",wedgeA="down",wedgeB="up";(isCw&&"R"!==rs||!isCw&&"S"!==rs)&&(vertex.value.hydrogenDirection="up",wedgeA="up",wedgeB="down"),vertex.value.hasHydrogen&&(this.graph.getEdge(vertex.id,neighbours[order[order.length-1]]).wedge=wedgeA);let wedgeOrder=Array(neighbours.length-1),showHydrogen=1<vertex.value.rings.length&&vertex.value.hasHydrogen,offset=vertex.value.hasHydrogen?1:0;for(var j=0;j<order.length-offset;j++){wedgeOrder[j]=new Uint32Array(2);let neighbour=this.graph.vertices[neighbours[order[j]]];wedgeOrder[j][0]+=neighbour.value.isStereoCenter?0:1e5,wedgeOrder[j][0]+=this.areVerticesInSameRing(neighbour,vertex)?0:1e4,wedgeOrder[j][0]+=neighbour.value.isHeteroAtom()?1e3:0,wedgeOrder[j][0]-=0===neighbour.value.subtreeDepth?1e3:0,wedgeOrder[j][0]+=1e3-neighbour.value.subtreeDepth,wedgeOrder[j][1]=neighbours[order[j]]}if(wedgeOrder.sort(function(a,b){return a[0]>b[0]?-1:a[0]<b[0]?1:0}),!showHydrogen){let wedgeId=wedgeOrder[0][1];if(vertex.value.hasHydrogen)this.graph.getEdge(vertex.id,wedgeId).wedge=wedgeB;else{let wedge=wedgeB;for(var j=order.length-1;0<=j&&(wedge=wedge===wedgeA?wedgeB:wedgeA,neighbours[order[j]]!==wedgeId);j--);this.graph.getEdge(vertex.id,wedgeId).wedge=wedge}}vertex.value.chirality=rs}}visitStereochemistry(vertexId,previousVertexId,visited,priority,maxDepth,depth,parentAtomicNumber=0){visited[vertexId]=1;let vertex=this.graph.vertices[vertexId],atomicNumber=vertex.value.getAtomicNumber();priority.length<=depth&&priority.push([]);for(var i=0;i<this.graph.getEdge(vertexId,previousVertexId).weight;i++)priority[depth].push(1e3*parentAtomicNumber+atomicNumber);let neighbours=this.graph.vertices[vertexId].neighbours;for(var i=0;i<neighbours.length;i++)1!==visited[neighbours[i]]&&depth<maxDepth-1&&this.visitStereochemistry(neighbours[i],vertexId,visited.slice(),priority,maxDepth,depth+1,atomicNumber);if(depth<maxDepth-1){let bonds=0;for(var i=0;i<neighbours.length;i++)bonds+=this.graph.getEdge(vertexId,neighbours[i]).weight;for(var i=0;i<vertex.value.getMaxBonds()-bonds;i++)priority.length<=depth+1&&priority.push([]),priority[depth+1].push(1e3*atomicNumber+1)}}initPseudoElements(){for(var i=0;i<this.graph.vertices.length;i++){const vertex=this.graph.vertices[i],neighbourIds=vertex.neighbours;let neighbours=Array(neighbourIds.length);for(var j=0;j<neighbourIds.length;j++)neighbours[j]=this.graph.vertices[neighbourIds[j]];if(3>vertex.getNeighbourCount()||0<vertex.value.rings.length)continue;if("P"===vertex.value.element)continue;if("C"===vertex.value.element&&3===neighbours.length&&"N"===neighbours[0].value.element&&"N"===neighbours[1].value.element&&"N"===neighbours[2].value.element)continue;let heteroAtomCount=0,ctn=0;for(var j=0;j<neighbours.length;j++){let neighbour=neighbours[j],neighbouringElement=neighbour.value.element,neighbourCount=neighbour.getNeighbourCount();"C"!==neighbouringElement&&"H"!==neighbouringElement&&1===neighbourCount&&heteroAtomCount++,1<neighbourCount&&ctn++}if(1<ctn||2>heteroAtomCount)continue;let previous=null;for(var j=0;j<neighbours.length;j++){let neighbour=neighbours[j];1<neighbour.getNeighbourCount()&&(previous=neighbour)}for(var j=0;j<neighbours.length;j++){let neighbour=neighbours[j];if(1<neighbour.getNeighbourCount())continue;neighbour.value.isDrawn=!1;let hydrogens=Atom.maxBonds[neighbour.value.element]-neighbour.value.bondCount,charge="";neighbour.value.bracket&&(hydrogens=neighbour.value.bracket.hcount,charge=neighbour.value.bracket.charge||0),vertex.value.attachPseudoElement(neighbour.value.element,previous?previous.value.element:null,hydrogens,charge)}}for(var i=0;i<this.graph.vertices.length;i++){const vertex=this.graph.vertices[i],atom=vertex.value,element=atom.element;if("C"===element||"H"===element||!atom.isDrawn)continue;const neighbourIds=vertex.neighbours;let neighbours=Array(neighbourIds.length);for(var j=0;j<neighbourIds.length;j++)neighbours[j]=this.graph.vertices[neighbourIds[j]];for(var j=0;j<neighbours.length;j++){let neighbour=neighbours[j].value;if(!neighbour.hasAttachedPseudoElements||2!==neighbour.getAttachedPseudoElementsCount())continue;const pseudoElements=neighbour.getAttachedPseudoElements();pseudoElements.hasOwnProperty("0O")&&pseudoElements.hasOwnProperty("3C")&&(neighbour.isDrawn=!1,vertex.value.attachPseudoElement("Ac","",0))}}}}},{"./ArrayHelper":3,"./Atom":4,"./CanvasWrapper":5,"./Edge":8,"./Graph":11,"./Line":12,"./MathHelper":13,"./Options":14,"./Ring":20,"./RingConnection":21,"./SSSR":22,"./ThemeManager":26,"./Vector2":28,"./Vertex":29}],8:[function(require,module){"use strict";class Edge{constructor(sourceId,targetId,weight=1){this.id=null,this.sourceId=sourceId,this.targetId=targetId,this.weight=weight,this.bondType="-",this.isPartOfAromaticRing=!1,this.center=!1,this.wedge=""}setBondType(bondType){this.bondType=bondType,this.weight=Edge.bonds[bondType]}static get bonds(){return{"-":1,"/":1,"\\":1,"=":2,"#":3,$:4}}}module.exports=Edge},{}],9:[function(require,module){"use strict";module.exports={C2H4O2:"acetic acid",C3H6O:"acetone",C2H3N:"acetonitrile",C6H6:"benzene",CCl4:"carbon tetrachloride",C6H5Cl:"chlorobenzene",CHCl3:"chloroform",C6H12:"cyclohexane",C2H4Cl2:"1,2-dichloroethane",C4H10O3:"diethylene glycol",C6H14O3:"diglyme",C4H10O2:"DME",C3H7NO:"DMF",C2H6OS:"DMSO",C2H6O:"ethanol",C2H6O2:"ethylene glycol",C3H8O3:"glycerin",C7H16:"heptane",C6H18N3OP:"HMPA",C6H18N3P:"HMPT",C6H14:"hexane",CH4O:"methanol",C5H12O:"MTBE",CH2Cl2:"methylene chloride",CH5H9NO:"NMP",CH3NO2:"nitromethane",C5H12:"pentane",C5H5N:"pyridine",C7H8:"toluene",C6H15N:"triethyl amine",H2O:"water"}},{}],10:[function(require,module){"use strict";var _NumberMAX_SAFE_INTEGER=Number.MAX_SAFE_INTEGER,_Mathabs3=Math.abs;const Vector2=require("./Vector2"),convertImage=require("./PixelsToSvg"),chroma=require("chroma-js");module.exports=class{constructor(points,weights,width,height,sigma=.3,interval=0,colormap=null,opacity=1,normalized=!1){if(this.points=points,this.weights=weights,this.width=width,this.height=height,this.sigma=sigma,this.interval=interval,this.opacity=opacity,this.normalized=normalized,null===colormap){colormap=["#c51b7d","#de77ae","#f1b6da","#fde0ef","#ffffff","#e6f5d0","#b8e186","#7fbc41","#4d9221"]}this.colormap=colormap,this.canvas=document.createElement("canvas"),this.context=this.canvas.getContext("2d"),this.canvas.width=this.width,this.canvas.height=this.height}setFromArray(arr_points,arr_weights){this.points=[],arr_points.forEach(a=>{this.points.push(new Vector2(a[0],a[1]))}),this.weights=[],arr_weights.forEach(w=>{this.weights.push(w)})}draw(){let m=[];for(let x=0,row;x<this.width;x++){row=[];for(let y=0;y<this.height;y++)row.push(0);m.push(row)}let divisor=1/(2*this.sigma**2);for(let i=0;i<this.points.length;i++){let v=this.points[i],a=this.weights[i];for(let x=0;x<this.width;x++)for(let y=0;y<this.height;y++){let v_xy=((x-v.x)**2+(y-v.y)**2)*divisor,val=a*Math.exp(-v_xy);m[x][y]+=val}}let abs_max=1;if(!this.normalized){let max=-_NumberMAX_SAFE_INTEGER,min=_NumberMAX_SAFE_INTEGER;for(let x=0;x<this.width;x++)for(let y=0;y<this.height;y++)m[x][y]<min&&(min=m[x][y]),m[x][y]>max&&(max=m[x][y]);abs_max=Math.max(_Mathabs3(min),_Mathabs3(max))}const scale=chroma.scale(this.colormap).domain([-1,1]);for(let x=0;x<this.width;x++)for(let y=0;y<this.height;y++){this.normalized||(m[x][y]/=abs_max),0!==this.interval&&(m[x][y]=Math.round(m[x][y]/this.interval)*this.interval);let[r,g,b]=scale(m[x][y]).rgb();this.setPixel(new Vector2(x,y),r,g,b)}}getImage(callback){let image=new Image;image.onload=()=>{this.context.imageSmoothingEnabled=!1,this.context.drawImage(image,0,0,this.width,this.height),callback&&callback(image)},image.onerror=function(err){console.log(err)},image.src=this.canvas.toDataURL()}getSVG(){return convertImage(this.context.getImageData(0,0,this.width,this.height))}setPixel(vec,r,g,b){this.context.fillStyle="rgba("+r+","+g+","+b+","+this.opacity+")",this.context.fillRect(vec.x,vec.y,1,1)}}},{"./PixelsToSvg":16,"./Vector2":28,"chroma-js":2}],11:[function(require,module){"use strict";var _Mathpow2=Math.pow,_Mathsqrt3=Math.sqrt,_Mathmin5=Math.min;const MathHelper=require("./MathHelper"),Vector2=require("./Vector2"),Vertex=require("./Vertex"),Edge=require("./Edge"),Ring=require("./Ring"),Atom=require("./Atom");class Graph{constructor(parseTree,isomeric=!1){this.vertices=[],this.edges=[],this.atomIdxToVertexId=[],this.vertexIdsToEdgeId={},this.isomeric=isomeric,this._atomIdx=0,this._time=0,this._init(parseTree)}_init(node,order=0,parentVertexId=null,isBranch=!1){const element=node.atom.element?node.atom.element:node.atom;let atom=new Atom(element,node.bond);"H"===element&&(node.hasNext||null!==parentVertexId)||(atom.idx=this._atomIdx,this._atomIdx++),atom.branchBond=node.branchBond,atom.ringbonds=node.ringbonds,atom.bracket=node.atom.element?node.atom:null,atom.class=node.atom.class;let vertex=new Vertex(atom),parentVertex=this.vertices[parentVertexId];if(this.addVertex(vertex),null!==atom.idx&&this.atomIdxToVertexId.push(vertex.id),null!==parentVertexId){vertex.setParentVertexId(parentVertexId),vertex.value.addNeighbouringElement(parentVertex.value.element),parentVertex.addChild(vertex.id),parentVertex.value.addNeighbouringElement(atom.element),parentVertex.spanningTreeChildren.push(vertex.id);let edge=new Edge(parentVertexId,vertex.id,1),vertexId=null;isBranch?(edge.setBondType(vertex.value.branchBond||"-"),vertexId=vertex.id,edge.setBondType(vertex.value.branchBond||"-"),vertexId=vertex.id):(edge.setBondType(parentVertex.value.bondType||"-"),vertexId=parentVertex.id);this.addEdge(edge)}let offset=node.ringbondCount+1;atom.bracket&&(offset+=atom.bracket.hcount);let stereoHydrogens=0;if(atom.bracket&&atom.bracket.chirality){atom.isStereoCenter=!0,stereoHydrogens=atom.bracket.hcount;for(var i=0;i<stereoHydrogens;i++)this._init({atom:"H",isBracket:"false",branches:[],branchCount:0,ringbonds:[],ringbondCount:!1,next:null,hasNext:!1,bond:"-"},i,vertex.id,!0)}for(var i=0;i<node.branchCount;i++)this._init(node.branches[i],i+offset,vertex.id,!0);node.hasNext&&this._init(node.next,node.branchCount+offset,vertex.id)}clear(){this.vertices=[],this.edges=[],this.vertexIdsToEdgeId={}}addVertex(vertex){return vertex.id=this.vertices.length,this.vertices.push(vertex),vertex.id}addEdge(edge){let source=this.vertices[edge.sourceId],target=this.vertices[edge.targetId];return edge.id=this.edges.length,this.edges.push(edge),this.vertexIdsToEdgeId[edge.sourceId+"_"+edge.targetId]=edge.id,this.vertexIdsToEdgeId[edge.targetId+"_"+edge.sourceId]=edge.id,edge.isPartOfAromaticRing=source.value.isPartOfAromaticRing&&target.value.isPartOfAromaticRing,source.value.bondCount+=edge.weight,target.value.bondCount+=edge.weight,source.edges.push(edge.id),target.edges.push(edge.id),edge.id}getEdge(vertexIdA,vertexIdB){let edgeId=this.vertexIdsToEdgeId[vertexIdA+"_"+vertexIdB];return edgeId===void 0?null:this.edges[edgeId]}getEdges(vertexId){let edgeIds=[],vertex=this.vertices[vertexId];for(var i=0;i<vertex.neighbours.length;i++)edgeIds.push(this.vertexIdsToEdgeId[vertexId+"_"+vertex.neighbours[i]]);return edgeIds}hasEdge(vertexIdA,vertexIdB){return this.vertexIdsToEdgeId[vertexIdA+"_"+vertexIdB]!==void 0}getVertexList(){let arr=[this.vertices.length];for(var i=0;i<this.vertices.length;i++)arr[i]=this.vertices[i].id;return arr}getEdgeList(){let arr=Array(this.edges.length);for(var i=0;i<this.edges.length;i++)arr[i]=[this.edges[i].sourceId,this.edges[i].targetId];return arr}getAdjacencyMatrix(){let length=this.vertices.length,adjacencyMatrix=Array(length);for(var i=0;i<length;i++)adjacencyMatrix[i]=Array(length),adjacencyMatrix[i].fill(0);for(var i=0;i<this.edges.length;i++){let edge=this.edges[i];adjacencyMatrix[edge.sourceId][edge.targetId]=1,adjacencyMatrix[edge.targetId][edge.sourceId]=1}return adjacencyMatrix}getComponentsAdjacencyMatrix(){let length=this.vertices.length,adjacencyMatrix=Array(length),bridges=this.getBridges();for(var i=0;i<length;i++)adjacencyMatrix[i]=Array(length),adjacencyMatrix[i].fill(0);for(var i=0;i<this.edges.length;i++){let edge=this.edges[i];adjacencyMatrix[edge.sourceId][edge.targetId]=1,adjacencyMatrix[edge.targetId][edge.sourceId]=1}for(var i=0;i<bridges.length;i++)adjacencyMatrix[bridges[i][0]][bridges[i][1]]=0,adjacencyMatrix[bridges[i][1]][bridges[i][0]]=0;return adjacencyMatrix}getSubgraphAdjacencyMatrix(vertexIds){let length=vertexIds.length,adjacencyMatrix=Array(length);for(var i=0;i<length;i++){adjacencyMatrix[i]=Array(length),adjacencyMatrix[i].fill(0);for(var j=0;j<length;j++)i!==j&&this.hasEdge(vertexIds[i],vertexIds[j])&&(adjacencyMatrix[i][j]=1)}return adjacencyMatrix}getDistanceMatrix(){let length=this.vertices.length,adja=this.getAdjacencyMatrix(),dist=Array(length);for(var i=0;i<length;i++)dist[i]=Array(length),dist[i].fill(1/0);for(var i=0;i<length;i++)for(var j=0;j<length;j++)1===adja[i][j]&&(dist[i][j]=1);for(var k=0;k<length;k++)for(var i=0;i<length;i++)for(var j=0;j<length;j++)dist[i][j]>dist[i][k]+dist[k][j]&&(dist[i][j]=dist[i][k]+dist[k][j]);return dist}getSubgraphDistanceMatrix(vertexIds){let length=vertexIds.length,adja=this.getSubgraphAdjacencyMatrix(vertexIds),dist=Array(length);for(var i=0;i<length;i++)dist[i]=Array(length),dist[i].fill(1/0);for(var i=0;i<length;i++)for(var j=0;j<length;j++)1===adja[i][j]&&(dist[i][j]=1);for(var k=0;k<length;k++)for(var i=0;i<length;i++)for(var j=0;j<length;j++)dist[i][j]>dist[i][k]+dist[k][j]&&(dist[i][j]=dist[i][k]+dist[k][j]);return dist}getAdjacencyList(){let length=this.vertices.length,adjacencyList=Array(length);for(var i=0;i<length;i++){adjacencyList[i]=[];for(var j=0;j<length;j++)i!==j&&this.hasEdge(this.vertices[i].id,this.vertices[j].id)&&adjacencyList[i].push(j)}return adjacencyList}getSubgraphAdjacencyList(vertexIds){let length=vertexIds.length,adjacencyList=Array(length);for(var i=0;i<length;i++){adjacencyList[i]=[];for(var j=0;j<length;j++)i!==j&&this.hasEdge(vertexIds[i],vertexIds[j])&&adjacencyList[i].push(j)}return adjacencyList}getBridges(){let length=this.vertices.length,visited=Array(length),disc=Array(length),low=Array(length),parent=Array(length),adj=this.getAdjacencyList(),outBridges=[];visited.fill(!1),parent.fill(null),this._time=0;for(var i=0;i<length;i++)visited[i]||this._bridgeDfs(i,visited,disc,low,parent,adj,outBridges);return outBridges}traverseBF(startVertexId,callback){let length=this.vertices.length,visited=Array(length);visited.fill(!1);for(var queue=[startVertexId];0<queue.length;){let u=queue.shift(),vertex=this.vertices[u];callback(vertex);for(var i=0;i<vertex.neighbours.length;i++){let v=vertex.neighbours[i];visited[v]||(visited[v]=!0,queue.push(v))}}}getTreeDepth(vertexId,parentVertexId){if(null===vertexId||null===parentVertexId)return 0;let neighbours=this.vertices[vertexId].getSpanningTreeNeighbours(parentVertexId),max=0;for(var i=0;i<neighbours.length;i++){let childId=neighbours[i],d=this.getTreeDepth(childId,vertexId);d>max&&(max=d)}return max+1}traverseTree(vertexId,parentVertexId,callback,maxDepth=999999,ignoreFirst=!1,depth=1,visited=null){if(null===visited&&(visited=new Uint8Array(this.vertices.length)),depth>maxDepth+1||1===visited[vertexId])return;visited[vertexId]=1;let vertex=this.vertices[vertexId],neighbours=vertex.getNeighbours(parentVertexId);(!ignoreFirst||1<depth)&&callback(vertex);for(var i=0;i<neighbours.length;i++)this.traverseTree(neighbours[i],vertexId,callback,maxDepth,ignoreFirst,depth+1,visited)}kkLayout(vertexIds,center,startVertexId,ring,bondLength,threshold=.1,innerThreshold=.1,maxIteration=2e3,maxInnerIteration=50,maxEnergy=1e9){for(var i=vertexIds.length;i--;){let vertex=this.vertices[vertexIds[i]];var j=vertex.neighbours.length}let matDist=this.getSubgraphDistanceMatrix(vertexIds),length=vertexIds.length,radius=MathHelper.polyCircumradius(500,length),angle=MathHelper.centralAngle(length),a=0,arrPositionX=new Float32Array(length),arrPositionY=new Float32Array(length),arrPositioned=Array(length);for(i=length;i--;){let vertex=this.vertices[vertexIds[i]];vertex.positioned?(arrPositionX[i]=vertex.position.x,arrPositionY[i]=vertex.position.y):(arrPositionX[i]=center.x+Math.cos(a)*radius,arrPositionY[i]=center.y+Math.sin(a)*radius),arrPositioned[i]=vertex.positioned,a+=angle}let matLength=Array(length);for(i=length;i--;){matLength[i]=Array(length);for(var j=length;j--;)matLength[i][j]=bondLength*matDist[i][j]}let matStrength=Array(length);for(i=length;i--;){matStrength[i]=Array(length);for(var j=length;j--;)matStrength[i][j]=bondLength*_Mathpow2(matDist[i][j],-2)}let matEnergy=Array(length),arrEnergySumX=new Float32Array(length),arrEnergySumY=new Float32Array(length);for(i=length;i--;)matEnergy[i]=Array(length);i=length;for(let ux,uy,dEx,dEy,vx,vy,denom;i--;){ux=arrPositionX[i],uy=arrPositionY[i],dEx=0,dEy=0;for(let j=length;j--;)i!==j&&(vx=arrPositionX[j],vy=arrPositionY[j],denom=1/_Mathsqrt3((ux-vx)*(ux-vx)+(uy-vy)*(uy-vy)),matEnergy[i][j]=[matStrength[i][j]*(ux-vx-matLength[i][j]*(ux-vx)*denom),matStrength[i][j]*(uy-vy-matLength[i][j]*(uy-vy)*denom)],matEnergy[j][i]=matEnergy[i][j],dEx+=matEnergy[i][j][0],dEy+=matEnergy[i][j][1]);arrEnergySumX[i]=dEx,arrEnergySumY[i]=dEy}let energy=function(index){return[arrEnergySumX[index]*arrEnergySumX[index]+arrEnergySumY[index]*arrEnergySumY[index],arrEnergySumX[index],arrEnergySumY[index]]},highestEnergy=function(){let maxEnergy=0,maxEnergyId=0,maxDEX=0,maxDEY=0;for(i=length;i--;){let[delta,dEX,dEY]=energy(i);delta>maxEnergy&&!1===arrPositioned[i]&&(maxEnergy=delta,maxEnergyId=i,maxDEX=dEX,maxDEY=dEY)}return[maxEnergyId,maxEnergy,maxDEX,maxDEY]},update=function(index,dEX,dEY){let dxx=0,dyy=0,dxy=0,ux=arrPositionX[index],uy=arrPositionY[index],arrL=matLength[index],arrK=matStrength[index];for(i=length;i--;){if(i===index)continue;let vx=arrPositionX[i],vy=arrPositionY[i],l=arrL[i],k=arrK[i],m=(ux-vx)*(ux-vx),denom=1/_Mathpow2(m+(uy-vy)*(uy-vy),1.5);dxx+=k*(1-l*(uy-vy)*(uy-vy)*denom),dyy+=k*(1-l*m*denom),dxy+=k*(l*(ux-vx)*(uy-vy)*denom)}0==dxx&&(dxx=.1),0===dyy&&(dyy=.1),0===dxy&&(dxy=.1);let dy=dEX/dxx+dEY/dxy;dy/=dxy/dxx-dyy/dxy;let dx=-(dxy*dy+dEX)/dxx;arrPositionX[index]+=dx,arrPositionY[index]+=dy;let arrE=matEnergy[index];dEX=0,dEY=0,ux=arrPositionX[index],uy=arrPositionY[index];let vx,vy,prevEx,prevEy,denom;for(i=length;i--;)index!==i&&(vx=arrPositionX[i],vy=arrPositionY[i],prevEx=arrE[i][0],prevEy=arrE[i][1],denom=1/_Mathsqrt3((ux-vx)*(ux-vx)+(uy-vy)*(uy-vy)),dx=arrK[i]*(ux-vx-arrL[i]*(ux-vx)*denom),dy=arrK[i]*(uy-vy-arrL[i]*(uy-vy)*denom),arrE[i]=[dx,dy],dEX+=dx,dEY+=dy,arrEnergySumX[i]+=dx-prevEx,arrEnergySumY[i]+=dy-prevEy);arrEnergySumX[index]=dEX,arrEnergySumY[index]=dEY},maxEnergyId=0,dEX=0,dEY=0,delta=0,iteration=0,innerIteration=0;for(;maxEnergy>threshold&&maxIteration>iteration;)for(iteration++,[maxEnergyId,maxEnergy,dEX,dEY]=highestEnergy(),delta=maxEnergy,innerIteration=0;delta>innerThreshold&&maxInnerIteration>innerIteration;)innerIteration++,update(maxEnergyId,dEX,dEY),[delta,dEX,dEY]=energy(maxEnergyId);for(i=length;i--;){let index=vertexIds[i],vertex=this.vertices[index];vertex.position.x=arrPositionX[i],vertex.position.y=arrPositionY[i],vertex.positioned=!0,vertex.forcePositioned=!0}}_bridgeDfs(u,visited,disc,low,parent,adj,outBridges){visited[u]=!0,disc[u]=low[u]=++this._time;for(var i=0;i<adj[u].length;i++){let v=adj[u][i];visited[v]?v!==parent[u]&&(low[u]=_Mathmin5(low[u],disc[v])):(parent[v]=u,this._bridgeDfs(v,visited,disc,low,parent,adj,outBridges),low[u]=_Mathmin5(low[u],low[v]),low[v]>disc[u]&&outBridges.push([u,v]))}}static getConnectedComponents(adjacencyMatrix){let length=adjacencyMatrix.length,visited=Array(length),components=[],count=0;visited.fill(!1);for(var u=0;u<length;u++)if(!visited[u]){let component=[];visited[u]=!0,component.push(u),count++,Graph._ccGetDfs(u,visited,adjacencyMatrix,component),1<component.length&&components.push(component)}return components}static getConnectedComponentCount(adjacencyMatrix){let length=adjacencyMatrix.length,visited=Array(length),count=0;visited.fill(!1);for(var u=0;u<length;u++)visited[u]||(visited[u]=!0,count++,Graph._ccCountDfs(u,visited,adjacencyMatrix));return count}static _ccCountDfs(u,visited,adjacencyMatrix){for(var v=0;v<adjacencyMatrix[u].length;v++){let c=adjacencyMatrix[u][v];c&&!visited[v]&&u!==v&&(visited[v]=!0,Graph._ccCountDfs(v,visited,adjacencyMatrix))}}static _ccGetDfs(u,visited,adjacencyMatrix,component){for(var v=0;v<adjacencyMatrix[u].length;v++){let c=adjacencyMatrix[u][v];c&&!visited[v]&&u!==v&&(visited[v]=!0,component.push(v),Graph._ccGetDfs(v,visited,adjacencyMatrix,component))}}}module.exports=Graph},{"./Atom":4,"./Edge":8,"./MathHelper":13,"./Ring":20,"./Vector2":28,"./Vertex":29}],12:[function(require,module){"use strict";var _Mathsin3=Math.sin,_Mathpow3=Math.pow,_Mathcos3=Math.cos;const Vector2=require("./Vector2");class Line{constructor(from=new Vector2(0,0),to=new Vector2(0,0),elementFrom=null,elementTo=null,chiralFrom=!1,chiralTo=!1){this.from=from,this.to=to,this.elementFrom=elementFrom,this.elementTo=elementTo,this.chiralFrom=chiralFrom,this.chiralTo=chiralTo}clone(){return new Line(this.from.clone(),this.to.clone(),this.elementFrom,this.elementTo)}getLength(){return Math.sqrt(_Mathpow3(this.to.x-this.from.x,2)+_Mathpow3(this.to.y-this.from.y,2))}getAngle(){let diff=Vector2.subtract(this.getRightVector(),this.getLeftVector());return diff.angle()}getRightVector(){return this.from.x<this.to.x?this.to:this.from}getLeftVector(){return this.from.x<this.to.x?this.from:this.to}getRightElement(){return this.from.x<this.to.x?this.elementTo:this.elementFrom}getLeftElement(){return this.from.x<this.to.x?this.elementFrom:this.elementTo}getRightChiral(){return this.from.x<this.to.x?this.chiralTo:this.chiralFrom}getLeftChiral(){return this.from.x<this.to.x?this.chiralFrom:this.chiralTo}setRightVector(x,y){return this.from.x<this.to.x?(this.to.x=x,this.to.y=y):(this.from.x=x,this.from.y=y),this}setLeftVector(x,y){return this.from.x<this.to.x?(this.from.x=x,this.from.y=y):(this.to.x=x,this.to.y=y),this}rotateToXAxis(){let left=this.getLeftVector();return this.setRightVector(left.x+this.getLength(),left.y),this}rotate(theta){let l=this.getLeftVector(),r=this.getRightVector(),sinTheta=_Mathsin3(theta),cosTheta=_Mathcos3(theta),x=cosTheta*(r.x-l.x)-sinTheta*(r.y-l.y)+l.x,y=sinTheta*(r.x-l.x)-cosTheta*(r.y-l.y)+l.y;return this.setRightVector(x,y),this}shortenFrom(by){let f=Vector2.subtract(this.to,this.from);return f.normalize(),f.multiplyScalar(by),this.from.add(f),this}shortenTo(by){let f=Vector2.subtract(this.from,this.to);return f.normalize(),f.multiplyScalar(by),this.to.add(f),this}shortenRight(by){return this.from.x<this.to.x?this.shortenTo(by):this.shortenFrom(by),this}shortenLeft(by){return this.from.x<this.to.x?this.shortenFrom(by):this.shortenTo(by),this}shorten(by){let f=Vector2.subtract(this.from,this.to);return f.normalize(),f.multiplyScalar(by/2),this.to.add(f),this.from.subtract(f),this}}module.exports=Line},{"./Vector2":28}],13:[function(require,module){"use strict";var _Mathsin4=Math.sin,_Mathcos4=Math.cos,_Mathround2=Math.round,_MathPI3=Math.PI;class MathHelper{static round(value,decimals){return decimals=decimals?decimals:1,+(_Mathround2(value+"e"+decimals)+"e-"+decimals)}static meanAngle(arr){let sin=0,cos=0;for(var i=0;i<arr.length;i++)sin+=_Mathsin4(arr[i]),cos+=_Mathcos4(arr[i]);return Math.atan2(sin/arr.length,cos/arr.length)}static innerAngle(n){return MathHelper.toRad(180*(n-2)/n)}static polyCircumradius(s,n){return s/(2*_Mathsin4(_MathPI3/n))}static apothem(r,n){return r*_Mathcos4(_MathPI3/n)}static apothemFromSideLength(s,n){let r=MathHelper.polyCircumradius(s,n);return MathHelper.apothem(r,n)}static centralAngle(n){return MathHelper.toRad(360/n)}static toDeg(rad){return rad*MathHelper.degFactor}static toRad(deg){return deg*MathHelper.radFactor}static parityOfPermutation(arr){let visited=new Uint8Array(arr.length),evenLengthCycleCount=0,traverseCycle=function(i,cycleLength=0){return 1===visited[i]?cycleLength:(cycleLength++,visited[i]=1,traverseCycle(arr[i],cycleLength))};for(var i=0;i<arr.length;i++){if(1===visited[i])continue;let cycleLength=traverseCycle(i);evenLengthCycleCount+=1-cycleLength%2}return evenLengthCycleCount%2?-1:1}static get radFactor(){return _MathPI3/180}static get degFactor(){return 180/_MathPI3}static get twoPI(){return 2*_MathPI3}}module.exports=MathHelper},{}],14:[function(require,module){"use strict";module.exports=class{static extend(){let that=this,extended={},deep=!1,i=0,length=arguments.length;"[object Boolean]"===Object.prototype.toString.call(arguments[0])&&(deep=arguments[0],i++);for(let merge=function(obj){for(var prop in obj)Object.prototype.hasOwnProperty.call(obj,prop)&&(extended[prop]=deep&&"[object Object]"===Object.prototype.toString.call(obj[prop])?that.extend(!0,extended[prop],obj[prop]):obj[prop])};i<length;i++){let obj=arguments[i];merge(obj)}return extended}}},{}],15:[function(require,module){"use strict";module.exports=function(){function peg$SyntaxError(message,expected,found,location){this.message=message,this.expected=expected,this.found=found,this.location=location,this.name="SyntaxError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,peg$SyntaxError)}function peg$parse(input,options){function peg$literalExpectation(text,ignoreCase){return{type:"literal",text:text,ignoreCase:ignoreCase}}function peg$classExpectation(parts,inverted,ignoreCase){return{type:"class",parts:parts,inverted:inverted,ignoreCase:ignoreCase}}function peg$computePosDetails(pos){var details=peg$posDetailsCache[pos],p;if(details)return details;for(p=pos-1;!peg$posDetailsCache[p];)p--;for(details=peg$posDetailsCache[p],details={line:details.line,column:details.column};p<pos;)10===input.charCodeAt(p)?(details.line++,details.column=1):details.column++,p++;return peg$posDetailsCache[pos]=details,details}function peg$computeLocation(startPos,endPos){var startPosDetails=peg$computePosDetails(startPos),endPosDetails=peg$computePosDetails(endPos);return{start:{offset:startPos,line:startPosDetails.line,column:startPosDetails.column},end:{offset:endPos,line:endPosDetails.line,column:endPosDetails.column}}}function peg$fail(expected){peg$currPos<peg$maxFailPos||(peg$currPos>peg$maxFailPos&&(peg$maxFailPos=peg$currPos,peg$maxFailExpected=[]),peg$maxFailExpected.push(expected))}function peg$buildSimpleError(message,location){return new peg$SyntaxError(message,null,null,location)}function peg$parsechain(){var s0,s1,s2,s3,s4,s5,s6,s7,s8,s9;if(s0=peg$currPos,s1=peg$currPos,s2=peg$parseatom(),s2!==peg$FAILED){for(s3=[],s4=peg$parsebranch();s4!==peg$FAILED;)s3.push(s4),s4=peg$parsebranch();if(s3!==peg$FAILED){for(s4=[],s5=peg$currPos,s6=peg$parsebond(),s6===peg$FAILED&&(s6=null),s6===peg$FAILED?(peg$currPos=s5,s5=peg$FAILED):(s7=peg$parsering(),s7===peg$FAILED?(peg$currPos=s5,s5=peg$FAILED):(s6=[s6,s7],s5=s6));s5!==peg$FAILED;)s4.push(s5),s5=peg$currPos,s6=peg$parsebond(),s6===peg$FAILED&&(s6=null),s6===peg$FAILED?(peg$currPos=s5,s5=peg$FAILED):(s7=peg$parsering(),s7===peg$FAILED?(peg$currPos=s5,s5=peg$FAILED):(s6=[s6,s7],s5=s6));if(s4!==peg$FAILED){for(s5=[],s6=peg$parsebranch();s6!==peg$FAILED;)s5.push(s6),s6=peg$parsebranch();if(s5===peg$FAILED)peg$currPos=s1,s1=peg$FAILED;else if(s6=peg$parsebond(),s6===peg$FAILED&&(s6=null),s6===peg$FAILED)peg$currPos=s1,s1=peg$FAILED;else if(s7=peg$parsechain(),s7===peg$FAILED&&(s7=null),s7!==peg$FAILED){for(s8=[],s9=peg$parsebranch();s9!==peg$FAILED;)s8.push(s9),s9=peg$parsebranch();s8===peg$FAILED?(peg$currPos=s1,s1=peg$FAILED):(s2=[s2,s3,s4,s5,s6,s7,s8],s1=s2)}else peg$currPos=s1,s1=peg$FAILED}else peg$currPos=s1,s1=peg$FAILED}else peg$currPos=s1,s1=peg$FAILED}else peg$currPos=s1,s1=peg$FAILED;return s1!==peg$FAILED&&(peg$savedPos=s0,s1=peg$c0(s1)),s0=s1,s0}function peg$parsebranch(){var s0,s1,s2,s3,s4,s5;return s0=peg$currPos,s1=peg$currPos,40===input.charCodeAt(peg$currPos)?(s2="(",peg$currPos++):(s2=peg$FAILED,peg$fail(peg$c2)),s2===peg$FAILED?(peg$currPos=s1,s1=peg$FAILED):(s3=peg$parsebond(),s3===peg$FAILED&&(s3=null),s3===peg$FAILED?(peg$currPos=s1,s1=peg$FAILED):(s4=peg$parsechain(),s4===peg$FAILED?(peg$currPos=s1,s1=peg$FAILED):(41===input.charCodeAt(peg$currPos)?(s5=")",peg$currPos++):(s5=peg$FAILED,peg$fail(peg$c4)),s5===peg$FAILED?(peg$currPos=s1,s1=peg$FAILED):(s2=[s2,s3,s4,s5],s1=s2)))),s1!==peg$FAILED&&(peg$savedPos=s0,s1=peg$c5(s1)),s0=s1,s0}function peg$parseatom(){var s0,s1;return s0=peg$currPos,s1=peg$parseorganicsymbol(),s1===peg$FAILED&&(s1=peg$parsearomaticsymbol(),s1===peg$FAILED&&(s1=peg$parsebracketatom(),s1===peg$FAILED&&(s1=peg$parsewildcard()))),s1!==peg$FAILED&&(peg$savedPos=s0,s1=peg$c6(s1)),s0=s1,s0}function peg$parsebond(){var s0,s1;if(s0=peg$currPos,peg$c7.test(input.charAt(peg$currPos))){if(s1=input.charAt(peg$currPos),s1===input.charAt(peg$currPos+1))throw s1=peg$FAILED,peg$buildSimpleError("The parser encountered a bond repetition.",peg$currPos+1);peg$currPos++}else s1=peg$FAILED,peg$fail(peg$c8);return s1!==peg$FAILED&&(peg$savedPos=s0,s1=peg$c9(s1)),s0=s1,s0}function peg$parsebracketatom(){var s0,s1,s2,s3,s4,s5,s6,s7,s8,s9;return s0=peg$currPos,s1=peg$currPos,91===input.charCodeAt(peg$currPos)?(s2="[",peg$currPos++):(s2=peg$FAILED,peg$fail(peg$c11)),s2===peg$FAILED?(peg$currPos=s1,s1=peg$FAILED):(s3=peg$parseisotope(),s3===peg$FAILED&&(s3=null),s3===peg$FAILED?(peg$currPos=s1,s1=peg$FAILED):("se"===input.substr(peg$currPos,2)?(s4="se",peg$currPos+=2):(s4=peg$FAILED,peg$fail(peg$c13)),s4===peg$FAILED&&("as"===input.substr(peg$currPos,2)?(s4="as",peg$currPos+=2):(s4=peg$FAILED,peg$fail(peg$c15)),s4===peg$FAILED&&(s4=peg$parsearomaticsymbol(),s4===peg$FAILED&&(s4=peg$parseelementsymbol(),s4===peg$FAILED&&(s4=peg$parsewildcard())))),s4===peg$FAILED?(peg$currPos=s1,s1=peg$FAILED):(s5=peg$parsechiral(),s5===peg$FAILED&&(s5=null),s5===peg$FAILED?(peg$currPos=s1,s1=peg$FAILED):(s6=peg$parsehcount(),s6===peg$FAILED&&(s6=null),s6===peg$FAILED?(peg$currPos=s1,s1=peg$FAILED):(s7=peg$parsecharge(),s7===peg$FAILED&&(s7=null),s7===peg$FAILED?(peg$currPos=s1,s1=peg$FAILED):(s8=peg$parseclass(),s8===peg$FAILED&&(s8=null),s8===peg$FAILED?(peg$currPos=s1,s1=peg$FAILED):(93===input.charCodeAt(peg$currPos)?(s9="]",peg$currPos++):(s9=peg$FAILED,peg$fail(peg$c17)),s9===peg$FAILED?(peg$currPos=s1,s1=peg$FAILED):(s2=[s2,s3,s4,s5,s6,s7,s8,s9],s1=s2)))))))),s1!==peg$FAILED&&(peg$savedPos=s0,s1=peg$c18(s1)),s0=s1,s0}function peg$parseorganicsymbol(){var s0,s1,s2,s3;return s0=peg$currPos,s1=peg$currPos,66===input.charCodeAt(peg$currPos)?(s2="B",peg$currPos++):(s2=peg$FAILED,peg$fail(peg$c20)),s2===peg$FAILED?(peg$currPos=s1,s1=peg$FAILED):(114===input.charCodeAt(peg$currPos)?(s3="r",peg$currPos++):(s3=peg$FAILED,peg$fail(peg$c22)),s3===peg$FAILED&&(s3=null),s3===peg$FAILED?(peg$currPos=s1,s1=peg$FAILED):(s2=[s2,s3],s1=s2)),s1===peg$FAILED&&(s1=peg$currPos,67===input.charCodeAt(peg$currPos)?(s2="C",peg$currPos++):(s2=peg$FAILED,peg$fail(peg$c24)),s2===peg$FAILED?(peg$currPos=s1,s1=peg$FAILED):(108===input.charCodeAt(peg$currPos)?(s3="l",peg$currPos++):(s3=peg$FAILED,peg$fail(peg$c26)),s3===peg$FAILED&&(s3=null),s3===peg$FAILED?(peg$currPos=s1,s1=peg$FAILED):(s2=[s2,s3],s1=s2)),s1===peg$FAILED&&(peg$c27.test(input.charAt(peg$currPos))?(s1=input.charAt(peg$currPos),peg$currPos++):(s1=peg$FAILED,peg$fail(peg$c28)))),s1!==peg$FAILED&&(peg$savedPos=s0,s1=peg$c29(s1)),s0=s1,s0}function peg$parsearomaticsymbol(){var s0,s1;return s0=peg$currPos,peg$c30.test(input.charAt(peg$currPos))?(s1=input.charAt(peg$currPos),peg$currPos++):(s1=peg$FAILED,peg$fail(peg$c31)),s1!==peg$FAILED&&(peg$savedPos=s0,s1=peg$c6(s1)),s0=s1,s0}function peg$parsewildcard(){var s0,s1;return s0=peg$currPos,42===input.charCodeAt(peg$currPos)?(s1="*",peg$currPos++):(s1=peg$FAILED,peg$fail(peg$c33)),s1!==peg$FAILED&&(peg$savedPos=s0,s1=peg$c34(s1)),s0=s1,s0}function peg$parseelementsymbol(){var s0,s1,s2,s3;return s0=peg$currPos,s1=peg$currPos,peg$c35.test(input.charAt(peg$currPos))?(s2=input.charAt(peg$currPos),peg$currPos++):(s2=peg$FAILED,peg$fail(peg$c36)),s2===peg$FAILED?(peg$currPos=s1,s1=peg$FAILED):(peg$c37.test(input.charAt(peg$currPos))?(s3=input.charAt(peg$currPos),peg$currPos++):(s3=peg$FAILED,peg$fail(peg$c38)),s3===peg$FAILED&&(s3=null),s3===peg$FAILED?(peg$currPos=s1,s1=peg$FAILED):(s2=[s2,s3],s1=s2)),s1!==peg$FAILED&&(peg$savedPos=s0,s1=peg$c39(s1)),s0=s1,s0}function peg$parsering(){var s0,s1,s2,s3,s4;return s0=peg$currPos,s1=peg$currPos,37===input.charCodeAt(peg$currPos)?(s2="%",peg$currPos++):(s2=peg$FAILED,peg$fail(peg$c41)),s2===peg$FAILED?(peg$currPos=s1,s1=peg$FAILED):(peg$c42.test(input.charAt(peg$currPos))?(s3=input.charAt(peg$currPos),peg$currPos++):(s3=peg$FAILED,peg$fail(peg$c43)),s3===peg$FAILED?(peg$currPos=s1,s1=peg$FAILED):(peg$c44.test(input.charAt(peg$currPos))?(s4=input.charAt(peg$currPos),peg$currPos++):(s4=peg$FAILED,peg$fail(peg$c45)),s4===peg$FAILED?(peg$currPos=s1,s1=peg$FAILED):(s2=[s2,s3,s4],s1=s2))),s1===peg$FAILED&&(peg$c44.test(input.charAt(peg$currPos))?(s1=input.charAt(peg$currPos),peg$currPos++):(s1=peg$FAILED,peg$fail(peg$c45))),s1!==peg$FAILED&&(peg$savedPos=s0,s1=peg$c46(s1)),s0=s1,s0}function peg$parsechiral(){var s0,s1,s2,s3,s4,s5,s6;return s0=peg$currPos,s1=peg$currPos,64===input.charCodeAt(peg$currPos)?(s2="@",peg$currPos++):(s2=peg$FAILED,peg$fail(peg$c48)),s2===peg$FAILED?(peg$currPos=s1,s1=peg$FAILED):(64===input.charCodeAt(peg$currPos)?(s3="@",peg$currPos++):(s3=peg$FAILED,peg$fail(peg$c48)),s3===peg$FAILED&&(s3=peg$currPos,"TH"===input.substr(peg$currPos,2)?(s4="TH",peg$currPos+=2):(s4=peg$FAILED,peg$fail(peg$c50)),s4===peg$FAILED?(peg$currPos=s3,s3=peg$FAILED):(peg$c51.test(input.charAt(peg$currPos))?(s5=input.charAt(peg$currPos),peg$currPos++):(s5=peg$FAILED,peg$fail(peg$c52)),s5===peg$FAILED?(peg$currPos=s3,s3=peg$FAILED):(s4=[s4,s5],s3=s4)),s3===peg$FAILED&&(s3=peg$currPos,"AL"===input.substr(peg$currPos,2)?(s4="AL",peg$currPos+=2):(s4=peg$FAILED,peg$fail(peg$c54)),s4===peg$FAILED?(peg$currPos=s3,s3=peg$FAILED):(peg$c51.test(input.charAt(peg$currPos))?(s5=input.charAt(peg$currPos),peg$currPos++):(s5=peg$FAILED,peg$fail(peg$c52)),s5===peg$FAILED?(peg$currPos=s3,s3=peg$FAILED):(s4=[s4,s5],s3=s4)),s3===peg$FAILED&&(s3=peg$currPos,"SP"===input.substr(peg$currPos,2)?(s4="SP",peg$currPos+=2):(s4=peg$FAILED,peg$fail(peg$c56)),s4===peg$FAILED?(peg$currPos=s3,s3=peg$FAILED):(peg$c57.test(input.charAt(peg$currPos))?(s5=input.charAt(peg$currPos),peg$currPos++):(s5=peg$FAILED,peg$fail(peg$c58)),s5===peg$FAILED?(peg$currPos=s3,s3=peg$FAILED):(s4=[s4,s5],s3=s4)),s3===peg$FAILED&&(s3=peg$currPos,"TB"===input.substr(peg$currPos,2)?(s4="TB",peg$currPos+=2):(s4=peg$FAILED,peg$fail(peg$c60)),s4===peg$FAILED?(peg$currPos=s3,s3=peg$FAILED):(peg$c42.test(input.charAt(peg$currPos))?(s5=input.charAt(peg$currPos),peg$currPos++):(s5=peg$FAILED,peg$fail(peg$c43)),s5===peg$FAILED?(peg$currPos=s3,s3=peg$FAILED):(peg$c44.test(input.charAt(peg$currPos))?(s6=input.charAt(peg$currPos),peg$currPos++):(s6=peg$FAILED,peg$fail(peg$c45)),s6===peg$FAILED&&(s6=null),s6===peg$FAILED?(peg$currPos=s3,s3=peg$FAILED):(s4=[s4,s5,s6],s3=s4))),s3===peg$FAILED&&(s3=peg$currPos,"OH"===input.substr(peg$currPos,2)?(s4="OH",peg$currPos+=2):(s4=peg$FAILED,peg$fail(peg$c62)),s4===peg$FAILED?(peg$currPos=s3,s3=peg$FAILED):(peg$c42.test(input.charAt(peg$currPos))?(s5=input.charAt(peg$currPos),peg$currPos++):(s5=peg$FAILED,peg$fail(peg$c43)),s5===peg$FAILED?(peg$currPos=s3,s3=peg$FAILED):(peg$c44.test(input.charAt(peg$currPos))?(s6=input.charAt(peg$currPos),peg$currPos++):(s6=peg$FAILED,peg$fail(peg$c45)),s6===peg$FAILED&&(s6=null),s6===peg$FAILED?(peg$currPos=s3,s3=peg$FAILED):(s4=[s4,s5,s6],s3=s4)))))))),s3===peg$FAILED&&(s3=null),s3===peg$FAILED?(peg$currPos=s1,s1=peg$FAILED):(s2=[s2,s3],s1=s2)),s1!==peg$FAILED&&(peg$savedPos=s0,s1=peg$c63(s1)),s0=s1,s0}function peg$parsecharge(){var s0,s1;return s0=peg$currPos,s1=peg$parseposcharge(),s1===peg$FAILED&&(s1=peg$parsenegcharge()),s1!==peg$FAILED&&(peg$savedPos=s0,s1=peg$c64(s1)),s0=s1,s0}function peg$parseposcharge(){var s0,s1,s2,s3,s4,s5;return s0=peg$currPos,s1=peg$currPos,43===input.charCodeAt(peg$currPos)?(s2="+",peg$currPos++):(s2=peg$FAILED,peg$fail(peg$c66)),s2===peg$FAILED?(peg$currPos=s1,s1=peg$FAILED):(43===input.charCodeAt(peg$currPos)?(s3="+",peg$currPos++):(s3=peg$FAILED,peg$fail(peg$c66)),s3===peg$FAILED&&(s3=peg$currPos,peg$c42.test(input.charAt(peg$currPos))?(s4=input.charAt(peg$currPos),peg$currPos++):(s4=peg$FAILED,peg$fail(peg$c43)),s4===peg$FAILED?(peg$currPos=s3,s3=peg$FAILED):(peg$c44.test(input.charAt(peg$currPos))?(s5=input.charAt(peg$currPos),peg$currPos++):(s5=peg$FAILED,peg$fail(peg$c45)),s5===peg$FAILED&&(s5=null),s5===peg$FAILED?(peg$currPos=s3,s3=peg$FAILED):(s4=[s4,s5],s3=s4))),s3===peg$FAILED&&(s3=null),s3===peg$FAILED?(peg$currPos=s1,s1=peg$FAILED):(s2=[s2,s3],s1=s2)),s1!==peg$FAILED&&(peg$savedPos=s0,s1=peg$c67(s1)),s0=s1,s0}function peg$parsenegcharge(){var s0,s1,s2,s3,s4,s5;return s0=peg$currPos,s1=peg$currPos,45===input.charCodeAt(peg$currPos)?(s2="-",peg$currPos++):(s2=peg$FAILED,peg$fail(peg$c69)),s2===peg$FAILED?(peg$currPos=s1,s1=peg$FAILED):(45===input.charCodeAt(peg$currPos)?(s3="-",peg$currPos++):(s3=peg$FAILED,peg$fail(peg$c69)),s3===peg$FAILED&&(s3=peg$currPos,peg$c42.test(input.charAt(peg$currPos))?(s4=input.charAt(peg$currPos),peg$currPos++):(s4=peg$FAILED,peg$fail(peg$c43)),s4===peg$FAILED?(peg$currPos=s3,s3=peg$FAILED):(peg$c44.test(input.charAt(peg$currPos))?(s5=input.charAt(peg$currPos),peg$currPos++):(s5=peg$FAILED,peg$fail(peg$c45)),s5===peg$FAILED&&(s5=null),s5===peg$FAILED?(peg$currPos=s3,s3=peg$FAILED):(s4=[s4,s5],s3=s4))),s3===peg$FAILED&&(s3=null),s3===peg$FAILED?(peg$currPos=s1,s1=peg$FAILED):(s2=[s2,s3],s1=s2)),s1!==peg$FAILED&&(peg$savedPos=s0,s1=peg$c70(s1)),s0=s1,s0}function peg$parsehcount(){var s0,s1,s2,s3;return s0=peg$currPos,s1=peg$currPos,72===input.charCodeAt(peg$currPos)?(s2="H",peg$currPos++):(s2=peg$FAILED,peg$fail(peg$c72)),s2===peg$FAILED?(peg$currPos=s1,s1=peg$FAILED):(peg$c44.test(input.charAt(peg$currPos))?(s3=input.charAt(peg$currPos),peg$currPos++):(s3=peg$FAILED,peg$fail(peg$c45)),s3===peg$FAILED&&(s3=null),s3===peg$FAILED?(peg$currPos=s1,s1=peg$FAILED):(s2=[s2,s3],s1=s2)),s1!==peg$FAILED&&(peg$savedPos=s0,s1=peg$c73(s1)),s0=s1,s0}function peg$parseclass(){var s0,s1,s2,s3,s4,s5,s6;if(s0=peg$currPos,s1=peg$currPos,58===input.charCodeAt(peg$currPos)?(s2=":",peg$currPos++):(s2=peg$FAILED,peg$fail(peg$c75)),s2!==peg$FAILED){if(s3=peg$currPos,peg$c42.test(input.charAt(peg$currPos))?(s4=input.charAt(peg$currPos),peg$currPos++):(s4=peg$FAILED,peg$fail(peg$c43)),s4!==peg$FAILED){for(s5=[],peg$c44.test(input.charAt(peg$currPos))?(s6=input.charAt(peg$currPos),peg$currPos++):(s6=peg$FAILED,peg$fail(peg$c45));s6!==peg$FAILED;)s5.push(s6),peg$c44.test(input.charAt(peg$currPos))?(s6=input.charAt(peg$currPos),peg$currPos++):(s6=peg$FAILED,peg$fail(peg$c45));s5===peg$FAILED?(peg$currPos=s3,s3=peg$FAILED):(s4=[s4,s5],s3=s4)}else peg$currPos=s3,s3=peg$FAILED;s3===peg$FAILED&&(peg$c76.test(input.charAt(peg$currPos))?(s3=input.charAt(peg$currPos),peg$currPos++):(s3=peg$FAILED,peg$fail(peg$c77))),s3===peg$FAILED?(peg$currPos=s1,s1=peg$FAILED):(s2=[s2,s3],s1=s2)}else peg$currPos=s1,s1=peg$FAILED;return s1!==peg$FAILED&&(peg$savedPos=s0,s1=peg$c78(s1)),s0=s1,s0}function peg$parseisotope(){var s0,s1,s2,s3,s4;return s0=peg$currPos,s1=peg$currPos,peg$c42.test(input.charAt(peg$currPos))?(s2=input.charAt(peg$currPos),peg$currPos++):(s2=peg$FAILED,peg$fail(peg$c43)),s2===peg$FAILED?(peg$currPos=s1,s1=peg$FAILED):(peg$c44.test(input.charAt(peg$currPos))?(s3=input.charAt(peg$currPos),peg$currPos++):(s3=peg$FAILED,peg$fail(peg$c45)),s3===peg$FAILED&&(s3=null),s3===peg$FAILED?(peg$currPos=s1,s1=peg$FAILED):(peg$c44.test(input.charAt(peg$currPos))?(s4=input.charAt(peg$currPos),peg$currPos++):(s4=peg$FAILED,peg$fail(peg$c45)),s4===peg$FAILED&&(s4=null),s4===peg$FAILED?(peg$currPos=s1,s1=peg$FAILED):(s2=[s2,s3,s4],s1=s2))),s1!==peg$FAILED&&(peg$savedPos=s0,s1=peg$c79(s1)),s0=s1,s0}options=void 0===options?{}:options;var nOpenParentheses=input.split("(").length-1,nCloseParentheses=input.split(")").length-1;if(nOpenParentheses!==nCloseParentheses)throw peg$buildSimpleError("The number of opening parentheses does not match the number of closing parentheses.",0);var peg$FAILED={},peg$startRuleFunctions={chain:peg$parsechain},peg$startRuleFunction=peg$parsechain,peg$c0=function(s){for(var branches=[],rings=[],i=0;i<s[1].length;i++)branches.push(s[1][i]);for(var i=0,bond;i<s[2].length;i++)bond=s[2][i][0]?s[2][i][0]:"-",rings.push({bond:bond,id:s[2][i][1]});for(var i=0;i<s[3].length;i++)branches.push(s[3][i]);for(var i=0;i<s[6].length;i++)branches.push(s[6][i]);return{atom:s[0],isBracket:!!s[0].element,branches:branches,branchCount:branches.length,ringbonds:rings,ringbondCount:rings.length,bond:s[4]?s[4]:"-",next:s[5],hasNext:!!s[5]}},peg$c2=peg$literalExpectation("(",!1),peg$c4=peg$literalExpectation(")",!1),peg$c5=function(b){var bond=b[1]?b[1]:"-";return b[2].branchBond=bond,b[2]},peg$c6=function(a){return a},peg$c7=/^[\-=#$:\/\\.]/,peg$c8=peg$classExpectation(["-","=","#","$",":","/","\\","."],!1,!1),peg$c9=function(b){return b},peg$c11=peg$literalExpectation("[",!1),peg$c13=peg$literalExpectation("se",!1),peg$c15=peg$literalExpectation("as",!1),peg$c17=peg$literalExpectation("]",!1),peg$c18=function(b){return{isotope:b[1],element:b[2],chirality:b[3],hcount:b[4],charge:b[5],class:b[6]}},peg$c20=peg$literalExpectation("B",!1),peg$c22=peg$literalExpectation("r",!1),peg$c24=peg$literalExpectation("C",!1),peg$c26=peg$literalExpectation("l",!1),peg$c27=/^[NOPSFI]/,peg$c28=peg$classExpectation(["N","O","P","S","F","I"],!1,!1),peg$c29=function(o){return 1<o.length?o.join(""):o},peg$c30=/^[bcnops]/,peg$c31=peg$classExpectation(["b","c","n","o","p","s"],!1,!1),peg$c33=peg$literalExpectation("*",!1),peg$c34=function(w){return w},peg$c35=/^[A-Z]/,peg$c36=peg$classExpectation([["A","Z"]],!1,!1),peg$c37=/^[a-z]/,peg$c38=peg$classExpectation([["a","z"]],!1,!1),peg$c39=function(e){return e.join("")},peg$c41=peg$literalExpectation("%",!1),peg$c42=/^[1-9]/,peg$c43=peg$classExpectation([["1","9"]],!1,!1),peg$c44=/^[0-9]/,peg$c45=peg$classExpectation([["0","9"]],!1,!1),peg$c46=function(r){return 1==r.length?+r:+r.join("").replace("%","")},peg$c48=peg$literalExpectation("@",!1),peg$c50=peg$literalExpectation("TH",!1),peg$c51=/^[12]/,peg$c52=peg$classExpectation(["1","2"],!1,!1),peg$c54=peg$literalExpectation("AL",!1),peg$c56=peg$literalExpectation("SP",!1),peg$c57=/^[1-3]/,peg$c58=peg$classExpectation([["1","3"]],!1,!1),peg$c60=peg$literalExpectation("TB",!1),peg$c62=peg$literalExpectation("OH",!1),peg$c63=function(c){return c[1]?"@"==c[1]?"@@":c[1].join("").replace(",",""):"@"},peg$c64=function(c){return c},peg$c66=peg$literalExpectation("+",!1),peg$c67=function(c){return c[1]?"+"==c[1]?2:+c[1].join(""):1},peg$c69=peg$literalExpectation("-",!1),peg$c70=function(c){return c[1]?"-"==c[1]?-2:-+c[1].join(""):-1},peg$c72=peg$literalExpectation("H",!1),peg$c73=function(h){return h[1]?+h[1]:1},peg$c75=peg$literalExpectation(":",!1),peg$c76=/^[0]/,peg$c77=peg$classExpectation(["0"],!1,!1),peg$c78=function(c){return+(c[1][0]+c[1][1].join(""))},peg$c79=function(i){return+i.join("")},peg$currPos=0,peg$savedPos=0,peg$posDetailsCache=[{line:1,column:1}],peg$maxFailPos=0,peg$maxFailExpected=[],peg$result;if("startRule"in options){if(!(options.startRule in peg$startRuleFunctions))throw new Error("Can't start parsing from rule \""+options.startRule+"\".");peg$startRuleFunction=peg$startRuleFunctions[options.startRule]}if(peg$result=peg$startRuleFunction(),peg$result!==peg$FAILED&&peg$currPos===input.length)return peg$result;throw peg$result!==peg$FAILED&&peg$currPos<input.length&&peg$fail(function(){return{type:"end"}}()),function(expected,found,location){return new peg$SyntaxError(peg$SyntaxError.buildMessage(expected,found),expected,found,location)}(peg$maxFailExpected,peg$maxFailPos<input.length?input.charAt(peg$maxFailPos):null,peg$maxFailPos<input.length?peg$computeLocation(peg$maxFailPos,peg$maxFailPos+1):peg$computeLocation(peg$maxFailPos,peg$maxFailPos))}return function(child,parent){function ctor(){this.constructor=child}ctor.prototype=parent.prototype,child.prototype=new ctor}(peg$SyntaxError,Error),peg$SyntaxError.buildMessage=function(expected,found){function hex(ch){return ch.charCodeAt(0).toString(16).toUpperCase()}function literalEscape(s){return s.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,function(ch){return"\\x0"+hex(ch)}).replace(/[\x10-\x1F\x7F-\x9F]/g,function(ch){return"\\x"+hex(ch)})}function classEscape(s){return s.replace(/\\/g,"\\\\").replace(/\]/g,"\\]").replace(/\^/g,"\\^").replace(/-/g,"\\-").replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,function(ch){return"\\x0"+hex(ch)}).replace(/[\x10-\x1F\x7F-\x9F]/g,function(ch){return"\\x"+hex(ch)})}function describeExpectation(expectation){return DESCRIBE_EXPECTATION_FNS[expectation.type](expectation)}var DESCRIBE_EXPECTATION_FNS={literal:function(expectation){return"\""+literalEscape(expectation.text)+"\""},class:function(expectation){var escapedParts="",i;for(i=0;i<expectation.parts.length;i++)escapedParts+=expectation.parts[i]instanceof Array?classEscape(expectation.parts[i][0])+"-"+classEscape(expectation.parts[i][1]):classEscape(expectation.parts[i]);return"["+(expectation.inverted?"^":"")+escapedParts+"]"},any:function(){return"any character"},end:function(){return"end of input"},other:function(expectation){return expectation.description}};return"Expected "+function(expected){var descriptions=Array(expected.length),i,j;for(i=0;i<expected.length;i++)descriptions[i]=describeExpectation(expected[i]);if(descriptions.sort(),0<descriptions.length){for(i=1,j=1;i<descriptions.length;i++)descriptions[i-1]!==descriptions[i]&&(descriptions[j]=descriptions[i],j++);descriptions.length=j}switch(descriptions.length){case 1:return descriptions[0];case 2:return descriptions[0]+" or "+descriptions[1];default:return descriptions.slice(0,-1).join(", ")+", or "+descriptions[descriptions.length-1];}}(expected)+" but "+function(found){return found?"\""+literalEscape(found)+"\"":"end of input"}(found)+" found."},{SyntaxError:peg$SyntaxError,parse:peg$parse}}()},{}],16:[function(require,module){"use strict";var _Mathfloor2=Math.floor;module.exports=function(img){function each(obj,fn){var length=obj.length,likeArray=0===length||0<length&&length-1 in obj,i=0;if(likeArray)for(;i<length&&!1!==fn.call(obj[i],i,obj[i]);i++);else for(i in obj)if(!1===fn.call(obj[i],i,obj[i]))break}function componentToHex(c){var hex=parseInt(c).toString(16);return 1==hex.length?"0"+hex:hex}function getColor(r,g,b,a){return a=parseInt(a),void 0===a||255===a?"#"+componentToHex(r)+componentToHex(g)+componentToHex(b):0!==a&&"rgba("+r+","+g+","+b+","+a/255+")"}function makePathData(x,y,w){return"M"+x+" "+y+"h"+w+""}function makePath(color,data){return"<path stroke=\""+color+"\" d=\""+data+"\" />\n"}let colors=function(img){for(var colors={},data=img.data,len=data.length,w=img.width,h=img.height,x=0,y=0,i=0,color;i<len;i+=4)0<data[i+3]&&(color=data[i]+","+data[i+1]+","+data[i+2]+","+data[i+3],colors[color]=colors[color]||[],x=i/4%w,y=_Mathfloor2(i/4/w),colors[color].push([x,y]));return colors}(img),paths=function(colors){var output="";return each(colors,function(color,values){if(color=getColor.apply(null,color.split(",")),!1!==color){var paths=[],w=1,curPath;each(values,function(){curPath&&this[1]===curPath[1]&&this[0]===curPath[0]+w?w++:(curPath&&(paths.push(makePathData(curPath[0],curPath[1],w)),w=1),curPath=this)}),paths.push(makePathData(curPath[0],curPath[1],w)),output+=makePath(color,paths.join(""))}}),output}(colors),output="<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 -0.5 "+img.width+" "+img.height+"\" shape-rendering=\"crispEdges\"><g shape-rendering=\"crispEdges\">"+paths+"</g></svg>";var dummyDiv=document.createElement("div");return dummyDiv.innerHTML=output,dummyDiv.firstChild}},{}],17:[function(require,module){"use strict";const Parser=require("./Parser");module.exports=class{constructor(reactionSmiles){this.reactantsSmiles=[],this.reagentsSmiles=[],this.productsSmiles=[],this.reactantsWeights=[],this.reagentsWeights=[],this.productsWeights=[],this.reactants=[],this.reagents=[],this.products=[];let parts=reactionSmiles.split(">");if(3!==parts.length)throw new Error("Invalid reaction SMILES. Did you add fewer than or more than two '>'?");""!==parts[0]&&(this.reactantsSmiles=parts[0].split(".")),""!==parts[1]&&(this.reagentsSmiles=parts[1].split(".")),""!==parts[2]&&(this.productsSmiles=parts[2].split("."));for(var i=0;i<this.reactantsSmiles.length;i++)this.reactants.push(Parser.parse(this.reactantsSmiles[i]));for(var i=0;i<this.reagentsSmiles.length;i++)this.reagents.push(Parser.parse(this.reagentsSmiles[i]));for(var i=0;i<this.productsSmiles.length;i++)this.products.push(Parser.parse(this.productsSmiles[i]))}}},{"./Parser":15}],18:[function(require,module){"use strict";var _NumberMAX_SAFE_INTEGER2=Number.MAX_SAFE_INTEGER,_Mathround3=Math.round,_Mathabs4=Math.abs,_Mathmax4=Math.max;const SvgDrawer=require("./SvgDrawer"),SvgWrapper=require("./SvgWrapper"),Options=require("./Options"),ThemeManager=require("./ThemeManager"),formulaToCommonName=require("./FormulaToCommonName");module.exports=class{constructor(options,moleculeOptions){this.defaultOptions={scale:0<moleculeOptions.scale?moleculeOptions.scale:1,fontSize:.8*moleculeOptions.fontSizeLarge,fontFamily:"Arial, Helvetica, sans-serif",spacing:10,plus:{size:9,thickness:1},arrow:{length:4*moleculeOptions.bondLength,headSize:6,thickness:1,margin:3},weights:{normalize:!1}},this.opts=Options.extend(!0,this.defaultOptions,options),this.drawer=new SvgDrawer(moleculeOptions),this.molOpts=this.drawer.opts}draw(reaction,target,themeName="light",weights=null,textAbove="{reagents}",textBelow="",infoOnly=!1){if(this.themeManager=new ThemeManager(this.molOpts.themes,themeName),this.opts.weights.normalize){let max=-_NumberMAX_SAFE_INTEGER2,min=_NumberMAX_SAFE_INTEGER2;if(weights.hasOwnProperty("reactants"))for(let i=0;i<weights.reactants.length;i++)for(let j=0;j<weights.reactants[i].length;j++)weights.reactants[i][j]<min&&(min=weights.reactants[i][j]),weights.reactants[i][j]>max&&(max=weights.reactants[i][j]);if(weights.hasOwnProperty("reagents"))for(let i=0;i<weights.reagents.length;i++)for(let j=0;j<weights.reagents[i].length;j++)weights.reagents[i][j]<min&&(min=weights.reagents[i][j]),weights.reagents[i][j]>max&&(max=weights.reagents[i][j]);if(weights.hasOwnProperty("products"))for(let i=0;i<weights.products.length;i++)for(let j=0;j<weights.products[i].length;j++)weights.products[i][j]<min&&(min=weights.products[i][j]),weights.products[i][j]>max&&(max=weights.products[i][j]);let abs_max=_Mathmax4(_Mathabs4(min),_Mathabs4(max));if(0===abs_max&&(abs_max=1),weights.hasOwnProperty("reactants"))for(let i=0;i<weights.reactants.length;i++)for(let j=0;j<weights.reactants[i].length;j++)weights.reactants[i][j]/=abs_max;if(weights.hasOwnProperty("reagents"))for(let i=0;i<weights.reagents.length;i++)for(let j=0;j<weights.reagents[i].length;j++)weights.reagents[i][j]/=abs_max;if(weights.hasOwnProperty("products"))for(let i=0;i<weights.products.length;i++)for(let j=0;j<weights.products[i].length;j++)weights.products[i][j]/=abs_max}let svg=null;for(null===target||"svg"===target?(svg=document.createElementNS("http://www.w3.org/2000/svg","svg"),svg.setAttribute("xmlns","http://www.w3.org/2000/svg"),svg.setAttributeNS(null,"width","500"),svg.setAttributeNS(null,"height","500")):"string"==typeof target||target instanceof String?svg=document.getElementById(target):svg=target;svg.firstChild;)svg.removeChild(svg.firstChild);let elements=[],maxHeight=0;for(var i=0;i<reaction.reactants.length;i++){0<i&&elements.push({width:this.opts.plus.size*this.opts.scale,height:this.opts.plus.size*this.opts.scale,svg:this.getPlus()});let reactantWeights=null;weights&&weights.hasOwnProperty("reactants")&&weights.reactants.length>i&&(reactantWeights=weights.reactants[i]);let reactantSvg=document.createElementNS("http://www.w3.org/2000/svg","svg");this.drawer.draw(reaction.reactants[i],reactantSvg,themeName,reactantWeights,infoOnly,[],this.opts.weights.normalize);let element={width:reactantSvg.viewBox.baseVal.width*this.opts.scale,height:reactantSvg.viewBox.baseVal.height*this.opts.scale,svg:reactantSvg};elements.push(element),element.height>maxHeight&&(maxHeight=element.height)}elements.push({width:this.opts.arrow.length*this.opts.scale,height:2*this.opts.arrow.headSize*this.opts.scale,svg:this.getArrow()});let reagentsText="";for(var i=0;i<reaction.reagents.length;i++){0<i&&(reagentsText+=", ");let text=this.drawer.getMolecularFormula(reaction.reagents[i]);text in formulaToCommonName&&(text=formulaToCommonName[text]),reagentsText+=SvgWrapper.replaceNumbersWithSubscript(text)}textAbove=textAbove.replace("{reagents}",reagentsText);const topText=SvgWrapper.writeText(textAbove,this.themeManager,this.opts.fontSize*this.opts.scale,this.opts.fontFamily,this.opts.arrow.length*this.opts.scale);let centerOffsetX=(this.opts.arrow.length*this.opts.scale-topText.width)/2;elements.push({svg:topText.svg,height:topText.height,width:this.opts.arrow.length*this.opts.scale,offsetX:-(this.opts.arrow.length*this.opts.scale+this.opts.spacing)+centerOffsetX,offsetY:-(topText.height/2)-this.opts.arrow.margin,position:"relative"});const bottomText=SvgWrapper.writeText(textBelow,this.themeManager,this.opts.fontSize*this.opts.scale,this.opts.fontFamily,this.opts.arrow.length*this.opts.scale);centerOffsetX=(this.opts.arrow.length*this.opts.scale-bottomText.width)/2,elements.push({svg:bottomText.svg,height:bottomText.height,width:this.opts.arrow.length*this.opts.scale,offsetX:-(this.opts.arrow.length*this.opts.scale+this.opts.spacing)+centerOffsetX,offsetY:bottomText.height/2+this.opts.arrow.margin,position:"relative"});for(var i=0;i<reaction.products.length;i++){0<i&&elements.push({width:this.opts.plus.size*this.opts.scale,height:this.opts.plus.size*this.opts.scale,svg:this.getPlus()});let productWeights=null;weights&&weights.hasOwnProperty("products")&&weights.products.length>i&&(productWeights=weights.products[i]);let productSvg=document.createElementNS("http://www.w3.org/2000/svg","svg");this.drawer.draw(reaction.products[i],productSvg,themeName,productWeights,infoOnly,[],this.opts.weights.normalize);let element={width:productSvg.viewBox.baseVal.width*this.opts.scale,height:productSvg.viewBox.baseVal.height*this.opts.scale,svg:productSvg};elements.push(element),element.height>maxHeight&&(maxHeight=element.height)}let totalWidth=0;return elements.forEach(element=>{let offsetX=element.offsetX??0,offsetY=element.offsetY??0;element.svg.setAttributeNS(null,"x",_Mathround3(totalWidth+offsetX)),element.svg.setAttributeNS(null,"y",_Mathround3((maxHeight-element.height)/2+offsetY)),element.svg.setAttributeNS(null,"width",_Mathround3(element.width)),element.svg.setAttributeNS(null,"height",_Mathround3(element.height)),svg.appendChild(element.svg),"relative"!==element.position&&(totalWidth+=_Mathround3(element.width+this.opts.spacing+offsetX))}),svg.setAttributeNS(null,"viewBox",`0 0 ${totalWidth} ${maxHeight}`),svg.style.width=totalWidth+"px",svg.style.height=maxHeight+"px",svg}getPlus(){let s=this.opts.plus.size,w=this.opts.plus.thickness,svg=document.createElementNS("http://www.w3.org/2000/svg","svg"),rect_h=document.createElementNS("http://www.w3.org/2000/svg","rect"),rect_v=document.createElementNS("http://www.w3.org/2000/svg","rect");return svg.setAttributeNS(null,"id","plus"),rect_h.setAttributeNS(null,"x",0),rect_h.setAttributeNS(null,"y",s/2-w/2),rect_h.setAttributeNS(null,"width",s),rect_h.setAttributeNS(null,"height",w),rect_h.setAttributeNS(null,"fill",this.themeManager.getColor("C")),rect_v.setAttributeNS(null,"x",s/2-w/2),rect_v.setAttributeNS(null,"y",0),rect_v.setAttributeNS(null,"width",w),rect_v.setAttributeNS(null,"height",s),rect_v.setAttributeNS(null,"fill",this.themeManager.getColor("C")),svg.appendChild(rect_h),svg.appendChild(rect_v),svg.setAttributeNS(null,"viewBox",`0 0 ${s} ${s}`),svg}getArrowhead(){let s=this.opts.arrow.headSize,marker=document.createElementNS("http://www.w3.org/2000/svg","marker"),polygon=document.createElementNS("http://www.w3.org/2000/svg","polygon");return marker.setAttributeNS(null,"id","arrowhead"),marker.setAttributeNS(null,"viewBox",`0 0 ${s} ${s}`),marker.setAttributeNS(null,"markerUnits","userSpaceOnUse"),marker.setAttributeNS(null,"markerWidth",s),marker.setAttributeNS(null,"markerHeight",s),marker.setAttributeNS(null,"refX",0),marker.setAttributeNS(null,"refY",s/2),marker.setAttributeNS(null,"orient","auto"),marker.setAttributeNS(null,"fill",this.themeManager.getColor("C")),polygon.setAttributeNS(null,"points",`0 0, ${s} ${s/2}, 0 ${s}`),marker.appendChild(polygon),marker}getCDArrowhead(){let s=this.opts.arrow.headSize,sw=s*(7/4.5),marker=document.createElementNS("http://www.w3.org/2000/svg","marker"),path=document.createElementNS("http://www.w3.org/2000/svg","path");return marker.setAttributeNS(null,"id","arrowhead"),marker.setAttributeNS(null,"viewBox",`0 0 ${sw} ${s}`),marker.setAttributeNS(null,"markerUnits","userSpaceOnUse"),marker.setAttributeNS(null,"markerWidth",2*sw),marker.setAttributeNS(null,"markerHeight",2*s),marker.setAttributeNS(null,"refX",2.2),marker.setAttributeNS(null,"refY",2.2),marker.setAttributeNS(null,"orient","auto"),marker.setAttributeNS(null,"fill",this.themeManager.getColor("C")),path.setAttributeNS(null,"style","fill-rule:nonzero;"),path.setAttributeNS(null,"d","m 0 0 l 7 2.25 l -7 2.25 c 0 0 0.735 -1.084 0.735 -2.28 c 0 -1.196 -0.735 -2.22 -0.735 -2.22 z"),marker.appendChild(path),marker}getArrow(){let s=this.opts.arrow.headSize,l=this.opts.arrow.length,svg=document.createElementNS("http://www.w3.org/2000/svg","svg"),defs=document.createElementNS("http://www.w3.org/2000/svg","defs"),line=document.createElementNS("http://www.w3.org/2000/svg","line");return defs.appendChild(this.getCDArrowhead()),svg.appendChild(defs),svg.setAttributeNS(null,"id","arrow"),line.setAttributeNS(null,"x1",0),line.setAttributeNS(null,"y1",-this.opts.arrow.thickness/2),line.setAttributeNS(null,"x2",l),line.setAttributeNS(null,"y2",-this.opts.arrow.thickness/2),line.setAttributeNS(null,"stroke-width",this.opts.arrow.thickness),line.setAttributeNS(null,"stroke",this.themeManager.getColor("C")),line.setAttributeNS(null,"marker-end","url(#arrowhead)"),svg.appendChild(line),svg.setAttributeNS(null,"viewBox",`0 ${-s/2} ${l+s*(7/4.5)} ${s}`),svg}}},{"./FormulaToCommonName":9,"./Options":14,"./SvgDrawer":24,"./SvgWrapper":25,"./ThemeManager":26}],19:[function(require,module){"use strict";const Reaction=require("./Reaction");module.exports=class{static parse(reactionSmiles){let reaction=new Reaction(reactionSmiles);return reaction}}},{"./Reaction":17}],20:[function(require,module){"use strict";const ArrayHelper=require("./ArrayHelper"),Vector2=require("./Vector2"),Vertex=require("./Vertex"),RingConnection=require("./RingConnection");class Ring{constructor(members){this.id=null,this.members=members,this.edges=[],this.insiders=[],this.neighbours=[],this.positioned=!1,this.center=new Vector2(0,0),this.rings=[],this.isBridged=!1,this.isPartOfBridged=!1,this.isSpiro=!1,this.isFused=!1,this.centralAngle=0,this.canFlip=!0}clone(){let clone=new Ring(this.members);return clone.id=this.id,clone.insiders=ArrayHelper.clone(this.insiders),clone.neighbours=ArrayHelper.clone(this.neighbours),clone.positioned=this.positioned,clone.center=this.center.clone(),clone.rings=ArrayHelper.clone(this.rings),clone.isBridged=this.isBridged,clone.isPartOfBridged=this.isPartOfBridged,clone.isSpiro=this.isSpiro,clone.isFused=this.isFused,clone.centralAngle=this.centralAngle,clone.canFlip=this.canFlip,clone}getSize(){return this.members.length}getPolygon(vertices){let polygon=[];for(let i=0;i<this.members.length;i++)polygon.push(vertices[this.members[i]].position);return polygon}getAngle(){return Math.PI-this.centralAngle}eachMember(vertices,callback,startVertexId,previousVertexId){startVertexId=startVertexId||0===startVertexId?startVertexId:this.members[0];let current=startVertexId,max=0;for(;null!=current&&100>max;){let prev=current;callback(prev),current=vertices[current].getNextInRing(vertices,this.id,previousVertexId),previousVertexId=prev,current==startVertexId&&(current=null),max++}}getOrderedNeighbours(ringConnections){let orderedNeighbours=Array(this.neighbours.length);for(let i=0,vertices;i<this.neighbours.length;i++)vertices=RingConnection.getVertices(ringConnections,this.id,this.neighbours[i]),orderedNeighbours[i]={n:vertices.length,neighbour:this.neighbours[i]};return orderedNeighbours.sort(function(a,b){return b.n-a.n}),orderedNeighbours}isBenzeneLike(vertices){let db=this.getDoubleBondCount(vertices),length=this.members.length;return 3===db&&6===length||2===db&&5===length}getDoubleBondCount(vertices){let doubleBondCount=0;for(let i=0,atom;i<this.members.length;i++)atom=vertices[this.members[i]].value,("="===atom.bondType||"="===atom.branchBond)&&doubleBondCount++;return doubleBondCount}contains(vertexId){for(let i=0;i<this.members.length;i++)if(this.members[i]==vertexId)return!0;return!1}}module.exports=Ring},{"./ArrayHelper":3,"./RingConnection":21,"./Vector2":28,"./Vertex":29}],21:[function(require,module){"use strict";const Vertex=require("./Vertex"),Ring=require("./Ring");module.exports=class{constructor(firstRing,secondRing){this.id=null,this.firstRingId=firstRing.id,this.secondRingId=secondRing.id,this.vertices=new Set;for(var m=0;m<firstRing.members.length;m++){let c=firstRing.members[m];for(let n=0,d;n<secondRing.members.length;n++)d=secondRing.members[n],c===d&&this.addVertex(c)}}addVertex(vertexId){this.vertices.add(vertexId)}updateOther(ringId,otherRingId){this.firstRingId===otherRingId?this.secondRingId=ringId:this.firstRingId=ringId}containsRing(ringId){return this.firstRingId===ringId||this.secondRingId===ringId}isBridge(vertices){if(2<this.vertices.size)return!0;for(let vertexId of this.vertices)if(2<vertices[vertexId].value.rings.length)return!0;return!1}static isBridge(ringConnections,vertices,firstRingId,secondRingId){let ringConnection=null;for(let i=0;i<ringConnections.length;i++)if(ringConnection=ringConnections[i],ringConnection.firstRingId===firstRingId&&ringConnection.secondRingId===secondRingId||ringConnection.firstRingId===secondRingId&&ringConnection.secondRingId===firstRingId)return ringConnection.isBridge(vertices);return!1}static getNeighbours(ringConnections,ringId){let neighbours=[];for(let i=0,ringConnection;i<ringConnections.length;i++)ringConnection=ringConnections[i],ringConnection.firstRingId===ringId?neighbours.push(ringConnection.secondRingId):ringConnection.secondRingId===ringId&&neighbours.push(ringConnection.firstRingId);return neighbours}static getVertices(ringConnections,firstRingId,secondRingId){for(let i=0,ringConnection;i<ringConnections.length;i++)if(ringConnection=ringConnections[i],ringConnection.firstRingId===firstRingId&&ringConnection.secondRingId===secondRingId||ringConnection.firstRingId===secondRingId&&ringConnection.secondRingId===firstRingId)return[...ringConnection.vertices]}}},{"./Ring":20,"./Vertex":29}],22:[function(require,module){"use strict";const Graph=require("./Graph");class SSSR{static getRings(graph,experimental=!1){let adjacencyMatrix=graph.getComponentsAdjacencyMatrix();if(0===adjacencyMatrix.length)return null;let connectedComponents=Graph.getConnectedComponents(adjacencyMatrix),rings=[];for(var i=0;i<connectedComponents.length;i++){let connectedComponent=connectedComponents[i],ccAdjacencyMatrix=graph.getSubgraphAdjacencyMatrix([...connectedComponent]),arrBondCount=new Uint16Array(ccAdjacencyMatrix.length),arrRingCount=new Uint16Array(ccAdjacencyMatrix.length);for(var j=0;j<ccAdjacencyMatrix.length;j++){arrRingCount[j]=0,arrBondCount[j]=0;for(var k=0;k<ccAdjacencyMatrix[j].length;k++)arrBondCount[j]+=ccAdjacencyMatrix[j][k]}let nEdges=0;for(var j=0;j<ccAdjacencyMatrix.length;j++)for(var k=j+1;k<ccAdjacencyMatrix.length;k++)nEdges+=ccAdjacencyMatrix[j][k];let nSssr=nEdges-ccAdjacencyMatrix.length+1,allThree=!0;for(var j=0;j<arrBondCount.length;j++)3!==arrBondCount[j]&&(allThree=!1);if(allThree&&(nSssr=2+nEdges-ccAdjacencyMatrix.length),1==nSssr){rings.push([...connectedComponent]);continue}experimental&&(nSssr=999);let{d,pe,pe_prime}=SSSR.getPathIncludedDistanceMatrices(ccAdjacencyMatrix),c=SSSR.getRingCandidates(d,pe,pe_prime),sssr=SSSR.getSSSR(c,d,ccAdjacencyMatrix,pe,pe_prime,arrBondCount,arrRingCount,nSssr);for(var j=0;j<sssr.length;j++){let ring=Array(sssr[j].size),index=0;for(let val of sssr[j])ring[index++]=connectedComponent[val];rings.push(ring)}}return rings}static matrixToString(matrix){let str="";for(var i=0;i<matrix.length;i++){for(var j=0;j<matrix[i].length;j++)str+=matrix[i][j]+" ";str+="\n"}return str}static getPathIncludedDistanceMatrices(adjacencyMatrix){var _NumberPOSITIVE_INFINITY=Number.POSITIVE_INFINITY;let length=adjacencyMatrix.length,d=Array(length),pe=Array(length),pe_prime=Array(length);for(var l=0,m=0,n=0,i=length;i--;){d[i]=Array(length),pe[i]=Array(length),pe_prime[i]=Array(length);for(var j=length;j--;)d[i][j]=i===j||1===adjacencyMatrix[i][j]?adjacencyMatrix[i][j]:_NumberPOSITIVE_INFINITY,pe[i][j]=1===d[i][j]?[[[i,j]]]:[],pe_prime[i][j]=[]}for(var k=length,j;k--;)for(i=length;i--;)for(j=length;j--;){const previousPathLength=d[i][j],newPathLength=d[i][k]+d[k][j];if(previousPathLength>newPathLength){var l,m,n;if(previousPathLength===newPathLength+1)for(pe_prime[i][j]=[pe[i][j].length],l=pe[i][j].length;l--;)for(pe_prime[i][j][l]=[pe[i][j][l].length],m=pe[i][j][l].length;m--;)for(pe_prime[i][j][l][m]=[pe[i][j][l][m].length],n=pe[i][j][l][m].length;n--;)pe_prime[i][j][l][m][n]=[pe[i][j][l][m][0],pe[i][j][l][m][1]];else pe_prime[i][j]=[];for(d[i][j]=newPathLength,pe[i][j]=[[]],l=pe[i][k][0].length;l--;)pe[i][j][0].push(pe[i][k][0][l]);for(l=pe[k][j][0].length;l--;)pe[i][j][0].push(pe[k][j][0][l])}else if(previousPathLength===newPathLength){if(pe[i][k].length&&pe[k][j].length){var l;if(pe[i][j].length){let tmp=[];for(l=pe[i][k][0].length;l--;)tmp.push(pe[i][k][0][l]);for(l=pe[k][j][0].length;l--;)tmp.push(pe[k][j][0][l]);pe[i][j].push(tmp)}else{let tmp=[];for(l=pe[i][k][0].length;l--;)tmp.push(pe[i][k][0][l]);for(l=pe[k][j][0].length;l--;)tmp.push(pe[k][j][0][l]);pe[i][j][0]=tmp}}}else if(previousPathLength===newPathLength-1){var l;if(pe_prime[i][j].length){let tmp=[];for(l=pe[i][k][0].length;l--;)tmp.push(pe[i][k][0][l]);for(l=pe[k][j][0].length;l--;)tmp.push(pe[k][j][0][l]);pe_prime[i][j].push(tmp)}else{let tmp=[];for(l=pe[i][k][0].length;l--;)tmp.push(pe[i][k][0][l]);for(l=pe[k][j][0].length;l--;)tmp.push(pe[k][j][0][l]);pe_prime[i][j][0]=tmp}}}return{d:d,pe:pe,pe_prime:pe_prime}}static getRingCandidates(d,pe,pe_prime){let length=d.length,candidates=[],c=0;for(let i=0;i<length;i++)for(let j=0;j<length;j++)if(0===d[i][j]||1===pe[i][j].length&&0===pe_prime[i][j])continue;else c=0===pe_prime[i][j].length?2*d[i][j]:2*(d[i][j]+.5),c!==1/0&&candidates.push([c,pe[i][j],pe_prime[i][j]]);return candidates.sort(function(a,b){return a[0]-b[0]}),candidates}static getSSSR(c,d,adjacencyMatrix,pe,pe_prime,arrBondCount,arrRingCount,nsssr){let cSssr=[],allBonds=[];for(let i=0;i<c.length;i++)if(0!=c[i][0]%2)for(let j=0,bonds;j<c[i][2].length;j++){bonds=c[i][1][0].concat(c[i][2][j]);for(var k=0;k<bonds.length;k++)bonds[k][0].constructor===Array&&(bonds[k]=bonds[k][0]);let atoms=SSSR.bondsToAtoms(bonds);if(SSSR.getBondCount(atoms,adjacencyMatrix)!==atoms.size||SSSR.pathSetsContain(cSssr,atoms,bonds,allBonds,arrBondCount,arrRingCount)||(cSssr.push(atoms),allBonds=allBonds.concat(bonds)),cSssr.length>nsssr)return cSssr}else for(let j=0,bonds;j<c[i][1].length-1;j++){bonds=c[i][1][j].concat(c[i][1][j+1]);for(var k=0;k<bonds.length;k++)bonds[k][0].constructor===Array&&(bonds[k]=bonds[k][0]);let atoms=SSSR.bondsToAtoms(bonds);if(SSSR.getBondCount(atoms,adjacencyMatrix)!==atoms.size||SSSR.pathSetsContain(cSssr,atoms,bonds,allBonds,arrBondCount,arrRingCount)||(cSssr.push(atoms),allBonds=allBonds.concat(bonds)),cSssr.length>nsssr)return cSssr}return cSssr}static getEdgeCount(adjacencyMatrix){let edgeCount=0,length=adjacencyMatrix.length;for(var i=length-1;i--;)for(var j=length;j--;)1===adjacencyMatrix[i][j]&&edgeCount++;return edgeCount}static getEdgeList(adjacencyMatrix){let length=adjacencyMatrix.length,edgeList=[];for(var i=length-1;i--;)for(var j=length;j--;)1===adjacencyMatrix[i][j]&&edgeList.push([i,j]);return edgeList}static bondsToAtoms(bonds){let atoms=new Set;for(var i=bonds.length;i--;)atoms.add(bonds[i][0]),atoms.add(bonds[i][1]);return atoms}static getBondCount(atoms,adjacencyMatrix){let count=0;for(let u of atoms)for(let v of atoms)u!==v&&(count+=adjacencyMatrix[u][v]);return count/2}static pathSetsContain(pathSets,pathSet,bonds,allBonds,arrBondCount,arrRingCount){for(var i=pathSets.length;i--;){if(SSSR.isSupersetOf(pathSet,pathSets[i]))return!0;if(pathSets[i].size===pathSet.size&&SSSR.areSetsEqual(pathSets[i],pathSet))return!0}let count=0,allContained=!1;for(i=bonds.length;i--;)for(var j=allBonds.length;j--;)(bonds[i][0]===allBonds[j][0]&&bonds[i][1]===allBonds[j][1]||bonds[i][1]===allBonds[j][0]&&bonds[i][0]===allBonds[j][1])&&count++,count===bonds.length&&(allContained=!0);let specialCase=!1;if(allContained)for(let element of pathSet)if(arrRingCount[element]<arrBondCount[element]){specialCase=!0;break}if(allContained&&!specialCase)return!0;for(let element of pathSet)arrRingCount[element]++;return!1}static areSetsEqual(setA,setB){if(setA.size!==setB.size)return!1;for(let element of setA)if(!setB.has(element))return!1;return!0}static isSupersetOf(setA,setB){for(var element of setB)if(!setA.has(element))return!1;return!0}}module.exports=SSSR},{"./Graph":11}],23:[function(require,module){"use strict";const Drawer=require("./Drawer"),Parser=require("./Parser"),ReactionParser=require("./ReactionParser"),SvgDrawer=require("./SvgDrawer"),ReactionDrawer=require("./ReactionDrawer"),SvgWrapper=require("./SvgWrapper"),Options=require("./Options");class SmilesDrawer{constructor(moleculeOptions={},reactionOptions={}){this.drawer=new SvgDrawer(moleculeOptions),this.reactionDrawer=new ReactionDrawer(reactionOptions,JSON.parse(JSON.stringify(this.drawer.opts)))}static apply(moleculeOptions={},reactionOptions={},attribute="data-smiles",theme="light",successCallback=null,errorCallback=null){const drawer=new SmilesDrawer(moleculeOptions,reactionOptions);drawer.apply(attribute,theme,successCallback,errorCallback)}apply(attribute="data-smiles",theme="light",successCallback=null,errorCallback=null){let elements=document.querySelectorAll(`[${attribute}]`);elements.forEach(element=>{let smiles=element.getAttribute(attribute);if(null===smiles)throw Error("No SMILES provided.");let currentTheme=theme,weights=null;if(element.hasAttribute("data-smiles-theme")&&(currentTheme=element.getAttribute("data-smiles-theme")),element.hasAttribute("data-smiles-weights")&&(weights=element.getAttribute("data-smiles-weights").split(",").map(parseFloat)),(element.hasAttribute("data-smiles-reactant-weights")||element.hasAttribute("data-smiles-reagent-weights")||element.hasAttribute("data-smiles-product-weights"))&&(weights={reactants:[],reagents:[],products:[]},element.hasAttribute("data-smiles-reactant-weights")&&(weights.reactants=element.getAttribute("data-smiles-reactant-weights").split(";").map(v=>v.split(",").map(parseFloat))),element.hasAttribute("data-smiles-reagent-weights")&&(weights.reagents=element.getAttribute("data-smiles-reagent-weights").split(";").map(v=>v.split(",").map(parseFloat))),element.hasAttribute("data-smiles-product-weights")&&(weights.products=element.getAttribute("data-smiles-product-weights").split(";").map(v=>v.split(",").map(parseFloat)))),element.hasAttribute("data-smiles-options")||element.hasAttribute("data-smiles-reaction-options")){let moleculeOptions={};element.hasAttribute("data-smiles-options")&&(moleculeOptions=JSON.parse(element.getAttribute("data-smiles-options").replaceAll("'","\"")));let reactionOptions={};element.hasAttribute("data-smiles-reaction-options")&&(reactionOptions=JSON.parse(element.getAttribute("data-smiles-reaction-options").replaceAll("'","\"")));let smilesDrawer=new SmilesDrawer(moleculeOptions,reactionOptions);smilesDrawer.draw(smiles,element,currentTheme,successCallback,errorCallback,weights)}else this.draw(smiles,element,currentTheme,successCallback,errorCallback,weights)})}draw(smiles,target,theme="light",successCallback=null,errorCallback=null,weights=null){let rest=[];[smiles,...rest]=smiles.split(" ");let info=rest.join(" "),settings={};if(info.includes("__")){let settingsString=info.substring(info.indexOf("__")+2,info.lastIndexOf("__"));settings=JSON.parse(settingsString.replaceAll("'","\""))}if(settings=Options.extend(!0,{textAboveArrow:"{reagents}",textBelowArrow:""},settings),smiles.includes(">"))try{this.drawReaction(smiles,target,theme,settings,weights,successCallback)}catch(err){errorCallback?errorCallback(err):console.error(err)}else try{this.drawMolecule(smiles,target,theme,weights,successCallback)}catch(err){errorCallback?errorCallback(err):console.error(err)}}drawMolecule(smiles,target,theme,weights,callback){let parseTree=Parser.parse(smiles);if(null===target||"svg"===target){let svg=this.drawer.draw(parseTree,null,theme,weights),dims=this.getDimensions(svg);svg.setAttributeNS(null,"width",""+dims.w),svg.setAttributeNS(null,"height",""+dims.h),callback&&callback(svg)}else if("canvas"===target){let canvas=this.svgToCanvas(this.drawer.draw(parseTree,null,theme,weights));callback&&callback(canvas)}else if("img"===target){let img=this.svgToImg(this.drawer.draw(parseTree,null,theme,weights));callback&&callback(img)}else if(target instanceof HTMLImageElement)this.svgToImg(this.drawer.draw(parseTree,null,theme,weights),target),callback&&callback(target);else if(target instanceof SVGElement)this.drawer.draw(parseTree,target,theme,weights),callback&&callback(target);else{let elements=document.querySelectorAll(target);elements.forEach(element=>{let tag=element.nodeName.toLowerCase();"svg"===tag?(this.drawer.draw(parseTree,element,theme,weights),callback&&callback(element)):"canvas"===tag?(this.svgToCanvas(this.drawer.draw(parseTree,null,theme,weights),element),callback&&callback(element)):"img"===tag&&(this.svgToImg(this.drawer.draw(parseTree,null,theme,weights),element),callback&&callback(element))})}}drawReaction(smiles,target,theme,settings,weights,callback){let reaction=ReactionParser.parse(smiles);if(null===target||"svg"===target){let svg=this.reactionDrawer.draw(reaction,null,theme),dims=this.getDimensions(svg);svg.setAttributeNS(null,"width",""+dims.w),svg.setAttributeNS(null,"height",""+dims.h),callback&&callback(svg)}else if("canvas"===target){let canvas=this.svgToCanvas(this.reactionDrawer.draw(reaction,null,theme,weights,settings.textAboveArrow,settings.textBelowArrow));callback&&callback(canvas)}else if("img"===target){let img=this.svgToImg(this.reactionDrawer.draw(reaction,null,theme,weights,settings.textAboveArrow,settings.textBelowArrow));callback&&callback(img)}else if(target instanceof HTMLImageElement)this.svgToImg(this.reactionDrawer.draw(reaction,null,theme,weights,settings.textAboveArrow,settings.textBelowArrow),target),callback&&callback(target);else if(target instanceof SVGElement)this.reactionDrawer.draw(reaction,target,theme,weights,settings.textAboveArrow,settings.textBelowArrow),callback&&callback(target);else{let elements=document.querySelectorAll(target);elements.forEach(element=>{let tag=element.nodeName.toLowerCase();"svg"===tag?(this.reactionDrawer.draw(reaction,element,theme,weights,settings.textAboveArrow,settings.textBelowArrow),0>=this.reactionDrawer.opts.scale&&(element.style.width=null,element.style.height=null),callback&&callback(element)):"canvas"===tag?(this.svgToCanvas(this.reactionDrawer.draw(reaction,null,theme,weights,settings.textAboveArrow,settings.textBelowArrow),element),callback&&callback(element)):"img"===tag&&(this.svgToImg(this.reactionDrawer.draw(reaction,null,theme,weights,settings.textAboveArrow,settings.textBelowArrow),element),callback&&callback(element))})}}svgToCanvas(svg,canvas=null){null===canvas&&(canvas=document.createElement("canvas"));let dims=this.getDimensions(canvas,svg);return SvgWrapper.svgToCanvas(svg,canvas,dims.w,dims.h),canvas}svgToImg(svg,img=null){null===img&&(img=document.createElement("img"));let dims=this.getDimensions(img,svg);return SvgWrapper.svgToImg(svg,img,dims.w,dims.h),img}getDimensions(element,svg=null){let w=this.drawer.opts.width,h=this.drawer.opts.height;return 0>=this.drawer.opts.scale?(null===w&&(w=element.width),null===h&&(h=element.height),""!==element.style.width&&(w=parseInt(element.style.width)),""!==element.style.height&&(h=parseInt(element.style.height))):svg&&(w=parseFloat(svg.style.width),h=parseFloat(svg.style.height)),{w:w,h:h}}}module.exports=SmilesDrawer},{"./Drawer":6,"./Options":14,"./Parser":15,"./ReactionDrawer":18,"./ReactionParser":19,"./SvgDrawer":24,"./SvgWrapper":25}],24:[function(require,module){"use strict";var _MathPI4=Math.PI,_Mathabs5=Math.abs;const ArrayHelper=require("./ArrayHelper"),Atom=require("./Atom"),DrawerBase=require("./DrawerBase"),Graph=require("./Graph"),Line=require("./Line"),SvgWrapper=require("./SvgWrapper"),ThemeManager=require("./ThemeManager"),Vector2=require("./Vector2"),GaussDrawer=require("./GaussDrawer");module.exports=class{constructor(options,clear=!0){this.preprocessor=new DrawerBase(options),this.opts=this.preprocessor.opts,this.clear=clear,this.svgWrapper=null}draw(data,target,themeName="light",weights=null,infoOnly=!1,highlight_atoms=[],weightsNormalized=!1){null===target||"svg"===target?(target=document.createElementNS("http://www.w3.org/2000/svg","svg"),target.setAttribute("xmlns","http://www.w3.org/2000/svg"),target.setAttribute("xmlns:xlink","http://www.w3.org/1999/xlink"),target.setAttributeNS(null,"width",this.opts.width),target.setAttributeNS(null,"height",this.opts.height)):target instanceof String&&(target=document.getElementById(target));let optionBackup={padding:this.opts.padding,compactDrawing:this.opts.compactDrawing};null!==weights&&(this.opts.padding+=this.opts.weights.additionalPadding,this.opts.compactDrawing=!1);let preprocessor=this.preprocessor;return preprocessor.initDraw(data,themeName,infoOnly,highlight_atoms),infoOnly||(this.themeManager=new ThemeManager(this.opts.themes,themeName),(null===this.svgWrapper||this.clear)&&(this.svgWrapper=new SvgWrapper(this.themeManager,target,this.opts,this.clear))),preprocessor.processGraph(),this.svgWrapper.determineDimensions(preprocessor.graph.vertices),this.drawAtomHighlights(preprocessor.opts.debug),this.drawEdges(preprocessor.opts.debug),this.drawVertices(preprocessor.opts.debug),null!==weights&&this.drawWeights(weights,weightsNormalized),preprocessor.opts.debug&&(console.log(preprocessor.graph),console.log(preprocessor.rings),console.log(preprocessor.ringConnections)),this.svgWrapper.constructSvg(),null!==weights&&(this.opts.padding=optionBackup.padding,this.opts.compactDrawing=optionBackup.padding),target}drawCanvas(data,target,themeName="light",infoOnly=!1){let canvas=null;canvas="string"==typeof target||target instanceof String?document.getElementById(target):target;let svg=document.createElementNS("http://www.w3.org/2000/svg","svg");return svg.setAttribute("xmlns","http://www.w3.org/2000/svg"),svg.setAttributeNS(null,"viewBox","0 0 500 500"),svg.setAttributeNS(null,"width","500"),svg.setAttributeNS(null,"height","500"),svg.setAttributeNS(null,"style","visibility: hidden: position: absolute; left: -1000px"),document.body.appendChild(svg),this.svgDrawer.draw(data,svg,themeName,infoOnly),this.svgDrawer.svgWrapper.toCanvas(canvas,this.svgDrawer.opts.width,this.svgDrawer.opts.height),document.body.removeChild(svg),target}drawAromaticityRing(ring){let svgWrapper=this.svgWrapper;svgWrapper.drawRing(ring.center.x,ring.center.y,ring.getSize())}drawEdges(debug){let preprocessor=this.preprocessor,graph=preprocessor.graph,rings=preprocessor.rings,drawn=Array(this.preprocessor.graph.edges.length);if(drawn.fill(!1),graph.traverseBF(0,vertex=>{let edges=graph.getEdges(vertex.id);for(var i=0;i<edges.length;i++){let edgeId=edges[i];drawn[edgeId]||(drawn[edgeId]=!0,this.drawEdge(edgeId,debug))}}),!this.bridgedRing)for(var i=0;i<rings.length;i++){let ring=rings[i];preprocessor.isRingAromatic(ring)&&this.drawAromaticityRing(ring)}}drawEdge(edgeId,debug){let preprocessor=this.preprocessor,opts=preprocessor.opts,svgWrapper=this.svgWrapper,edge=preprocessor.graph.edges[edgeId],vertexA=preprocessor.graph.vertices[edge.sourceId],vertexB=preprocessor.graph.vertices[edge.targetId],elementA=vertexA.value.element,elementB=vertexB.value.element;if(vertexA.value.isDrawn&&vertexB.value.isDrawn||"default"!==preprocessor.opts.atomVisualization){let a=vertexA.position,b=vertexB.position,normals=preprocessor.getEdgeNormals(edge),sides=ArrayHelper.clone(normals);if(sides[0].multiplyScalar(10).add(a),sides[1].multiplyScalar(10).add(a),"="===edge.bondType||"="===preprocessor.getRingbondType(vertexA,vertexB)||edge.isPartOfAromaticRing&&preprocessor.bridgedRing){let inRing=preprocessor.areVerticesInSameRing(vertexA,vertexB),s=preprocessor.chooseSide(vertexA,vertexB,sides);if(inRing){let lcr=preprocessor.getLargestOrAromaticCommonRing(vertexA,vertexB),center=lcr.center;normals[0].multiplyScalar(opts.bondSpacing),normals[1].multiplyScalar(opts.bondSpacing);let line=null;line=center.sameSideAs(vertexA.position,vertexB.position,Vector2.add(a,normals[0]))?new Line(Vector2.add(a,normals[0]),Vector2.add(b,normals[0]),elementA,elementB):new Line(Vector2.add(a,normals[1]),Vector2.add(b,normals[1]),elementA,elementB),line.shorten(opts.bondLength-opts.shortBondLength*opts.bondLength),edge.isPartOfAromaticRing?svgWrapper.drawLine(line,!0):svgWrapper.drawLine(line),svgWrapper.drawLine(new Line(a,b,elementA,elementB))}else if(edge.center||vertexA.isTerminal()&&vertexB.isTerminal()||0==s.anCount&&1<s.bnCount||0==s.bnCount&&1<s.anCount){this.multiplyNormals(normals,opts.halfBondSpacing);let lineA=new Line(Vector2.add(a,normals[0]),Vector2.add(b,normals[0]),elementA,elementB),lineB=new Line(Vector2.add(a,normals[1]),Vector2.add(b,normals[1]),elementA,elementB);svgWrapper.drawLine(lineA),svgWrapper.drawLine(lineB)}else if(s.sideCount[0]>s.sideCount[1]||s.totalSideCount[0]>s.totalSideCount[1]){this.multiplyNormals(normals,opts.bondSpacing);let line=new Line(Vector2.add(a,normals[0]),Vector2.add(b,normals[0]),elementA,elementB);line.shorten(opts.bondLength-opts.shortBondLength*opts.bondLength),svgWrapper.drawLine(line),svgWrapper.drawLine(new Line(a,b,elementA,elementB))}else if(s.sideCount[0]<s.sideCount[1]||s.totalSideCount[0]<=s.totalSideCount[1]){this.multiplyNormals(normals,opts.bondSpacing);let line=new Line(Vector2.add(a,normals[1]),Vector2.add(b,normals[1]),elementA,elementB);line.shorten(opts.bondLength-opts.shortBondLength*opts.bondLength),svgWrapper.drawLine(line),svgWrapper.drawLine(new Line(a,b,elementA,elementB))}}else if("#"===edge.bondType){normals[0].multiplyScalar(opts.bondSpacing/1.5),normals[1].multiplyScalar(opts.bondSpacing/1.5);let lineA=new Line(Vector2.add(a,normals[0]),Vector2.add(b,normals[0]),elementA,elementB),lineB=new Line(Vector2.add(a,normals[1]),Vector2.add(b,normals[1]),elementA,elementB);svgWrapper.drawLine(lineA),svgWrapper.drawLine(lineB),svgWrapper.drawLine(new Line(a,b,elementA,elementB))}else if("."===edge.bondType);else{let isChiralCenterA=vertexA.value.isStereoCenter,isChiralCenterB=vertexB.value.isStereoCenter;"up"===edge.wedge?svgWrapper.drawWedge(new Line(a,b,elementA,elementB,isChiralCenterA,isChiralCenterB)):"down"===edge.wedge?svgWrapper.drawDashedWedge(new Line(a,b,elementA,elementB,isChiralCenterA,isChiralCenterB)):svgWrapper.drawLine(new Line(a,b,elementA,elementB,isChiralCenterA,isChiralCenterB))}if(debug){let midpoint=Vector2.midpoint(a,b);svgWrapper.drawDebugText(midpoint.x,midpoint.y,"e: "+edgeId)}}}drawAtomHighlights(debug){let preprocessor=this.preprocessor,opts=preprocessor.opts,graph=preprocessor.graph,rings=preprocessor.rings,svgWrapper=this.svgWrapper;for(var i=0;i<graph.vertices.length;i++){let vertex=graph.vertices[i],atom=vertex.value;for(var j=0;j<preprocessor.highlight_atoms.length;j++){let highlight=preprocessor.highlight_atoms[j];atom.class===highlight[0]&&svgWrapper.drawAtomHighlight(vertex.position.x,vertex.position.y,highlight[1])}}}drawVertices(debug){let preprocessor=this.preprocessor,opts=preprocessor.opts,graph=preprocessor.graph,rings=preprocessor.rings,svgWrapper=this.svgWrapper;for(var i=graph.vertices.length,i=0;i<graph.vertices.length;i++){let vertex=graph.vertices[i],atom=vertex.value,charge=0,isotope=0,bondCount=vertex.value.bondCount,element=atom.element,hydrogens=Atom.maxBonds[element]-bondCount,dir=vertex.getTextDirection(graph.vertices,atom.hasAttachedPseudoElements),isTerminal=!!(opts.terminalCarbons||"C"!==element||atom.hasAttachedPseudoElements)&&vertex.isTerminal(),isCarbon="C"===atom.element;if(3>graph.vertices.length&&(isCarbon=!1),"N"===atom.element&&atom.isPartOfAromaticRing&&(hydrogens=0),atom.bracket&&(hydrogens=atom.bracket.hcount,charge=atom.bracket.charge,isotope=atom.bracket.isotope),"allballs"===opts.atomVisualization)svgWrapper.drawBall(vertex.position.x,vertex.position.y,element);else if(atom.isDrawn&&(!isCarbon||atom.drawExplicit||isTerminal||atom.hasAttachedPseudoElements)||1===graph.vertices.length){if("default"===opts.atomVisualization){let attachedPseudoElements=atom.getAttachedPseudoElements();atom.hasAttachedPseudoElements&&graph.vertices.length===Object.keys(attachedPseudoElements).length+1&&(dir="right"),svgWrapper.drawText(vertex.position.x,vertex.position.y,element,hydrogens,dir,isTerminal,charge,isotope,graph.vertices.length,attachedPseudoElements)}else"balls"===opts.atomVisualization&&svgWrapper.drawBall(vertex.position.x,vertex.position.y,element);}else if(2===vertex.getNeighbourCount()&&!0==vertex.forcePositioned){let a=graph.vertices[vertex.neighbours[0]].position,b=graph.vertices[vertex.neighbours[1]].position,angle=Vector2.threePointangle(vertex.position,a,b);.1>_Mathabs5(_MathPI4-angle)&&svgWrapper.drawPoint(vertex.position.x,vertex.position.y,element)}if(debug){let value="v: "+vertex.id+" "+ArrayHelper.print(atom.ringbonds);svgWrapper.drawDebugText(vertex.position.x,vertex.position.y,value)}}if(opts.debug)for(var i=0;i<rings.length;i++){let center=rings[i].center;svgWrapper.drawDebugPoint(center.x,center.y,"r: "+rings[i].id)}}drawWeights(weights,weightsNormalized){if(!weights.every(w=>0===w)){if(weights.length!==this.preprocessor.graph.atomIdxToVertexId.length)throw new Error("The number of weights supplied must be equal to the number of (heavy) atoms in the molecule.");let points=[];for(const atomIdx of this.preprocessor.graph.atomIdxToVertexId){let vertex=this.preprocessor.graph.vertices[atomIdx];points.push(new Vector2(vertex.position.x-this.svgWrapper.minX,vertex.position.y-this.svgWrapper.minY))}let gd=new GaussDrawer(points,weights,this.svgWrapper.drawingWidth,this.svgWrapper.drawingHeight,this.opts.weights.sigma,this.opts.weights.interval,this.opts.weights.colormap,this.opts.weights.opacity,weightsNormalized);gd.draw(),this.svgWrapper.addLayer(gd.getSVG())}}getTotalOverlapScore(){return this.preprocessor.getTotalOverlapScore()}getMolecularFormula(graph=null){return this.preprocessor.getMolecularFormula(graph)}multiplyNormals(normals,spacing){normals[0].multiplyScalar(spacing),normals[1].multiplyScalar(spacing)}}},{"./ArrayHelper":3,"./Atom":4,"./DrawerBase":7,"./GaussDrawer":10,"./Graph":11,"./Line":12,"./SvgWrapper":25,"./ThemeManager":26,"./Vector2":28}],25:[function(require,module){"use strict";var _NumberMAX_SAFE_INTEGER3=Number.MAX_SAFE_INTEGER,_NumberMAX_VALUE3=Number.MAX_VALUE,_Mathabs6=Math.abs;function makeid(length){for(var result="",characters="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",charactersLength=characters.length,i=0;i<length;i++)result+=characters.charAt(Math.floor(Math.random()*charactersLength));return result}const{getChargeText}=require("./UtilityFunctions"),Line=require("./Line"),Vector2=require("./Vector2"),MathHelper=require("./MathHelper");class SvgWrapper{constructor(themeManager,target,options,clear=!0){if(this.svg="string"==typeof target||target instanceof String?document.getElementById(target):target,this.container=null,this.opts=options,this.uid=makeid(5),this.gradientId=0,this.backgroundItems=[],this.paths=[],this.vertices=[],this.gradients=[],this.highlights=[],this.drawingWidth=0,this.drawingHeight=0,this.halfBondThickness=this.opts.bondThickness/2,this.themeManager=themeManager,this.maskElements=[],this.maxX=-_NumberMAX_VALUE3,this.maxY=-_NumberMAX_VALUE3,this.minX=_NumberMAX_VALUE3,this.minY=_NumberMAX_VALUE3,clear)for(;this.svg.firstChild;)this.svg.removeChild(this.svg.firstChild);this.style=document.createElementNS("http://www.w3.org/2000/svg","style"),this.style.appendChild(document.createTextNode(`
|
|
.element {
|
|
font: ${this.opts.fontSizeLarge}pt ${this.opts.fontFamily};
|
|
}
|
|
.sub {
|
|
font: ${this.opts.fontSizeSmall}pt ${this.opts.fontFamily};
|
|
}
|
|
`)),this.svg?this.svg.appendChild(this.style):(this.container=document.createElementNS("http://www.w3.org/2000/svg","g"),container.appendChild(this.style))}constructSvg(){let defs=document.createElementNS("http://www.w3.org/2000/svg","defs"),masks=document.createElementNS("http://www.w3.org/2000/svg","mask"),background=document.createElementNS("http://www.w3.org/2000/svg","g"),highlights=document.createElementNS("http://www.w3.org/2000/svg","g"),paths=document.createElementNS("http://www.w3.org/2000/svg","g"),vertices=document.createElementNS("http://www.w3.org/2000/svg","g"),pathChildNodes=this.paths,mask=document.createElementNS("http://www.w3.org/2000/svg","rect");mask.setAttributeNS(null,"x",this.minX),mask.setAttributeNS(null,"y",this.minY),mask.setAttributeNS(null,"width",this.maxX-this.minX),mask.setAttributeNS(null,"height",this.maxY-this.minY),mask.setAttributeNS(null,"fill","white"),masks.appendChild(mask),masks.setAttributeNS(null,"id",this.uid+"-text-mask");for(let path of pathChildNodes)paths.appendChild(path);for(let backgroundItem of this.backgroundItems)background.appendChild(backgroundItem);for(let highlight of this.highlights)highlights.appendChild(highlight);for(let vertex of this.vertices)vertices.appendChild(vertex);for(let mask of this.maskElements)masks.appendChild(mask);for(let gradient of this.gradients)defs.appendChild(gradient);return paths.setAttributeNS(null,"mask","url(#"+this.uid+"-text-mask)"),this.updateViewbox(this.opts.scale),background.setAttributeNS(null,"style",`transform: translateX(${this.minX}px) translateY(${this.minY}px)`),this.svg?void(this.svg.appendChild(defs),this.svg.appendChild(masks),this.svg.appendChild(background),this.svg.appendChild(highlights),this.svg.appendChild(paths),this.svg.appendChild(vertices)):(this.container.appendChild(defs),this.container.appendChild(masks),this.container.appendChild(background),this.container.appendChild(paths),this.container.appendChild(vertices),this.container)}addLayer(svg){this.backgroundItems.push(svg.firstChild)}createGradient(line){let gradient=document.createElementNS("http://www.w3.org/2000/svg","linearGradient"),gradientUrl=this.uid+`-line-${this.gradientId++}`,l=line.getLeftVector(),r=line.getRightVector(),fromX=l.x,fromY=l.y,toX=r.x,toY=r.y;gradient.setAttributeNS(null,"id",gradientUrl),gradient.setAttributeNS(null,"gradientUnits","userSpaceOnUse"),gradient.setAttributeNS(null,"x1",fromX),gradient.setAttributeNS(null,"y1",fromY),gradient.setAttributeNS(null,"x2",toX),gradient.setAttributeNS(null,"y2",toY);let firstStop=document.createElementNS("http://www.w3.org/2000/svg","stop");firstStop.setAttributeNS(null,"stop-color",this.themeManager.getColor(line.getLeftElement())||this.themeManager.getColor("C")),firstStop.setAttributeNS(null,"offset","20%");let secondStop=document.createElementNS("http://www.w3.org/2000/svg","stop");return secondStop.setAttributeNS(null,"stop-color",this.themeManager.getColor(line.getRightElement()||this.themeManager.getColor("C"))),secondStop.setAttributeNS(null,"offset","100%"),gradient.appendChild(firstStop),gradient.appendChild(secondStop),this.gradients.push(gradient),gradientUrl}createSubSuperScripts(text,shift){let elem=document.createElementNS("http://www.w3.org/2000/svg","tspan");return elem.setAttributeNS(null,"baseline-shift",shift),elem.appendChild(document.createTextNode(text)),elem.setAttributeNS(null,"class","sub"),elem}static createUnicodeCharge(n){return 1===n?"\u207A":-1===n?"\u207B":1<n?SvgWrapper.createUnicodeSuperscript(n)+"\u207A":-1>n?SvgWrapper.createUnicodeSuperscript(n)+"\u207B":""}determineDimensions(vertices){for(var i=0;i<vertices.length;i++){if(!vertices[i].value.isDrawn)continue;let p=vertices[i].position;this.maxX<p.x&&(this.maxX=p.x),this.maxY<p.y&&(this.maxY=p.y),this.minX>p.x&&(this.minX=p.x),this.minY>p.y&&(this.minY=p.y)}let padding=this.opts.padding;this.maxX+=padding,this.maxY+=padding,this.minX-=padding,this.minY-=padding,this.drawingWidth=this.maxX-this.minX,this.drawingHeight=this.maxY-this.minY}updateViewbox(scale){let x=this.minX,y=this.minY,width=this.maxX-this.minX,height=this.maxY-this.minY;if(!(0>=scale))this.svg&&(this.svg.style.width=scale*width+"px",this.svg.style.height=scale*height+"px");else if(width>height){let diff=width-height;height=width,y-=diff/2}else{let diff=height-width;width=height,x-=diff/2}this.svg.setAttributeNS(null,"viewBox",`${x} ${y} ${width} ${height}`)}drawBall(x,y,elementName){let r=this.opts.bondLength/4.5;x-r<this.minX&&(this.minX=x-r),x+r>this.maxX&&(this.maxX=x+r),y-r<this.minY&&(this.minY=y-r),y+r>this.maxY&&(this.maxY=y+r);let ball=document.createElementNS("http://www.w3.org/2000/svg","circle");ball.setAttributeNS(null,"cx",x),ball.setAttributeNS(null,"cy",y),ball.setAttributeNS(null,"r",r),ball.setAttributeNS(null,"fill",this.themeManager.getColor(elementName)),this.vertices.push(ball)}drawWedge(line){let l=line.getLeftVector().clone(),r=line.getRightVector().clone(),normals=Vector2.normals(l,r);normals[0].normalize(),normals[1].normalize();let isRightChiralCenter=line.getRightChiral(),start=l,end=r;isRightChiralCenter&&(start=r,end=l);let t=Vector2.add(start,Vector2.multiplyScalar(normals[0],this.halfBondThickness)),u=Vector2.add(end,Vector2.multiplyScalar(normals[0],3+this.opts.fontSizeLarge/4)),v=Vector2.add(end,Vector2.multiplyScalar(normals[1],3+this.opts.fontSizeLarge/4)),w=Vector2.add(start,Vector2.multiplyScalar(normals[1],this.halfBondThickness)),polygon=document.createElementNS("http://www.w3.org/2000/svg","polygon"),gradient=this.createGradient(line,l.x,l.y,r.x,r.y);polygon.setAttributeNS(null,"points",`${t.x},${t.y} ${u.x},${u.y} ${v.x},${v.y} ${w.x},${w.y}`),polygon.setAttributeNS(null,"fill",`url('#${gradient}')`),this.paths.push(polygon)}drawAtomHighlight(x,y,color="#03fc9d"){let ball=document.createElementNS("http://www.w3.org/2000/svg","circle");ball.setAttributeNS(null,"cx",x),ball.setAttributeNS(null,"cy",y),ball.setAttributeNS(null,"r",this.opts.bondLength/3),ball.setAttributeNS(null,"fill",color),this.highlights.push(ball)}drawDashedWedge(line){if(isNaN(line.from.x)||isNaN(line.from.y)||isNaN(line.to.x)||isNaN(line.to.y))return;let l=line.getLeftVector().clone(),r=line.getRightVector().clone(),normals=Vector2.normals(l,r);normals[0].normalize(),normals[1].normalize();let isRightChiralCenter=line.getRightChiral(),start,end;isRightChiralCenter?(start=r,end=l):(start=l,end=r);let dir=Vector2.subtract(end,start).normalize(),length=line.getLength(),step=1.25/(length/(this.opts.bondLength/10)),gradient=this.createGradient(line);for(let t=0;1>t;t+=step){let to=Vector2.multiplyScalar(dir,t*length),startDash=Vector2.add(start,to),width=this.opts.fontSizeLarge/2*t,dashOffset=Vector2.multiplyScalar(normals[0],width);startDash.subtract(dashOffset);let endDash=startDash.clone();endDash.add(Vector2.multiplyScalar(dashOffset,2)),this.drawLine(new Line(startDash,endDash),null,gradient)}}drawDebugPoint(x,y,debugText="",color="#f00"){let point=document.createElementNS("http://www.w3.org/2000/svg","circle");point.setAttributeNS(null,"cx",x),point.setAttributeNS(null,"cy",y),point.setAttributeNS(null,"r","2"),point.setAttributeNS(null,"fill","#f00"),this.vertices.push(point),this.drawDebugText(x,y,debugText)}drawDebugText(x,y,text){let textElem=document.createElementNS("http://www.w3.org/2000/svg","text");textElem.setAttributeNS(null,"x",x),textElem.setAttributeNS(null,"y",y),textElem.setAttributeNS(null,"class","debug"),textElem.setAttributeNS(null,"fill","#ff0000"),textElem.setAttributeNS(null,"style",`
|
|
font: 5px Droid Sans, sans-serif;
|
|
`),textElem.appendChild(document.createTextNode(text)),this.vertices.push(textElem)}drawRing(x,y,s){let circleElem=document.createElementNS("http://www.w3.org/2000/svg","circle"),radius=MathHelper.apothemFromSideLength(this.opts.bondLength,s);circleElem.setAttributeNS(null,"cx",x),circleElem.setAttributeNS(null,"cy",y),circleElem.setAttributeNS(null,"r",radius-this.opts.bondSpacing),circleElem.setAttributeNS(null,"stroke",this.themeManager.getColor("C")),circleElem.setAttributeNS(null,"stroke-width",this.opts.bondThickness),circleElem.setAttributeNS(null,"fill","none"),this.paths.push(circleElem)}drawLine(line,dashed=!1,gradient=null,linecap="round"){let opts=this.opts,stylesArr=[["stroke-width",this.opts.bondThickness],["stroke-linecap",linecap],["stroke-dasharray",dashed?"5, 5":"none"]],l=line.getLeftVector(),r=line.getRightVector(),fromX=l.x,fromY=l.y,toX=r.x,toY=r.y,styles=stylesArr.map(sub=>sub.join(":")).join(";"),lineElem=document.createElementNS("http://www.w3.org/2000/svg","line");lineElem.setAttributeNS(null,"x1",fromX),lineElem.setAttributeNS(null,"y1",fromY),lineElem.setAttributeNS(null,"x2",toX),lineElem.setAttributeNS(null,"y2",toY),lineElem.setAttributeNS(null,"style",styles),this.paths.push(lineElem),null==gradient&&(gradient=this.createGradient(line,fromX,fromY,toX,toY)),lineElem.setAttributeNS(null,"stroke",`url('#${gradient}')`)}drawPoint(x,y,elementName){let r=.75;x-r<this.minX&&(this.minX=x-r),x+r>this.maxX&&(this.maxX=x+r),y-r<this.minY&&(this.minY=y-r),y+r>this.maxY&&(this.maxY=y+r);let mask=document.createElementNS("http://www.w3.org/2000/svg","circle");mask.setAttributeNS(null,"cx",x),mask.setAttributeNS(null,"cy",y),mask.setAttributeNS(null,"r","1.5"),mask.setAttributeNS(null,"fill","black"),this.maskElements.push(mask);let point=document.createElementNS("http://www.w3.org/2000/svg","circle");point.setAttributeNS(null,"cx",x),point.setAttributeNS(null,"cy",y),point.setAttributeNS(null,"r",r),point.setAttributeNS(null,"fill",this.themeManager.getColor(elementName)),this.vertices.push(point)}drawText(x,y,elementName,hydrogens,direction,isTerminal,charge,isotope,totalVertices,attachedPseudoElement={}){let text=[],display=elementName;for(let key in 0!==charge&&null!==charge&&(display+=SvgWrapper.createUnicodeCharge(charge)),0!==isotope&&null!==isotope&&(display=SvgWrapper.createUnicodeSuperscript(isotope)+display),text.push([display,elementName]),1===hydrogens?text.push(["H","H"]):1<hydrogens&&text.push(["H"+SvgWrapper.createUnicodeSubscript(hydrogens),"H"]),1===charge&&"N"===elementName&&attachedPseudoElement.hasOwnProperty("0O")&&attachedPseudoElement.hasOwnProperty("0O-1")&&(attachedPseudoElement={"0O":{element:"O",count:2,hydrogenCount:0,previousElement:"C",charge:""}},charge=0),attachedPseudoElement){if(!attachedPseudoElement.hasOwnProperty(key))continue;let pe=attachedPseudoElement[key],display=pe.element;1<pe.count&&(display+=SvgWrapper.createUnicodeSubscript(pe.count)),""!==pe.charge&&(display+=SvgWrapper.createUnicodeCharge(charge)),text.push([display,pe.element]),1===pe.hydrogenCount?text.push(["H","H"]):1<pe.hydrogenCount&&text.push(["H"+SvgWrapper.createUnicodeSubscript(pe.hydrogenCount),"H"])}this.write(text,direction,x,y,1===totalVertices)}write(text,direction,x,y,singleVertex){let bbox=SvgWrapper.measureText(text[0][1],this.opts.fontSizeLarge,this.opts.fontFamily);"left"===direction&&text[0][0]!==text[0][1]&&(bbox.width*=2),singleVertex?(x+bbox.width*text.length>this.maxX&&(this.maxX=x+bbox.width*text.length),x-bbox.width/2<this.minX&&(this.minX=x-bbox.width/2),y-bbox.height<this.minY&&(this.minY=y-bbox.height),y+bbox.height>this.maxY&&(this.maxY=y+bbox.height)):("right"===direction?"left"!=direction&&(x+bbox.width*text.length>this.maxX&&(this.maxX=x+bbox.width*text.length),x-bbox.width/2<this.minX&&(this.minX=x-bbox.width/2)):(x+bbox.width*text.length>this.maxX&&(this.maxX=x+bbox.width*text.length),x-bbox.width*text.length<this.minX&&(this.minX=x-bbox.width*text.length)),y-bbox.height<this.minY&&(this.minY=y-bbox.height),y+bbox.height>this.maxY&&(this.maxY=y+bbox.height),"down"===direction&&y+.8*bbox.height*text.length>this.maxY&&(this.maxY=y+.8*bbox.height*text.length),"up"===direction&&y-.8*bbox.height*text.length<this.minY&&(this.minY=y-.8*bbox.height*text.length));let cx=x,textElem=document.createElementNS("http://www.w3.org/2000/svg","text");textElem.setAttributeNS(null,"class","element");let g=document.createElementNS("http://www.w3.org/2000/svg","g");textElem.setAttributeNS(null,"fill","#ffffff"),"left"===direction&&(text=text.reverse()),("right"===direction||"down"===direction||"up"===direction)&&(x-=bbox.width/2),"left"===direction&&(x+=bbox.width/2),text.forEach((part,i)=>{const display=part[0],elementName=part[1];let tspanElem=document.createElementNS("http://www.w3.org/2000/svg","tspan");tspanElem.setAttributeNS(null,"fill",this.themeManager.getColor(elementName)),tspanElem.textContent=display,("up"===direction||"down"===direction)&&(tspanElem.setAttributeNS(null,"x","0px"),"up"===direction?tspanElem.setAttributeNS(null,"y",`-${.9*i}em`):tspanElem.setAttributeNS(null,"y",`${.9*i}em`)),textElem.appendChild(tspanElem)}),textElem.setAttributeNS(null,"data-direction",direction),"left"===direction||"right"===direction?(textElem.setAttributeNS(null,"dominant-baseline","alphabetic"),textElem.setAttributeNS(null,"y","0.36em")):textElem.setAttributeNS(null,"dominant-baseline","central"),"left"===direction&&textElem.setAttributeNS(null,"text-anchor","end"),g.appendChild(textElem),g.setAttributeNS(null,"style",`transform: translateX(${x}px) translateY(${y}px)`);let maskRadius=.75*this.opts.fontSizeLarge;1<text[0][1].length&&(maskRadius=1.1*this.opts.fontSizeLarge);let mask=document.createElementNS("http://www.w3.org/2000/svg","circle");mask.setAttributeNS(null,"cx",cx),mask.setAttributeNS(null,"cy",y),mask.setAttributeNS(null,"r",maskRadius),mask.setAttributeNS(null,"fill","black"),this.maskElements.push(mask),this.vertices.push(g)}toCanvas(canvas,width,height){("string"==typeof canvas||canvas instanceof String)&&(canvas=document.getElementById(canvas));let image=new Image;image.onload=function(){canvas.width=width,canvas.height=height,canvas.getContext("2d").drawImage(image,0,0,width,height)},image.src="data:image/svg+xml;charset-utf-8,"+encodeURIComponent(this.svg.outerHTML)}static createUnicodeSubscript(n){let result="";return n.toString().split("").forEach(d=>{result+=["\u2080","\u2081","\u2082","\u2083","\u2084","\u2085","\u2086","\u2087","\u2088","\u2089"][parseInt(d)]}),result}static createUnicodeSuperscript(n){let result="";return n.toString().split("").forEach(d=>{let parsed=parseInt(d);parsed&&(result+=["\u2070","\xB9","\xB2","\xB3","\u2074","\u2075","\u2076","\u2077","\u2078","\u2079"][parseInt(d)])}),result}static replaceNumbersWithSubscript(text){let subscriptNumbers={0:"\u2080",1:"\u2081",2:"\u2082",3:"\u2083",4:"\u2084",5:"\u2085",6:"\u2086",7:"\u2087",8:"\u2088",9:"\u2089"};for(const[key,value]of Object.entries(subscriptNumbers))text=text.replaceAll(key,value);return text}static measureText(text,fontSize,fontFamily,lineHeight=.9){const element=document.createElement("canvas"),ctx=element.getContext("2d");ctx.font=`${fontSize}pt ${fontFamily}`;let textMetrics=ctx.measureText(text),compWidth=_Mathabs6(textMetrics.actualBoundingBoxLeft)+_Mathabs6(textMetrics.actualBoundingBoxRight);return{width:textMetrics.width>compWidth?textMetrics.width:compWidth,height:(_Mathabs6(textMetrics.actualBoundingBoxAscent)+_Mathabs6(textMetrics.actualBoundingBoxAscent))*lineHeight}}static svgToCanvas(svg,canvas,width,height,callback=null){svg.setAttributeNS(null,"width",width),svg.setAttributeNS(null,"height",height);let image=new Image;return image.onload=function(){canvas.width=width,canvas.height=height;let context=canvas.getContext("2d");context.imageSmoothingEnabled=!1,context.drawImage(image,0,0,width,height),callback&&callback(canvas)},image.onerror=function(err){console.log(err)},image.src="data:image/svg+xml;charset-utf-8,"+encodeURIComponent(svg.outerHTML),canvas}static svgToImg(svg,img,width,height){let canvas=document.createElement("canvas");this.svgToCanvas(svg,canvas,width,height,()=>{img.src=canvas.toDataURL("image/png")})}static writeText(text,themeManager,fontSize,fontFamily,maxWidth=_NumberMAX_SAFE_INTEGER3){let svg=document.createElementNS("http://www.w3.org/2000/svg","svg"),style=document.createElementNS("http://www.w3.org/2000/svg","style");style.appendChild(document.createTextNode(`
|
|
.text {
|
|
font: ${fontSize}pt ${fontFamily};
|
|
dominant-baseline: ideographic;
|
|
}
|
|
`)),svg.appendChild(style);let textElem=document.createElementNS("http://www.w3.org/2000/svg","text");textElem.setAttributeNS(null,"class","text");let maxLineWidth=0,totalHeight=0,lines=[];return text.split("\n").forEach(line=>{let dims=SvgWrapper.measureText(line,fontSize,fontFamily,1);if(dims.width>=maxWidth){let totalWordsWidth=0,maxWordsHeight=0,words=line.split(" "),offset=0;for(let i=0,wordDims;i<words.length;i++)wordDims=SvgWrapper.measureText(words[i],fontSize,fontFamily,1),totalWordsWidth+wordDims.width>maxWidth&&(lines.push({text:words.slice(offset,i).join(" "),width:totalWordsWidth,height:maxWordsHeight}),totalWordsWidth=0,maxWordsHeight=0,offset=i),wordDims.height>maxWordsHeight&&(maxWordsHeight=wordDims.height),totalWordsWidth+=wordDims.width;offset<words.length&&lines.push({text:words.slice(offset,words.length).join(" "),width:totalWordsWidth,height:maxWordsHeight})}else lines.push({text:line,width:dims.width,height:dims.height})}),lines.forEach(line=>{totalHeight+=line.height;let tspanElem=document.createElementNS("http://www.w3.org/2000/svg","tspan");tspanElem.setAttributeNS(null,"fill",themeManager.getColor("C")),tspanElem.textContent=line.text,tspanElem.setAttributeNS(null,"x","0px"),tspanElem.setAttributeNS(null,"y",`${totalHeight}px`),textElem.appendChild(tspanElem),line.width>maxLineWidth&&(maxLineWidth=line.width)}),svg.appendChild(textElem),{svg:svg,width:maxLineWidth,height:totalHeight}}}module.exports=SvgWrapper},{"./Line":12,"./MathHelper":13,"./UtilityFunctions":27,"./Vector2":28}],26:[function(require,module){"use strict";module.exports=class{constructor(colors,theme){this.colors=colors,this.theme=this.colors[theme]}getColor(key){return key&&(key=key.toUpperCase(),key in this.theme)?this.theme[key]:this.theme.C}setTheme(theme){this.colors.hasOwnProperty(theme)&&(this.theme=this.colors[theme])}}},{}],27:[function(require,module){"use strict";module.exports={getChargeText:function(charge){return 1===charge?"+":2===charge?"2+":-1===charge?"-":-2===charge?"2-":""}}},{}],28:[function(require,module){"use strict";var _Mathsin5=Math.sin,_Mathcos5=Math.cos,_Mathacos=Math.acos,_Mathsqrt4=Math.sqrt;class Vector2{constructor(x,y){0==arguments.length?(this.x=0,this.y=0):1==arguments.length?(this.x=x.x,this.y=x.y):(this.x=x,this.y=y)}clone(){return new Vector2(this.x,this.y)}toString(){return"("+this.x+","+this.y+")"}add(vec){return this.x+=vec.x,this.y+=vec.y,this}subtract(vec){return this.x-=vec.x,this.y-=vec.y,this}divide(scalar){return this.x/=scalar,this.y/=scalar,this}multiply(v){return this.x*=v.x,this.y*=v.y,this}multiplyScalar(scalar){return this.x*=scalar,this.y*=scalar,this}invert(){return this.x=-this.x,this.y=-this.y,this}angle(){return Math.atan2(this.y,this.x)}distance(vec){return _Mathsqrt4((vec.x-this.x)*(vec.x-this.x)+(vec.y-this.y)*(vec.y-this.y))}distanceSq(vec){return(vec.x-this.x)*(vec.x-this.x)+(vec.y-this.y)*(vec.y-this.y)}clockwise(vec){let a=this.y*vec.x,b=this.x*vec.y;if(a>b)return-1;return a===b?0:1}relativeClockwise(center,vec){let a=(this.y-center.y)*(vec.x-center.x),b=(this.x-center.x)*(vec.y-center.y);if(a>b)return-1;return a===b?0:1}rotate(angle){let tmp=new Vector2(0,0),cosAngle=_Mathcos5(angle),sinAngle=_Mathsin5(angle);return tmp.x=this.x*cosAngle-this.y*sinAngle,tmp.y=this.x*sinAngle+this.y*cosAngle,this.x=tmp.x,this.y=tmp.y,this}rotateAround(angle,vec){let s=_Mathsin5(angle),c=_Mathcos5(angle);this.x-=vec.x,this.y-=vec.y;let x=this.x*c-this.y*s,y=this.x*s+this.y*c;return this.x=x+vec.x,this.y=y+vec.y,this}rotateTo(vec,center,offsetAngle=0){this.x+=.001,this.y-=.001;let a=Vector2.subtract(this,center),b=Vector2.subtract(vec,center),angle=Vector2.angle(b,a);return this.rotateAround(angle+offsetAngle,center),this}rotateAwayFrom(vec,center,angle){this.rotateAround(angle,center);let distSqA=this.distanceSq(vec);this.rotateAround(-2*angle,center);let distSqB=this.distanceSq(vec);distSqB<distSqA&&this.rotateAround(2*angle,center)}getRotateAwayFromAngle(vec,center,angle){let tmp=this.clone();tmp.rotateAround(angle,center);let distSqA=tmp.distanceSq(vec);tmp.rotateAround(-2*angle,center);let distSqB=tmp.distanceSq(vec);return distSqB<distSqA?angle:-angle}getRotateTowardsAngle(vec,center,angle){let tmp=this.clone();tmp.rotateAround(angle,center);let distSqA=tmp.distanceSq(vec);tmp.rotateAround(-2*angle,center);let distSqB=tmp.distanceSq(vec);return distSqB>distSqA?angle:-angle}getRotateToAngle(vec,center){let a=Vector2.subtract(this,center),b=Vector2.subtract(vec,center),angle=Vector2.angle(b,a);return Number.isNaN(angle)?0:angle}isInPolygon(polygon){let inside=!1;for(let i=0,j=polygon.length-1;i<polygon.length;j=i++)polygon[i].y>this.y!=polygon[j].y>this.y&&this.x<(polygon[j].x-polygon[i].x)*(this.y-polygon[i].y)/(polygon[j].y-polygon[i].y)+polygon[i].x&&(inside=!inside);return inside}length(){return _Mathsqrt4(this.x*this.x+this.y*this.y)}lengthSq(){return this.x*this.x+this.y*this.y}normalize(){return this.divide(this.length()),this}normalized(){return Vector2.divideScalar(this,this.length())}whichSide(vecA,vecB){return(this.x-vecA.x)*(vecB.y-vecA.y)-(this.y-vecA.y)*(vecB.x-vecA.x)}sameSideAs(vecA,vecB,vecC){let d=this.whichSide(vecA,vecB),dRef=vecC.whichSide(vecA,vecB);return 0>d&&0>dRef||0==d&&0==dRef||0<d&&0<dRef}static add(vecA,vecB){return new Vector2(vecA.x+vecB.x,vecA.y+vecB.y)}static subtract(vecA,vecB){return new Vector2(vecA.x-vecB.x,vecA.y-vecB.y)}static multiply(vecA,vecB){return new Vector2(vecA.x*vecB.x,vecA.y*vecB.y)}static multiplyScalar(vec,scalar){return new Vector2(vec.x,vec.y).multiplyScalar(scalar)}static midpoint(vecA,vecB){return new Vector2((vecA.x+vecB.x)/2,(vecA.y+vecB.y)/2)}static normals(vecA,vecB){let delta=Vector2.subtract(vecB,vecA);return[new Vector2(-delta.y,delta.x),new Vector2(delta.y,-delta.x)]}static units(vecA,vecB){let delta=Vector2.subtract(vecB,vecA);return[new Vector2(-delta.y,delta.x).normalize(),new Vector2(delta.y,-delta.x).normalize()]}static divide(vecA,vecB){return new Vector2(vecA.x/vecB.x,vecA.y/vecB.y)}static divideScalar(vecA,s){return new Vector2(vecA.x/s,vecA.y/s)}static dot(vecA,vecB){return vecA.x*vecB.x+vecA.y*vecB.y}static angle(vecA,vecB){let dot=Vector2.dot(vecA,vecB);return _Mathacos(dot/(vecA.length()*vecB.length()))}static threePointangle(vecA,vecB,vecC){let ab=Vector2.subtract(vecB,vecA),bc=Vector2.subtract(vecC,vecB),abLength=vecA.distance(vecB),bcLength=vecB.distance(vecC);return _Mathacos(Vector2.dot(ab,bc)/(abLength*bcLength))}static scalarProjection(vecA,vecB){let unit=vecB.normalized();return Vector2.dot(vecA,unit)}static averageDirection(vecs){let avg=new Vector2(0,0);for(var i=0;i<vecs.length;i++){let vec=vecs[i];avg.add(vec)}return avg.normalize()}}module.exports=Vector2},{}],29:[function(require,module){"use strict";var _Mathround4=Math.round,_MathPI5=Math.PI;const MathHelper=require("./MathHelper"),ArrayHelper=require("./ArrayHelper"),Vector2=require("./Vector2"),Atom=require("./Atom");class Vertex{constructor(value,x=0,y=0){this.id=null,this.value=value,this.position=new Vector2(x?x:0,y?y:0),this.previousPosition=new Vector2(0,0),this.parentVertexId=null,this.children=[],this.spanningTreeChildren=[],this.edges=[],this.positioned=!1,this.angle=null,this.dir=1,this.neighbourCount=0,this.neighbours=[],this.neighbouringElements=[],this.forcePositioned=!1}setPosition(x,y){this.position.x=x,this.position.y=y}setPositionFromVector(v){this.position.x=v.x,this.position.y=v.y}addChild(vertexId){this.children.push(vertexId),this.neighbours.push(vertexId),this.neighbourCount++}addRingbondChild(vertexId,ringbondIndex){if(this.children.push(vertexId),this.value.bracket){let index=1;0===this.id&&0===this.value.bracket.hcount&&(index=0),1===this.value.bracket.hcount&&0===ringbondIndex&&(index=2),1===this.value.bracket.hcount&&1===ringbondIndex&&(3>this.neighbours.length?index=2:index=3),null===this.value.bracket.hcount&&0===ringbondIndex&&(index=1),null===this.value.bracket.hcount&&1===ringbondIndex&&(3>this.neighbours.length?index=1:index=2),this.neighbours.splice(index,0,vertexId)}else this.neighbours.push(vertexId);this.neighbourCount++}setParentVertexId(parentVertexId){this.neighbourCount++,this.parentVertexId=parentVertexId,this.neighbours.push(parentVertexId)}isTerminal(){return!!this.value.hasAttachedPseudoElements||null===this.parentVertexId&&2>this.children.length||0===this.children.length}clone(){let clone=new Vertex(this.value,this.position.x,this.position.y);return clone.id=this.id,clone.previousPosition=new Vector2(this.previousPosition.x,this.previousPosition.y),clone.parentVertexId=this.parentVertexId,clone.children=ArrayHelper.clone(this.children),clone.spanningTreeChildren=ArrayHelper.clone(this.spanningTreeChildren),clone.edges=ArrayHelper.clone(this.edges),clone.positioned=this.positioned,clone.angle=this.angle,clone.forcePositioned=this.forcePositioned,clone}equals(vertex){return this.id===vertex.id}getAngle(referenceVector=null,returnAsDegrees=!1){let u=null;return u=referenceVector?Vector2.subtract(this.position,referenceVector):Vector2.subtract(this.position,this.previousPosition),returnAsDegrees?MathHelper.toDeg(u.angle()):u.angle()}getTextDirection(vertices,onlyHorizontal=!1){let neighbours=this.getDrawnNeighbours(vertices),angles=[];if(1===vertices.length)return"right";for(let i=0;i<neighbours.length;i++)angles.push(this.getAngle(vertices[neighbours[i]].position));let textAngle=MathHelper.meanAngle(angles);if(this.isTerminal()||onlyHorizontal)1.57==_Mathround4(100*textAngle)/100&&(textAngle-=.2),textAngle=_Mathround4(_Mathround4(textAngle/_MathPI5)*_MathPI5);else{let halfPi=_MathPI5/2;textAngle=_Mathround4(_Mathround4(textAngle/halfPi)*halfPi)}return 2===textAngle?"down":-2===textAngle?"up":0===textAngle||-0===textAngle?"right":3===textAngle||-3===textAngle?"left":"down"}getNeighbours(vertexId=null){if(null===vertexId)return this.neighbours.slice();let arr=[];for(let i=0;i<this.neighbours.length;i++)this.neighbours[i]!==vertexId&&arr.push(this.neighbours[i]);return arr}getDrawnNeighbours(vertices){let arr=[];for(let i=0;i<this.neighbours.length;i++)vertices[this.neighbours[i]].value.isDrawn&&arr.push(this.neighbours[i]);return arr}getNeighbourCount(){return this.neighbourCount}getSpanningTreeNeighbours(vertexId=null){let neighbours=[];for(let i=0;i<this.spanningTreeChildren.length;i++)(void 0===vertexId||vertexId!=this.spanningTreeChildren[i])&&neighbours.push(this.spanningTreeChildren[i]);return null!=this.parentVertexId&&(void 0===vertexId||vertexId!=this.parentVertexId)&&neighbours.push(this.parentVertexId),neighbours}getNextInRing(vertices,ringId,previousVertexId){let neighbours=this.getNeighbours();for(let i=0;i<neighbours.length;i++)if(ArrayHelper.contains(vertices[neighbours[i]].value.rings,{value:ringId})&&neighbours[i]!=previousVertexId)return neighbours[i];return null}}module.exports=Vertex},{"./ArrayHelper":3,"./Atom":4,"./MathHelper":13,"./Vector2":28}]},{},[1]);
|
|
//# sourceMappingURL=smiles-drawer.min.js.map
|