tinymce.js 1.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448
  1. /**
  2. * Copyright (c) Tiny Technologies, Inc. All rights reserved.
  3. * Licensed under the LGPL or a commercial license.
  4. * For LGPL see License.txt in the project root for license information.
  5. * For commercial licenses see https://www.tiny.cloud/
  6. *
  7. * Version: 5.5.1 (2020-10-01)
  8. */
  9. (function () {
  10. 'use strict';
  11. var typeOf = function (x) {
  12. if (x === null) {
  13. return 'null';
  14. }
  15. if (x === undefined) {
  16. return 'undefined';
  17. }
  18. var t = typeof x;
  19. if (t === 'object' && (Array.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'Array')) {
  20. return 'array';
  21. }
  22. if (t === 'object' && (String.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'String')) {
  23. return 'string';
  24. }
  25. return t;
  26. };
  27. var isEquatableType = function (x) {
  28. return [
  29. 'undefined',
  30. 'boolean',
  31. 'number',
  32. 'string',
  33. 'function',
  34. 'xml',
  35. 'null'
  36. ].indexOf(x) !== -1;
  37. };
  38. var sort = function (xs, compareFn) {
  39. var clone = Array.prototype.slice.call(xs);
  40. return clone.sort(compareFn);
  41. };
  42. var contramap = function (eqa, f) {
  43. return eq(function (x, y) {
  44. return eqa.eq(f(x), f(y));
  45. });
  46. };
  47. var eq = function (f) {
  48. return { eq: f };
  49. };
  50. var tripleEq = eq(function (x, y) {
  51. return x === y;
  52. });
  53. var eqString = tripleEq;
  54. var eqArray = function (eqa) {
  55. return eq(function (x, y) {
  56. if (x.length !== y.length) {
  57. return false;
  58. }
  59. var len = x.length;
  60. for (var i = 0; i < len; i++) {
  61. if (!eqa.eq(x[i], y[i])) {
  62. return false;
  63. }
  64. }
  65. return true;
  66. });
  67. };
  68. var eqSortedArray = function (eqa, compareFn) {
  69. return contramap(eqArray(eqa), function (xs) {
  70. return sort(xs, compareFn);
  71. });
  72. };
  73. var eqRecord = function (eqa) {
  74. return eq(function (x, y) {
  75. var kx = Object.keys(x);
  76. var ky = Object.keys(y);
  77. if (!eqSortedArray(eqString).eq(kx, ky)) {
  78. return false;
  79. }
  80. var len = kx.length;
  81. for (var i = 0; i < len; i++) {
  82. var q = kx[i];
  83. if (!eqa.eq(x[q], y[q])) {
  84. return false;
  85. }
  86. }
  87. return true;
  88. });
  89. };
  90. var eqAny = eq(function (x, y) {
  91. if (x === y) {
  92. return true;
  93. }
  94. var tx = typeOf(x);
  95. var ty = typeOf(y);
  96. if (tx !== ty) {
  97. return false;
  98. }
  99. if (isEquatableType(tx)) {
  100. return x === y;
  101. } else if (tx === 'array') {
  102. return eqArray(eqAny).eq(x, y);
  103. } else if (tx === 'object') {
  104. return eqRecord(eqAny).eq(x, y);
  105. }
  106. return false;
  107. });
  108. var noop = function () {
  109. };
  110. var compose = function (fa, fb) {
  111. return function () {
  112. var args = [];
  113. for (var _i = 0; _i < arguments.length; _i++) {
  114. args[_i] = arguments[_i];
  115. }
  116. return fa(fb.apply(null, args));
  117. };
  118. };
  119. var compose1 = function (fbc, fab) {
  120. return function (a) {
  121. return fbc(fab(a));
  122. };
  123. };
  124. var constant = function (value) {
  125. return function () {
  126. return value;
  127. };
  128. };
  129. var identity = function (x) {
  130. return x;
  131. };
  132. function curry(fn) {
  133. var initialArgs = [];
  134. for (var _i = 1; _i < arguments.length; _i++) {
  135. initialArgs[_i - 1] = arguments[_i];
  136. }
  137. return function () {
  138. var restArgs = [];
  139. for (var _i = 0; _i < arguments.length; _i++) {
  140. restArgs[_i] = arguments[_i];
  141. }
  142. var all = initialArgs.concat(restArgs);
  143. return fn.apply(null, all);
  144. };
  145. }
  146. var not = function (f) {
  147. return function (t) {
  148. return !f(t);
  149. };
  150. };
  151. var die = function (msg) {
  152. return function () {
  153. throw new Error(msg);
  154. };
  155. };
  156. var never = constant(false);
  157. var always = constant(true);
  158. var none = function () {
  159. return NONE;
  160. };
  161. var NONE = function () {
  162. var eq = function (o) {
  163. return o.isNone();
  164. };
  165. var call = function (thunk) {
  166. return thunk();
  167. };
  168. var id = function (n) {
  169. return n;
  170. };
  171. var me = {
  172. fold: function (n, _s) {
  173. return n();
  174. },
  175. is: never,
  176. isSome: never,
  177. isNone: always,
  178. getOr: id,
  179. getOrThunk: call,
  180. getOrDie: function (msg) {
  181. throw new Error(msg || 'error: getOrDie called on none.');
  182. },
  183. getOrNull: constant(null),
  184. getOrUndefined: constant(undefined),
  185. or: id,
  186. orThunk: call,
  187. map: none,
  188. each: noop,
  189. bind: none,
  190. exists: never,
  191. forall: always,
  192. filter: none,
  193. equals: eq,
  194. equals_: eq,
  195. toArray: function () {
  196. return [];
  197. },
  198. toString: constant('none()')
  199. };
  200. return me;
  201. }();
  202. var some = function (a) {
  203. var constant_a = constant(a);
  204. var self = function () {
  205. return me;
  206. };
  207. var bind = function (f) {
  208. return f(a);
  209. };
  210. var me = {
  211. fold: function (n, s) {
  212. return s(a);
  213. },
  214. is: function (v) {
  215. return a === v;
  216. },
  217. isSome: always,
  218. isNone: never,
  219. getOr: constant_a,
  220. getOrThunk: constant_a,
  221. getOrDie: constant_a,
  222. getOrNull: constant_a,
  223. getOrUndefined: constant_a,
  224. or: self,
  225. orThunk: self,
  226. map: function (f) {
  227. return some(f(a));
  228. },
  229. each: function (f) {
  230. f(a);
  231. },
  232. bind: bind,
  233. exists: bind,
  234. forall: bind,
  235. filter: function (f) {
  236. return f(a) ? me : NONE;
  237. },
  238. toArray: function () {
  239. return [a];
  240. },
  241. toString: function () {
  242. return 'some(' + a + ')';
  243. },
  244. equals: function (o) {
  245. return o.is(a);
  246. },
  247. equals_: function (o, elementEq) {
  248. return o.fold(never, function (b) {
  249. return elementEq(a, b);
  250. });
  251. }
  252. };
  253. return me;
  254. };
  255. var from = function (value) {
  256. return value === null || value === undefined ? NONE : some(value);
  257. };
  258. var Optional = {
  259. some: some,
  260. none: none,
  261. from: from
  262. };
  263. var typeOf$1 = function (x) {
  264. var t = typeof x;
  265. if (x === null) {
  266. return 'null';
  267. } else if (t === 'object' && (Array.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'Array')) {
  268. return 'array';
  269. } else if (t === 'object' && (String.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'String')) {
  270. return 'string';
  271. } else {
  272. return t;
  273. }
  274. };
  275. var isType = function (type) {
  276. return function (value) {
  277. return typeOf$1(value) === type;
  278. };
  279. };
  280. var isSimpleType = function (type) {
  281. return function (value) {
  282. return typeof value === type;
  283. };
  284. };
  285. var eq$1 = function (t) {
  286. return function (a) {
  287. return t === a;
  288. };
  289. };
  290. var isString = isType('string');
  291. var isObject = isType('object');
  292. var isArray = isType('array');
  293. var isNull = eq$1(null);
  294. var isBoolean = isSimpleType('boolean');
  295. var isUndefined = eq$1(undefined);
  296. var isNullable = function (a) {
  297. return a === null || a === undefined;
  298. };
  299. var isNonNullable = function (a) {
  300. return !isNullable(a);
  301. };
  302. var isFunction = isSimpleType('function');
  303. var isNumber = isSimpleType('number');
  304. var nativeSlice = Array.prototype.slice;
  305. var nativeIndexOf = Array.prototype.indexOf;
  306. var nativePush = Array.prototype.push;
  307. var rawIndexOf = function (ts, t) {
  308. return nativeIndexOf.call(ts, t);
  309. };
  310. var indexOf = function (xs, x) {
  311. var r = rawIndexOf(xs, x);
  312. return r === -1 ? Optional.none() : Optional.some(r);
  313. };
  314. var contains = function (xs, x) {
  315. return rawIndexOf(xs, x) > -1;
  316. };
  317. var exists = function (xs, pred) {
  318. for (var i = 0, len = xs.length; i < len; i++) {
  319. var x = xs[i];
  320. if (pred(x, i)) {
  321. return true;
  322. }
  323. }
  324. return false;
  325. };
  326. var map = function (xs, f) {
  327. var len = xs.length;
  328. var r = new Array(len);
  329. for (var i = 0; i < len; i++) {
  330. var x = xs[i];
  331. r[i] = f(x, i);
  332. }
  333. return r;
  334. };
  335. var each = function (xs, f) {
  336. for (var i = 0, len = xs.length; i < len; i++) {
  337. var x = xs[i];
  338. f(x, i);
  339. }
  340. };
  341. var eachr = function (xs, f) {
  342. for (var i = xs.length - 1; i >= 0; i--) {
  343. var x = xs[i];
  344. f(x, i);
  345. }
  346. };
  347. var partition = function (xs, pred) {
  348. var pass = [];
  349. var fail = [];
  350. for (var i = 0, len = xs.length; i < len; i++) {
  351. var x = xs[i];
  352. var arr = pred(x, i) ? pass : fail;
  353. arr.push(x);
  354. }
  355. return {
  356. pass: pass,
  357. fail: fail
  358. };
  359. };
  360. var filter = function (xs, pred) {
  361. var r = [];
  362. for (var i = 0, len = xs.length; i < len; i++) {
  363. var x = xs[i];
  364. if (pred(x, i)) {
  365. r.push(x);
  366. }
  367. }
  368. return r;
  369. };
  370. var foldr = function (xs, f, acc) {
  371. eachr(xs, function (x) {
  372. acc = f(acc, x);
  373. });
  374. return acc;
  375. };
  376. var foldl = function (xs, f, acc) {
  377. each(xs, function (x) {
  378. acc = f(acc, x);
  379. });
  380. return acc;
  381. };
  382. var findUntil = function (xs, pred, until) {
  383. for (var i = 0, len = xs.length; i < len; i++) {
  384. var x = xs[i];
  385. if (pred(x, i)) {
  386. return Optional.some(x);
  387. } else if (until(x, i)) {
  388. break;
  389. }
  390. }
  391. return Optional.none();
  392. };
  393. var find = function (xs, pred) {
  394. return findUntil(xs, pred, never);
  395. };
  396. var findIndex = function (xs, pred) {
  397. for (var i = 0, len = xs.length; i < len; i++) {
  398. var x = xs[i];
  399. if (pred(x, i)) {
  400. return Optional.some(i);
  401. }
  402. }
  403. return Optional.none();
  404. };
  405. var flatten = function (xs) {
  406. var r = [];
  407. for (var i = 0, len = xs.length; i < len; ++i) {
  408. if (!isArray(xs[i])) {
  409. throw new Error('Arr.flatten item ' + i + ' was not an array, input: ' + xs);
  410. }
  411. nativePush.apply(r, xs[i]);
  412. }
  413. return r;
  414. };
  415. var bind = function (xs, f) {
  416. return flatten(map(xs, f));
  417. };
  418. var forall = function (xs, pred) {
  419. for (var i = 0, len = xs.length; i < len; ++i) {
  420. var x = xs[i];
  421. if (pred(x, i) !== true) {
  422. return false;
  423. }
  424. }
  425. return true;
  426. };
  427. var reverse = function (xs) {
  428. var r = nativeSlice.call(xs, 0);
  429. r.reverse();
  430. return r;
  431. };
  432. var difference = function (a1, a2) {
  433. return filter(a1, function (x) {
  434. return !contains(a2, x);
  435. });
  436. };
  437. var mapToObject = function (xs, f) {
  438. var r = {};
  439. for (var i = 0, len = xs.length; i < len; i++) {
  440. var x = xs[i];
  441. r[String(x)] = f(x, i);
  442. }
  443. return r;
  444. };
  445. var sort$1 = function (xs, comparator) {
  446. var copy = nativeSlice.call(xs, 0);
  447. copy.sort(comparator);
  448. return copy;
  449. };
  450. var head = function (xs) {
  451. return xs.length === 0 ? Optional.none() : Optional.some(xs[0]);
  452. };
  453. var last = function (xs) {
  454. return xs.length === 0 ? Optional.none() : Optional.some(xs[xs.length - 1]);
  455. };
  456. var from$1 = isFunction(Array.from) ? Array.from : function (x) {
  457. return nativeSlice.call(x);
  458. };
  459. var keys = Object.keys;
  460. var hasOwnProperty = Object.hasOwnProperty;
  461. var each$1 = function (obj, f) {
  462. var props = keys(obj);
  463. for (var k = 0, len = props.length; k < len; k++) {
  464. var i = props[k];
  465. var x = obj[i];
  466. f(x, i);
  467. }
  468. };
  469. var map$1 = function (obj, f) {
  470. return tupleMap(obj, function (x, i) {
  471. return {
  472. k: i,
  473. v: f(x, i)
  474. };
  475. });
  476. };
  477. var tupleMap = function (obj, f) {
  478. var r = {};
  479. each$1(obj, function (x, i) {
  480. var tuple = f(x, i);
  481. r[tuple.k] = tuple.v;
  482. });
  483. return r;
  484. };
  485. var objAcc = function (r) {
  486. return function (x, i) {
  487. r[i] = x;
  488. };
  489. };
  490. var internalFilter = function (obj, pred, onTrue, onFalse) {
  491. var r = {};
  492. each$1(obj, function (x, i) {
  493. (pred(x, i) ? onTrue : onFalse)(x, i);
  494. });
  495. return r;
  496. };
  497. var bifilter = function (obj, pred) {
  498. var t = {};
  499. var f = {};
  500. internalFilter(obj, pred, objAcc(t), objAcc(f));
  501. return {
  502. t: t,
  503. f: f
  504. };
  505. };
  506. var filter$1 = function (obj, pred) {
  507. var t = {};
  508. internalFilter(obj, pred, objAcc(t), noop);
  509. return t;
  510. };
  511. var mapToArray = function (obj, f) {
  512. var r = [];
  513. each$1(obj, function (value, name) {
  514. r.push(f(value, name));
  515. });
  516. return r;
  517. };
  518. var values = function (obj) {
  519. return mapToArray(obj, function (v) {
  520. return v;
  521. });
  522. };
  523. var get = function (obj, key) {
  524. return has(obj, key) ? Optional.from(obj[key]) : Optional.none();
  525. };
  526. var has = function (obj, key) {
  527. return hasOwnProperty.call(obj, key);
  528. };
  529. var equal = function (a1, a2, eq) {
  530. if (eq === void 0) {
  531. eq = eqAny;
  532. }
  533. return eqRecord(eq).eq(a1, a2);
  534. };
  535. var isArray$1 = Array.isArray;
  536. var toArray = function (obj) {
  537. if (!isArray$1(obj)) {
  538. var array = [];
  539. for (var i = 0, l = obj.length; i < l; i++) {
  540. array[i] = obj[i];
  541. }
  542. return array;
  543. } else {
  544. return obj;
  545. }
  546. };
  547. var each$2 = function (o, cb, s) {
  548. var n, l;
  549. if (!o) {
  550. return false;
  551. }
  552. s = s || o;
  553. if (o.length !== undefined) {
  554. for (n = 0, l = o.length; n < l; n++) {
  555. if (cb.call(s, o[n], n, o) === false) {
  556. return false;
  557. }
  558. }
  559. } else {
  560. for (n in o) {
  561. if (o.hasOwnProperty(n)) {
  562. if (cb.call(s, o[n], n, o) === false) {
  563. return false;
  564. }
  565. }
  566. }
  567. }
  568. return true;
  569. };
  570. var map$2 = function (array, callback) {
  571. var out = [];
  572. each$2(array, function (item, index) {
  573. out.push(callback(item, index, array));
  574. });
  575. return out;
  576. };
  577. var filter$2 = function (a, f) {
  578. var o = [];
  579. each$2(a, function (v, index) {
  580. if (!f || f(v, index, a)) {
  581. o.push(v);
  582. }
  583. });
  584. return o;
  585. };
  586. var indexOf$1 = function (a, v) {
  587. if (a) {
  588. for (var i = 0, l = a.length; i < l; i++) {
  589. if (a[i] === v) {
  590. return i;
  591. }
  592. }
  593. }
  594. return -1;
  595. };
  596. var reduce = function (collection, iteratee, accumulator, thisArg) {
  597. var acc = isUndefined(accumulator) ? collection[0] : accumulator;
  598. for (var i = 0; i < collection.length; i++) {
  599. acc = iteratee.call(thisArg, acc, collection[i], i);
  600. }
  601. return acc;
  602. };
  603. var findIndex$1 = function (array, predicate, thisArg) {
  604. var i, l;
  605. for (i = 0, l = array.length; i < l; i++) {
  606. if (predicate.call(thisArg, array[i], i, array)) {
  607. return i;
  608. }
  609. }
  610. return -1;
  611. };
  612. var last$1 = function (collection) {
  613. return collection[collection.length - 1];
  614. };
  615. var __assign = function () {
  616. __assign = Object.assign || function __assign(t) {
  617. for (var s, i = 1, n = arguments.length; i < n; i++) {
  618. s = arguments[i];
  619. for (var p in s)
  620. if (Object.prototype.hasOwnProperty.call(s, p))
  621. t[p] = s[p];
  622. }
  623. return t;
  624. };
  625. return __assign.apply(this, arguments);
  626. };
  627. function __rest(s, e) {
  628. var t = {};
  629. for (var p in s)
  630. if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
  631. t[p] = s[p];
  632. if (s != null && typeof Object.getOwnPropertySymbols === 'function')
  633. for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
  634. if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
  635. t[p[i]] = s[p[i]];
  636. }
  637. return t;
  638. }
  639. function __spreadArrays() {
  640. for (var s = 0, i = 0, il = arguments.length; i < il; i++)
  641. s += arguments[i].length;
  642. for (var r = Array(s), k = 0, i = 0; i < il; i++)
  643. for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
  644. r[k] = a[j];
  645. return r;
  646. }
  647. var cached = function (f) {
  648. var called = false;
  649. var r;
  650. return function () {
  651. var args = [];
  652. for (var _i = 0; _i < arguments.length; _i++) {
  653. args[_i] = arguments[_i];
  654. }
  655. if (!called) {
  656. called = true;
  657. r = f.apply(null, args);
  658. }
  659. return r;
  660. };
  661. };
  662. var DeviceType = function (os, browser, userAgent, mediaMatch) {
  663. var isiPad = os.isiOS() && /ipad/i.test(userAgent) === true;
  664. var isiPhone = os.isiOS() && !isiPad;
  665. var isMobile = os.isiOS() || os.isAndroid();
  666. var isTouch = isMobile || mediaMatch('(pointer:coarse)');
  667. var isTablet = isiPad || !isiPhone && isMobile && mediaMatch('(min-device-width:768px)');
  668. var isPhone = isiPhone || isMobile && !isTablet;
  669. var iOSwebview = browser.isSafari() && os.isiOS() && /safari/i.test(userAgent) === false;
  670. var isDesktop = !isPhone && !isTablet && !iOSwebview;
  671. return {
  672. isiPad: constant(isiPad),
  673. isiPhone: constant(isiPhone),
  674. isTablet: constant(isTablet),
  675. isPhone: constant(isPhone),
  676. isTouch: constant(isTouch),
  677. isAndroid: os.isAndroid,
  678. isiOS: os.isiOS,
  679. isWebView: constant(iOSwebview),
  680. isDesktop: constant(isDesktop)
  681. };
  682. };
  683. var firstMatch = function (regexes, s) {
  684. for (var i = 0; i < regexes.length; i++) {
  685. var x = regexes[i];
  686. if (x.test(s)) {
  687. return x;
  688. }
  689. }
  690. return undefined;
  691. };
  692. var find$1 = function (regexes, agent) {
  693. var r = firstMatch(regexes, agent);
  694. if (!r) {
  695. return {
  696. major: 0,
  697. minor: 0
  698. };
  699. }
  700. var group = function (i) {
  701. return Number(agent.replace(r, '$' + i));
  702. };
  703. return nu(group(1), group(2));
  704. };
  705. var detect = function (versionRegexes, agent) {
  706. var cleanedAgent = String(agent).toLowerCase();
  707. if (versionRegexes.length === 0) {
  708. return unknown();
  709. }
  710. return find$1(versionRegexes, cleanedAgent);
  711. };
  712. var unknown = function () {
  713. return nu(0, 0);
  714. };
  715. var nu = function (major, minor) {
  716. return {
  717. major: major,
  718. minor: minor
  719. };
  720. };
  721. var Version = {
  722. nu: nu,
  723. detect: detect,
  724. unknown: unknown
  725. };
  726. var detect$1 = function (candidates, userAgent) {
  727. var agent = String(userAgent).toLowerCase();
  728. return find(candidates, function (candidate) {
  729. return candidate.search(agent);
  730. });
  731. };
  732. var detectBrowser = function (browsers, userAgent) {
  733. return detect$1(browsers, userAgent).map(function (browser) {
  734. var version = Version.detect(browser.versionRegexes, userAgent);
  735. return {
  736. current: browser.name,
  737. version: version
  738. };
  739. });
  740. };
  741. var detectOs = function (oses, userAgent) {
  742. return detect$1(oses, userAgent).map(function (os) {
  743. var version = Version.detect(os.versionRegexes, userAgent);
  744. return {
  745. current: os.name,
  746. version: version
  747. };
  748. });
  749. };
  750. var UaString = {
  751. detectBrowser: detectBrowser,
  752. detectOs: detectOs
  753. };
  754. var checkRange = function (str, substr, start) {
  755. return substr === '' || str.length >= substr.length && str.substr(start, start + substr.length) === substr;
  756. };
  757. var contains$1 = function (str, substr) {
  758. return str.indexOf(substr) !== -1;
  759. };
  760. var startsWith = function (str, prefix) {
  761. return checkRange(str, prefix, 0);
  762. };
  763. var blank = function (r) {
  764. return function (s) {
  765. return s.replace(r, '');
  766. };
  767. };
  768. var trim = blank(/^\s+|\s+$/g);
  769. var lTrim = blank(/^\s+/g);
  770. var rTrim = blank(/\s+$/g);
  771. var normalVersionRegex = /.*?version\/\ ?([0-9]+)\.([0-9]+).*/;
  772. var checkContains = function (target) {
  773. return function (uastring) {
  774. return contains$1(uastring, target);
  775. };
  776. };
  777. var browsers = [
  778. {
  779. name: 'Edge',
  780. versionRegexes: [/.*?edge\/ ?([0-9]+)\.([0-9]+)$/],
  781. search: function (uastring) {
  782. return contains$1(uastring, 'edge/') && contains$1(uastring, 'chrome') && contains$1(uastring, 'safari') && contains$1(uastring, 'applewebkit');
  783. }
  784. },
  785. {
  786. name: 'Chrome',
  787. versionRegexes: [
  788. /.*?chrome\/([0-9]+)\.([0-9]+).*/,
  789. normalVersionRegex
  790. ],
  791. search: function (uastring) {
  792. return contains$1(uastring, 'chrome') && !contains$1(uastring, 'chromeframe');
  793. }
  794. },
  795. {
  796. name: 'IE',
  797. versionRegexes: [
  798. /.*?msie\ ?([0-9]+)\.([0-9]+).*/,
  799. /.*?rv:([0-9]+)\.([0-9]+).*/
  800. ],
  801. search: function (uastring) {
  802. return contains$1(uastring, 'msie') || contains$1(uastring, 'trident');
  803. }
  804. },
  805. {
  806. name: 'Opera',
  807. versionRegexes: [
  808. normalVersionRegex,
  809. /.*?opera\/([0-9]+)\.([0-9]+).*/
  810. ],
  811. search: checkContains('opera')
  812. },
  813. {
  814. name: 'Firefox',
  815. versionRegexes: [/.*?firefox\/\ ?([0-9]+)\.([0-9]+).*/],
  816. search: checkContains('firefox')
  817. },
  818. {
  819. name: 'Safari',
  820. versionRegexes: [
  821. normalVersionRegex,
  822. /.*?cpu os ([0-9]+)_([0-9]+).*/
  823. ],
  824. search: function (uastring) {
  825. return (contains$1(uastring, 'safari') || contains$1(uastring, 'mobile/')) && contains$1(uastring, 'applewebkit');
  826. }
  827. }
  828. ];
  829. var oses = [
  830. {
  831. name: 'Windows',
  832. search: checkContains('win'),
  833. versionRegexes: [/.*?windows\ nt\ ?([0-9]+)\.([0-9]+).*/]
  834. },
  835. {
  836. name: 'iOS',
  837. search: function (uastring) {
  838. return contains$1(uastring, 'iphone') || contains$1(uastring, 'ipad');
  839. },
  840. versionRegexes: [
  841. /.*?version\/\ ?([0-9]+)\.([0-9]+).*/,
  842. /.*cpu os ([0-9]+)_([0-9]+).*/,
  843. /.*cpu iphone os ([0-9]+)_([0-9]+).*/
  844. ]
  845. },
  846. {
  847. name: 'Android',
  848. search: checkContains('android'),
  849. versionRegexes: [/.*?android\ ?([0-9]+)\.([0-9]+).*/]
  850. },
  851. {
  852. name: 'OSX',
  853. search: checkContains('mac os x'),
  854. versionRegexes: [/.*?mac\ os\ x\ ?([0-9]+)_([0-9]+).*/]
  855. },
  856. {
  857. name: 'Linux',
  858. search: checkContains('linux'),
  859. versionRegexes: []
  860. },
  861. {
  862. name: 'Solaris',
  863. search: checkContains('sunos'),
  864. versionRegexes: []
  865. },
  866. {
  867. name: 'FreeBSD',
  868. search: checkContains('freebsd'),
  869. versionRegexes: []
  870. },
  871. {
  872. name: 'ChromeOS',
  873. search: checkContains('cros'),
  874. versionRegexes: [/.*?chrome\/([0-9]+)\.([0-9]+).*/]
  875. }
  876. ];
  877. var PlatformInfo = {
  878. browsers: constant(browsers),
  879. oses: constant(oses)
  880. };
  881. var edge = 'Edge';
  882. var chrome = 'Chrome';
  883. var ie = 'IE';
  884. var opera = 'Opera';
  885. var firefox = 'Firefox';
  886. var safari = 'Safari';
  887. var unknown$1 = function () {
  888. return nu$1({
  889. current: undefined,
  890. version: Version.unknown()
  891. });
  892. };
  893. var nu$1 = function (info) {
  894. var current = info.current;
  895. var version = info.version;
  896. var isBrowser = function (name) {
  897. return function () {
  898. return current === name;
  899. };
  900. };
  901. return {
  902. current: current,
  903. version: version,
  904. isEdge: isBrowser(edge),
  905. isChrome: isBrowser(chrome),
  906. isIE: isBrowser(ie),
  907. isOpera: isBrowser(opera),
  908. isFirefox: isBrowser(firefox),
  909. isSafari: isBrowser(safari)
  910. };
  911. };
  912. var Browser = {
  913. unknown: unknown$1,
  914. nu: nu$1,
  915. edge: constant(edge),
  916. chrome: constant(chrome),
  917. ie: constant(ie),
  918. opera: constant(opera),
  919. firefox: constant(firefox),
  920. safari: constant(safari)
  921. };
  922. var windows = 'Windows';
  923. var ios = 'iOS';
  924. var android = 'Android';
  925. var linux = 'Linux';
  926. var osx = 'OSX';
  927. var solaris = 'Solaris';
  928. var freebsd = 'FreeBSD';
  929. var chromeos = 'ChromeOS';
  930. var unknown$2 = function () {
  931. return nu$2({
  932. current: undefined,
  933. version: Version.unknown()
  934. });
  935. };
  936. var nu$2 = function (info) {
  937. var current = info.current;
  938. var version = info.version;
  939. var isOS = function (name) {
  940. return function () {
  941. return current === name;
  942. };
  943. };
  944. return {
  945. current: current,
  946. version: version,
  947. isWindows: isOS(windows),
  948. isiOS: isOS(ios),
  949. isAndroid: isOS(android),
  950. isOSX: isOS(osx),
  951. isLinux: isOS(linux),
  952. isSolaris: isOS(solaris),
  953. isFreeBSD: isOS(freebsd),
  954. isChromeOS: isOS(chromeos)
  955. };
  956. };
  957. var OperatingSystem = {
  958. unknown: unknown$2,
  959. nu: nu$2,
  960. windows: constant(windows),
  961. ios: constant(ios),
  962. android: constant(android),
  963. linux: constant(linux),
  964. osx: constant(osx),
  965. solaris: constant(solaris),
  966. freebsd: constant(freebsd),
  967. chromeos: constant(chromeos)
  968. };
  969. var detect$2 = function (userAgent, mediaMatch) {
  970. var browsers = PlatformInfo.browsers();
  971. var oses = PlatformInfo.oses();
  972. var browser = UaString.detectBrowser(browsers, userAgent).fold(Browser.unknown, Browser.nu);
  973. var os = UaString.detectOs(oses, userAgent).fold(OperatingSystem.unknown, OperatingSystem.nu);
  974. var deviceType = DeviceType(os, browser, userAgent, mediaMatch);
  975. return {
  976. browser: browser,
  977. os: os,
  978. deviceType: deviceType
  979. };
  980. };
  981. var PlatformDetection = { detect: detect$2 };
  982. var mediaMatch = function (query) {
  983. return window.matchMedia(query).matches;
  984. };
  985. var platform = cached(function () {
  986. return PlatformDetection.detect(navigator.userAgent, mediaMatch);
  987. });
  988. var detect$3 = function () {
  989. return platform();
  990. };
  991. var userAgent = navigator.userAgent;
  992. var platform$1 = detect$3();
  993. var browser = platform$1.browser;
  994. var os = platform$1.os;
  995. var deviceType = platform$1.deviceType;
  996. var webkit = /WebKit/.test(userAgent) && !browser.isEdge();
  997. var fileApi = 'FormData' in window && 'FileReader' in window && 'URL' in window && !!URL.createObjectURL;
  998. var windowsPhone = userAgent.indexOf('Windows Phone') !== -1;
  999. var Env = {
  1000. opera: browser.isOpera(),
  1001. webkit: webkit,
  1002. ie: browser.isIE() || browser.isEdge() ? browser.version.major : false,
  1003. gecko: browser.isFirefox(),
  1004. mac: os.isOSX() || os.isiOS(),
  1005. iOS: deviceType.isiPad() || deviceType.isiPhone(),
  1006. android: os.isAndroid(),
  1007. contentEditable: true,
  1008. transparentSrc: 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7',
  1009. caretAfter: true,
  1010. range: window.getSelection && 'Range' in window,
  1011. documentMode: browser.isIE() ? document.documentMode || 7 : 10,
  1012. fileApi: fileApi,
  1013. ceFalse: true,
  1014. cacheSuffix: null,
  1015. container: null,
  1016. experimentalShadowDom: false,
  1017. canHaveCSP: !browser.isIE(),
  1018. desktop: deviceType.isDesktop(),
  1019. windowsPhone: windowsPhone,
  1020. browser: {
  1021. current: browser.current,
  1022. version: browser.version,
  1023. isChrome: browser.isChrome,
  1024. isEdge: browser.isEdge,
  1025. isFirefox: browser.isFirefox,
  1026. isIE: browser.isIE,
  1027. isOpera: browser.isOpera,
  1028. isSafari: browser.isSafari
  1029. },
  1030. os: {
  1031. current: os.current,
  1032. version: os.version,
  1033. isAndroid: os.isAndroid,
  1034. isChromeOS: os.isChromeOS,
  1035. isFreeBSD: os.isFreeBSD,
  1036. isiOS: os.isiOS,
  1037. isLinux: os.isLinux,
  1038. isOSX: os.isOSX,
  1039. isSolaris: os.isSolaris,
  1040. isWindows: os.isWindows
  1041. },
  1042. deviceType: {
  1043. isDesktop: deviceType.isDesktop,
  1044. isiPad: deviceType.isiPad,
  1045. isiPhone: deviceType.isiPhone,
  1046. isPhone: deviceType.isPhone,
  1047. isTablet: deviceType.isTablet,
  1048. isTouch: deviceType.isTouch,
  1049. isWebView: deviceType.isWebView
  1050. }
  1051. };
  1052. var whiteSpaceRegExp = /^\s*|\s*$/g;
  1053. var trim$1 = function (str) {
  1054. return str === null || str === undefined ? '' : ('' + str).replace(whiteSpaceRegExp, '');
  1055. };
  1056. var is = function (obj, type) {
  1057. if (!type) {
  1058. return obj !== undefined;
  1059. }
  1060. if (type === 'array' && isArray$1(obj)) {
  1061. return true;
  1062. }
  1063. return typeof obj === type;
  1064. };
  1065. var makeMap = function (items, delim, map) {
  1066. var i;
  1067. items = items || [];
  1068. delim = delim || ',';
  1069. if (typeof items === 'string') {
  1070. items = items.split(delim);
  1071. }
  1072. map = map || {};
  1073. i = items.length;
  1074. while (i--) {
  1075. map[items[i]] = {};
  1076. }
  1077. return map;
  1078. };
  1079. var hasOwnProperty$1 = function (obj, prop) {
  1080. return Object.prototype.hasOwnProperty.call(obj, prop);
  1081. };
  1082. var create = function (s, p, root) {
  1083. var self = this;
  1084. var sp, scn, c, de = 0;
  1085. s = /^((static) )?([\w.]+)(:([\w.]+))?/.exec(s);
  1086. var cn = s[3].match(/(^|\.)(\w+)$/i)[2];
  1087. var ns = self.createNS(s[3].replace(/\.\w+$/, ''), root);
  1088. if (ns[cn]) {
  1089. return;
  1090. }
  1091. if (s[2] === 'static') {
  1092. ns[cn] = p;
  1093. if (this.onCreate) {
  1094. this.onCreate(s[2], s[3], ns[cn]);
  1095. }
  1096. return;
  1097. }
  1098. if (!p[cn]) {
  1099. p[cn] = function () {
  1100. };
  1101. de = 1;
  1102. }
  1103. ns[cn] = p[cn];
  1104. self.extend(ns[cn].prototype, p);
  1105. if (s[5]) {
  1106. sp = self.resolve(s[5]).prototype;
  1107. scn = s[5].match(/\.(\w+)$/i)[1];
  1108. c = ns[cn];
  1109. if (de) {
  1110. ns[cn] = function () {
  1111. return sp[scn].apply(this, arguments);
  1112. };
  1113. } else {
  1114. ns[cn] = function () {
  1115. this.parent = sp[scn];
  1116. return c.apply(this, arguments);
  1117. };
  1118. }
  1119. ns[cn].prototype[cn] = ns[cn];
  1120. self.each(sp, function (f, n) {
  1121. ns[cn].prototype[n] = sp[n];
  1122. });
  1123. self.each(p, function (f, n) {
  1124. if (sp[n]) {
  1125. ns[cn].prototype[n] = function () {
  1126. this.parent = sp[n];
  1127. return f.apply(this, arguments);
  1128. };
  1129. } else {
  1130. if (n !== cn) {
  1131. ns[cn].prototype[n] = f;
  1132. }
  1133. }
  1134. });
  1135. }
  1136. self.each(p.static, function (f, n) {
  1137. ns[cn][n] = f;
  1138. });
  1139. };
  1140. var extend = function (obj) {
  1141. var exts = [];
  1142. for (var _i = 1; _i < arguments.length; _i++) {
  1143. exts[_i - 1] = arguments[_i];
  1144. }
  1145. for (var i = 0; i < exts.length; i++) {
  1146. var ext = exts[i];
  1147. for (var name_1 in ext) {
  1148. if (ext.hasOwnProperty(name_1)) {
  1149. var value = ext[name_1];
  1150. if (value !== undefined) {
  1151. obj[name_1] = value;
  1152. }
  1153. }
  1154. }
  1155. }
  1156. return obj;
  1157. };
  1158. var walk = function (o, f, n, s) {
  1159. s = s || this;
  1160. if (o) {
  1161. if (n) {
  1162. o = o[n];
  1163. }
  1164. each$2(o, function (o, i) {
  1165. if (f.call(s, o, i, n) === false) {
  1166. return false;
  1167. }
  1168. walk(o, f, n, s);
  1169. });
  1170. }
  1171. };
  1172. var createNS = function (n, o) {
  1173. var i, v;
  1174. o = o || window;
  1175. n = n.split('.');
  1176. for (i = 0; i < n.length; i++) {
  1177. v = n[i];
  1178. if (!o[v]) {
  1179. o[v] = {};
  1180. }
  1181. o = o[v];
  1182. }
  1183. return o;
  1184. };
  1185. var resolve = function (n, o) {
  1186. var i, l;
  1187. o = o || window;
  1188. n = n.split('.');
  1189. for (i = 0, l = n.length; i < l; i++) {
  1190. o = o[n[i]];
  1191. if (!o) {
  1192. break;
  1193. }
  1194. }
  1195. return o;
  1196. };
  1197. var explode = function (s, d) {
  1198. if (!s || is(s, 'array')) {
  1199. return s;
  1200. }
  1201. return map$2(s.split(d || ','), trim$1);
  1202. };
  1203. var _addCacheSuffix = function (url) {
  1204. var cacheSuffix = Env.cacheSuffix;
  1205. if (cacheSuffix) {
  1206. url += (url.indexOf('?') === -1 ? '?' : '&') + cacheSuffix;
  1207. }
  1208. return url;
  1209. };
  1210. var Tools = {
  1211. trim: trim$1,
  1212. isArray: isArray$1,
  1213. is: is,
  1214. toArray: toArray,
  1215. makeMap: makeMap,
  1216. each: each$2,
  1217. map: map$2,
  1218. grep: filter$2,
  1219. inArray: indexOf$1,
  1220. hasOwn: hasOwnProperty$1,
  1221. extend: extend,
  1222. create: create,
  1223. walk: walk,
  1224. createNS: createNS,
  1225. resolve: resolve,
  1226. explode: explode,
  1227. _addCacheSuffix: _addCacheSuffix
  1228. };
  1229. var fromHtml = function (html, scope) {
  1230. var doc = scope || document;
  1231. var div = doc.createElement('div');
  1232. div.innerHTML = html;
  1233. if (!div.hasChildNodes() || div.childNodes.length > 1) {
  1234. console.error('HTML does not have a single root node', html);
  1235. throw new Error('HTML must have a single root node');
  1236. }
  1237. return fromDom(div.childNodes[0]);
  1238. };
  1239. var fromTag = function (tag, scope) {
  1240. var doc = scope || document;
  1241. var node = doc.createElement(tag);
  1242. return fromDom(node);
  1243. };
  1244. var fromText = function (text, scope) {
  1245. var doc = scope || document;
  1246. var node = doc.createTextNode(text);
  1247. return fromDom(node);
  1248. };
  1249. var fromDom = function (node) {
  1250. if (node === null || node === undefined) {
  1251. throw new Error('Node cannot be null or undefined');
  1252. }
  1253. return { dom: node };
  1254. };
  1255. var fromPoint = function (docElm, x, y) {
  1256. return Optional.from(docElm.dom.elementFromPoint(x, y)).map(fromDom);
  1257. };
  1258. var SugarElement = {
  1259. fromHtml: fromHtml,
  1260. fromTag: fromTag,
  1261. fromText: fromText,
  1262. fromDom: fromDom,
  1263. fromPoint: fromPoint
  1264. };
  1265. var toArray$1 = function (target, f) {
  1266. var r = [];
  1267. var recurse = function (e) {
  1268. r.push(e);
  1269. return f(e);
  1270. };
  1271. var cur = f(target);
  1272. do {
  1273. cur = cur.bind(recurse);
  1274. } while (cur.isSome());
  1275. return r;
  1276. };
  1277. var compareDocumentPosition = function (a, b, match) {
  1278. return (a.compareDocumentPosition(b) & match) !== 0;
  1279. };
  1280. var documentPositionContainedBy = function (a, b) {
  1281. return compareDocumentPosition(a, b, Node.DOCUMENT_POSITION_CONTAINED_BY);
  1282. };
  1283. var COMMENT = 8;
  1284. var DOCUMENT = 9;
  1285. var DOCUMENT_FRAGMENT = 11;
  1286. var ELEMENT = 1;
  1287. var TEXT = 3;
  1288. var is$1 = function (element, selector) {
  1289. var dom = element.dom;
  1290. if (dom.nodeType !== ELEMENT) {
  1291. return false;
  1292. } else {
  1293. var elem = dom;
  1294. if (elem.matches !== undefined) {
  1295. return elem.matches(selector);
  1296. } else if (elem.msMatchesSelector !== undefined) {
  1297. return elem.msMatchesSelector(selector);
  1298. } else if (elem.webkitMatchesSelector !== undefined) {
  1299. return elem.webkitMatchesSelector(selector);
  1300. } else if (elem.mozMatchesSelector !== undefined) {
  1301. return elem.mozMatchesSelector(selector);
  1302. } else {
  1303. throw new Error('Browser lacks native selectors');
  1304. }
  1305. }
  1306. };
  1307. var bypassSelector = function (dom) {
  1308. return dom.nodeType !== ELEMENT && dom.nodeType !== DOCUMENT && dom.nodeType !== DOCUMENT_FRAGMENT || dom.childElementCount === 0;
  1309. };
  1310. var all = function (selector, scope) {
  1311. var base = scope === undefined ? document : scope.dom;
  1312. return bypassSelector(base) ? [] : map(base.querySelectorAll(selector), SugarElement.fromDom);
  1313. };
  1314. var one = function (selector, scope) {
  1315. var base = scope === undefined ? document : scope.dom;
  1316. return bypassSelector(base) ? Optional.none() : Optional.from(base.querySelector(selector)).map(SugarElement.fromDom);
  1317. };
  1318. var eq$2 = function (e1, e2) {
  1319. return e1.dom === e2.dom;
  1320. };
  1321. var regularContains = function (e1, e2) {
  1322. var d1 = e1.dom;
  1323. var d2 = e2.dom;
  1324. return d1 === d2 ? false : d1.contains(d2);
  1325. };
  1326. var ieContains = function (e1, e2) {
  1327. return documentPositionContainedBy(e1.dom, e2.dom);
  1328. };
  1329. var contains$2 = function (e1, e2) {
  1330. return detect$3().browser.isIE() ? ieContains(e1, e2) : regularContains(e1, e2);
  1331. };
  1332. var Global = typeof window !== 'undefined' ? window : Function('return this;')();
  1333. var name = function (element) {
  1334. var r = element.dom.nodeName;
  1335. return r.toLowerCase();
  1336. };
  1337. var type = function (element) {
  1338. return element.dom.nodeType;
  1339. };
  1340. var isType$1 = function (t) {
  1341. return function (element) {
  1342. return type(element) === t;
  1343. };
  1344. };
  1345. var isComment = function (element) {
  1346. return type(element) === COMMENT || name(element) === '#comment';
  1347. };
  1348. var isElement = isType$1(ELEMENT);
  1349. var isText = isType$1(TEXT);
  1350. var isDocument = isType$1(DOCUMENT);
  1351. var isDocumentFragment = isType$1(DOCUMENT_FRAGMENT);
  1352. var owner = function (element) {
  1353. return SugarElement.fromDom(element.dom.ownerDocument);
  1354. };
  1355. var documentOrOwner = function (dos) {
  1356. return isDocument(dos) ? dos : owner(dos);
  1357. };
  1358. var documentElement = function (element) {
  1359. return SugarElement.fromDom(documentOrOwner(element).dom.documentElement);
  1360. };
  1361. var defaultView = function (element) {
  1362. return SugarElement.fromDom(documentOrOwner(element).dom.defaultView);
  1363. };
  1364. var parent = function (element) {
  1365. return Optional.from(element.dom.parentNode).map(SugarElement.fromDom);
  1366. };
  1367. var parents = function (element, isRoot) {
  1368. var stop = isFunction(isRoot) ? isRoot : never;
  1369. var dom = element.dom;
  1370. var ret = [];
  1371. while (dom.parentNode !== null && dom.parentNode !== undefined) {
  1372. var rawParent = dom.parentNode;
  1373. var p = SugarElement.fromDom(rawParent);
  1374. ret.push(p);
  1375. if (stop(p) === true) {
  1376. break;
  1377. } else {
  1378. dom = rawParent;
  1379. }
  1380. }
  1381. return ret;
  1382. };
  1383. var siblings = function (element) {
  1384. var filterSelf = function (elements) {
  1385. return filter(elements, function (x) {
  1386. return !eq$2(element, x);
  1387. });
  1388. };
  1389. return parent(element).map(children).map(filterSelf).getOr([]);
  1390. };
  1391. var prevSibling = function (element) {
  1392. return Optional.from(element.dom.previousSibling).map(SugarElement.fromDom);
  1393. };
  1394. var nextSibling = function (element) {
  1395. return Optional.from(element.dom.nextSibling).map(SugarElement.fromDom);
  1396. };
  1397. var prevSiblings = function (element) {
  1398. return reverse(toArray$1(element, prevSibling));
  1399. };
  1400. var nextSiblings = function (element) {
  1401. return toArray$1(element, nextSibling);
  1402. };
  1403. var children = function (element) {
  1404. return map(element.dom.childNodes, SugarElement.fromDom);
  1405. };
  1406. var child = function (element, index) {
  1407. var cs = element.dom.childNodes;
  1408. return Optional.from(cs[index]).map(SugarElement.fromDom);
  1409. };
  1410. var firstChild = function (element) {
  1411. return child(element, 0);
  1412. };
  1413. var lastChild = function (element) {
  1414. return child(element, element.dom.childNodes.length - 1);
  1415. };
  1416. var childNodesCount = function (element) {
  1417. return element.dom.childNodes.length;
  1418. };
  1419. var getHead = function (doc) {
  1420. var b = doc.dom.head;
  1421. if (b === null || b === undefined) {
  1422. throw new Error('Head is not available yet');
  1423. }
  1424. return SugarElement.fromDom(b);
  1425. };
  1426. var isShadowRoot = function (dos) {
  1427. return isDocumentFragment(dos);
  1428. };
  1429. var supported = isFunction(Element.prototype.attachShadow) && isFunction(Node.prototype.getRootNode);
  1430. var isSupported = constant(supported);
  1431. var getRootNode = supported ? function (e) {
  1432. return SugarElement.fromDom(e.dom.getRootNode());
  1433. } : documentOrOwner;
  1434. var getStyleContainer = function (dos) {
  1435. return isShadowRoot(dos) ? dos : getHead(documentOrOwner(dos));
  1436. };
  1437. var getShadowRoot = function (e) {
  1438. var r = getRootNode(e);
  1439. return isShadowRoot(r) ? Optional.some(r) : Optional.none();
  1440. };
  1441. var getShadowHost = function (e) {
  1442. return SugarElement.fromDom(e.dom.host);
  1443. };
  1444. var getOriginalEventTarget = function (event) {
  1445. if (isSupported() && isNonNullable(event.target)) {
  1446. var el = SugarElement.fromDom(event.target);
  1447. if (isElement(el) && isOpenShadowHost(el)) {
  1448. if (event.composed && event.composedPath) {
  1449. var composedPath = event.composedPath();
  1450. if (composedPath) {
  1451. return head(composedPath);
  1452. }
  1453. }
  1454. }
  1455. }
  1456. return Optional.from(event.target);
  1457. };
  1458. var isOpenShadowHost = function (element) {
  1459. return isNonNullable(element.dom.shadowRoot);
  1460. };
  1461. var before = function (marker, element) {
  1462. var parent$1 = parent(marker);
  1463. parent$1.each(function (v) {
  1464. v.dom.insertBefore(element.dom, marker.dom);
  1465. });
  1466. };
  1467. var after = function (marker, element) {
  1468. var sibling = nextSibling(marker);
  1469. sibling.fold(function () {
  1470. var parent$1 = parent(marker);
  1471. parent$1.each(function (v) {
  1472. append(v, element);
  1473. });
  1474. }, function (v) {
  1475. before(v, element);
  1476. });
  1477. };
  1478. var prepend = function (parent, element) {
  1479. var firstChild$1 = firstChild(parent);
  1480. firstChild$1.fold(function () {
  1481. append(parent, element);
  1482. }, function (v) {
  1483. parent.dom.insertBefore(element.dom, v.dom);
  1484. });
  1485. };
  1486. var append = function (parent, element) {
  1487. parent.dom.appendChild(element.dom);
  1488. };
  1489. var wrap = function (element, wrapper) {
  1490. before(element, wrapper);
  1491. append(wrapper, element);
  1492. };
  1493. var before$1 = function (marker, elements) {
  1494. each(elements, function (x) {
  1495. before(marker, x);
  1496. });
  1497. };
  1498. var append$1 = function (parent, elements) {
  1499. each(elements, function (x) {
  1500. append(parent, x);
  1501. });
  1502. };
  1503. var empty = function (element) {
  1504. element.dom.textContent = '';
  1505. each(children(element), function (rogue) {
  1506. remove(rogue);
  1507. });
  1508. };
  1509. var remove = function (element) {
  1510. var dom = element.dom;
  1511. if (dom.parentNode !== null) {
  1512. dom.parentNode.removeChild(dom);
  1513. }
  1514. };
  1515. var unwrap = function (wrapper) {
  1516. var children$1 = children(wrapper);
  1517. if (children$1.length > 0) {
  1518. before$1(wrapper, children$1);
  1519. }
  1520. remove(wrapper);
  1521. };
  1522. var inBody = function (element) {
  1523. var dom = isText(element) ? element.dom.parentNode : element.dom;
  1524. if (dom === undefined || dom === null || dom.ownerDocument === null) {
  1525. return false;
  1526. }
  1527. var doc = dom.ownerDocument;
  1528. return getShadowRoot(SugarElement.fromDom(dom)).fold(function () {
  1529. return doc.body.contains(dom);
  1530. }, compose1(inBody, getShadowHost));
  1531. };
  1532. var r = function (left, top) {
  1533. var translate = function (x, y) {
  1534. return r(left + x, top + y);
  1535. };
  1536. return {
  1537. left: left,
  1538. top: top,
  1539. translate: translate
  1540. };
  1541. };
  1542. var SugarPosition = r;
  1543. var boxPosition = function (dom) {
  1544. var box = dom.getBoundingClientRect();
  1545. return SugarPosition(box.left, box.top);
  1546. };
  1547. var firstDefinedOrZero = function (a, b) {
  1548. if (a !== undefined) {
  1549. return a;
  1550. } else {
  1551. return b !== undefined ? b : 0;
  1552. }
  1553. };
  1554. var absolute = function (element) {
  1555. var doc = element.dom.ownerDocument;
  1556. var body = doc.body;
  1557. var win = doc.defaultView;
  1558. var html = doc.documentElement;
  1559. if (body === element.dom) {
  1560. return SugarPosition(body.offsetLeft, body.offsetTop);
  1561. }
  1562. var scrollTop = firstDefinedOrZero(win === null || win === void 0 ? void 0 : win.pageYOffset, html.scrollTop);
  1563. var scrollLeft = firstDefinedOrZero(win === null || win === void 0 ? void 0 : win.pageXOffset, html.scrollLeft);
  1564. var clientTop = firstDefinedOrZero(html.clientTop, body.clientTop);
  1565. var clientLeft = firstDefinedOrZero(html.clientLeft, body.clientLeft);
  1566. return viewport(element).translate(scrollLeft - clientLeft, scrollTop - clientTop);
  1567. };
  1568. var viewport = function (element) {
  1569. var dom = element.dom;
  1570. var doc = dom.ownerDocument;
  1571. var body = doc.body;
  1572. if (body === dom) {
  1573. return SugarPosition(body.offsetLeft, body.offsetTop);
  1574. }
  1575. if (!inBody(element)) {
  1576. return SugarPosition(0, 0);
  1577. }
  1578. return boxPosition(dom);
  1579. };
  1580. var get$1 = function (_DOC) {
  1581. var doc = _DOC !== undefined ? _DOC.dom : document;
  1582. var x = doc.body.scrollLeft || doc.documentElement.scrollLeft;
  1583. var y = doc.body.scrollTop || doc.documentElement.scrollTop;
  1584. return SugarPosition(x, y);
  1585. };
  1586. var to = function (x, y, _DOC) {
  1587. var doc = _DOC !== undefined ? _DOC.dom : document;
  1588. var win = doc.defaultView;
  1589. if (win) {
  1590. win.scrollTo(x, y);
  1591. }
  1592. };
  1593. var intoView = function (element, alignToTop) {
  1594. var isSafari = detect$3().browser.isSafari();
  1595. if (isSafari && isFunction(element.dom.scrollIntoViewIfNeeded)) {
  1596. element.dom.scrollIntoViewIfNeeded(false);
  1597. } else {
  1598. element.dom.scrollIntoView(alignToTop);
  1599. }
  1600. };
  1601. var get$2 = function (_win) {
  1602. var win = _win === undefined ? window : _win;
  1603. return Optional.from(win['visualViewport']);
  1604. };
  1605. var bounds = function (x, y, width, height) {
  1606. return {
  1607. x: x,
  1608. y: y,
  1609. width: width,
  1610. height: height,
  1611. right: x + width,
  1612. bottom: y + height
  1613. };
  1614. };
  1615. var getBounds = function (_win) {
  1616. var win = _win === undefined ? window : _win;
  1617. var doc = win.document;
  1618. var scroll = get$1(SugarElement.fromDom(doc));
  1619. return get$2(win).fold(function () {
  1620. var html = win.document.documentElement;
  1621. var width = html.clientWidth;
  1622. var height = html.clientHeight;
  1623. return bounds(scroll.left, scroll.top, width, height);
  1624. }, function (visualViewport) {
  1625. return bounds(Math.max(visualViewport.pageLeft, scroll.left), Math.max(visualViewport.pageTop, scroll.top), visualViewport.width, visualViewport.height);
  1626. });
  1627. };
  1628. var isNodeType = function (type) {
  1629. return function (node) {
  1630. return !!node && node.nodeType === type;
  1631. };
  1632. };
  1633. var isRestrictedNode = function (node) {
  1634. return !!node && !Object.getPrototypeOf(node);
  1635. };
  1636. var isElement$1 = isNodeType(1);
  1637. var matchNodeNames = function (names) {
  1638. var lowercasedNames = names.map(function (s) {
  1639. return s.toLowerCase();
  1640. });
  1641. return function (node) {
  1642. if (node && node.nodeName) {
  1643. var nodeName = node.nodeName.toLowerCase();
  1644. return contains(lowercasedNames, nodeName);
  1645. }
  1646. return false;
  1647. };
  1648. };
  1649. var matchStyleValues = function (name, values) {
  1650. var items = values.toLowerCase().split(' ');
  1651. return function (node) {
  1652. var i, cssValue;
  1653. if (isElement$1(node)) {
  1654. for (i = 0; i < items.length; i++) {
  1655. var computed = node.ownerDocument.defaultView.getComputedStyle(node, null);
  1656. cssValue = computed ? computed.getPropertyValue(name) : null;
  1657. if (cssValue === items[i]) {
  1658. return true;
  1659. }
  1660. }
  1661. }
  1662. return false;
  1663. };
  1664. };
  1665. var hasAttribute = function (attrName) {
  1666. return function (node) {
  1667. return isElement$1(node) && node.hasAttribute(attrName);
  1668. };
  1669. };
  1670. var hasAttributeValue = function (attrName, attrValue) {
  1671. return function (node) {
  1672. return isElement$1(node) && node.getAttribute(attrName) === attrValue;
  1673. };
  1674. };
  1675. var isBogus = function (node) {
  1676. return isElement$1(node) && node.hasAttribute('data-mce-bogus');
  1677. };
  1678. var isBogusAll = function (node) {
  1679. return isElement$1(node) && node.getAttribute('data-mce-bogus') === 'all';
  1680. };
  1681. var isTable = function (node) {
  1682. return isElement$1(node) && node.tagName === 'TABLE';
  1683. };
  1684. var hasContentEditableState = function (value) {
  1685. return function (node) {
  1686. if (isElement$1(node)) {
  1687. if (node.contentEditable === value) {
  1688. return true;
  1689. }
  1690. if (node.getAttribute('data-mce-contenteditable') === value) {
  1691. return true;
  1692. }
  1693. }
  1694. return false;
  1695. };
  1696. };
  1697. var isTextareaOrInput = matchNodeNames([
  1698. 'textarea',
  1699. 'input'
  1700. ]);
  1701. var isText$1 = isNodeType(3);
  1702. var isComment$1 = isNodeType(8);
  1703. var isDocument$1 = isNodeType(9);
  1704. var isDocumentFragment$1 = isNodeType(11);
  1705. var isBr = matchNodeNames(['br']);
  1706. var isImg = matchNodeNames(['img']);
  1707. var isContentEditableTrue = hasContentEditableState('true');
  1708. var isContentEditableFalse = hasContentEditableState('false');
  1709. var isTableCell = matchNodeNames([
  1710. 'td',
  1711. 'th'
  1712. ]);
  1713. var isMedia = matchNodeNames([
  1714. 'video',
  1715. 'audio',
  1716. 'object',
  1717. 'embed'
  1718. ]);
  1719. var isSupported$1 = function (dom) {
  1720. return dom.style !== undefined && isFunction(dom.style.getPropertyValue);
  1721. };
  1722. var rawSet = function (dom, key, value) {
  1723. if (isString(value) || isBoolean(value) || isNumber(value)) {
  1724. dom.setAttribute(key, value + '');
  1725. } else {
  1726. console.error('Invalid call to Attribute.set. Key ', key, ':: Value ', value, ':: Element ', dom);
  1727. throw new Error('Attribute value was not simple');
  1728. }
  1729. };
  1730. var set = function (element, key, value) {
  1731. rawSet(element.dom, key, value);
  1732. };
  1733. var setAll = function (element, attrs) {
  1734. var dom = element.dom;
  1735. each$1(attrs, function (v, k) {
  1736. rawSet(dom, k, v);
  1737. });
  1738. };
  1739. var get$3 = function (element, key) {
  1740. var v = element.dom.getAttribute(key);
  1741. return v === null ? undefined : v;
  1742. };
  1743. var getOpt = function (element, key) {
  1744. return Optional.from(get$3(element, key));
  1745. };
  1746. var has$1 = function (element, key) {
  1747. var dom = element.dom;
  1748. return dom && dom.hasAttribute ? dom.hasAttribute(key) : false;
  1749. };
  1750. var remove$1 = function (element, key) {
  1751. element.dom.removeAttribute(key);
  1752. };
  1753. var clone = function (element) {
  1754. return foldl(element.dom.attributes, function (acc, attr) {
  1755. acc[attr.name] = attr.value;
  1756. return acc;
  1757. }, {});
  1758. };
  1759. var internalSet = function (dom, property, value) {
  1760. if (!isString(value)) {
  1761. console.error('Invalid call to CSS.set. Property ', property, ':: Value ', value, ':: Element ', dom);
  1762. throw new Error('CSS value must be a string: ' + value);
  1763. }
  1764. if (isSupported$1(dom)) {
  1765. dom.style.setProperty(property, value);
  1766. }
  1767. };
  1768. var setAll$1 = function (element, css) {
  1769. var dom = element.dom;
  1770. each$1(css, function (v, k) {
  1771. internalSet(dom, k, v);
  1772. });
  1773. };
  1774. var get$4 = function (element, property) {
  1775. var dom = element.dom;
  1776. var styles = window.getComputedStyle(dom);
  1777. var r = styles.getPropertyValue(property);
  1778. return r === '' && !inBody(element) ? getUnsafeProperty(dom, property) : r;
  1779. };
  1780. var getUnsafeProperty = function (dom, property) {
  1781. return isSupported$1(dom) ? dom.style.getPropertyValue(property) : '';
  1782. };
  1783. var getRaw = function (element, property) {
  1784. var dom = element.dom;
  1785. var raw = getUnsafeProperty(dom, property);
  1786. return Optional.from(raw).filter(function (r) {
  1787. return r.length > 0;
  1788. });
  1789. };
  1790. var getAllRaw = function (element) {
  1791. var css = {};
  1792. var dom = element.dom;
  1793. if (isSupported$1(dom)) {
  1794. for (var i = 0; i < dom.style.length; i++) {
  1795. var ruleName = dom.style.item(i);
  1796. css[ruleName] = dom.style[ruleName];
  1797. }
  1798. }
  1799. return css;
  1800. };
  1801. var reflow = function (e) {
  1802. return e.dom.offsetWidth;
  1803. };
  1804. var browser$1 = detect$3().browser;
  1805. var firstElement = function (nodes) {
  1806. return find(nodes, isElement);
  1807. };
  1808. var getTableCaptionDeltaY = function (elm) {
  1809. if (browser$1.isFirefox() && name(elm) === 'table') {
  1810. return firstElement(children(elm)).filter(function (elm) {
  1811. return name(elm) === 'caption';
  1812. }).bind(function (caption) {
  1813. return firstElement(nextSiblings(caption)).map(function (body) {
  1814. var bodyTop = body.dom.offsetTop;
  1815. var captionTop = caption.dom.offsetTop;
  1816. var captionHeight = caption.dom.offsetHeight;
  1817. return bodyTop <= captionTop ? -captionHeight : 0;
  1818. });
  1819. }).getOr(0);
  1820. } else {
  1821. return 0;
  1822. }
  1823. };
  1824. var hasChild = function (elm, child) {
  1825. return elm.children && contains(elm.children, child);
  1826. };
  1827. var getPos = function (body, elm, rootElm) {
  1828. var x = 0, y = 0, offsetParent;
  1829. var doc = body.ownerDocument;
  1830. var pos;
  1831. rootElm = rootElm ? rootElm : body;
  1832. if (elm) {
  1833. if (rootElm === body && elm.getBoundingClientRect && get$4(SugarElement.fromDom(body), 'position') === 'static') {
  1834. pos = elm.getBoundingClientRect();
  1835. x = pos.left + (doc.documentElement.scrollLeft || body.scrollLeft) - doc.documentElement.clientLeft;
  1836. y = pos.top + (doc.documentElement.scrollTop || body.scrollTop) - doc.documentElement.clientTop;
  1837. return {
  1838. x: x,
  1839. y: y
  1840. };
  1841. }
  1842. offsetParent = elm;
  1843. while (offsetParent && offsetParent !== rootElm && offsetParent.nodeType && !hasChild(offsetParent, rootElm)) {
  1844. x += offsetParent.offsetLeft || 0;
  1845. y += offsetParent.offsetTop || 0;
  1846. offsetParent = offsetParent.offsetParent;
  1847. }
  1848. offsetParent = elm.parentNode;
  1849. while (offsetParent && offsetParent !== rootElm && offsetParent.nodeType && !hasChild(offsetParent, rootElm)) {
  1850. x -= offsetParent.scrollLeft || 0;
  1851. y -= offsetParent.scrollTop || 0;
  1852. offsetParent = offsetParent.parentNode;
  1853. }
  1854. y += getTableCaptionDeltaY(SugarElement.fromDom(elm));
  1855. }
  1856. return {
  1857. x: x,
  1858. y: y
  1859. };
  1860. };
  1861. var exports$1 = {}, module$1 = { exports: exports$1 };
  1862. (function (define, exports, module, require) {
  1863. (function (f) {
  1864. if (typeof exports === 'object' && typeof module !== 'undefined') {
  1865. module.exports = f();
  1866. } else if (typeof define === 'function' && define.amd) {
  1867. define([], f);
  1868. } else {
  1869. var g;
  1870. if (typeof window !== 'undefined') {
  1871. g = window;
  1872. } else if (typeof global !== 'undefined') {
  1873. g = global;
  1874. } else if (typeof self !== 'undefined') {
  1875. g = self;
  1876. } else {
  1877. g = this;
  1878. }
  1879. g.EphoxContactWrapper = f();
  1880. }
  1881. }(function () {
  1882. return function () {
  1883. function r(e, n, t) {
  1884. function o(i, f) {
  1885. if (!n[i]) {
  1886. if (!e[i]) {
  1887. var c = 'function' == typeof require && require;
  1888. if (!f && c)
  1889. return c(i, !0);
  1890. if (u)
  1891. return u(i, !0);
  1892. var a = new Error('Cannot find module \'' + i + '\'');
  1893. throw a.code = 'MODULE_NOT_FOUND', a;
  1894. }
  1895. var p = n[i] = { exports: {} };
  1896. e[i][0].call(p.exports, function (r) {
  1897. var n = e[i][1][r];
  1898. return o(n || r);
  1899. }, p, p.exports, r, e, n, t);
  1900. }
  1901. return n[i].exports;
  1902. }
  1903. for (var u = 'function' == typeof require && require, i = 0; i < t.length; i++)
  1904. o(t[i]);
  1905. return o;
  1906. }
  1907. return r;
  1908. }()({
  1909. 1: [
  1910. function (require, module, exports) {
  1911. var process = module.exports = {};
  1912. var cachedSetTimeout;
  1913. var cachedClearTimeout;
  1914. function defaultSetTimout() {
  1915. throw new Error('setTimeout has not been defined');
  1916. }
  1917. function defaultClearTimeout() {
  1918. throw new Error('clearTimeout has not been defined');
  1919. }
  1920. (function () {
  1921. try {
  1922. if (typeof setTimeout === 'function') {
  1923. cachedSetTimeout = setTimeout;
  1924. } else {
  1925. cachedSetTimeout = defaultSetTimout;
  1926. }
  1927. } catch (e) {
  1928. cachedSetTimeout = defaultSetTimout;
  1929. }
  1930. try {
  1931. if (typeof clearTimeout === 'function') {
  1932. cachedClearTimeout = clearTimeout;
  1933. } else {
  1934. cachedClearTimeout = defaultClearTimeout;
  1935. }
  1936. } catch (e) {
  1937. cachedClearTimeout = defaultClearTimeout;
  1938. }
  1939. }());
  1940. function runTimeout(fun) {
  1941. if (cachedSetTimeout === setTimeout) {
  1942. return setTimeout(fun, 0);
  1943. }
  1944. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  1945. cachedSetTimeout = setTimeout;
  1946. return setTimeout(fun, 0);
  1947. }
  1948. try {
  1949. return cachedSetTimeout(fun, 0);
  1950. } catch (e) {
  1951. try {
  1952. return cachedSetTimeout.call(null, fun, 0);
  1953. } catch (e) {
  1954. return cachedSetTimeout.call(this, fun, 0);
  1955. }
  1956. }
  1957. }
  1958. function runClearTimeout(marker) {
  1959. if (cachedClearTimeout === clearTimeout) {
  1960. return clearTimeout(marker);
  1961. }
  1962. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  1963. cachedClearTimeout = clearTimeout;
  1964. return clearTimeout(marker);
  1965. }
  1966. try {
  1967. return cachedClearTimeout(marker);
  1968. } catch (e) {
  1969. try {
  1970. return cachedClearTimeout.call(null, marker);
  1971. } catch (e) {
  1972. return cachedClearTimeout.call(this, marker);
  1973. }
  1974. }
  1975. }
  1976. var queue = [];
  1977. var draining = false;
  1978. var currentQueue;
  1979. var queueIndex = -1;
  1980. function cleanUpNextTick() {
  1981. if (!draining || !currentQueue) {
  1982. return;
  1983. }
  1984. draining = false;
  1985. if (currentQueue.length) {
  1986. queue = currentQueue.concat(queue);
  1987. } else {
  1988. queueIndex = -1;
  1989. }
  1990. if (queue.length) {
  1991. drainQueue();
  1992. }
  1993. }
  1994. function drainQueue() {
  1995. if (draining) {
  1996. return;
  1997. }
  1998. var timeout = runTimeout(cleanUpNextTick);
  1999. draining = true;
  2000. var len = queue.length;
  2001. while (len) {
  2002. currentQueue = queue;
  2003. queue = [];
  2004. while (++queueIndex < len) {
  2005. if (currentQueue) {
  2006. currentQueue[queueIndex].run();
  2007. }
  2008. }
  2009. queueIndex = -1;
  2010. len = queue.length;
  2011. }
  2012. currentQueue = null;
  2013. draining = false;
  2014. runClearTimeout(timeout);
  2015. }
  2016. process.nextTick = function (fun) {
  2017. var args = new Array(arguments.length - 1);
  2018. if (arguments.length > 1) {
  2019. for (var i = 1; i < arguments.length; i++) {
  2020. args[i - 1] = arguments[i];
  2021. }
  2022. }
  2023. queue.push(new Item(fun, args));
  2024. if (queue.length === 1 && !draining) {
  2025. runTimeout(drainQueue);
  2026. }
  2027. };
  2028. function Item(fun, array) {
  2029. this.fun = fun;
  2030. this.array = array;
  2031. }
  2032. Item.prototype.run = function () {
  2033. this.fun.apply(null, this.array);
  2034. };
  2035. process.title = 'browser';
  2036. process.browser = true;
  2037. process.env = {};
  2038. process.argv = [];
  2039. process.version = '';
  2040. process.versions = {};
  2041. function noop() {
  2042. }
  2043. process.on = noop;
  2044. process.addListener = noop;
  2045. process.once = noop;
  2046. process.off = noop;
  2047. process.removeListener = noop;
  2048. process.removeAllListeners = noop;
  2049. process.emit = noop;
  2050. process.prependListener = noop;
  2051. process.prependOnceListener = noop;
  2052. process.listeners = function (name) {
  2053. return [];
  2054. };
  2055. process.binding = function (name) {
  2056. throw new Error('process.binding is not supported');
  2057. };
  2058. process.cwd = function () {
  2059. return '/';
  2060. };
  2061. process.chdir = function (dir) {
  2062. throw new Error('process.chdir is not supported');
  2063. };
  2064. process.umask = function () {
  2065. return 0;
  2066. };
  2067. },
  2068. {}
  2069. ],
  2070. 2: [
  2071. function (require, module, exports) {
  2072. (function (setImmediate) {
  2073. (function (root) {
  2074. var setTimeoutFunc = setTimeout;
  2075. function noop() {
  2076. }
  2077. function bind(fn, thisArg) {
  2078. return function () {
  2079. fn.apply(thisArg, arguments);
  2080. };
  2081. }
  2082. function Promise(fn) {
  2083. if (typeof this !== 'object')
  2084. throw new TypeError('Promises must be constructed via new');
  2085. if (typeof fn !== 'function')
  2086. throw new TypeError('not a function');
  2087. this._state = 0;
  2088. this._handled = false;
  2089. this._value = undefined;
  2090. this._deferreds = [];
  2091. doResolve(fn, this);
  2092. }
  2093. function handle(self, deferred) {
  2094. while (self._state === 3) {
  2095. self = self._value;
  2096. }
  2097. if (self._state === 0) {
  2098. self._deferreds.push(deferred);
  2099. return;
  2100. }
  2101. self._handled = true;
  2102. Promise._immediateFn(function () {
  2103. var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected;
  2104. if (cb === null) {
  2105. (self._state === 1 ? resolve : reject)(deferred.promise, self._value);
  2106. return;
  2107. }
  2108. var ret;
  2109. try {
  2110. ret = cb(self._value);
  2111. } catch (e) {
  2112. reject(deferred.promise, e);
  2113. return;
  2114. }
  2115. resolve(deferred.promise, ret);
  2116. });
  2117. }
  2118. function resolve(self, newValue) {
  2119. try {
  2120. if (newValue === self)
  2121. throw new TypeError('A promise cannot be resolved with itself.');
  2122. if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
  2123. var then = newValue.then;
  2124. if (newValue instanceof Promise) {
  2125. self._state = 3;
  2126. self._value = newValue;
  2127. finale(self);
  2128. return;
  2129. } else if (typeof then === 'function') {
  2130. doResolve(bind(then, newValue), self);
  2131. return;
  2132. }
  2133. }
  2134. self._state = 1;
  2135. self._value = newValue;
  2136. finale(self);
  2137. } catch (e) {
  2138. reject(self, e);
  2139. }
  2140. }
  2141. function reject(self, newValue) {
  2142. self._state = 2;
  2143. self._value = newValue;
  2144. finale(self);
  2145. }
  2146. function finale(self) {
  2147. if (self._state === 2 && self._deferreds.length === 0) {
  2148. Promise._immediateFn(function () {
  2149. if (!self._handled) {
  2150. Promise._unhandledRejectionFn(self._value);
  2151. }
  2152. });
  2153. }
  2154. for (var i = 0, len = self._deferreds.length; i < len; i++) {
  2155. handle(self, self._deferreds[i]);
  2156. }
  2157. self._deferreds = null;
  2158. }
  2159. function Handler(onFulfilled, onRejected, promise) {
  2160. this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  2161. this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  2162. this.promise = promise;
  2163. }
  2164. function doResolve(fn, self) {
  2165. var done = false;
  2166. try {
  2167. fn(function (value) {
  2168. if (done)
  2169. return;
  2170. done = true;
  2171. resolve(self, value);
  2172. }, function (reason) {
  2173. if (done)
  2174. return;
  2175. done = true;
  2176. reject(self, reason);
  2177. });
  2178. } catch (ex) {
  2179. if (done)
  2180. return;
  2181. done = true;
  2182. reject(self, ex);
  2183. }
  2184. }
  2185. Promise.prototype['catch'] = function (onRejected) {
  2186. return this.then(null, onRejected);
  2187. };
  2188. Promise.prototype.then = function (onFulfilled, onRejected) {
  2189. var prom = new this.constructor(noop);
  2190. handle(this, new Handler(onFulfilled, onRejected, prom));
  2191. return prom;
  2192. };
  2193. Promise.all = function (arr) {
  2194. var args = Array.prototype.slice.call(arr);
  2195. return new Promise(function (resolve, reject) {
  2196. if (args.length === 0)
  2197. return resolve([]);
  2198. var remaining = args.length;
  2199. function res(i, val) {
  2200. try {
  2201. if (val && (typeof val === 'object' || typeof val === 'function')) {
  2202. var then = val.then;
  2203. if (typeof then === 'function') {
  2204. then.call(val, function (val) {
  2205. res(i, val);
  2206. }, reject);
  2207. return;
  2208. }
  2209. }
  2210. args[i] = val;
  2211. if (--remaining === 0) {
  2212. resolve(args);
  2213. }
  2214. } catch (ex) {
  2215. reject(ex);
  2216. }
  2217. }
  2218. for (var i = 0; i < args.length; i++) {
  2219. res(i, args[i]);
  2220. }
  2221. });
  2222. };
  2223. Promise.resolve = function (value) {
  2224. if (value && typeof value === 'object' && value.constructor === Promise) {
  2225. return value;
  2226. }
  2227. return new Promise(function (resolve) {
  2228. resolve(value);
  2229. });
  2230. };
  2231. Promise.reject = function (value) {
  2232. return new Promise(function (resolve, reject) {
  2233. reject(value);
  2234. });
  2235. };
  2236. Promise.race = function (values) {
  2237. return new Promise(function (resolve, reject) {
  2238. for (var i = 0, len = values.length; i < len; i++) {
  2239. values[i].then(resolve, reject);
  2240. }
  2241. });
  2242. };
  2243. Promise._immediateFn = typeof setImmediate === 'function' ? function (fn) {
  2244. setImmediate(fn);
  2245. } : function (fn) {
  2246. setTimeoutFunc(fn, 0);
  2247. };
  2248. Promise._unhandledRejectionFn = function _unhandledRejectionFn(err) {
  2249. if (typeof console !== 'undefined' && console) {
  2250. console.warn('Possible Unhandled Promise Rejection:', err);
  2251. }
  2252. };
  2253. Promise._setImmediateFn = function _setImmediateFn(fn) {
  2254. Promise._immediateFn = fn;
  2255. };
  2256. Promise._setUnhandledRejectionFn = function _setUnhandledRejectionFn(fn) {
  2257. Promise._unhandledRejectionFn = fn;
  2258. };
  2259. if (typeof module !== 'undefined' && module.exports) {
  2260. module.exports = Promise;
  2261. } else if (!root.Promise) {
  2262. root.Promise = Promise;
  2263. }
  2264. }(this));
  2265. }.call(this, require('timers').setImmediate));
  2266. },
  2267. { 'timers': 3 }
  2268. ],
  2269. 3: [
  2270. function (require, module, exports) {
  2271. (function (setImmediate, clearImmediate) {
  2272. var nextTick = require('process/browser.js').nextTick;
  2273. var apply = Function.prototype.apply;
  2274. var slice = Array.prototype.slice;
  2275. var immediateIds = {};
  2276. var nextImmediateId = 0;
  2277. exports.setTimeout = function () {
  2278. return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
  2279. };
  2280. exports.setInterval = function () {
  2281. return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
  2282. };
  2283. exports.clearTimeout = exports.clearInterval = function (timeout) {
  2284. timeout.close();
  2285. };
  2286. function Timeout(id, clearFn) {
  2287. this._id = id;
  2288. this._clearFn = clearFn;
  2289. }
  2290. Timeout.prototype.unref = Timeout.prototype.ref = function () {
  2291. };
  2292. Timeout.prototype.close = function () {
  2293. this._clearFn.call(window, this._id);
  2294. };
  2295. exports.enroll = function (item, msecs) {
  2296. clearTimeout(item._idleTimeoutId);
  2297. item._idleTimeout = msecs;
  2298. };
  2299. exports.unenroll = function (item) {
  2300. clearTimeout(item._idleTimeoutId);
  2301. item._idleTimeout = -1;
  2302. };
  2303. exports._unrefActive = exports.active = function (item) {
  2304. clearTimeout(item._idleTimeoutId);
  2305. var msecs = item._idleTimeout;
  2306. if (msecs >= 0) {
  2307. item._idleTimeoutId = setTimeout(function onTimeout() {
  2308. if (item._onTimeout)
  2309. item._onTimeout();
  2310. }, msecs);
  2311. }
  2312. };
  2313. exports.setImmediate = typeof setImmediate === 'function' ? setImmediate : function (fn) {
  2314. var id = nextImmediateId++;
  2315. var args = arguments.length < 2 ? false : slice.call(arguments, 1);
  2316. immediateIds[id] = true;
  2317. nextTick(function onNextTick() {
  2318. if (immediateIds[id]) {
  2319. if (args) {
  2320. fn.apply(null, args);
  2321. } else {
  2322. fn.call(null);
  2323. }
  2324. exports.clearImmediate(id);
  2325. }
  2326. });
  2327. return id;
  2328. };
  2329. exports.clearImmediate = typeof clearImmediate === 'function' ? clearImmediate : function (id) {
  2330. delete immediateIds[id];
  2331. };
  2332. }.call(this, require('timers').setImmediate, require('timers').clearImmediate));
  2333. },
  2334. {
  2335. 'process/browser.js': 1,
  2336. 'timers': 3
  2337. }
  2338. ],
  2339. 4: [
  2340. function (require, module, exports) {
  2341. var promisePolyfill = require('promise-polyfill');
  2342. var Global = function () {
  2343. if (typeof window !== 'undefined') {
  2344. return window;
  2345. } else {
  2346. return Function('return this;')();
  2347. }
  2348. }();
  2349. module.exports = { boltExport: Global.Promise || promisePolyfill };
  2350. },
  2351. { 'promise-polyfill': 2 }
  2352. ]
  2353. }, {}, [4])(4);
  2354. }));
  2355. }(undefined, exports$1, module$1, undefined));
  2356. var Promise = module$1.exports.boltExport;
  2357. var nu$3 = function (baseFn) {
  2358. var data = Optional.none();
  2359. var callbacks = [];
  2360. var map = function (f) {
  2361. return nu$3(function (nCallback) {
  2362. get(function (data) {
  2363. nCallback(f(data));
  2364. });
  2365. });
  2366. };
  2367. var get = function (nCallback) {
  2368. if (isReady()) {
  2369. call(nCallback);
  2370. } else {
  2371. callbacks.push(nCallback);
  2372. }
  2373. };
  2374. var set = function (x) {
  2375. if (!isReady()) {
  2376. data = Optional.some(x);
  2377. run(callbacks);
  2378. callbacks = [];
  2379. }
  2380. };
  2381. var isReady = function () {
  2382. return data.isSome();
  2383. };
  2384. var run = function (cbs) {
  2385. each(cbs, call);
  2386. };
  2387. var call = function (cb) {
  2388. data.each(function (x) {
  2389. setTimeout(function () {
  2390. cb(x);
  2391. }, 0);
  2392. });
  2393. };
  2394. baseFn(set);
  2395. return {
  2396. get: get,
  2397. map: map,
  2398. isReady: isReady
  2399. };
  2400. };
  2401. var pure = function (a) {
  2402. return nu$3(function (callback) {
  2403. callback(a);
  2404. });
  2405. };
  2406. var LazyValue = {
  2407. nu: nu$3,
  2408. pure: pure
  2409. };
  2410. var errorReporter = function (err) {
  2411. setTimeout(function () {
  2412. throw err;
  2413. }, 0);
  2414. };
  2415. var make = function (run) {
  2416. var get = function (callback) {
  2417. run().then(callback, errorReporter);
  2418. };
  2419. var map = function (fab) {
  2420. return make(function () {
  2421. return run().then(fab);
  2422. });
  2423. };
  2424. var bind = function (aFutureB) {
  2425. return make(function () {
  2426. return run().then(function (v) {
  2427. return aFutureB(v).toPromise();
  2428. });
  2429. });
  2430. };
  2431. var anonBind = function (futureB) {
  2432. return make(function () {
  2433. return run().then(function () {
  2434. return futureB.toPromise();
  2435. });
  2436. });
  2437. };
  2438. var toLazy = function () {
  2439. return LazyValue.nu(get);
  2440. };
  2441. var toCached = function () {
  2442. var cache = null;
  2443. return make(function () {
  2444. if (cache === null) {
  2445. cache = run();
  2446. }
  2447. return cache;
  2448. });
  2449. };
  2450. var toPromise = run;
  2451. return {
  2452. map: map,
  2453. bind: bind,
  2454. anonBind: anonBind,
  2455. toLazy: toLazy,
  2456. toCached: toCached,
  2457. toPromise: toPromise,
  2458. get: get
  2459. };
  2460. };
  2461. var nu$4 = function (baseFn) {
  2462. return make(function () {
  2463. return new Promise(baseFn);
  2464. });
  2465. };
  2466. var pure$1 = function (a) {
  2467. return make(function () {
  2468. return Promise.resolve(a);
  2469. });
  2470. };
  2471. var Future = {
  2472. nu: nu$4,
  2473. pure: pure$1
  2474. };
  2475. var par = function (asyncValues, nu) {
  2476. return nu(function (callback) {
  2477. var r = [];
  2478. var count = 0;
  2479. var cb = function (i) {
  2480. return function (value) {
  2481. r[i] = value;
  2482. count++;
  2483. if (count >= asyncValues.length) {
  2484. callback(r);
  2485. }
  2486. };
  2487. };
  2488. if (asyncValues.length === 0) {
  2489. callback([]);
  2490. } else {
  2491. each(asyncValues, function (asyncValue, i) {
  2492. asyncValue.get(cb(i));
  2493. });
  2494. }
  2495. });
  2496. };
  2497. var par$1 = function (futures) {
  2498. return par(futures, Future.nu);
  2499. };
  2500. var value = function (o) {
  2501. var is = function (v) {
  2502. return o === v;
  2503. };
  2504. var or = function (_opt) {
  2505. return value(o);
  2506. };
  2507. var orThunk = function (_f) {
  2508. return value(o);
  2509. };
  2510. var map = function (f) {
  2511. return value(f(o));
  2512. };
  2513. var mapError = function (_f) {
  2514. return value(o);
  2515. };
  2516. var each = function (f) {
  2517. f(o);
  2518. };
  2519. var bind = function (f) {
  2520. return f(o);
  2521. };
  2522. var fold = function (_, onValue) {
  2523. return onValue(o);
  2524. };
  2525. var exists = function (f) {
  2526. return f(o);
  2527. };
  2528. var forall = function (f) {
  2529. return f(o);
  2530. };
  2531. var toOptional = function () {
  2532. return Optional.some(o);
  2533. };
  2534. return {
  2535. is: is,
  2536. isValue: always,
  2537. isError: never,
  2538. getOr: constant(o),
  2539. getOrThunk: constant(o),
  2540. getOrDie: constant(o),
  2541. or: or,
  2542. orThunk: orThunk,
  2543. fold: fold,
  2544. map: map,
  2545. mapError: mapError,
  2546. each: each,
  2547. bind: bind,
  2548. exists: exists,
  2549. forall: forall,
  2550. toOptional: toOptional
  2551. };
  2552. };
  2553. var error = function (message) {
  2554. var getOrThunk = function (f) {
  2555. return f();
  2556. };
  2557. var getOrDie = function () {
  2558. return die(String(message))();
  2559. };
  2560. var or = function (opt) {
  2561. return opt;
  2562. };
  2563. var orThunk = function (f) {
  2564. return f();
  2565. };
  2566. var map = function (_f) {
  2567. return error(message);
  2568. };
  2569. var mapError = function (f) {
  2570. return error(f(message));
  2571. };
  2572. var bind = function (_f) {
  2573. return error(message);
  2574. };
  2575. var fold = function (onError, _) {
  2576. return onError(message);
  2577. };
  2578. return {
  2579. is: never,
  2580. isValue: never,
  2581. isError: always,
  2582. getOr: identity,
  2583. getOrThunk: getOrThunk,
  2584. getOrDie: getOrDie,
  2585. or: or,
  2586. orThunk: orThunk,
  2587. fold: fold,
  2588. map: map,
  2589. mapError: mapError,
  2590. each: noop,
  2591. bind: bind,
  2592. exists: never,
  2593. forall: always,
  2594. toOptional: Optional.none
  2595. };
  2596. };
  2597. var fromOption = function (opt, err) {
  2598. return opt.fold(function () {
  2599. return error(err);
  2600. }, value);
  2601. };
  2602. var Result = {
  2603. value: value,
  2604. error: error,
  2605. fromOption: fromOption
  2606. };
  2607. var generate = function (cases) {
  2608. if (!isArray(cases)) {
  2609. throw new Error('cases must be an array');
  2610. }
  2611. if (cases.length === 0) {
  2612. throw new Error('there must be at least one case');
  2613. }
  2614. var constructors = [];
  2615. var adt = {};
  2616. each(cases, function (acase, count) {
  2617. var keys$1 = keys(acase);
  2618. if (keys$1.length !== 1) {
  2619. throw new Error('one and only one name per case');
  2620. }
  2621. var key = keys$1[0];
  2622. var value = acase[key];
  2623. if (adt[key] !== undefined) {
  2624. throw new Error('duplicate key detected:' + key);
  2625. } else if (key === 'cata') {
  2626. throw new Error('cannot have a case named cata (sorry)');
  2627. } else if (!isArray(value)) {
  2628. throw new Error('case arguments must be an array');
  2629. }
  2630. constructors.push(key);
  2631. adt[key] = function () {
  2632. var argLength = arguments.length;
  2633. if (argLength !== value.length) {
  2634. throw new Error('Wrong number of arguments to case ' + key + '. Expected ' + value.length + ' (' + value + '), got ' + argLength);
  2635. }
  2636. var args = new Array(argLength);
  2637. for (var i = 0; i < args.length; i++) {
  2638. args[i] = arguments[i];
  2639. }
  2640. var match = function (branches) {
  2641. var branchKeys = keys(branches);
  2642. if (constructors.length !== branchKeys.length) {
  2643. throw new Error('Wrong number of arguments to match. Expected: ' + constructors.join(',') + '\nActual: ' + branchKeys.join(','));
  2644. }
  2645. var allReqd = forall(constructors, function (reqKey) {
  2646. return contains(branchKeys, reqKey);
  2647. });
  2648. if (!allReqd) {
  2649. throw new Error('Not all branches were specified when using match. Specified: ' + branchKeys.join(', ') + '\nRequired: ' + constructors.join(', '));
  2650. }
  2651. return branches[key].apply(null, args);
  2652. };
  2653. return {
  2654. fold: function () {
  2655. if (arguments.length !== cases.length) {
  2656. throw new Error('Wrong number of arguments to fold. Expected ' + cases.length + ', got ' + arguments.length);
  2657. }
  2658. var target = arguments[count];
  2659. return target.apply(null, args);
  2660. },
  2661. match: match,
  2662. log: function (label) {
  2663. console.log(label, {
  2664. constructors: constructors,
  2665. constructor: key,
  2666. params: args
  2667. });
  2668. }
  2669. };
  2670. };
  2671. });
  2672. return adt;
  2673. };
  2674. var Adt = { generate: generate };
  2675. var comparison = Adt.generate([
  2676. {
  2677. bothErrors: [
  2678. 'error1',
  2679. 'error2'
  2680. ]
  2681. },
  2682. {
  2683. firstError: [
  2684. 'error1',
  2685. 'value2'
  2686. ]
  2687. },
  2688. {
  2689. secondError: [
  2690. 'value1',
  2691. 'error2'
  2692. ]
  2693. },
  2694. {
  2695. bothValues: [
  2696. 'value1',
  2697. 'value2'
  2698. ]
  2699. }
  2700. ]);
  2701. var unite = function (result) {
  2702. return result.fold(identity, identity);
  2703. };
  2704. function ClosestOrAncestor (is, ancestor, scope, a, isRoot) {
  2705. return is(scope, a) ? Optional.some(scope) : isFunction(isRoot) && isRoot(scope) ? Optional.none() : ancestor(scope, a, isRoot);
  2706. }
  2707. var ancestor = function (scope, predicate, isRoot) {
  2708. var element = scope.dom;
  2709. var stop = isFunction(isRoot) ? isRoot : never;
  2710. while (element.parentNode) {
  2711. element = element.parentNode;
  2712. var el = SugarElement.fromDom(element);
  2713. if (predicate(el)) {
  2714. return Optional.some(el);
  2715. } else if (stop(el)) {
  2716. break;
  2717. }
  2718. }
  2719. return Optional.none();
  2720. };
  2721. var closest = function (scope, predicate, isRoot) {
  2722. var is = function (s, test) {
  2723. return test(s);
  2724. };
  2725. return ClosestOrAncestor(is, ancestor, scope, predicate, isRoot);
  2726. };
  2727. var ancestor$1 = function (scope, selector, isRoot) {
  2728. return ancestor(scope, function (e) {
  2729. return is$1(e, selector);
  2730. }, isRoot);
  2731. };
  2732. var descendant = function (scope, selector) {
  2733. return one(selector, scope);
  2734. };
  2735. var closest$1 = function (scope, selector, isRoot) {
  2736. var is = function (element, selector) {
  2737. return is$1(element, selector);
  2738. };
  2739. return ClosestOrAncestor(is, ancestor$1, scope, selector, isRoot);
  2740. };
  2741. var promise = function () {
  2742. function bind(fn, thisArg) {
  2743. return function () {
  2744. fn.apply(thisArg, arguments);
  2745. };
  2746. }
  2747. var isArray = Array.isArray || function (value) {
  2748. return Object.prototype.toString.call(value) === '[object Array]';
  2749. };
  2750. var Promise = function (fn) {
  2751. if (typeof this !== 'object') {
  2752. throw new TypeError('Promises must be constructed via new');
  2753. }
  2754. if (typeof fn !== 'function') {
  2755. throw new TypeError('not a function');
  2756. }
  2757. this._state = null;
  2758. this._value = null;
  2759. this._deferreds = [];
  2760. doResolve(fn, bind(resolve, this), bind(reject, this));
  2761. };
  2762. var asap = Promise.immediateFn || typeof setImmediate === 'function' && setImmediate || function (fn) {
  2763. setTimeout(fn, 1);
  2764. };
  2765. function handle(deferred) {
  2766. var me = this;
  2767. if (this._state === null) {
  2768. this._deferreds.push(deferred);
  2769. return;
  2770. }
  2771. asap(function () {
  2772. var cb = me._state ? deferred.onFulfilled : deferred.onRejected;
  2773. if (cb === null) {
  2774. (me._state ? deferred.resolve : deferred.reject)(me._value);
  2775. return;
  2776. }
  2777. var ret;
  2778. try {
  2779. ret = cb(me._value);
  2780. } catch (e) {
  2781. deferred.reject(e);
  2782. return;
  2783. }
  2784. deferred.resolve(ret);
  2785. });
  2786. }
  2787. function resolve(newValue) {
  2788. try {
  2789. if (newValue === this) {
  2790. throw new TypeError('A promise cannot be resolved with itself.');
  2791. }
  2792. if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
  2793. var then = newValue.then;
  2794. if (typeof then === 'function') {
  2795. doResolve(bind(then, newValue), bind(resolve, this), bind(reject, this));
  2796. return;
  2797. }
  2798. }
  2799. this._state = true;
  2800. this._value = newValue;
  2801. finale.call(this);
  2802. } catch (e) {
  2803. reject.call(this, e);
  2804. }
  2805. }
  2806. function reject(newValue) {
  2807. this._state = false;
  2808. this._value = newValue;
  2809. finale.call(this);
  2810. }
  2811. function finale() {
  2812. for (var i = 0, len = this._deferreds.length; i < len; i++) {
  2813. handle.call(this, this._deferreds[i]);
  2814. }
  2815. this._deferreds = null;
  2816. }
  2817. function Handler(onFulfilled, onRejected, resolve, reject) {
  2818. this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  2819. this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  2820. this.resolve = resolve;
  2821. this.reject = reject;
  2822. }
  2823. function doResolve(fn, onFulfilled, onRejected) {
  2824. var done = false;
  2825. try {
  2826. fn(function (value) {
  2827. if (done) {
  2828. return;
  2829. }
  2830. done = true;
  2831. onFulfilled(value);
  2832. }, function (reason) {
  2833. if (done) {
  2834. return;
  2835. }
  2836. done = true;
  2837. onRejected(reason);
  2838. });
  2839. } catch (ex) {
  2840. if (done) {
  2841. return;
  2842. }
  2843. done = true;
  2844. onRejected(ex);
  2845. }
  2846. }
  2847. Promise.prototype.catch = function (onRejected) {
  2848. return this.then(null, onRejected);
  2849. };
  2850. Promise.prototype.then = function (onFulfilled, onRejected) {
  2851. var me = this;
  2852. return new Promise(function (resolve, reject) {
  2853. handle.call(me, new Handler(onFulfilled, onRejected, resolve, reject));
  2854. });
  2855. };
  2856. Promise.all = function () {
  2857. var args = Array.prototype.slice.call(arguments.length === 1 && isArray(arguments[0]) ? arguments[0] : arguments);
  2858. return new Promise(function (resolve, reject) {
  2859. if (args.length === 0) {
  2860. return resolve([]);
  2861. }
  2862. var remaining = args.length;
  2863. function res(i, val) {
  2864. try {
  2865. if (val && (typeof val === 'object' || typeof val === 'function')) {
  2866. var then = val.then;
  2867. if (typeof then === 'function') {
  2868. then.call(val, function (val) {
  2869. res(i, val);
  2870. }, reject);
  2871. return;
  2872. }
  2873. }
  2874. args[i] = val;
  2875. if (--remaining === 0) {
  2876. resolve(args);
  2877. }
  2878. } catch (ex) {
  2879. reject(ex);
  2880. }
  2881. }
  2882. for (var i = 0; i < args.length; i++) {
  2883. res(i, args[i]);
  2884. }
  2885. });
  2886. };
  2887. Promise.resolve = function (value) {
  2888. if (value && typeof value === 'object' && value.constructor === Promise) {
  2889. return value;
  2890. }
  2891. return new Promise(function (resolve) {
  2892. resolve(value);
  2893. });
  2894. };
  2895. Promise.reject = function (value) {
  2896. return new Promise(function (resolve, reject) {
  2897. reject(value);
  2898. });
  2899. };
  2900. Promise.race = function (values) {
  2901. return new Promise(function (resolve, reject) {
  2902. for (var i = 0, len = values.length; i < len; i++) {
  2903. values[i].then(resolve, reject);
  2904. }
  2905. });
  2906. };
  2907. return Promise;
  2908. };
  2909. var promiseObj = window.Promise ? window.Promise : promise();
  2910. var requestAnimationFramePromise;
  2911. var requestAnimationFrame = function (callback, element) {
  2912. var i, requestAnimationFrameFunc = window.requestAnimationFrame;
  2913. var vendors = [
  2914. 'ms',
  2915. 'moz',
  2916. 'webkit'
  2917. ];
  2918. var featurefill = function (callback) {
  2919. window.setTimeout(callback, 0);
  2920. };
  2921. for (i = 0; i < vendors.length && !requestAnimationFrameFunc; i++) {
  2922. requestAnimationFrameFunc = window[vendors[i] + 'RequestAnimationFrame'];
  2923. }
  2924. if (!requestAnimationFrameFunc) {
  2925. requestAnimationFrameFunc = featurefill;
  2926. }
  2927. requestAnimationFrameFunc(callback, element);
  2928. };
  2929. var wrappedSetTimeout = function (callback, time) {
  2930. if (typeof time !== 'number') {
  2931. time = 0;
  2932. }
  2933. return setTimeout(callback, time);
  2934. };
  2935. var wrappedSetInterval = function (callback, time) {
  2936. if (typeof time !== 'number') {
  2937. time = 1;
  2938. }
  2939. return setInterval(callback, time);
  2940. };
  2941. var wrappedClearTimeout = function (id) {
  2942. return clearTimeout(id);
  2943. };
  2944. var wrappedClearInterval = function (id) {
  2945. return clearInterval(id);
  2946. };
  2947. var debounce = function (callback, time) {
  2948. var timer;
  2949. var func = function () {
  2950. var args = [];
  2951. for (var _i = 0; _i < arguments.length; _i++) {
  2952. args[_i] = arguments[_i];
  2953. }
  2954. clearTimeout(timer);
  2955. timer = wrappedSetTimeout(function () {
  2956. callback.apply(this, args);
  2957. }, time);
  2958. };
  2959. func.stop = function () {
  2960. clearTimeout(timer);
  2961. };
  2962. return func;
  2963. };
  2964. var Delay = {
  2965. requestAnimationFrame: function (callback, element) {
  2966. if (requestAnimationFramePromise) {
  2967. requestAnimationFramePromise.then(callback);
  2968. return;
  2969. }
  2970. requestAnimationFramePromise = new promiseObj(function (resolve) {
  2971. if (!element) {
  2972. element = document.body;
  2973. }
  2974. requestAnimationFrame(resolve, element);
  2975. }).then(callback);
  2976. },
  2977. setTimeout: wrappedSetTimeout,
  2978. setInterval: wrappedSetInterval,
  2979. setEditorTimeout: function (editor, callback, time) {
  2980. return wrappedSetTimeout(function () {
  2981. if (!editor.removed) {
  2982. callback();
  2983. }
  2984. }, time);
  2985. },
  2986. setEditorInterval: function (editor, callback, time) {
  2987. var timer = wrappedSetInterval(function () {
  2988. if (!editor.removed) {
  2989. callback();
  2990. } else {
  2991. clearInterval(timer);
  2992. }
  2993. }, time);
  2994. return timer;
  2995. },
  2996. debounce: debounce,
  2997. throttle: debounce,
  2998. clearInterval: wrappedClearInterval,
  2999. clearTimeout: wrappedClearTimeout
  3000. };
  3001. function StyleSheetLoader(documentOrShadowRoot, settings) {
  3002. if (settings === void 0) {
  3003. settings = {};
  3004. }
  3005. var idCount = 0;
  3006. var loadedStates = {};
  3007. var edos = SugarElement.fromDom(documentOrShadowRoot);
  3008. var doc = documentOrOwner(edos);
  3009. var maxLoadTime = settings.maxLoadTime || 5000;
  3010. var _setReferrerPolicy = function (referrerPolicy) {
  3011. settings.referrerPolicy = referrerPolicy;
  3012. };
  3013. var addStyle = function (element) {
  3014. append(getStyleContainer(edos), element);
  3015. };
  3016. var removeStyle = function (id) {
  3017. var styleContainer = getStyleContainer(edos);
  3018. descendant(styleContainer, '#' + id).each(remove);
  3019. };
  3020. var getOrCreateState = function (url) {
  3021. return get(loadedStates, url).getOrThunk(function () {
  3022. return {
  3023. id: 'mce-u' + idCount++,
  3024. passed: [],
  3025. failed: [],
  3026. count: 0
  3027. };
  3028. });
  3029. };
  3030. var load = function (url, success, failure) {
  3031. var link;
  3032. var urlWithSuffix = Tools._addCacheSuffix(url);
  3033. var state = getOrCreateState(urlWithSuffix);
  3034. loadedStates[urlWithSuffix] = state;
  3035. state.count++;
  3036. var resolve = function (callbacks, status) {
  3037. var i = callbacks.length;
  3038. while (i--) {
  3039. callbacks[i]();
  3040. }
  3041. state.status = status;
  3042. state.passed = [];
  3043. state.failed = [];
  3044. if (link) {
  3045. link.onload = null;
  3046. link.onerror = null;
  3047. link = null;
  3048. }
  3049. };
  3050. var passed = function () {
  3051. return resolve(state.passed, 2);
  3052. };
  3053. var failed = function () {
  3054. return resolve(state.failed, 3);
  3055. };
  3056. var wait = function (testCallback, waitCallback) {
  3057. if (!testCallback()) {
  3058. if (Date.now() - startTime < maxLoadTime) {
  3059. Delay.setTimeout(waitCallback);
  3060. } else {
  3061. failed();
  3062. }
  3063. }
  3064. };
  3065. var waitForWebKitLinkLoaded = function () {
  3066. wait(function () {
  3067. var styleSheets = documentOrShadowRoot.styleSheets;
  3068. var i = styleSheets.length;
  3069. while (i--) {
  3070. var styleSheet = styleSheets[i];
  3071. var owner = styleSheet.ownerNode;
  3072. if (owner && owner.id === link.id) {
  3073. passed();
  3074. return true;
  3075. }
  3076. }
  3077. return false;
  3078. }, waitForWebKitLinkLoaded);
  3079. };
  3080. if (success) {
  3081. state.passed.push(success);
  3082. }
  3083. if (failure) {
  3084. state.failed.push(failure);
  3085. }
  3086. if (state.status === 1) {
  3087. return;
  3088. }
  3089. if (state.status === 2) {
  3090. passed();
  3091. return;
  3092. }
  3093. if (state.status === 3) {
  3094. failed();
  3095. return;
  3096. }
  3097. state.status = 1;
  3098. var linkElem = SugarElement.fromTag('link', doc.dom);
  3099. setAll(linkElem, {
  3100. rel: 'stylesheet',
  3101. type: 'text/css',
  3102. id: state.id
  3103. });
  3104. var startTime = Date.now();
  3105. if (settings.contentCssCors) {
  3106. set(linkElem, 'crossOrigin', 'anonymous');
  3107. }
  3108. if (settings.referrerPolicy) {
  3109. set(linkElem, 'referrerpolicy', settings.referrerPolicy);
  3110. }
  3111. link = linkElem.dom;
  3112. link.onload = waitForWebKitLinkLoaded;
  3113. link.onerror = failed;
  3114. addStyle(linkElem);
  3115. set(linkElem, 'href', urlWithSuffix);
  3116. };
  3117. var loadF = function (url) {
  3118. return Future.nu(function (resolve) {
  3119. load(url, compose(resolve, constant(Result.value(url))), compose(resolve, constant(Result.error(url))));
  3120. });
  3121. };
  3122. var loadAll = function (urls, success, failure) {
  3123. par$1(map(urls, loadF)).get(function (result) {
  3124. var parts = partition(result, function (r) {
  3125. return r.isValue();
  3126. });
  3127. if (parts.fail.length > 0) {
  3128. failure(parts.fail.map(unite));
  3129. } else {
  3130. success(parts.pass.map(unite));
  3131. }
  3132. });
  3133. };
  3134. var unload = function (url) {
  3135. var urlWithSuffix = Tools._addCacheSuffix(url);
  3136. get(loadedStates, urlWithSuffix).each(function (state) {
  3137. var count = --state.count;
  3138. if (count === 0) {
  3139. delete loadedStates[urlWithSuffix];
  3140. removeStyle(state.id);
  3141. }
  3142. });
  3143. };
  3144. var unloadAll = function (urls) {
  3145. each(urls, function (url) {
  3146. unload(url);
  3147. });
  3148. };
  3149. return {
  3150. load: load,
  3151. loadAll: loadAll,
  3152. unload: unload,
  3153. unloadAll: unloadAll,
  3154. _setReferrerPolicy: _setReferrerPolicy
  3155. };
  3156. }
  3157. var create$1 = function () {
  3158. var map = new WeakMap();
  3159. var forElement = function (referenceElement, settings) {
  3160. var root = getRootNode(referenceElement);
  3161. var rootDom = root.dom;
  3162. return Optional.from(map.get(rootDom)).getOrThunk(function () {
  3163. var sl = StyleSheetLoader(rootDom, settings);
  3164. map.set(rootDom, sl);
  3165. return sl;
  3166. });
  3167. };
  3168. return { forElement: forElement };
  3169. };
  3170. var instance = create$1();
  3171. var DomTreeWalker = function () {
  3172. function DomTreeWalker(startNode, rootNode) {
  3173. this.node = startNode;
  3174. this.rootNode = rootNode;
  3175. this.current = this.current.bind(this);
  3176. this.next = this.next.bind(this);
  3177. this.prev = this.prev.bind(this);
  3178. this.prev2 = this.prev2.bind(this);
  3179. }
  3180. DomTreeWalker.prototype.current = function () {
  3181. return this.node;
  3182. };
  3183. DomTreeWalker.prototype.next = function (shallow) {
  3184. this.node = this.findSibling(this.node, 'firstChild', 'nextSibling', shallow);
  3185. return this.node;
  3186. };
  3187. DomTreeWalker.prototype.prev = function (shallow) {
  3188. this.node = this.findSibling(this.node, 'lastChild', 'previousSibling', shallow);
  3189. return this.node;
  3190. };
  3191. DomTreeWalker.prototype.prev2 = function (shallow) {
  3192. this.node = this.findPreviousNode(this.node, 'lastChild', 'previousSibling', shallow);
  3193. return this.node;
  3194. };
  3195. DomTreeWalker.prototype.findSibling = function (node, startName, siblingName, shallow) {
  3196. var sibling, parent;
  3197. if (node) {
  3198. if (!shallow && node[startName]) {
  3199. return node[startName];
  3200. }
  3201. if (node !== this.rootNode) {
  3202. sibling = node[siblingName];
  3203. if (sibling) {
  3204. return sibling;
  3205. }
  3206. for (parent = node.parentNode; parent && parent !== this.rootNode; parent = parent.parentNode) {
  3207. sibling = parent[siblingName];
  3208. if (sibling) {
  3209. return sibling;
  3210. }
  3211. }
  3212. }
  3213. }
  3214. };
  3215. DomTreeWalker.prototype.findPreviousNode = function (node, startName, siblingName, shallow) {
  3216. var sibling, parent, child;
  3217. if (node) {
  3218. sibling = node[siblingName];
  3219. if (this.rootNode && sibling === this.rootNode) {
  3220. return;
  3221. }
  3222. if (sibling) {
  3223. if (!shallow) {
  3224. for (child = sibling[startName]; child; child = child[startName]) {
  3225. if (!child[startName]) {
  3226. return child;
  3227. }
  3228. }
  3229. }
  3230. return sibling;
  3231. }
  3232. parent = node.parentNode;
  3233. if (parent && parent !== this.rootNode) {
  3234. return parent;
  3235. }
  3236. }
  3237. };
  3238. return DomTreeWalker;
  3239. }();
  3240. var blocks = [
  3241. 'article',
  3242. 'aside',
  3243. 'details',
  3244. 'div',
  3245. 'dt',
  3246. 'figcaption',
  3247. 'footer',
  3248. 'form',
  3249. 'fieldset',
  3250. 'header',
  3251. 'hgroup',
  3252. 'html',
  3253. 'main',
  3254. 'nav',
  3255. 'section',
  3256. 'summary',
  3257. 'body',
  3258. 'p',
  3259. 'dl',
  3260. 'multicol',
  3261. 'dd',
  3262. 'figure',
  3263. 'address',
  3264. 'center',
  3265. 'blockquote',
  3266. 'h1',
  3267. 'h2',
  3268. 'h3',
  3269. 'h4',
  3270. 'h5',
  3271. 'h6',
  3272. 'listing',
  3273. 'xmp',
  3274. 'pre',
  3275. 'plaintext',
  3276. 'menu',
  3277. 'dir',
  3278. 'ul',
  3279. 'ol',
  3280. 'li',
  3281. 'hr',
  3282. 'table',
  3283. 'tbody',
  3284. 'thead',
  3285. 'tfoot',
  3286. 'th',
  3287. 'tr',
  3288. 'td',
  3289. 'caption'
  3290. ];
  3291. var tableCells = [
  3292. 'td',
  3293. 'th'
  3294. ];
  3295. var tableSections = [
  3296. 'thead',
  3297. 'tbody',
  3298. 'tfoot'
  3299. ];
  3300. var textBlocks = [
  3301. 'h1',
  3302. 'h2',
  3303. 'h3',
  3304. 'h4',
  3305. 'h5',
  3306. 'h6',
  3307. 'p',
  3308. 'div',
  3309. 'address',
  3310. 'pre',
  3311. 'form',
  3312. 'blockquote',
  3313. 'center',
  3314. 'dir',
  3315. 'fieldset',
  3316. 'header',
  3317. 'footer',
  3318. 'article',
  3319. 'section',
  3320. 'hgroup',
  3321. 'aside',
  3322. 'nav',
  3323. 'figure'
  3324. ];
  3325. var headings = [
  3326. 'h1',
  3327. 'h2',
  3328. 'h3',
  3329. 'h4',
  3330. 'h5',
  3331. 'h6'
  3332. ];
  3333. var listItems = [
  3334. 'li',
  3335. 'dd',
  3336. 'dt'
  3337. ];
  3338. var lists = [
  3339. 'ul',
  3340. 'ol',
  3341. 'dl'
  3342. ];
  3343. var wsElements = [
  3344. 'pre',
  3345. 'script',
  3346. 'textarea',
  3347. 'style'
  3348. ];
  3349. var lazyLookup = function (items) {
  3350. var lookup;
  3351. return function (node) {
  3352. lookup = lookup ? lookup : mapToObject(items, always);
  3353. return lookup.hasOwnProperty(name(node));
  3354. };
  3355. };
  3356. var isHeading = lazyLookup(headings);
  3357. var isBlock = lazyLookup(blocks);
  3358. var isTable$1 = function (node) {
  3359. return name(node) === 'table';
  3360. };
  3361. var isInline = function (node) {
  3362. return isElement(node) && !isBlock(node);
  3363. };
  3364. var isBr$1 = function (node) {
  3365. return isElement(node) && name(node) === 'br';
  3366. };
  3367. var isTextBlock = lazyLookup(textBlocks);
  3368. var isList = lazyLookup(lists);
  3369. var isListItem = lazyLookup(listItems);
  3370. var isTableSection = lazyLookup(tableSections);
  3371. var isTableCell$1 = lazyLookup(tableCells);
  3372. var isWsPreserveElement = lazyLookup(wsElements);
  3373. var ancestor$2 = function (scope, selector, isRoot) {
  3374. return ancestor$1(scope, selector, isRoot).isSome();
  3375. };
  3376. var zeroWidth = '\uFEFF';
  3377. var nbsp = '\xA0';
  3378. var isZwsp = function (char) {
  3379. return char === zeroWidth;
  3380. };
  3381. var removeZwsp = function (s) {
  3382. return s.replace(/\uFEFF/g, '');
  3383. };
  3384. var ZWSP = zeroWidth;
  3385. var isZwsp$1 = isZwsp;
  3386. var trim$2 = removeZwsp;
  3387. var isElement$2 = isElement$1;
  3388. var isText$2 = isText$1;
  3389. var isCaretContainerBlock = function (node) {
  3390. if (isText$2(node)) {
  3391. node = node.parentNode;
  3392. }
  3393. return isElement$2(node) && node.hasAttribute('data-mce-caret');
  3394. };
  3395. var isCaretContainerInline = function (node) {
  3396. return isText$2(node) && isZwsp$1(node.data);
  3397. };
  3398. var isCaretContainer = function (node) {
  3399. return isCaretContainerBlock(node) || isCaretContainerInline(node);
  3400. };
  3401. var hasContent = function (node) {
  3402. return node.firstChild !== node.lastChild || !isBr(node.firstChild);
  3403. };
  3404. var insertInline = function (node, before) {
  3405. var sibling;
  3406. var doc = node.ownerDocument;
  3407. var textNode = doc.createTextNode(ZWSP);
  3408. var parentNode = node.parentNode;
  3409. if (!before) {
  3410. sibling = node.nextSibling;
  3411. if (isText$2(sibling)) {
  3412. if (isCaretContainer(sibling)) {
  3413. return sibling;
  3414. }
  3415. if (startsWithCaretContainer(sibling)) {
  3416. sibling.splitText(1);
  3417. return sibling;
  3418. }
  3419. }
  3420. if (node.nextSibling) {
  3421. parentNode.insertBefore(textNode, node.nextSibling);
  3422. } else {
  3423. parentNode.appendChild(textNode);
  3424. }
  3425. } else {
  3426. sibling = node.previousSibling;
  3427. if (isText$2(sibling)) {
  3428. if (isCaretContainer(sibling)) {
  3429. return sibling;
  3430. }
  3431. if (endsWithCaretContainer(sibling)) {
  3432. return sibling.splitText(sibling.data.length - 1);
  3433. }
  3434. }
  3435. parentNode.insertBefore(textNode, node);
  3436. }
  3437. return textNode;
  3438. };
  3439. var isBeforeInline = function (pos) {
  3440. var container = pos.container();
  3441. if (!isText$1(container)) {
  3442. return false;
  3443. }
  3444. return container.data.charAt(pos.offset()) === ZWSP || pos.isAtStart() && isCaretContainerInline(container.previousSibling);
  3445. };
  3446. var isAfterInline = function (pos) {
  3447. var container = pos.container();
  3448. if (!isText$1(container)) {
  3449. return false;
  3450. }
  3451. return container.data.charAt(pos.offset() - 1) === ZWSP || pos.isAtEnd() && isCaretContainerInline(container.nextSibling);
  3452. };
  3453. var createBogusBr = function () {
  3454. var br = document.createElement('br');
  3455. br.setAttribute('data-mce-bogus', '1');
  3456. return br;
  3457. };
  3458. var insertBlock = function (blockName, node, before) {
  3459. var doc = node.ownerDocument;
  3460. var blockNode = doc.createElement(blockName);
  3461. blockNode.setAttribute('data-mce-caret', before ? 'before' : 'after');
  3462. blockNode.setAttribute('data-mce-bogus', 'all');
  3463. blockNode.appendChild(createBogusBr());
  3464. var parentNode = node.parentNode;
  3465. if (!before) {
  3466. if (node.nextSibling) {
  3467. parentNode.insertBefore(blockNode, node.nextSibling);
  3468. } else {
  3469. parentNode.appendChild(blockNode);
  3470. }
  3471. } else {
  3472. parentNode.insertBefore(blockNode, node);
  3473. }
  3474. return blockNode;
  3475. };
  3476. var startsWithCaretContainer = function (node) {
  3477. return isText$2(node) && node.data[0] === ZWSP;
  3478. };
  3479. var endsWithCaretContainer = function (node) {
  3480. return isText$2(node) && node.data[node.data.length - 1] === ZWSP;
  3481. };
  3482. var trimBogusBr = function (elm) {
  3483. var brs = elm.getElementsByTagName('br');
  3484. var lastBr = brs[brs.length - 1];
  3485. if (isBogus(lastBr)) {
  3486. lastBr.parentNode.removeChild(lastBr);
  3487. }
  3488. };
  3489. var showCaretContainerBlock = function (caretContainer) {
  3490. if (caretContainer && caretContainer.hasAttribute('data-mce-caret')) {
  3491. trimBogusBr(caretContainer);
  3492. caretContainer.removeAttribute('data-mce-caret');
  3493. caretContainer.removeAttribute('data-mce-bogus');
  3494. caretContainer.removeAttribute('style');
  3495. caretContainer.removeAttribute('_moz_abspos');
  3496. return caretContainer;
  3497. }
  3498. return null;
  3499. };
  3500. var isRangeInCaretContainerBlock = function (range) {
  3501. return isCaretContainerBlock(range.startContainer);
  3502. };
  3503. var isContentEditableTrue$1 = isContentEditableTrue;
  3504. var isContentEditableFalse$1 = isContentEditableFalse;
  3505. var isBr$2 = isBr;
  3506. var isText$3 = isText$1;
  3507. var isInvalidTextElement = matchNodeNames([
  3508. 'script',
  3509. 'style',
  3510. 'textarea'
  3511. ]);
  3512. var isAtomicInline = matchNodeNames([
  3513. 'img',
  3514. 'input',
  3515. 'textarea',
  3516. 'hr',
  3517. 'iframe',
  3518. 'video',
  3519. 'audio',
  3520. 'object',
  3521. 'embed'
  3522. ]);
  3523. var isTable$2 = matchNodeNames(['table']);
  3524. var isCaretContainer$1 = isCaretContainer;
  3525. var isCaretCandidate = function (node) {
  3526. if (isCaretContainer$1(node)) {
  3527. return false;
  3528. }
  3529. if (isText$3(node)) {
  3530. return !isInvalidTextElement(node.parentNode);
  3531. }
  3532. return isAtomicInline(node) || isBr$2(node) || isTable$2(node) || isNonUiContentEditableFalse(node);
  3533. };
  3534. var isUnselectable = function (node) {
  3535. return isElement$1(node) && node.getAttribute('unselectable') === 'true';
  3536. };
  3537. var isNonUiContentEditableFalse = function (node) {
  3538. return isUnselectable(node) === false && isContentEditableFalse$1(node);
  3539. };
  3540. var isInEditable = function (node, root) {
  3541. for (node = node.parentNode; node && node !== root; node = node.parentNode) {
  3542. if (isNonUiContentEditableFalse(node)) {
  3543. return false;
  3544. }
  3545. if (isContentEditableTrue$1(node)) {
  3546. return true;
  3547. }
  3548. }
  3549. return true;
  3550. };
  3551. var isAtomicContentEditableFalse = function (node) {
  3552. if (!isNonUiContentEditableFalse(node)) {
  3553. return false;
  3554. }
  3555. return foldl(from$1(node.getElementsByTagName('*')), function (result, elm) {
  3556. return result || isContentEditableTrue$1(elm);
  3557. }, false) !== true;
  3558. };
  3559. var isAtomic = function (node) {
  3560. return isAtomicInline(node) || isAtomicContentEditableFalse(node);
  3561. };
  3562. var isEditableCaretCandidate = function (node, root) {
  3563. return isCaretCandidate(node) && isInEditable(node, root);
  3564. };
  3565. var whiteSpaceRegExp$1 = /^[ \t\r\n]*$/;
  3566. var isWhitespaceText = function (text) {
  3567. return whiteSpaceRegExp$1.test(text);
  3568. };
  3569. var hasWhitespacePreserveParent = function (node, rootNode) {
  3570. var rootElement = SugarElement.fromDom(rootNode);
  3571. var startNode = SugarElement.fromDom(node);
  3572. return ancestor$2(startNode, 'pre,code', curry(eq$2, rootElement));
  3573. };
  3574. var isWhitespace = function (node, rootNode) {
  3575. return isText$1(node) && isWhitespaceText(node.data) && hasWhitespacePreserveParent(node, rootNode) === false;
  3576. };
  3577. var isNamedAnchor = function (node) {
  3578. return isElement$1(node) && node.nodeName === 'A' && !node.hasAttribute('href') && (node.hasAttribute('name') || node.hasAttribute('id'));
  3579. };
  3580. var isContent = function (node, rootNode) {
  3581. return isCaretCandidate(node) && isWhitespace(node, rootNode) === false || isNamedAnchor(node) || isBookmark(node);
  3582. };
  3583. var isBookmark = hasAttribute('data-mce-bookmark');
  3584. var isBogus$1 = hasAttribute('data-mce-bogus');
  3585. var isBogusAll$1 = hasAttributeValue('data-mce-bogus', 'all');
  3586. var isEmptyNode = function (targetNode, skipBogus) {
  3587. var node, brCount = 0;
  3588. if (isContent(targetNode, targetNode)) {
  3589. return false;
  3590. } else {
  3591. node = targetNode.firstChild;
  3592. if (!node) {
  3593. return true;
  3594. }
  3595. var walker = new DomTreeWalker(node, targetNode);
  3596. do {
  3597. if (skipBogus) {
  3598. if (isBogusAll$1(node)) {
  3599. node = walker.next(true);
  3600. continue;
  3601. }
  3602. if (isBogus$1(node)) {
  3603. node = walker.next();
  3604. continue;
  3605. }
  3606. }
  3607. if (isBr(node)) {
  3608. brCount++;
  3609. node = walker.next();
  3610. continue;
  3611. }
  3612. if (isContent(node, targetNode)) {
  3613. return false;
  3614. }
  3615. node = walker.next();
  3616. } while (node);
  3617. return brCount <= 1;
  3618. }
  3619. };
  3620. var isEmpty = function (elm, skipBogus) {
  3621. if (skipBogus === void 0) {
  3622. skipBogus = true;
  3623. }
  3624. return isEmptyNode(elm.dom, skipBogus);
  3625. };
  3626. var isSpan = function (node) {
  3627. return node.nodeName.toLowerCase() === 'span';
  3628. };
  3629. var isInlineContent = function (node, root) {
  3630. return isNonNullable(node) && (isContent(node, root) || isInline(SugarElement.fromDom(node)));
  3631. };
  3632. var surroundedByInlineContent = function (node, root) {
  3633. var prev = new DomTreeWalker(node, root).prev(false);
  3634. var next = new DomTreeWalker(node, root).next(false);
  3635. var prevIsInline = isUndefined(prev) || isInlineContent(prev, root);
  3636. var nextIsInline = isUndefined(next) || isInlineContent(next, root);
  3637. return prevIsInline && nextIsInline;
  3638. };
  3639. var isBookmarkNode = function (node) {
  3640. return isSpan(node) && node.getAttribute('data-mce-type') === 'bookmark';
  3641. };
  3642. var isKeepTextNode = function (node, root) {
  3643. return isText$1(node) && node.data.length > 0 && surroundedByInlineContent(node, root);
  3644. };
  3645. var isKeepElement = function (node) {
  3646. return isElement$1(node) ? node.childNodes.length > 0 : false;
  3647. };
  3648. var isDocument$2 = function (node) {
  3649. return isDocumentFragment$1(node) || isDocument$1(node);
  3650. };
  3651. var trimNode = function (dom, node, root) {
  3652. var rootNode = root || node;
  3653. if (isElement$1(node) && isBookmarkNode(node)) {
  3654. return node;
  3655. }
  3656. var children = node.childNodes;
  3657. for (var i = children.length - 1; i >= 0; i--) {
  3658. trimNode(dom, children[i], rootNode);
  3659. }
  3660. if (isElement$1(node)) {
  3661. var currentChildren = node.childNodes;
  3662. if (currentChildren.length === 1 && isBookmarkNode(currentChildren[0])) {
  3663. node.parentNode.insertBefore(currentChildren[0], node);
  3664. }
  3665. }
  3666. if (!isDocument$2(node) && !isContent(node, rootNode) && !isKeepElement(node) && !isKeepTextNode(node, rootNode)) {
  3667. dom.remove(node);
  3668. }
  3669. return node;
  3670. };
  3671. var makeMap$1 = Tools.makeMap;
  3672. var attrsCharsRegExp = /[&<>\"\u0060\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
  3673. var textCharsRegExp = /[<>&\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
  3674. var rawCharsRegExp = /[<>&\"\']/g;
  3675. var entityRegExp = /&#([a-z0-9]+);?|&([a-z0-9]+);/gi;
  3676. var asciiMap = {
  3677. 128: '\u20AC',
  3678. 130: '\u201A',
  3679. 131: '\u0192',
  3680. 132: '\u201E',
  3681. 133: '\u2026',
  3682. 134: '\u2020',
  3683. 135: '\u2021',
  3684. 136: '\u02c6',
  3685. 137: '\u2030',
  3686. 138: '\u0160',
  3687. 139: '\u2039',
  3688. 140: '\u0152',
  3689. 142: '\u017d',
  3690. 145: '\u2018',
  3691. 146: '\u2019',
  3692. 147: '\u201C',
  3693. 148: '\u201D',
  3694. 149: '\u2022',
  3695. 150: '\u2013',
  3696. 151: '\u2014',
  3697. 152: '\u02DC',
  3698. 153: '\u2122',
  3699. 154: '\u0161',
  3700. 155: '\u203A',
  3701. 156: '\u0153',
  3702. 158: '\u017e',
  3703. 159: '\u0178'
  3704. };
  3705. var baseEntities = {
  3706. '"': '&quot;',
  3707. '\'': '&#39;',
  3708. '<': '&lt;',
  3709. '>': '&gt;',
  3710. '&': '&amp;',
  3711. '`': '&#96;'
  3712. };
  3713. var reverseEntities = {
  3714. '&lt;': '<',
  3715. '&gt;': '>',
  3716. '&amp;': '&',
  3717. '&quot;': '"',
  3718. '&apos;': '\''
  3719. };
  3720. var nativeDecode = function (text) {
  3721. var elm = SugarElement.fromTag('div').dom;
  3722. elm.innerHTML = text;
  3723. return elm.textContent || elm.innerText || text;
  3724. };
  3725. var buildEntitiesLookup = function (items, radix) {
  3726. var i, chr, entity;
  3727. var lookup = {};
  3728. if (items) {
  3729. items = items.split(',');
  3730. radix = radix || 10;
  3731. for (i = 0; i < items.length; i += 2) {
  3732. chr = String.fromCharCode(parseInt(items[i], radix));
  3733. if (!baseEntities[chr]) {
  3734. entity = '&' + items[i + 1] + ';';
  3735. lookup[chr] = entity;
  3736. lookup[entity] = chr;
  3737. }
  3738. }
  3739. return lookup;
  3740. }
  3741. };
  3742. var namedEntities = buildEntitiesLookup('50,nbsp,51,iexcl,52,cent,53,pound,54,curren,55,yen,56,brvbar,57,sect,58,uml,59,copy,' + '5a,ordf,5b,laquo,5c,not,5d,shy,5e,reg,5f,macr,5g,deg,5h,plusmn,5i,sup2,5j,sup3,5k,acute,' + '5l,micro,5m,para,5n,middot,5o,cedil,5p,sup1,5q,ordm,5r,raquo,5s,frac14,5t,frac12,5u,frac34,' + '5v,iquest,60,Agrave,61,Aacute,62,Acirc,63,Atilde,64,Auml,65,Aring,66,AElig,67,Ccedil,' + '68,Egrave,69,Eacute,6a,Ecirc,6b,Euml,6c,Igrave,6d,Iacute,6e,Icirc,6f,Iuml,6g,ETH,6h,Ntilde,' + '6i,Ograve,6j,Oacute,6k,Ocirc,6l,Otilde,6m,Ouml,6n,times,6o,Oslash,6p,Ugrave,6q,Uacute,' + '6r,Ucirc,6s,Uuml,6t,Yacute,6u,THORN,6v,szlig,70,agrave,71,aacute,72,acirc,73,atilde,74,auml,' + '75,aring,76,aelig,77,ccedil,78,egrave,79,eacute,7a,ecirc,7b,euml,7c,igrave,7d,iacute,7e,icirc,' + '7f,iuml,7g,eth,7h,ntilde,7i,ograve,7j,oacute,7k,ocirc,7l,otilde,7m,ouml,7n,divide,7o,oslash,' + '7p,ugrave,7q,uacute,7r,ucirc,7s,uuml,7t,yacute,7u,thorn,7v,yuml,ci,fnof,sh,Alpha,si,Beta,' + 'sj,Gamma,sk,Delta,sl,Epsilon,sm,Zeta,sn,Eta,so,Theta,sp,Iota,sq,Kappa,sr,Lambda,ss,Mu,' + 'st,Nu,su,Xi,sv,Omicron,t0,Pi,t1,Rho,t3,Sigma,t4,Tau,t5,Upsilon,t6,Phi,t7,Chi,t8,Psi,' + 't9,Omega,th,alpha,ti,beta,tj,gamma,tk,delta,tl,epsilon,tm,zeta,tn,eta,to,theta,tp,iota,' + 'tq,kappa,tr,lambda,ts,mu,tt,nu,tu,xi,tv,omicron,u0,pi,u1,rho,u2,sigmaf,u3,sigma,u4,tau,' + 'u5,upsilon,u6,phi,u7,chi,u8,psi,u9,omega,uh,thetasym,ui,upsih,um,piv,812,bull,816,hellip,' + '81i,prime,81j,Prime,81u,oline,824,frasl,88o,weierp,88h,image,88s,real,892,trade,89l,alefsym,' + '8cg,larr,8ch,uarr,8ci,rarr,8cj,darr,8ck,harr,8dl,crarr,8eg,lArr,8eh,uArr,8ei,rArr,8ej,dArr,' + '8ek,hArr,8g0,forall,8g2,part,8g3,exist,8g5,empty,8g7,nabla,8g8,isin,8g9,notin,8gb,ni,8gf,prod,' + '8gh,sum,8gi,minus,8gn,lowast,8gq,radic,8gt,prop,8gu,infin,8h0,ang,8h7,and,8h8,or,8h9,cap,8ha,cup,' + '8hb,int,8hk,there4,8hs,sim,8i5,cong,8i8,asymp,8j0,ne,8j1,equiv,8j4,le,8j5,ge,8k2,sub,8k3,sup,8k4,' + 'nsub,8k6,sube,8k7,supe,8kl,oplus,8kn,otimes,8l5,perp,8m5,sdot,8o8,lceil,8o9,rceil,8oa,lfloor,8ob,' + 'rfloor,8p9,lang,8pa,rang,9ea,loz,9j0,spades,9j3,clubs,9j5,hearts,9j6,diams,ai,OElig,aj,oelig,b0,' + 'Scaron,b1,scaron,bo,Yuml,m6,circ,ms,tilde,802,ensp,803,emsp,809,thinsp,80c,zwnj,80d,zwj,80e,lrm,' + '80f,rlm,80j,ndash,80k,mdash,80o,lsquo,80p,rsquo,80q,sbquo,80s,ldquo,80t,rdquo,80u,bdquo,810,dagger,' + '811,Dagger,81g,permil,81p,lsaquo,81q,rsaquo,85c,euro', 32);
  3743. var encodeRaw = function (text, attr) {
  3744. return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function (chr) {
  3745. return baseEntities[chr] || chr;
  3746. });
  3747. };
  3748. var encodeAllRaw = function (text) {
  3749. return ('' + text).replace(rawCharsRegExp, function (chr) {
  3750. return baseEntities[chr] || chr;
  3751. });
  3752. };
  3753. var encodeNumeric = function (text, attr) {
  3754. return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function (chr) {
  3755. if (chr.length > 1) {
  3756. return '&#' + ((chr.charCodeAt(0) - 55296) * 1024 + (chr.charCodeAt(1) - 56320) + 65536) + ';';
  3757. }
  3758. return baseEntities[chr] || '&#' + chr.charCodeAt(0) + ';';
  3759. });
  3760. };
  3761. var encodeNamed = function (text, attr, entities) {
  3762. entities = entities || namedEntities;
  3763. return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function (chr) {
  3764. return baseEntities[chr] || entities[chr] || chr;
  3765. });
  3766. };
  3767. var getEncodeFunc = function (name, entities) {
  3768. var entitiesMap = buildEntitiesLookup(entities) || namedEntities;
  3769. var encodeNamedAndNumeric = function (text, attr) {
  3770. return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function (chr) {
  3771. if (baseEntities[chr] !== undefined) {
  3772. return baseEntities[chr];
  3773. }
  3774. if (entitiesMap[chr] !== undefined) {
  3775. return entitiesMap[chr];
  3776. }
  3777. if (chr.length > 1) {
  3778. return '&#' + ((chr.charCodeAt(0) - 55296) * 1024 + (chr.charCodeAt(1) - 56320) + 65536) + ';';
  3779. }
  3780. return '&#' + chr.charCodeAt(0) + ';';
  3781. });
  3782. };
  3783. var encodeCustomNamed = function (text, attr) {
  3784. return encodeNamed(text, attr, entitiesMap);
  3785. };
  3786. var nameMap = makeMap$1(name.replace(/\+/g, ','));
  3787. if (nameMap.named && nameMap.numeric) {
  3788. return encodeNamedAndNumeric;
  3789. }
  3790. if (nameMap.named) {
  3791. if (entities) {
  3792. return encodeCustomNamed;
  3793. }
  3794. return encodeNamed;
  3795. }
  3796. if (nameMap.numeric) {
  3797. return encodeNumeric;
  3798. }
  3799. return encodeRaw;
  3800. };
  3801. var decode = function (text) {
  3802. return text.replace(entityRegExp, function (all, numeric) {
  3803. if (numeric) {
  3804. if (numeric.charAt(0).toLowerCase() === 'x') {
  3805. numeric = parseInt(numeric.substr(1), 16);
  3806. } else {
  3807. numeric = parseInt(numeric, 10);
  3808. }
  3809. if (numeric > 65535) {
  3810. numeric -= 65536;
  3811. return String.fromCharCode(55296 + (numeric >> 10), 56320 + (numeric & 1023));
  3812. }
  3813. return asciiMap[numeric] || String.fromCharCode(numeric);
  3814. }
  3815. return reverseEntities[all] || namedEntities[all] || nativeDecode(all);
  3816. });
  3817. };
  3818. var Entities = {
  3819. encodeRaw: encodeRaw,
  3820. encodeAllRaw: encodeAllRaw,
  3821. encodeNumeric: encodeNumeric,
  3822. encodeNamed: encodeNamed,
  3823. getEncodeFunc: getEncodeFunc,
  3824. decode: decode
  3825. };
  3826. var mapCache = {}, dummyObj = {};
  3827. var makeMap$2 = Tools.makeMap, each$3 = Tools.each, extend$1 = Tools.extend, explode$1 = Tools.explode, inArray = Tools.inArray;
  3828. var split = function (items, delim) {
  3829. items = Tools.trim(items);
  3830. return items ? items.split(delim || ' ') : [];
  3831. };
  3832. var compileSchema = function (type) {
  3833. var schema = {};
  3834. var globalAttributes, blockContent;
  3835. var phrasingContent, flowContent, html4BlockContent, html4PhrasingContent;
  3836. var add = function (name, attributes, children) {
  3837. var ni, attributesOrder, element;
  3838. var arrayToMap = function (array, obj) {
  3839. var map = {};
  3840. var i, l;
  3841. for (i = 0, l = array.length; i < l; i++) {
  3842. map[array[i]] = obj || {};
  3843. }
  3844. return map;
  3845. };
  3846. children = children || [];
  3847. attributes = attributes || '';
  3848. if (typeof children === 'string') {
  3849. children = split(children);
  3850. }
  3851. var names = split(name);
  3852. ni = names.length;
  3853. while (ni--) {
  3854. attributesOrder = split([
  3855. globalAttributes,
  3856. attributes
  3857. ].join(' '));
  3858. element = {
  3859. attributes: arrayToMap(attributesOrder),
  3860. attributesOrder: attributesOrder,
  3861. children: arrayToMap(children, dummyObj)
  3862. };
  3863. schema[names[ni]] = element;
  3864. }
  3865. };
  3866. var addAttrs = function (name, attributes) {
  3867. var ni, schemaItem, i, l;
  3868. var names = split(name);
  3869. ni = names.length;
  3870. var attrs = split(attributes);
  3871. while (ni--) {
  3872. schemaItem = schema[names[ni]];
  3873. for (i = 0, l = attrs.length; i < l; i++) {
  3874. schemaItem.attributes[attrs[i]] = {};
  3875. schemaItem.attributesOrder.push(attrs[i]);
  3876. }
  3877. }
  3878. };
  3879. if (mapCache[type]) {
  3880. return mapCache[type];
  3881. }
  3882. globalAttributes = 'id accesskey class dir lang style tabindex title role';
  3883. blockContent = 'address blockquote div dl fieldset form h1 h2 h3 h4 h5 h6 hr menu ol p pre table ul';
  3884. phrasingContent = 'a abbr b bdo br button cite code del dfn em embed i iframe img input ins kbd ' + 'label map noscript object q s samp script select small span strong sub sup ' + 'textarea u var #text #comment';
  3885. if (type !== 'html4') {
  3886. globalAttributes += ' contenteditable contextmenu draggable dropzone ' + 'hidden spellcheck translate';
  3887. blockContent += ' article aside details dialog figure main header footer hgroup section nav';
  3888. phrasingContent += ' audio canvas command datalist mark meter output picture ' + 'progress time wbr video ruby bdi keygen';
  3889. }
  3890. if (type !== 'html5-strict') {
  3891. globalAttributes += ' xml:lang';
  3892. html4PhrasingContent = 'acronym applet basefont big font strike tt';
  3893. phrasingContent = [
  3894. phrasingContent,
  3895. html4PhrasingContent
  3896. ].join(' ');
  3897. each$3(split(html4PhrasingContent), function (name) {
  3898. add(name, '', phrasingContent);
  3899. });
  3900. html4BlockContent = 'center dir isindex noframes';
  3901. blockContent = [
  3902. blockContent,
  3903. html4BlockContent
  3904. ].join(' ');
  3905. flowContent = [
  3906. blockContent,
  3907. phrasingContent
  3908. ].join(' ');
  3909. each$3(split(html4BlockContent), function (name) {
  3910. add(name, '', flowContent);
  3911. });
  3912. }
  3913. flowContent = flowContent || [
  3914. blockContent,
  3915. phrasingContent
  3916. ].join(' ');
  3917. add('html', 'manifest', 'head body');
  3918. add('head', '', 'base command link meta noscript script style title');
  3919. add('title hr noscript br');
  3920. add('base', 'href target');
  3921. add('link', 'href rel media hreflang type sizes hreflang');
  3922. add('meta', 'name http-equiv content charset');
  3923. add('style', 'media type scoped');
  3924. add('script', 'src async defer type charset');
  3925. add('body', 'onafterprint onbeforeprint onbeforeunload onblur onerror onfocus ' + 'onhashchange onload onmessage onoffline ononline onpagehide onpageshow ' + 'onpopstate onresize onscroll onstorage onunload', flowContent);
  3926. add('address dt dd div caption', '', flowContent);
  3927. add('h1 h2 h3 h4 h5 h6 pre p abbr code var samp kbd sub sup i b u bdo span legend em strong small s cite dfn', '', phrasingContent);
  3928. add('blockquote', 'cite', flowContent);
  3929. add('ol', 'reversed start type', 'li');
  3930. add('ul', '', 'li');
  3931. add('li', 'value', flowContent);
  3932. add('dl', '', 'dt dd');
  3933. add('a', 'href target rel media hreflang type', phrasingContent);
  3934. add('q', 'cite', phrasingContent);
  3935. add('ins del', 'cite datetime', flowContent);
  3936. add('img', 'src sizes srcset alt usemap ismap width height');
  3937. add('iframe', 'src name width height', flowContent);
  3938. add('embed', 'src type width height');
  3939. add('object', 'data type typemustmatch name usemap form width height', [
  3940. flowContent,
  3941. 'param'
  3942. ].join(' '));
  3943. add('param', 'name value');
  3944. add('map', 'name', [
  3945. flowContent,
  3946. 'area'
  3947. ].join(' '));
  3948. add('area', 'alt coords shape href target rel media hreflang type');
  3949. add('table', 'border', 'caption colgroup thead tfoot tbody tr' + (type === 'html4' ? ' col' : ''));
  3950. add('colgroup', 'span', 'col');
  3951. add('col', 'span');
  3952. add('tbody thead tfoot', '', 'tr');
  3953. add('tr', '', 'td th');
  3954. add('td', 'colspan rowspan headers', flowContent);
  3955. add('th', 'colspan rowspan headers scope abbr', flowContent);
  3956. add('form', 'accept-charset action autocomplete enctype method name novalidate target', flowContent);
  3957. add('fieldset', 'disabled form name', [
  3958. flowContent,
  3959. 'legend'
  3960. ].join(' '));
  3961. add('label', 'form for', phrasingContent);
  3962. add('input', 'accept alt autocomplete checked dirname disabled form formaction formenctype formmethod formnovalidate ' + 'formtarget height list max maxlength min multiple name pattern readonly required size src step type value width');
  3963. add('button', 'disabled form formaction formenctype formmethod formnovalidate formtarget name type value', type === 'html4' ? flowContent : phrasingContent);
  3964. add('select', 'disabled form multiple name required size', 'option optgroup');
  3965. add('optgroup', 'disabled label', 'option');
  3966. add('option', 'disabled label selected value');
  3967. add('textarea', 'cols dirname disabled form maxlength name readonly required rows wrap');
  3968. add('menu', 'type label', [
  3969. flowContent,
  3970. 'li'
  3971. ].join(' '));
  3972. add('noscript', '', flowContent);
  3973. if (type !== 'html4') {
  3974. add('wbr');
  3975. add('ruby', '', [
  3976. phrasingContent,
  3977. 'rt rp'
  3978. ].join(' '));
  3979. add('figcaption', '', flowContent);
  3980. add('mark rt rp summary bdi', '', phrasingContent);
  3981. add('canvas', 'width height', flowContent);
  3982. add('video', 'src crossorigin poster preload autoplay mediagroup loop ' + 'muted controls width height buffered', [
  3983. flowContent,
  3984. 'track source'
  3985. ].join(' '));
  3986. add('audio', 'src crossorigin preload autoplay mediagroup loop muted controls ' + 'buffered volume', [
  3987. flowContent,
  3988. 'track source'
  3989. ].join(' '));
  3990. add('picture', '', 'img source');
  3991. add('source', 'src srcset type media sizes');
  3992. add('track', 'kind src srclang label default');
  3993. add('datalist', '', [
  3994. phrasingContent,
  3995. 'option'
  3996. ].join(' '));
  3997. add('article section nav aside main header footer', '', flowContent);
  3998. add('hgroup', '', 'h1 h2 h3 h4 h5 h6');
  3999. add('figure', '', [
  4000. flowContent,
  4001. 'figcaption'
  4002. ].join(' '));
  4003. add('time', 'datetime', phrasingContent);
  4004. add('dialog', 'open', flowContent);
  4005. add('command', 'type label icon disabled checked radiogroup command');
  4006. add('output', 'for form name', phrasingContent);
  4007. add('progress', 'value max', phrasingContent);
  4008. add('meter', 'value min max low high optimum', phrasingContent);
  4009. add('details', 'open', [
  4010. flowContent,
  4011. 'summary'
  4012. ].join(' '));
  4013. add('keygen', 'autofocus challenge disabled form keytype name');
  4014. }
  4015. if (type !== 'html5-strict') {
  4016. addAttrs('script', 'language xml:space');
  4017. addAttrs('style', 'xml:space');
  4018. addAttrs('object', 'declare classid code codebase codetype archive standby align border hspace vspace');
  4019. addAttrs('embed', 'align name hspace vspace');
  4020. addAttrs('param', 'valuetype type');
  4021. addAttrs('a', 'charset name rev shape coords');
  4022. addAttrs('br', 'clear');
  4023. addAttrs('applet', 'codebase archive code object alt name width height align hspace vspace');
  4024. addAttrs('img', 'name longdesc align border hspace vspace');
  4025. addAttrs('iframe', 'longdesc frameborder marginwidth marginheight scrolling align');
  4026. addAttrs('font basefont', 'size color face');
  4027. addAttrs('input', 'usemap align');
  4028. addAttrs('select');
  4029. addAttrs('textarea');
  4030. addAttrs('h1 h2 h3 h4 h5 h6 div p legend caption', 'align');
  4031. addAttrs('ul', 'type compact');
  4032. addAttrs('li', 'type');
  4033. addAttrs('ol dl menu dir', 'compact');
  4034. addAttrs('pre', 'width xml:space');
  4035. addAttrs('hr', 'align noshade size width');
  4036. addAttrs('isindex', 'prompt');
  4037. addAttrs('table', 'summary width frame rules cellspacing cellpadding align bgcolor');
  4038. addAttrs('col', 'width align char charoff valign');
  4039. addAttrs('colgroup', 'width align char charoff valign');
  4040. addAttrs('thead', 'align char charoff valign');
  4041. addAttrs('tr', 'align char charoff valign bgcolor');
  4042. addAttrs('th', 'axis align char charoff valign nowrap bgcolor width height');
  4043. addAttrs('form', 'accept');
  4044. addAttrs('td', 'abbr axis scope align char charoff valign nowrap bgcolor width height');
  4045. addAttrs('tfoot', 'align char charoff valign');
  4046. addAttrs('tbody', 'align char charoff valign');
  4047. addAttrs('area', 'nohref');
  4048. addAttrs('body', 'background bgcolor text link vlink alink');
  4049. }
  4050. if (type !== 'html4') {
  4051. addAttrs('input button select textarea', 'autofocus');
  4052. addAttrs('input textarea', 'placeholder');
  4053. addAttrs('a', 'download');
  4054. addAttrs('link script img', 'crossorigin');
  4055. addAttrs('img', 'loading');
  4056. addAttrs('iframe', 'sandbox seamless allowfullscreen loading');
  4057. }
  4058. each$3(split('a form meter progress dfn'), function (name) {
  4059. if (schema[name]) {
  4060. delete schema[name].children[name];
  4061. }
  4062. });
  4063. delete schema.caption.children.table;
  4064. delete schema.script;
  4065. mapCache[type] = schema;
  4066. return schema;
  4067. };
  4068. var compileElementMap = function (value, mode) {
  4069. var styles;
  4070. if (value) {
  4071. styles = {};
  4072. if (typeof value === 'string') {
  4073. value = { '*': value };
  4074. }
  4075. each$3(value, function (value, key) {
  4076. styles[key] = styles[key.toUpperCase()] = mode === 'map' ? makeMap$2(value, /[, ]/) : explode$1(value, /[, ]/);
  4077. });
  4078. }
  4079. return styles;
  4080. };
  4081. function Schema(settings) {
  4082. var elements = {};
  4083. var children = {};
  4084. var patternElements = [];
  4085. var customElementsMap = {}, specialElements = {};
  4086. var createLookupTable = function (option, defaultValue, extendWith) {
  4087. var value = settings[option];
  4088. if (!value) {
  4089. value = mapCache[option];
  4090. if (!value) {
  4091. value = makeMap$2(defaultValue, ' ', makeMap$2(defaultValue.toUpperCase(), ' '));
  4092. value = extend$1(value, extendWith);
  4093. mapCache[option] = value;
  4094. }
  4095. } else {
  4096. value = makeMap$2(value, /[, ]/, makeMap$2(value.toUpperCase(), /[, ]/));
  4097. }
  4098. return value;
  4099. };
  4100. settings = settings || {};
  4101. var schemaItems = compileSchema(settings.schema);
  4102. if (settings.verify_html === false) {
  4103. settings.valid_elements = '*[*]';
  4104. }
  4105. var validStyles = compileElementMap(settings.valid_styles);
  4106. var invalidStyles = compileElementMap(settings.invalid_styles, 'map');
  4107. var validClasses = compileElementMap(settings.valid_classes, 'map');
  4108. var whiteSpaceElementsMap = createLookupTable('whitespace_elements', 'pre script noscript style textarea video audio iframe object code');
  4109. var selfClosingElementsMap = createLookupTable('self_closing_elements', 'colgroup dd dt li option p td tfoot th thead tr');
  4110. var shortEndedElementsMap = createLookupTable('short_ended_elements', 'area base basefont br col frame hr img input isindex link ' + 'meta param embed source wbr track');
  4111. var boolAttrMap = createLookupTable('boolean_attributes', 'checked compact declare defer disabled ismap multiple nohref noresize ' + 'noshade nowrap readonly selected autoplay loop controls');
  4112. var nonEmptyOrMoveCaretBeforeOnEnter = 'td th iframe video audio object script code';
  4113. var nonEmptyElementsMap = createLookupTable('non_empty_elements', nonEmptyOrMoveCaretBeforeOnEnter + ' pre', shortEndedElementsMap);
  4114. var moveCaretBeforeOnEnterElementsMap = createLookupTable('move_caret_before_on_enter_elements', nonEmptyOrMoveCaretBeforeOnEnter + ' table', shortEndedElementsMap);
  4115. var textBlockElementsMap = createLookupTable('text_block_elements', 'h1 h2 h3 h4 h5 h6 p div address pre form ' + 'blockquote center dir fieldset header footer article section hgroup aside main nav figure');
  4116. var blockElementsMap = createLookupTable('block_elements', 'hr table tbody thead tfoot ' + 'th tr td li ol ul caption dl dt dd noscript menu isindex option ' + 'datalist select optgroup figcaption details summary', textBlockElementsMap);
  4117. var textInlineElementsMap = createLookupTable('text_inline_elements', 'span strong b em i font strike u var cite ' + 'dfn code mark q sup sub samp');
  4118. each$3((settings.special || 'script noscript iframe noframes noembed title style textarea xmp').split(' '), function (name) {
  4119. specialElements[name] = new RegExp('</' + name + '[^>]*>', 'gi');
  4120. });
  4121. var patternToRegExp = function (str) {
  4122. return new RegExp('^' + str.replace(/([?+*])/g, '.$1') + '$');
  4123. };
  4124. var addValidElements = function (validElements) {
  4125. var ei, el, ai, al, matches, element, attr, attrData, elementName, attrName, attrType, attributes, attributesOrder, prefix, outputName, globalAttributes, globalAttributesOrder, value;
  4126. var elementRuleRegExp = /^([#+\-])?([^\[!\/]+)(?:\/([^\[!]+))?(?:(!?)\[([^\]]+)])?$/, attrRuleRegExp = /^([!\-])?(\w+[\\:]:\w+|[^=:<]+)?(?:([=:<])(.*))?$/, hasPatternsRegExp = /[*?+]/;
  4127. if (validElements) {
  4128. var validElementsArr = split(validElements, ',');
  4129. if (elements['@']) {
  4130. globalAttributes = elements['@'].attributes;
  4131. globalAttributesOrder = elements['@'].attributesOrder;
  4132. }
  4133. for (ei = 0, el = validElementsArr.length; ei < el; ei++) {
  4134. matches = elementRuleRegExp.exec(validElementsArr[ei]);
  4135. if (matches) {
  4136. prefix = matches[1];
  4137. elementName = matches[2];
  4138. outputName = matches[3];
  4139. attrData = matches[5];
  4140. attributes = {};
  4141. attributesOrder = [];
  4142. element = {
  4143. attributes: attributes,
  4144. attributesOrder: attributesOrder
  4145. };
  4146. if (prefix === '#') {
  4147. element.paddEmpty = true;
  4148. }
  4149. if (prefix === '-') {
  4150. element.removeEmpty = true;
  4151. }
  4152. if (matches[4] === '!') {
  4153. element.removeEmptyAttrs = true;
  4154. }
  4155. if (globalAttributes) {
  4156. each$1(globalAttributes, function (value, key) {
  4157. attributes[key] = value;
  4158. });
  4159. attributesOrder.push.apply(attributesOrder, globalAttributesOrder);
  4160. }
  4161. if (attrData) {
  4162. attrData = split(attrData, '|');
  4163. for (ai = 0, al = attrData.length; ai < al; ai++) {
  4164. matches = attrRuleRegExp.exec(attrData[ai]);
  4165. if (matches) {
  4166. attr = {};
  4167. attrType = matches[1];
  4168. attrName = matches[2].replace(/[\\:]:/g, ':');
  4169. prefix = matches[3];
  4170. value = matches[4];
  4171. if (attrType === '!') {
  4172. element.attributesRequired = element.attributesRequired || [];
  4173. element.attributesRequired.push(attrName);
  4174. attr.required = true;
  4175. }
  4176. if (attrType === '-') {
  4177. delete attributes[attrName];
  4178. attributesOrder.splice(inArray(attributesOrder, attrName), 1);
  4179. continue;
  4180. }
  4181. if (prefix) {
  4182. if (prefix === '=') {
  4183. element.attributesDefault = element.attributesDefault || [];
  4184. element.attributesDefault.push({
  4185. name: attrName,
  4186. value: value
  4187. });
  4188. attr.defaultValue = value;
  4189. }
  4190. if (prefix === ':') {
  4191. element.attributesForced = element.attributesForced || [];
  4192. element.attributesForced.push({
  4193. name: attrName,
  4194. value: value
  4195. });
  4196. attr.forcedValue = value;
  4197. }
  4198. if (prefix === '<') {
  4199. attr.validValues = makeMap$2(value, '?');
  4200. }
  4201. }
  4202. if (hasPatternsRegExp.test(attrName)) {
  4203. element.attributePatterns = element.attributePatterns || [];
  4204. attr.pattern = patternToRegExp(attrName);
  4205. element.attributePatterns.push(attr);
  4206. } else {
  4207. if (!attributes[attrName]) {
  4208. attributesOrder.push(attrName);
  4209. }
  4210. attributes[attrName] = attr;
  4211. }
  4212. }
  4213. }
  4214. }
  4215. if (!globalAttributes && elementName === '@') {
  4216. globalAttributes = attributes;
  4217. globalAttributesOrder = attributesOrder;
  4218. }
  4219. if (outputName) {
  4220. element.outputName = elementName;
  4221. elements[outputName] = element;
  4222. }
  4223. if (hasPatternsRegExp.test(elementName)) {
  4224. element.pattern = patternToRegExp(elementName);
  4225. patternElements.push(element);
  4226. } else {
  4227. elements[elementName] = element;
  4228. }
  4229. }
  4230. }
  4231. }
  4232. };
  4233. var setValidElements = function (validElements) {
  4234. elements = {};
  4235. patternElements = [];
  4236. addValidElements(validElements);
  4237. each$3(schemaItems, function (element, name) {
  4238. children[name] = element.children;
  4239. });
  4240. };
  4241. var addCustomElements = function (customElements) {
  4242. var customElementRegExp = /^(~)?(.+)$/;
  4243. if (customElements) {
  4244. mapCache.text_block_elements = mapCache.block_elements = null;
  4245. each$3(split(customElements, ','), function (rule) {
  4246. var matches = customElementRegExp.exec(rule), inline = matches[1] === '~', cloneName = inline ? 'span' : 'div', name = matches[2];
  4247. children[name] = children[cloneName];
  4248. customElementsMap[name] = cloneName;
  4249. if (!inline) {
  4250. blockElementsMap[name.toUpperCase()] = {};
  4251. blockElementsMap[name] = {};
  4252. }
  4253. if (!elements[name]) {
  4254. var customRule = elements[cloneName];
  4255. customRule = extend$1({}, customRule);
  4256. delete customRule.removeEmptyAttrs;
  4257. delete customRule.removeEmpty;
  4258. elements[name] = customRule;
  4259. }
  4260. each$3(children, function (element, elmName) {
  4261. if (element[cloneName]) {
  4262. children[elmName] = element = extend$1({}, children[elmName]);
  4263. element[name] = element[cloneName];
  4264. }
  4265. });
  4266. });
  4267. }
  4268. };
  4269. var addValidChildren = function (validChildren) {
  4270. var childRuleRegExp = /^([+\-]?)([A-Za-z0-9_\-.\u00b7\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u037d\u037f-\u1fff\u200c-\u200d\u203f-\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]+)\[([^\]]+)]$/;
  4271. mapCache[settings.schema] = null;
  4272. if (validChildren) {
  4273. each$3(split(validChildren, ','), function (rule) {
  4274. var matches = childRuleRegExp.exec(rule);
  4275. var parent, prefix;
  4276. if (matches) {
  4277. prefix = matches[1];
  4278. if (prefix) {
  4279. parent = children[matches[2]];
  4280. } else {
  4281. parent = children[matches[2]] = { '#comment': {} };
  4282. }
  4283. parent = children[matches[2]];
  4284. each$3(split(matches[3], '|'), function (child) {
  4285. if (prefix === '-') {
  4286. delete parent[child];
  4287. } else {
  4288. parent[child] = {};
  4289. }
  4290. });
  4291. }
  4292. });
  4293. }
  4294. };
  4295. var getElementRule = function (name) {
  4296. var element = elements[name], i;
  4297. if (element) {
  4298. return element;
  4299. }
  4300. i = patternElements.length;
  4301. while (i--) {
  4302. element = patternElements[i];
  4303. if (element.pattern.test(name)) {
  4304. return element;
  4305. }
  4306. }
  4307. };
  4308. if (!settings.valid_elements) {
  4309. each$3(schemaItems, function (element, name) {
  4310. elements[name] = {
  4311. attributes: element.attributes,
  4312. attributesOrder: element.attributesOrder
  4313. };
  4314. children[name] = element.children;
  4315. });
  4316. if (settings.schema !== 'html5') {
  4317. each$3(split('strong/b em/i'), function (item) {
  4318. var items = split(item, '/');
  4319. elements[items[1]].outputName = items[0];
  4320. });
  4321. }
  4322. each$3(split('ol ul sub sup blockquote span font a table tbody tr strong em b i'), function (name) {
  4323. if (elements[name]) {
  4324. elements[name].removeEmpty = true;
  4325. }
  4326. });
  4327. each$3(split('p h1 h2 h3 h4 h5 h6 th td pre div address caption li'), function (name) {
  4328. elements[name].paddEmpty = true;
  4329. });
  4330. each$3(split('span'), function (name) {
  4331. elements[name].removeEmptyAttrs = true;
  4332. });
  4333. } else {
  4334. setValidElements(settings.valid_elements);
  4335. }
  4336. addCustomElements(settings.custom_elements);
  4337. addValidChildren(settings.valid_children);
  4338. addValidElements(settings.extended_valid_elements);
  4339. addValidChildren('+ol[ul|ol],+ul[ul|ol]');
  4340. each$3({
  4341. dd: 'dl',
  4342. dt: 'dl',
  4343. li: 'ul ol',
  4344. td: 'tr',
  4345. th: 'tr',
  4346. tr: 'tbody thead tfoot',
  4347. tbody: 'table',
  4348. thead: 'table',
  4349. tfoot: 'table',
  4350. legend: 'fieldset',
  4351. area: 'map',
  4352. param: 'video audio object'
  4353. }, function (parents, item) {
  4354. if (elements[item]) {
  4355. elements[item].parentsRequired = split(parents);
  4356. }
  4357. });
  4358. if (settings.invalid_elements) {
  4359. each$3(explode$1(settings.invalid_elements), function (item) {
  4360. if (elements[item]) {
  4361. delete elements[item];
  4362. }
  4363. });
  4364. }
  4365. if (!getElementRule('span')) {
  4366. addValidElements('span[!data-mce-type|*]');
  4367. }
  4368. var getValidStyles = function () {
  4369. return validStyles;
  4370. };
  4371. var getInvalidStyles = function () {
  4372. return invalidStyles;
  4373. };
  4374. var getValidClasses = function () {
  4375. return validClasses;
  4376. };
  4377. var getBoolAttrs = function () {
  4378. return boolAttrMap;
  4379. };
  4380. var getBlockElements = function () {
  4381. return blockElementsMap;
  4382. };
  4383. var getTextBlockElements = function () {
  4384. return textBlockElementsMap;
  4385. };
  4386. var getTextInlineElements = function () {
  4387. return textInlineElementsMap;
  4388. };
  4389. var getShortEndedElements = function () {
  4390. return shortEndedElementsMap;
  4391. };
  4392. var getSelfClosingElements = function () {
  4393. return selfClosingElementsMap;
  4394. };
  4395. var getNonEmptyElements = function () {
  4396. return nonEmptyElementsMap;
  4397. };
  4398. var getMoveCaretBeforeOnEnterElements = function () {
  4399. return moveCaretBeforeOnEnterElementsMap;
  4400. };
  4401. var getWhiteSpaceElements = function () {
  4402. return whiteSpaceElementsMap;
  4403. };
  4404. var getSpecialElements = function () {
  4405. return specialElements;
  4406. };
  4407. var isValidChild = function (name, child) {
  4408. var parent = children[name.toLowerCase()];
  4409. return !!(parent && parent[child.toLowerCase()]);
  4410. };
  4411. var isValid = function (name, attr) {
  4412. var attrPatterns, i;
  4413. var rule = getElementRule(name);
  4414. if (rule) {
  4415. if (attr) {
  4416. if (rule.attributes[attr]) {
  4417. return true;
  4418. }
  4419. attrPatterns = rule.attributePatterns;
  4420. if (attrPatterns) {
  4421. i = attrPatterns.length;
  4422. while (i--) {
  4423. if (attrPatterns[i].pattern.test(name)) {
  4424. return true;
  4425. }
  4426. }
  4427. }
  4428. } else {
  4429. return true;
  4430. }
  4431. }
  4432. return false;
  4433. };
  4434. var getCustomElements = function () {
  4435. return customElementsMap;
  4436. };
  4437. return {
  4438. children: children,
  4439. elements: elements,
  4440. getValidStyles: getValidStyles,
  4441. getValidClasses: getValidClasses,
  4442. getBlockElements: getBlockElements,
  4443. getInvalidStyles: getInvalidStyles,
  4444. getShortEndedElements: getShortEndedElements,
  4445. getTextBlockElements: getTextBlockElements,
  4446. getTextInlineElements: getTextInlineElements,
  4447. getBoolAttrs: getBoolAttrs,
  4448. getElementRule: getElementRule,
  4449. getSelfClosingElements: getSelfClosingElements,
  4450. getNonEmptyElements: getNonEmptyElements,
  4451. getMoveCaretBeforeOnEnterElements: getMoveCaretBeforeOnEnterElements,
  4452. getWhiteSpaceElements: getWhiteSpaceElements,
  4453. getSpecialElements: getSpecialElements,
  4454. isValidChild: isValidChild,
  4455. isValid: isValid,
  4456. getCustomElements: getCustomElements,
  4457. addValidElements: addValidElements,
  4458. setValidElements: setValidElements,
  4459. addCustomElements: addCustomElements,
  4460. addValidChildren: addValidChildren
  4461. };
  4462. }
  4463. var toHex = function (match, r, g, b) {
  4464. var hex = function (val) {
  4465. val = parseInt(val, 10).toString(16);
  4466. return val.length > 1 ? val : '0' + val;
  4467. };
  4468. return '#' + hex(r) + hex(g) + hex(b);
  4469. };
  4470. var Styles = function (settings, schema) {
  4471. var rgbRegExp = /rgb\s*\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\s*\)/gi;
  4472. var urlOrStrRegExp = /(?:url(?:(?:\(\s*\"([^\"]+)\"\s*\))|(?:\(\s*\'([^\']+)\'\s*\))|(?:\(\s*([^)\s]+)\s*\))))|(?:\'([^\']+)\')|(?:\"([^\"]+)\")/gi;
  4473. var styleRegExp = /\s*([^:]+):\s*([^;]+);?/g;
  4474. var trimRightRegExp = /\s+$/;
  4475. var i;
  4476. var encodingLookup = {};
  4477. var validStyles;
  4478. var invalidStyles;
  4479. var invisibleChar = zeroWidth;
  4480. settings = settings || {};
  4481. if (schema) {
  4482. validStyles = schema.getValidStyles();
  4483. invalidStyles = schema.getInvalidStyles();
  4484. }
  4485. var encodingItems = ('\\" \\\' \\; \\: ; : ' + invisibleChar).split(' ');
  4486. for (i = 0; i < encodingItems.length; i++) {
  4487. encodingLookup[encodingItems[i]] = invisibleChar + i;
  4488. encodingLookup[invisibleChar + i] = encodingItems[i];
  4489. }
  4490. return {
  4491. toHex: function (color) {
  4492. return color.replace(rgbRegExp, toHex);
  4493. },
  4494. parse: function (css) {
  4495. var styles = {};
  4496. var matches, name, value, isEncoded;
  4497. var urlConverter = settings.url_converter;
  4498. var urlConverterScope = settings.url_converter_scope || this;
  4499. var compress = function (prefix, suffix, noJoin) {
  4500. var top = styles[prefix + '-top' + suffix];
  4501. if (!top) {
  4502. return;
  4503. }
  4504. var right = styles[prefix + '-right' + suffix];
  4505. if (!right) {
  4506. return;
  4507. }
  4508. var bottom = styles[prefix + '-bottom' + suffix];
  4509. if (!bottom) {
  4510. return;
  4511. }
  4512. var left = styles[prefix + '-left' + suffix];
  4513. if (!left) {
  4514. return;
  4515. }
  4516. var box = [
  4517. top,
  4518. right,
  4519. bottom,
  4520. left
  4521. ];
  4522. i = box.length - 1;
  4523. while (i--) {
  4524. if (box[i] !== box[i + 1]) {
  4525. break;
  4526. }
  4527. }
  4528. if (i > -1 && noJoin) {
  4529. return;
  4530. }
  4531. styles[prefix + suffix] = i === -1 ? box[0] : box.join(' ');
  4532. delete styles[prefix + '-top' + suffix];
  4533. delete styles[prefix + '-right' + suffix];
  4534. delete styles[prefix + '-bottom' + suffix];
  4535. delete styles[prefix + '-left' + suffix];
  4536. };
  4537. var canCompress = function (key) {
  4538. var value = styles[key], i;
  4539. if (!value) {
  4540. return;
  4541. }
  4542. value = value.split(' ');
  4543. i = value.length;
  4544. while (i--) {
  4545. if (value[i] !== value[0]) {
  4546. return false;
  4547. }
  4548. }
  4549. styles[key] = value[0];
  4550. return true;
  4551. };
  4552. var compress2 = function (target, a, b, c) {
  4553. if (!canCompress(a)) {
  4554. return;
  4555. }
  4556. if (!canCompress(b)) {
  4557. return;
  4558. }
  4559. if (!canCompress(c)) {
  4560. return;
  4561. }
  4562. styles[target] = styles[a] + ' ' + styles[b] + ' ' + styles[c];
  4563. delete styles[a];
  4564. delete styles[b];
  4565. delete styles[c];
  4566. };
  4567. var encode = function (str) {
  4568. isEncoded = true;
  4569. return encodingLookup[str];
  4570. };
  4571. var decode = function (str, keepSlashes) {
  4572. if (isEncoded) {
  4573. str = str.replace(/\uFEFF[0-9]/g, function (str) {
  4574. return encodingLookup[str];
  4575. });
  4576. }
  4577. if (!keepSlashes) {
  4578. str = str.replace(/\\([\'\";:])/g, '$1');
  4579. }
  4580. return str;
  4581. };
  4582. var decodeSingleHexSequence = function (escSeq) {
  4583. return String.fromCharCode(parseInt(escSeq.slice(1), 16));
  4584. };
  4585. var decodeHexSequences = function (value) {
  4586. return value.replace(/\\[0-9a-f]+/gi, decodeSingleHexSequence);
  4587. };
  4588. var processUrl = function (match, url, url2, url3, str, str2) {
  4589. str = str || str2;
  4590. if (str) {
  4591. str = decode(str);
  4592. return '\'' + str.replace(/\'/g, '\\\'') + '\'';
  4593. }
  4594. url = decode(url || url2 || url3);
  4595. if (!settings.allow_script_urls) {
  4596. var scriptUrl = url.replace(/[\s\r\n]+/g, '');
  4597. if (/(java|vb)script:/i.test(scriptUrl)) {
  4598. return '';
  4599. }
  4600. if (!settings.allow_svg_data_urls && /^data:image\/svg/i.test(scriptUrl)) {
  4601. return '';
  4602. }
  4603. }
  4604. if (urlConverter) {
  4605. url = urlConverter.call(urlConverterScope, url, 'style');
  4606. }
  4607. return 'url(\'' + url.replace(/\'/g, '\\\'') + '\')';
  4608. };
  4609. if (css) {
  4610. css = css.replace(/[\u0000-\u001F]/g, '');
  4611. css = css.replace(/\\[\"\';:\uFEFF]/g, encode).replace(/\"[^\"]+\"|\'[^\']+\'/g, function (str) {
  4612. return str.replace(/[;:]/g, encode);
  4613. });
  4614. while (matches = styleRegExp.exec(css)) {
  4615. styleRegExp.lastIndex = matches.index + matches[0].length;
  4616. name = matches[1].replace(trimRightRegExp, '').toLowerCase();
  4617. value = matches[2].replace(trimRightRegExp, '');
  4618. if (name && value) {
  4619. name = decodeHexSequences(name);
  4620. value = decodeHexSequences(value);
  4621. if (name.indexOf(invisibleChar) !== -1 || name.indexOf('"') !== -1) {
  4622. continue;
  4623. }
  4624. if (!settings.allow_script_urls && (name === 'behavior' || /expression\s*\(|\/\*|\*\//.test(value))) {
  4625. continue;
  4626. }
  4627. if (name === 'font-weight' && value === '700') {
  4628. value = 'bold';
  4629. } else if (name === 'color' || name === 'background-color') {
  4630. value = value.toLowerCase();
  4631. }
  4632. value = value.replace(rgbRegExp, toHex);
  4633. value = value.replace(urlOrStrRegExp, processUrl);
  4634. styles[name] = isEncoded ? decode(value, true) : value;
  4635. }
  4636. }
  4637. compress('border', '', true);
  4638. compress('border', '-width');
  4639. compress('border', '-color');
  4640. compress('border', '-style');
  4641. compress('padding', '');
  4642. compress('margin', '');
  4643. compress2('border', 'border-width', 'border-style', 'border-color');
  4644. if (styles.border === 'medium none') {
  4645. delete styles.border;
  4646. }
  4647. if (styles['border-image'] === 'none') {
  4648. delete styles['border-image'];
  4649. }
  4650. }
  4651. return styles;
  4652. },
  4653. serialize: function (styles, elementName) {
  4654. var css = '';
  4655. var serializeStyles = function (name) {
  4656. var value;
  4657. var styleList = validStyles[name];
  4658. if (styleList) {
  4659. for (var i_1 = 0, l = styleList.length; i_1 < l; i_1++) {
  4660. name = styleList[i_1];
  4661. value = styles[name];
  4662. if (value) {
  4663. css += (css.length > 0 ? ' ' : '') + name + ': ' + value + ';';
  4664. }
  4665. }
  4666. }
  4667. };
  4668. var isValid = function (name, elementName) {
  4669. var styleMap = invalidStyles['*'];
  4670. if (styleMap && styleMap[name]) {
  4671. return false;
  4672. }
  4673. styleMap = invalidStyles[elementName];
  4674. return !(styleMap && styleMap[name]);
  4675. };
  4676. if (elementName && validStyles) {
  4677. serializeStyles('*');
  4678. serializeStyles(elementName);
  4679. } else {
  4680. each$1(styles, function (value, name) {
  4681. if (value && (!invalidStyles || isValid(name, elementName))) {
  4682. css += (css.length > 0 ? ' ' : '') + name + ': ' + value + ';';
  4683. }
  4684. });
  4685. }
  4686. return css;
  4687. }
  4688. };
  4689. };
  4690. var eventExpandoPrefix = 'mce-data-';
  4691. var mouseEventRe = /^(?:mouse|contextmenu)|click/;
  4692. var deprecated = {
  4693. keyLocation: 1,
  4694. layerX: 1,
  4695. layerY: 1,
  4696. returnValue: 1,
  4697. webkitMovementX: 1,
  4698. webkitMovementY: 1,
  4699. keyIdentifier: 1,
  4700. mozPressure: 1
  4701. };
  4702. var hasIsDefaultPrevented = function (event) {
  4703. return event.isDefaultPrevented === returnTrue || event.isDefaultPrevented === returnFalse;
  4704. };
  4705. var returnFalse = function () {
  4706. return false;
  4707. };
  4708. var returnTrue = function () {
  4709. return true;
  4710. };
  4711. var addEvent = function (target, name, callback, capture) {
  4712. if (target.addEventListener) {
  4713. target.addEventListener(name, callback, capture || false);
  4714. } else if (target.attachEvent) {
  4715. target.attachEvent('on' + name, callback);
  4716. }
  4717. };
  4718. var removeEvent = function (target, name, callback, capture) {
  4719. if (target.removeEventListener) {
  4720. target.removeEventListener(name, callback, capture || false);
  4721. } else if (target.detachEvent) {
  4722. target.detachEvent('on' + name, callback);
  4723. }
  4724. };
  4725. var isMouseEvent = function (event) {
  4726. return mouseEventRe.test(event.type);
  4727. };
  4728. var fix = function (originalEvent, data) {
  4729. var name;
  4730. var event = data || {};
  4731. for (name in originalEvent) {
  4732. if (!deprecated[name]) {
  4733. event[name] = originalEvent[name];
  4734. }
  4735. }
  4736. if (!event.target) {
  4737. event.target = event.srcElement || document;
  4738. }
  4739. if (event.composedPath) {
  4740. event.composedPath = function () {
  4741. return originalEvent.composedPath();
  4742. };
  4743. }
  4744. if (originalEvent && isMouseEvent(originalEvent) && originalEvent.pageX === undefined && originalEvent.clientX !== undefined) {
  4745. var eventDoc = event.target.ownerDocument || document;
  4746. var doc = eventDoc.documentElement;
  4747. var body = eventDoc.body;
  4748. event.pageX = originalEvent.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
  4749. event.pageY = originalEvent.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0);
  4750. }
  4751. event.preventDefault = function () {
  4752. event.isDefaultPrevented = returnTrue;
  4753. if (originalEvent) {
  4754. if (originalEvent.preventDefault) {
  4755. originalEvent.preventDefault();
  4756. } else {
  4757. originalEvent.returnValue = false;
  4758. }
  4759. }
  4760. };
  4761. event.stopPropagation = function () {
  4762. event.isPropagationStopped = returnTrue;
  4763. if (originalEvent) {
  4764. if (originalEvent.stopPropagation) {
  4765. originalEvent.stopPropagation();
  4766. } else {
  4767. originalEvent.cancelBubble = true;
  4768. }
  4769. }
  4770. };
  4771. event.stopImmediatePropagation = function () {
  4772. event.isImmediatePropagationStopped = returnTrue;
  4773. event.stopPropagation();
  4774. };
  4775. if (hasIsDefaultPrevented(event) === false) {
  4776. event.isDefaultPrevented = returnFalse;
  4777. event.isPropagationStopped = returnFalse;
  4778. event.isImmediatePropagationStopped = returnFalse;
  4779. }
  4780. if (typeof event.metaKey === 'undefined') {
  4781. event.metaKey = false;
  4782. }
  4783. return event;
  4784. };
  4785. var bindOnReady = function (win, callback, eventUtils) {
  4786. var doc = win.document, event = { type: 'ready' };
  4787. if (eventUtils.domLoaded) {
  4788. callback(event);
  4789. return;
  4790. }
  4791. var isDocReady = function () {
  4792. return doc.readyState === 'complete' || doc.readyState === 'interactive' && doc.body;
  4793. };
  4794. var readyHandler = function () {
  4795. removeEvent(win, 'DOMContentLoaded', readyHandler);
  4796. removeEvent(win, 'load', readyHandler);
  4797. if (!eventUtils.domLoaded) {
  4798. eventUtils.domLoaded = true;
  4799. callback(event);
  4800. }
  4801. };
  4802. if (isDocReady()) {
  4803. readyHandler();
  4804. } else {
  4805. addEvent(win, 'DOMContentLoaded', readyHandler);
  4806. }
  4807. addEvent(win, 'load', readyHandler);
  4808. };
  4809. var EventUtils = function () {
  4810. function EventUtils() {
  4811. this.domLoaded = false;
  4812. this.events = {};
  4813. this.count = 1;
  4814. this.expando = eventExpandoPrefix + (+new Date()).toString(32);
  4815. this.hasMouseEnterLeave = 'onmouseenter' in document.documentElement;
  4816. this.hasFocusIn = 'onfocusin' in document.documentElement;
  4817. this.count = 1;
  4818. }
  4819. EventUtils.prototype.bind = function (target, names, callback, scope) {
  4820. var self = this;
  4821. var id, callbackList, i, name, fakeName, nativeHandler, capture;
  4822. var win = window;
  4823. var defaultNativeHandler = function (evt) {
  4824. self.executeHandlers(fix(evt || win.event), id);
  4825. };
  4826. if (!target || target.nodeType === 3 || target.nodeType === 8) {
  4827. return;
  4828. }
  4829. if (!target[self.expando]) {
  4830. id = self.count++;
  4831. target[self.expando] = id;
  4832. self.events[id] = {};
  4833. } else {
  4834. id = target[self.expando];
  4835. }
  4836. scope = scope || target;
  4837. var namesList = names.split(' ');
  4838. i = namesList.length;
  4839. while (i--) {
  4840. name = namesList[i];
  4841. nativeHandler = defaultNativeHandler;
  4842. fakeName = capture = false;
  4843. if (name === 'DOMContentLoaded') {
  4844. name = 'ready';
  4845. }
  4846. if (self.domLoaded && name === 'ready' && target.readyState === 'complete') {
  4847. callback.call(scope, fix({ type: name }));
  4848. continue;
  4849. }
  4850. if (!self.hasMouseEnterLeave) {
  4851. fakeName = self.mouseEnterLeave[name];
  4852. if (fakeName) {
  4853. nativeHandler = function (evt) {
  4854. var current = evt.currentTarget;
  4855. var related = evt.relatedTarget;
  4856. if (related && current.contains) {
  4857. related = current.contains(related);
  4858. } else {
  4859. while (related && related !== current) {
  4860. related = related.parentNode;
  4861. }
  4862. }
  4863. if (!related) {
  4864. evt = fix(evt || win.event);
  4865. evt.type = evt.type === 'mouseout' ? 'mouseleave' : 'mouseenter';
  4866. evt.target = current;
  4867. self.executeHandlers(evt, id);
  4868. }
  4869. };
  4870. }
  4871. }
  4872. if (!self.hasFocusIn && (name === 'focusin' || name === 'focusout')) {
  4873. capture = true;
  4874. fakeName = name === 'focusin' ? 'focus' : 'blur';
  4875. nativeHandler = function (evt) {
  4876. evt = fix(evt || win.event);
  4877. evt.type = evt.type === 'focus' ? 'focusin' : 'focusout';
  4878. self.executeHandlers(evt, id);
  4879. };
  4880. }
  4881. callbackList = self.events[id][name];
  4882. if (!callbackList) {
  4883. self.events[id][name] = callbackList = [{
  4884. func: callback,
  4885. scope: scope
  4886. }];
  4887. callbackList.fakeName = fakeName;
  4888. callbackList.capture = capture;
  4889. callbackList.nativeHandler = nativeHandler;
  4890. if (name === 'ready') {
  4891. bindOnReady(target, nativeHandler, self);
  4892. } else {
  4893. addEvent(target, fakeName || name, nativeHandler, capture);
  4894. }
  4895. } else {
  4896. if (name === 'ready' && self.domLoaded) {
  4897. callback(fix({ type: name }));
  4898. } else {
  4899. callbackList.push({
  4900. func: callback,
  4901. scope: scope
  4902. });
  4903. }
  4904. }
  4905. }
  4906. target = callbackList = null;
  4907. return callback;
  4908. };
  4909. EventUtils.prototype.unbind = function (target, names, callback) {
  4910. var callbackList, i, ci, name, eventMap;
  4911. if (!target || target.nodeType === 3 || target.nodeType === 8) {
  4912. return this;
  4913. }
  4914. var id = target[this.expando];
  4915. if (id) {
  4916. eventMap = this.events[id];
  4917. if (names) {
  4918. var namesList = names.split(' ');
  4919. i = namesList.length;
  4920. while (i--) {
  4921. name = namesList[i];
  4922. callbackList = eventMap[name];
  4923. if (callbackList) {
  4924. if (callback) {
  4925. ci = callbackList.length;
  4926. while (ci--) {
  4927. if (callbackList[ci].func === callback) {
  4928. var nativeHandler = callbackList.nativeHandler;
  4929. var fakeName = callbackList.fakeName, capture = callbackList.capture;
  4930. callbackList = callbackList.slice(0, ci).concat(callbackList.slice(ci + 1));
  4931. callbackList.nativeHandler = nativeHandler;
  4932. callbackList.fakeName = fakeName;
  4933. callbackList.capture = capture;
  4934. eventMap[name] = callbackList;
  4935. }
  4936. }
  4937. }
  4938. if (!callback || callbackList.length === 0) {
  4939. delete eventMap[name];
  4940. removeEvent(target, callbackList.fakeName || name, callbackList.nativeHandler, callbackList.capture);
  4941. }
  4942. }
  4943. }
  4944. } else {
  4945. each$1(eventMap, function (callbackList, name) {
  4946. removeEvent(target, callbackList.fakeName || name, callbackList.nativeHandler, callbackList.capture);
  4947. });
  4948. eventMap = {};
  4949. }
  4950. for (name in eventMap) {
  4951. if (has(eventMap, name)) {
  4952. return this;
  4953. }
  4954. }
  4955. delete this.events[id];
  4956. try {
  4957. delete target[this.expando];
  4958. } catch (ex) {
  4959. target[this.expando] = null;
  4960. }
  4961. }
  4962. return this;
  4963. };
  4964. EventUtils.prototype.fire = function (target, name, args) {
  4965. var id;
  4966. if (!target || target.nodeType === 3 || target.nodeType === 8) {
  4967. return this;
  4968. }
  4969. var event = fix(null, args);
  4970. event.type = name;
  4971. event.target = target;
  4972. do {
  4973. id = target[this.expando];
  4974. if (id) {
  4975. this.executeHandlers(event, id);
  4976. }
  4977. target = target.parentNode || target.ownerDocument || target.defaultView || target.parentWindow;
  4978. } while (target && !event.isPropagationStopped());
  4979. return this;
  4980. };
  4981. EventUtils.prototype.clean = function (target) {
  4982. var i, children;
  4983. if (!target || target.nodeType === 3 || target.nodeType === 8) {
  4984. return this;
  4985. }
  4986. if (target[this.expando]) {
  4987. this.unbind(target);
  4988. }
  4989. if (!target.getElementsByTagName) {
  4990. target = target.document;
  4991. }
  4992. if (target && target.getElementsByTagName) {
  4993. this.unbind(target);
  4994. children = target.getElementsByTagName('*');
  4995. i = children.length;
  4996. while (i--) {
  4997. target = children[i];
  4998. if (target[this.expando]) {
  4999. this.unbind(target);
  5000. }
  5001. }
  5002. }
  5003. return this;
  5004. };
  5005. EventUtils.prototype.destroy = function () {
  5006. this.events = {};
  5007. };
  5008. EventUtils.prototype.cancel = function (e) {
  5009. if (e) {
  5010. e.preventDefault();
  5011. e.stopImmediatePropagation();
  5012. }
  5013. return false;
  5014. };
  5015. EventUtils.prototype.executeHandlers = function (evt, id) {
  5016. var container = this.events[id];
  5017. var callbackList = container && container[evt.type];
  5018. if (callbackList) {
  5019. for (var i = 0, l = callbackList.length; i < l; i++) {
  5020. var callback = callbackList[i];
  5021. if (callback && callback.func.call(callback.scope, evt) === false) {
  5022. evt.preventDefault();
  5023. }
  5024. if (evt.isImmediatePropagationStopped()) {
  5025. return;
  5026. }
  5027. }
  5028. }
  5029. };
  5030. EventUtils.Event = new EventUtils();
  5031. return EventUtils;
  5032. }();
  5033. var support, Expr, getText, isXML, tokenize, compile, select, outermostContext, sortInput, hasDuplicate, setDocument, document$1, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains$3, expando = 'sizzle' + -new Date(), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), sortOrder = function (a, b) {
  5034. if (a === b) {
  5035. hasDuplicate = true;
  5036. }
  5037. return 0;
  5038. }, strundefined = typeof undefined, MAX_NEGATIVE = 1 << 31, hasOwn = {}.hasOwnProperty, arr = [], pop = arr.pop, push_native = arr.push, push = arr.push, slice = arr.slice, indexOf$2 = arr.indexOf || function (elem) {
  5039. var i = 0, len = this.length;
  5040. for (; i < len; i++) {
  5041. if (this[i] === elem) {
  5042. return i;
  5043. }
  5044. }
  5045. return -1;
  5046. }, booleans = 'checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped', whitespace = '[\\x20\\t\\r\\n\\f]', identifier = '(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+', attributes = '\\[' + whitespace + '*(' + identifier + ')(?:' + whitespace + '*([*^$|!~]?=)' + whitespace + '*(?:\'((?:\\\\.|[^\\\\\'])*)\'|"((?:\\\\.|[^\\\\"])*)"|(' + identifier + '))|)' + whitespace + '*\\]', pseudos = ':(' + identifier + ')(?:\\((' + '(\'((?:\\\\.|[^\\\\\'])*)\'|"((?:\\\\.|[^\\\\"])*)")|' + '((?:\\\\.|[^\\\\()[\\]]|' + attributes + ')*)|' + '.*' + ')\\)|)', rtrim = new RegExp('^' + whitespace + '+|((?:^|[^\\\\])(?:\\\\.)*)' + whitespace + '+$', 'g'), rcomma = new RegExp('^' + whitespace + '*,' + whitespace + '*'), rcombinators = new RegExp('^' + whitespace + '*([>+~]|' + whitespace + ')' + whitespace + '*'), rattributeQuotes = new RegExp('=' + whitespace + '*([^\\]\'"]*?)' + whitespace + '*\\]', 'g'), rpseudo = new RegExp(pseudos), ridentifier = new RegExp('^' + identifier + '$'), matchExpr = {
  5047. ID: new RegExp('^#(' + identifier + ')'),
  5048. CLASS: new RegExp('^\\.(' + identifier + ')'),
  5049. TAG: new RegExp('^(' + identifier + '|[*])'),
  5050. ATTR: new RegExp('^' + attributes),
  5051. PSEUDO: new RegExp('^' + pseudos),
  5052. CHILD: new RegExp('^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(' + whitespace + '*(even|odd|(([+-]|)(\\d*)n|)' + whitespace + '*(?:([+-]|)' + whitespace + '*(\\d+)|))' + whitespace + '*\\)|)', 'i'),
  5053. bool: new RegExp('^(?:' + booleans + ')$', 'i'),
  5054. needsContext: new RegExp('^' + whitespace + '*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(' + whitespace + '*((?:-\\d)?\\d*)' + whitespace + '*\\)|)(?=[^-]|$)', 'i')
  5055. }, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rnative = /^[^{]+\{\s*\[native \w/, rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rsibling = /[+~]/, rescape = /'|\\/g, runescape = new RegExp('\\\\([\\da-f]{1,6}' + whitespace + '?|(' + whitespace + ')|.)', 'ig'), funescape = function (_, escaped, escapedWhitespace) {
  5056. var high = '0x' + escaped - 65536;
  5057. return high !== high || escapedWhitespace ? escaped : high < 0 ? String.fromCharCode(high + 65536) : String.fromCharCode(high >> 10 | 55296, high & 1023 | 56320);
  5058. };
  5059. try {
  5060. push.apply(arr = slice.call(preferredDoc.childNodes), preferredDoc.childNodes);
  5061. arr[preferredDoc.childNodes.length].nodeType;
  5062. } catch (e) {
  5063. push = {
  5064. apply: arr.length ? function (target, els) {
  5065. push_native.apply(target, slice.call(els));
  5066. } : function (target, els) {
  5067. var j = target.length, i = 0;
  5068. while (target[j++] = els[i++]) {
  5069. }
  5070. target.length = j - 1;
  5071. }
  5072. };
  5073. }
  5074. var Sizzle = function (selector, context, results, seed) {
  5075. var match, elem, m, nodeType, i, groups, old, nid, newContext, newSelector;
  5076. if ((context ? context.ownerDocument || context : preferredDoc) !== document$1) {
  5077. setDocument(context);
  5078. }
  5079. context = context || document$1;
  5080. results = results || [];
  5081. if (!selector || typeof selector !== 'string') {
  5082. return results;
  5083. }
  5084. if ((nodeType = context.nodeType) !== 1 && nodeType !== 9) {
  5085. return [];
  5086. }
  5087. if (documentIsHTML && !seed) {
  5088. if (match = rquickExpr.exec(selector)) {
  5089. if (m = match[1]) {
  5090. if (nodeType === 9) {
  5091. elem = context.getElementById(m);
  5092. if (elem && elem.parentNode) {
  5093. if (elem.id === m) {
  5094. results.push(elem);
  5095. return results;
  5096. }
  5097. } else {
  5098. return results;
  5099. }
  5100. } else {
  5101. if (context.ownerDocument && (elem = context.ownerDocument.getElementById(m)) && contains$3(context, elem) && elem.id === m) {
  5102. results.push(elem);
  5103. return results;
  5104. }
  5105. }
  5106. } else if (match[2]) {
  5107. push.apply(results, context.getElementsByTagName(selector));
  5108. return results;
  5109. } else if ((m = match[3]) && support.getElementsByClassName) {
  5110. push.apply(results, context.getElementsByClassName(m));
  5111. return results;
  5112. }
  5113. }
  5114. if (support.qsa && (!rbuggyQSA || !rbuggyQSA.test(selector))) {
  5115. nid = old = expando;
  5116. newContext = context;
  5117. newSelector = nodeType === 9 && selector;
  5118. if (nodeType === 1 && context.nodeName.toLowerCase() !== 'object') {
  5119. groups = tokenize(selector);
  5120. if (old = context.getAttribute('id')) {
  5121. nid = old.replace(rescape, '\\$&');
  5122. } else {
  5123. context.setAttribute('id', nid);
  5124. }
  5125. nid = '[id=\'' + nid + '\'] ';
  5126. i = groups.length;
  5127. while (i--) {
  5128. groups[i] = nid + toSelector(groups[i]);
  5129. }
  5130. newContext = rsibling.test(selector) && testContext(context.parentNode) || context;
  5131. newSelector = groups.join(',');
  5132. }
  5133. if (newSelector) {
  5134. try {
  5135. push.apply(results, newContext.querySelectorAll(newSelector));
  5136. return results;
  5137. } catch (qsaError) {
  5138. } finally {
  5139. if (!old) {
  5140. context.removeAttribute('id');
  5141. }
  5142. }
  5143. }
  5144. }
  5145. }
  5146. return select(selector.replace(rtrim, '$1'), context, results, seed);
  5147. };
  5148. function createCache() {
  5149. var keys = [];
  5150. function cache(key, value) {
  5151. if (keys.push(key + ' ') > Expr.cacheLength) {
  5152. delete cache[keys.shift()];
  5153. }
  5154. return cache[key + ' '] = value;
  5155. }
  5156. return cache;
  5157. }
  5158. function markFunction(fn) {
  5159. fn[expando] = true;
  5160. return fn;
  5161. }
  5162. function siblingCheck(a, b) {
  5163. var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && (~b.sourceIndex || MAX_NEGATIVE) - (~a.sourceIndex || MAX_NEGATIVE);
  5164. if (diff) {
  5165. return diff;
  5166. }
  5167. if (cur) {
  5168. while (cur = cur.nextSibling) {
  5169. if (cur === b) {
  5170. return -1;
  5171. }
  5172. }
  5173. }
  5174. return a ? 1 : -1;
  5175. }
  5176. function createInputPseudo(type) {
  5177. return function (elem) {
  5178. var name = elem.nodeName.toLowerCase();
  5179. return name === 'input' && elem.type === type;
  5180. };
  5181. }
  5182. function createButtonPseudo(type) {
  5183. return function (elem) {
  5184. var name = elem.nodeName.toLowerCase();
  5185. return (name === 'input' || name === 'button') && elem.type === type;
  5186. };
  5187. }
  5188. function createPositionalPseudo(fn) {
  5189. return markFunction(function (argument) {
  5190. argument = +argument;
  5191. return markFunction(function (seed, matches) {
  5192. var j, matchIndexes = fn([], seed.length, argument), i = matchIndexes.length;
  5193. while (i--) {
  5194. if (seed[j = matchIndexes[i]]) {
  5195. seed[j] = !(matches[j] = seed[j]);
  5196. }
  5197. }
  5198. });
  5199. });
  5200. }
  5201. function testContext(context) {
  5202. return context && typeof context.getElementsByTagName !== strundefined && context;
  5203. }
  5204. support = Sizzle.support = {};
  5205. isXML = Sizzle.isXML = function (elem) {
  5206. var documentElement = elem && (elem.ownerDocument || elem).documentElement;
  5207. return documentElement ? documentElement.nodeName !== 'HTML' : false;
  5208. };
  5209. setDocument = Sizzle.setDocument = function (node) {
  5210. var hasCompare, doc = node ? node.ownerDocument || node : preferredDoc, parent = doc.defaultView;
  5211. function getTop(win) {
  5212. try {
  5213. return win.top;
  5214. } catch (ex) {
  5215. }
  5216. return null;
  5217. }
  5218. if (doc === document$1 || doc.nodeType !== 9 || !doc.documentElement) {
  5219. return document$1;
  5220. }
  5221. document$1 = doc;
  5222. docElem = doc.documentElement;
  5223. documentIsHTML = !isXML(doc);
  5224. if (parent && parent !== getTop(parent)) {
  5225. if (parent.addEventListener) {
  5226. parent.addEventListener('unload', function () {
  5227. setDocument();
  5228. }, false);
  5229. } else if (parent.attachEvent) {
  5230. parent.attachEvent('onunload', function () {
  5231. setDocument();
  5232. });
  5233. }
  5234. }
  5235. support.attributes = true;
  5236. support.getElementsByTagName = true;
  5237. support.getElementsByClassName = rnative.test(doc.getElementsByClassName);
  5238. support.getById = true;
  5239. Expr.find.ID = function (id, context) {
  5240. if (typeof context.getElementById !== strundefined && documentIsHTML) {
  5241. var m = context.getElementById(id);
  5242. return m && m.parentNode ? [m] : [];
  5243. }
  5244. };
  5245. Expr.filter.ID = function (id) {
  5246. var attrId = id.replace(runescape, funescape);
  5247. return function (elem) {
  5248. return elem.getAttribute('id') === attrId;
  5249. };
  5250. };
  5251. Expr.find.TAG = support.getElementsByTagName ? function (tag, context) {
  5252. if (typeof context.getElementsByTagName !== strundefined) {
  5253. return context.getElementsByTagName(tag);
  5254. }
  5255. } : function (tag, context) {
  5256. var elem, tmp = [], i = 0, results = context.getElementsByTagName(tag);
  5257. if (tag === '*') {
  5258. while (elem = results[i++]) {
  5259. if (elem.nodeType === 1) {
  5260. tmp.push(elem);
  5261. }
  5262. }
  5263. return tmp;
  5264. }
  5265. return results;
  5266. };
  5267. Expr.find.CLASS = support.getElementsByClassName && function (className, context) {
  5268. if (documentIsHTML) {
  5269. return context.getElementsByClassName(className);
  5270. }
  5271. };
  5272. rbuggyMatches = [];
  5273. rbuggyQSA = [];
  5274. support.disconnectedMatch = true;
  5275. rbuggyQSA = rbuggyQSA.length && new RegExp(rbuggyQSA.join('|'));
  5276. rbuggyMatches = rbuggyMatches.length && new RegExp(rbuggyMatches.join('|'));
  5277. hasCompare = rnative.test(docElem.compareDocumentPosition);
  5278. contains$3 = hasCompare || rnative.test(docElem.contains) ? function (a, b) {
  5279. var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode;
  5280. return a === bup || !!(bup && bup.nodeType === 1 && (adown.contains ? adown.contains(bup) : a.compareDocumentPosition && a.compareDocumentPosition(bup) & 16));
  5281. } : function (a, b) {
  5282. if (b) {
  5283. while (b = b.parentNode) {
  5284. if (b === a) {
  5285. return true;
  5286. }
  5287. }
  5288. }
  5289. return false;
  5290. };
  5291. sortOrder = hasCompare ? function (a, b) {
  5292. if (a === b) {
  5293. hasDuplicate = true;
  5294. return 0;
  5295. }
  5296. var compare = !a.compareDocumentPosition - !b.compareDocumentPosition;
  5297. if (compare) {
  5298. return compare;
  5299. }
  5300. compare = (a.ownerDocument || a) === (b.ownerDocument || b) ? a.compareDocumentPosition(b) : 1;
  5301. if (compare & 1 || !support.sortDetached && b.compareDocumentPosition(a) === compare) {
  5302. if (a === doc || a.ownerDocument === preferredDoc && contains$3(preferredDoc, a)) {
  5303. return -1;
  5304. }
  5305. if (b === doc || b.ownerDocument === preferredDoc && contains$3(preferredDoc, b)) {
  5306. return 1;
  5307. }
  5308. return sortInput ? indexOf$2.call(sortInput, a) - indexOf$2.call(sortInput, b) : 0;
  5309. }
  5310. return compare & 4 ? -1 : 1;
  5311. } : function (a, b) {
  5312. if (a === b) {
  5313. hasDuplicate = true;
  5314. return 0;
  5315. }
  5316. var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [a], bp = [b];
  5317. if (!aup || !bup) {
  5318. return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : sortInput ? indexOf$2.call(sortInput, a) - indexOf$2.call(sortInput, b) : 0;
  5319. } else if (aup === bup) {
  5320. return siblingCheck(a, b);
  5321. }
  5322. cur = a;
  5323. while (cur = cur.parentNode) {
  5324. ap.unshift(cur);
  5325. }
  5326. cur = b;
  5327. while (cur = cur.parentNode) {
  5328. bp.unshift(cur);
  5329. }
  5330. while (ap[i] === bp[i]) {
  5331. i++;
  5332. }
  5333. return i ? siblingCheck(ap[i], bp[i]) : ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0;
  5334. };
  5335. return doc;
  5336. };
  5337. Sizzle.matches = function (expr, elements) {
  5338. return Sizzle(expr, null, null, elements);
  5339. };
  5340. Sizzle.matchesSelector = function (elem, expr) {
  5341. if ((elem.ownerDocument || elem) !== document$1) {
  5342. setDocument(elem);
  5343. }
  5344. expr = expr.replace(rattributeQuotes, '=\'$1\']');
  5345. if (support.matchesSelector && documentIsHTML && (!rbuggyMatches || !rbuggyMatches.test(expr)) && (!rbuggyQSA || !rbuggyQSA.test(expr))) {
  5346. try {
  5347. var ret = matches.call(elem, expr);
  5348. if (ret || support.disconnectedMatch || elem.document && elem.document.nodeType !== 11) {
  5349. return ret;
  5350. }
  5351. } catch (e) {
  5352. }
  5353. }
  5354. return Sizzle(expr, document$1, null, [elem]).length > 0;
  5355. };
  5356. Sizzle.contains = function (context, elem) {
  5357. if ((context.ownerDocument || context) !== document$1) {
  5358. setDocument(context);
  5359. }
  5360. return contains$3(context, elem);
  5361. };
  5362. Sizzle.attr = function (elem, name) {
  5363. if ((elem.ownerDocument || elem) !== document$1) {
  5364. setDocument(elem);
  5365. }
  5366. var fn = Expr.attrHandle[name.toLowerCase()], val = fn && hasOwn.call(Expr.attrHandle, name.toLowerCase()) ? fn(elem, name, !documentIsHTML) : undefined;
  5367. return val !== undefined ? val : support.attributes || !documentIsHTML ? elem.getAttribute(name) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null;
  5368. };
  5369. Sizzle.error = function (msg) {
  5370. throw new Error('Syntax error, unrecognized expression: ' + msg);
  5371. };
  5372. Sizzle.uniqueSort = function (results) {
  5373. var elem, duplicates = [], j = 0, i = 0;
  5374. hasDuplicate = !support.detectDuplicates;
  5375. sortInput = !support.sortStable && results.slice(0);
  5376. results.sort(sortOrder);
  5377. if (hasDuplicate) {
  5378. while (elem = results[i++]) {
  5379. if (elem === results[i]) {
  5380. j = duplicates.push(i);
  5381. }
  5382. }
  5383. while (j--) {
  5384. results.splice(duplicates[j], 1);
  5385. }
  5386. }
  5387. sortInput = null;
  5388. return results;
  5389. };
  5390. getText = Sizzle.getText = function (elem) {
  5391. var node, ret = '', i = 0, nodeType = elem.nodeType;
  5392. if (!nodeType) {
  5393. while (node = elem[i++]) {
  5394. ret += getText(node);
  5395. }
  5396. } else if (nodeType === 1 || nodeType === 9 || nodeType === 11) {
  5397. if (typeof elem.textContent === 'string') {
  5398. return elem.textContent;
  5399. } else {
  5400. for (elem = elem.firstChild; elem; elem = elem.nextSibling) {
  5401. ret += getText(elem);
  5402. }
  5403. }
  5404. } else if (nodeType === 3 || nodeType === 4) {
  5405. return elem.nodeValue;
  5406. }
  5407. return ret;
  5408. };
  5409. Expr = Sizzle.selectors = {
  5410. cacheLength: 50,
  5411. createPseudo: markFunction,
  5412. match: matchExpr,
  5413. attrHandle: {},
  5414. find: {},
  5415. relative: {
  5416. '>': {
  5417. dir: 'parentNode',
  5418. first: true
  5419. },
  5420. ' ': { dir: 'parentNode' },
  5421. '+': {
  5422. dir: 'previousSibling',
  5423. first: true
  5424. },
  5425. '~': { dir: 'previousSibling' }
  5426. },
  5427. preFilter: {
  5428. ATTR: function (match) {
  5429. match[1] = match[1].replace(runescape, funescape);
  5430. match[3] = (match[3] || match[4] || match[5] || '').replace(runescape, funescape);
  5431. if (match[2] === '~=') {
  5432. match[3] = ' ' + match[3] + ' ';
  5433. }
  5434. return match.slice(0, 4);
  5435. },
  5436. CHILD: function (match) {
  5437. match[1] = match[1].toLowerCase();
  5438. if (match[1].slice(0, 3) === 'nth') {
  5439. if (!match[3]) {
  5440. Sizzle.error(match[0]);
  5441. }
  5442. match[4] = +(match[4] ? match[5] + (match[6] || 1) : 2 * (match[3] === 'even' || match[3] === 'odd'));
  5443. match[5] = +(match[7] + match[8] || match[3] === 'odd');
  5444. } else if (match[3]) {
  5445. Sizzle.error(match[0]);
  5446. }
  5447. return match;
  5448. },
  5449. PSEUDO: function (match) {
  5450. var excess, unquoted = !match[6] && match[2];
  5451. if (matchExpr.CHILD.test(match[0])) {
  5452. return null;
  5453. }
  5454. if (match[3]) {
  5455. match[2] = match[4] || match[5] || '';
  5456. } else if (unquoted && rpseudo.test(unquoted) && (excess = tokenize(unquoted, true)) && (excess = unquoted.indexOf(')', unquoted.length - excess) - unquoted.length)) {
  5457. match[0] = match[0].slice(0, excess);
  5458. match[2] = unquoted.slice(0, excess);
  5459. }
  5460. return match.slice(0, 3);
  5461. }
  5462. },
  5463. filter: {
  5464. TAG: function (nodeNameSelector) {
  5465. var nodeName = nodeNameSelector.replace(runescape, funescape).toLowerCase();
  5466. return nodeNameSelector === '*' ? function () {
  5467. return true;
  5468. } : function (elem) {
  5469. return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
  5470. };
  5471. },
  5472. CLASS: function (className) {
  5473. var pattern = classCache[className + ' '];
  5474. return pattern || (pattern = new RegExp('(^|' + whitespace + ')' + className + '(' + whitespace + '|$)')) && classCache(className, function (elem) {
  5475. return pattern.test(typeof elem.className === 'string' && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute('class') || '');
  5476. });
  5477. },
  5478. ATTR: function (name, operator, check) {
  5479. return function (elem) {
  5480. var result = Sizzle.attr(elem, name);
  5481. if (result == null) {
  5482. return operator === '!=';
  5483. }
  5484. if (!operator) {
  5485. return true;
  5486. }
  5487. result += '';
  5488. return operator === '=' ? result === check : operator === '!=' ? result !== check : operator === '^=' ? check && result.indexOf(check) === 0 : operator === '*=' ? check && result.indexOf(check) > -1 : operator === '$=' ? check && result.slice(-check.length) === check : operator === '~=' ? (' ' + result + ' ').indexOf(check) > -1 : operator === '|=' ? result === check || result.slice(0, check.length + 1) === check + '-' : false;
  5489. };
  5490. },
  5491. CHILD: function (type, what, argument, first, last) {
  5492. var simple = type.slice(0, 3) !== 'nth', forward = type.slice(-4) !== 'last', ofType = what === 'of-type';
  5493. return first === 1 && last === 0 ? function (elem) {
  5494. return !!elem.parentNode;
  5495. } : function (elem, context, xml) {
  5496. var cache, outerCache, node, diff, nodeIndex, start, dir = simple !== forward ? 'nextSibling' : 'previousSibling', parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType;
  5497. if (parent) {
  5498. if (simple) {
  5499. while (dir) {
  5500. node = elem;
  5501. while (node = node[dir]) {
  5502. if (ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1) {
  5503. return false;
  5504. }
  5505. }
  5506. start = dir = type === 'only' && !start && 'nextSibling';
  5507. }
  5508. return true;
  5509. }
  5510. start = [forward ? parent.firstChild : parent.lastChild];
  5511. if (forward && useCache) {
  5512. outerCache = parent[expando] || (parent[expando] = {});
  5513. cache = outerCache[type] || [];
  5514. nodeIndex = cache[0] === dirruns && cache[1];
  5515. diff = cache[0] === dirruns && cache[2];
  5516. node = nodeIndex && parent.childNodes[nodeIndex];
  5517. while (node = ++nodeIndex && node && node[dir] || (diff = nodeIndex = 0) || start.pop()) {
  5518. if (node.nodeType === 1 && ++diff && node === elem) {
  5519. outerCache[type] = [
  5520. dirruns,
  5521. nodeIndex,
  5522. diff
  5523. ];
  5524. break;
  5525. }
  5526. }
  5527. } else if (useCache && (cache = (elem[expando] || (elem[expando] = {}))[type]) && cache[0] === dirruns) {
  5528. diff = cache[1];
  5529. } else {
  5530. while (node = ++nodeIndex && node && node[dir] || (diff = nodeIndex = 0) || start.pop()) {
  5531. if ((ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1) && ++diff) {
  5532. if (useCache) {
  5533. (node[expando] || (node[expando] = {}))[type] = [
  5534. dirruns,
  5535. diff
  5536. ];
  5537. }
  5538. if (node === elem) {
  5539. break;
  5540. }
  5541. }
  5542. }
  5543. }
  5544. diff -= last;
  5545. return diff === first || diff % first === 0 && diff / first >= 0;
  5546. }
  5547. };
  5548. },
  5549. PSEUDO: function (pseudo, argument) {
  5550. var args, fn = Expr.pseudos[pseudo] || Expr.setFilters[pseudo.toLowerCase()] || Sizzle.error('unsupported pseudo: ' + pseudo);
  5551. if (fn[expando]) {
  5552. return fn(argument);
  5553. }
  5554. if (fn.length > 1) {
  5555. args = [
  5556. pseudo,
  5557. pseudo,
  5558. '',
  5559. argument
  5560. ];
  5561. return Expr.setFilters.hasOwnProperty(pseudo.toLowerCase()) ? markFunction(function (seed, matches) {
  5562. var idx, matched = fn(seed, argument), i = matched.length;
  5563. while (i--) {
  5564. idx = indexOf$2.call(seed, matched[i]);
  5565. seed[idx] = !(matches[idx] = matched[i]);
  5566. }
  5567. }) : function (elem) {
  5568. return fn(elem, 0, args);
  5569. };
  5570. }
  5571. return fn;
  5572. }
  5573. },
  5574. pseudos: {
  5575. not: markFunction(function (selector) {
  5576. var input = [], results = [], matcher = compile(selector.replace(rtrim, '$1'));
  5577. return matcher[expando] ? markFunction(function (seed, matches, context, xml) {
  5578. var elem, unmatched = matcher(seed, null, xml, []), i = seed.length;
  5579. while (i--) {
  5580. if (elem = unmatched[i]) {
  5581. seed[i] = !(matches[i] = elem);
  5582. }
  5583. }
  5584. }) : function (elem, context, xml) {
  5585. input[0] = elem;
  5586. matcher(input, null, xml, results);
  5587. return !results.pop();
  5588. };
  5589. }),
  5590. has: markFunction(function (selector) {
  5591. return function (elem) {
  5592. return Sizzle(selector, elem).length > 0;
  5593. };
  5594. }),
  5595. contains: markFunction(function (text) {
  5596. text = text.replace(runescape, funescape);
  5597. return function (elem) {
  5598. return (elem.textContent || elem.innerText || getText(elem)).indexOf(text) > -1;
  5599. };
  5600. }),
  5601. lang: markFunction(function (lang) {
  5602. if (!ridentifier.test(lang || '')) {
  5603. Sizzle.error('unsupported lang: ' + lang);
  5604. }
  5605. lang = lang.replace(runescape, funescape).toLowerCase();
  5606. return function (elem) {
  5607. var elemLang;
  5608. do {
  5609. if (elemLang = documentIsHTML ? elem.lang : elem.getAttribute('xml:lang') || elem.getAttribute('lang')) {
  5610. elemLang = elemLang.toLowerCase();
  5611. return elemLang === lang || elemLang.indexOf(lang + '-') === 0;
  5612. }
  5613. } while ((elem = elem.parentNode) && elem.nodeType === 1);
  5614. return false;
  5615. };
  5616. }),
  5617. target: function (elem) {
  5618. var hash = window.location && window.location.hash;
  5619. return hash && hash.slice(1) === elem.id;
  5620. },
  5621. root: function (elem) {
  5622. return elem === docElem;
  5623. },
  5624. focus: function (elem) {
  5625. return elem === document$1.activeElement && (!document$1.hasFocus || document$1.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
  5626. },
  5627. enabled: function (elem) {
  5628. return elem.disabled === false;
  5629. },
  5630. disabled: function (elem) {
  5631. return elem.disabled === true;
  5632. },
  5633. checked: function (elem) {
  5634. var nodeName = elem.nodeName.toLowerCase();
  5635. return nodeName === 'input' && !!elem.checked || nodeName === 'option' && !!elem.selected;
  5636. },
  5637. selected: function (elem) {
  5638. if (elem.parentNode) {
  5639. elem.parentNode.selectedIndex;
  5640. }
  5641. return elem.selected === true;
  5642. },
  5643. empty: function (elem) {
  5644. for (elem = elem.firstChild; elem; elem = elem.nextSibling) {
  5645. if (elem.nodeType < 6) {
  5646. return false;
  5647. }
  5648. }
  5649. return true;
  5650. },
  5651. parent: function (elem) {
  5652. return !Expr.pseudos.empty(elem);
  5653. },
  5654. header: function (elem) {
  5655. return rheader.test(elem.nodeName);
  5656. },
  5657. input: function (elem) {
  5658. return rinputs.test(elem.nodeName);
  5659. },
  5660. button: function (elem) {
  5661. var name = elem.nodeName.toLowerCase();
  5662. return name === 'input' && elem.type === 'button' || name === 'button';
  5663. },
  5664. text: function (elem) {
  5665. var attr;
  5666. return elem.nodeName.toLowerCase() === 'input' && elem.type === 'text' && ((attr = elem.getAttribute('type')) == null || attr.toLowerCase() === 'text');
  5667. },
  5668. first: createPositionalPseudo(function () {
  5669. return [0];
  5670. }),
  5671. last: createPositionalPseudo(function (matchIndexes, length) {
  5672. return [length - 1];
  5673. }),
  5674. eq: createPositionalPseudo(function (matchIndexes, length, argument) {
  5675. return [argument < 0 ? argument + length : argument];
  5676. }),
  5677. even: createPositionalPseudo(function (matchIndexes, length) {
  5678. var i = 0;
  5679. for (; i < length; i += 2) {
  5680. matchIndexes.push(i);
  5681. }
  5682. return matchIndexes;
  5683. }),
  5684. odd: createPositionalPseudo(function (matchIndexes, length) {
  5685. var i = 1;
  5686. for (; i < length; i += 2) {
  5687. matchIndexes.push(i);
  5688. }
  5689. return matchIndexes;
  5690. }),
  5691. lt: createPositionalPseudo(function (matchIndexes, length, argument) {
  5692. var i = argument < 0 ? argument + length : argument;
  5693. for (; --i >= 0;) {
  5694. matchIndexes.push(i);
  5695. }
  5696. return matchIndexes;
  5697. }),
  5698. gt: createPositionalPseudo(function (matchIndexes, length, argument) {
  5699. var i = argument < 0 ? argument + length : argument;
  5700. for (; ++i < length;) {
  5701. matchIndexes.push(i);
  5702. }
  5703. return matchIndexes;
  5704. })
  5705. }
  5706. };
  5707. Expr.pseudos.nth = Expr.pseudos.eq;
  5708. each([
  5709. 'radio',
  5710. 'checkbox',
  5711. 'file',
  5712. 'password',
  5713. 'image'
  5714. ], function (i) {
  5715. Expr.pseudos[i] = createInputPseudo(i);
  5716. });
  5717. each([
  5718. 'submit',
  5719. 'reset'
  5720. ], function (i) {
  5721. Expr.pseudos[i] = createButtonPseudo(i);
  5722. });
  5723. function setFilters() {
  5724. }
  5725. setFilters.prototype = Expr.filters = Expr.pseudos;
  5726. Expr.setFilters = new setFilters();
  5727. tokenize = Sizzle.tokenize = function (selector, parseOnly) {
  5728. var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[selector + ' '];
  5729. if (cached) {
  5730. return parseOnly ? 0 : cached.slice(0);
  5731. }
  5732. soFar = selector;
  5733. groups = [];
  5734. preFilters = Expr.preFilter;
  5735. while (soFar) {
  5736. if (!matched || (match = rcomma.exec(soFar))) {
  5737. if (match) {
  5738. soFar = soFar.slice(match[0].length) || soFar;
  5739. }
  5740. groups.push(tokens = []);
  5741. }
  5742. matched = false;
  5743. if (match = rcombinators.exec(soFar)) {
  5744. matched = match.shift();
  5745. tokens.push({
  5746. value: matched,
  5747. type: match[0].replace(rtrim, ' ')
  5748. });
  5749. soFar = soFar.slice(matched.length);
  5750. }
  5751. for (type in Expr.filter) {
  5752. if (!Expr.filter.hasOwnProperty(type)) {
  5753. continue;
  5754. }
  5755. if ((match = matchExpr[type].exec(soFar)) && (!preFilters[type] || (match = preFilters[type](match)))) {
  5756. matched = match.shift();
  5757. tokens.push({
  5758. value: matched,
  5759. type: type,
  5760. matches: match
  5761. });
  5762. soFar = soFar.slice(matched.length);
  5763. }
  5764. }
  5765. if (!matched) {
  5766. break;
  5767. }
  5768. }
  5769. return parseOnly ? soFar.length : soFar ? Sizzle.error(selector) : tokenCache(selector, groups).slice(0);
  5770. };
  5771. function toSelector(tokens) {
  5772. var i = 0, len = tokens.length, selector = '';
  5773. for (; i < len; i++) {
  5774. selector += tokens[i].value;
  5775. }
  5776. return selector;
  5777. }
  5778. function addCombinator(matcher, combinator, base) {
  5779. var dir = combinator.dir, checkNonElements = base && dir === 'parentNode', doneName = done++;
  5780. return combinator.first ? function (elem, context, xml) {
  5781. while (elem = elem[dir]) {
  5782. if (elem.nodeType === 1 || checkNonElements) {
  5783. return matcher(elem, context, xml);
  5784. }
  5785. }
  5786. } : function (elem, context, xml) {
  5787. var oldCache, outerCache, newCache = [
  5788. dirruns,
  5789. doneName
  5790. ];
  5791. if (xml) {
  5792. while (elem = elem[dir]) {
  5793. if (elem.nodeType === 1 || checkNonElements) {
  5794. if (matcher(elem, context, xml)) {
  5795. return true;
  5796. }
  5797. }
  5798. }
  5799. } else {
  5800. while (elem = elem[dir]) {
  5801. if (elem.nodeType === 1 || checkNonElements) {
  5802. outerCache = elem[expando] || (elem[expando] = {});
  5803. if ((oldCache = outerCache[dir]) && oldCache[0] === dirruns && oldCache[1] === doneName) {
  5804. return newCache[2] = oldCache[2];
  5805. } else {
  5806. outerCache[dir] = newCache;
  5807. if (newCache[2] = matcher(elem, context, xml)) {
  5808. return true;
  5809. }
  5810. }
  5811. }
  5812. }
  5813. }
  5814. };
  5815. }
  5816. function elementMatcher(matchers) {
  5817. return matchers.length > 1 ? function (elem, context, xml) {
  5818. var i = matchers.length;
  5819. while (i--) {
  5820. if (!matchers[i](elem, context, xml)) {
  5821. return false;
  5822. }
  5823. }
  5824. return true;
  5825. } : matchers[0];
  5826. }
  5827. function multipleContexts(selector, contexts, results) {
  5828. var i = 0, len = contexts.length;
  5829. for (; i < len; i++) {
  5830. Sizzle(selector, contexts[i], results);
  5831. }
  5832. return results;
  5833. }
  5834. function condense(unmatched, map, filter, context, xml) {
  5835. var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null;
  5836. for (; i < len; i++) {
  5837. if (elem = unmatched[i]) {
  5838. if (!filter || filter(elem, context, xml)) {
  5839. newUnmatched.push(elem);
  5840. if (mapped) {
  5841. map.push(i);
  5842. }
  5843. }
  5844. }
  5845. }
  5846. return newUnmatched;
  5847. }
  5848. function setMatcher(preFilter, selector, matcher, postFilter, postFinder, postSelector) {
  5849. if (postFilter && !postFilter[expando]) {
  5850. postFilter = setMatcher(postFilter);
  5851. }
  5852. if (postFinder && !postFinder[expando]) {
  5853. postFinder = setMatcher(postFinder, postSelector);
  5854. }
  5855. return markFunction(function (seed, results, context, xml) {
  5856. var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, elems = seed || multipleContexts(selector || '*', context.nodeType ? [context] : context, []), matcherIn = preFilter && (seed || !selector) ? condense(elems, preMap, preFilter, context, xml) : elems, matcherOut = matcher ? postFinder || (seed ? preFilter : preexisting || postFilter) ? [] : results : matcherIn;
  5857. if (matcher) {
  5858. matcher(matcherIn, matcherOut, context, xml);
  5859. }
  5860. if (postFilter) {
  5861. temp = condense(matcherOut, postMap);
  5862. postFilter(temp, [], context, xml);
  5863. i = temp.length;
  5864. while (i--) {
  5865. if (elem = temp[i]) {
  5866. matcherOut[postMap[i]] = !(matcherIn[postMap[i]] = elem);
  5867. }
  5868. }
  5869. }
  5870. if (seed) {
  5871. if (postFinder || preFilter) {
  5872. if (postFinder) {
  5873. temp = [];
  5874. i = matcherOut.length;
  5875. while (i--) {
  5876. if (elem = matcherOut[i]) {
  5877. temp.push(matcherIn[i] = elem);
  5878. }
  5879. }
  5880. postFinder(null, matcherOut = [], temp, xml);
  5881. }
  5882. i = matcherOut.length;
  5883. while (i--) {
  5884. if ((elem = matcherOut[i]) && (temp = postFinder ? indexOf$2.call(seed, elem) : preMap[i]) > -1) {
  5885. seed[temp] = !(results[temp] = elem);
  5886. }
  5887. }
  5888. }
  5889. } else {
  5890. matcherOut = condense(matcherOut === results ? matcherOut.splice(preexisting, matcherOut.length) : matcherOut);
  5891. if (postFinder) {
  5892. postFinder(null, results, matcherOut, xml);
  5893. } else {
  5894. push.apply(results, matcherOut);
  5895. }
  5896. }
  5897. });
  5898. }
  5899. function matcherFromTokens(tokens) {
  5900. var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[tokens[0].type], implicitRelative = leadingRelative || Expr.relative[' '], i = leadingRelative ? 1 : 0, matchContext = addCombinator(function (elem) {
  5901. return elem === checkContext;
  5902. }, implicitRelative, true), matchAnyContext = addCombinator(function (elem) {
  5903. return indexOf$2.call(checkContext, elem) > -1;
  5904. }, implicitRelative, true), matchers = [function (elem, context, xml) {
  5905. return !leadingRelative && (xml || context !== outermostContext) || ((checkContext = context).nodeType ? matchContext(elem, context, xml) : matchAnyContext(elem, context, xml));
  5906. }];
  5907. for (; i < len; i++) {
  5908. if (matcher = Expr.relative[tokens[i].type]) {
  5909. matchers = [addCombinator(elementMatcher(matchers), matcher)];
  5910. } else {
  5911. matcher = Expr.filter[tokens[i].type].apply(null, tokens[i].matches);
  5912. if (matcher[expando]) {
  5913. j = ++i;
  5914. for (; j < len; j++) {
  5915. if (Expr.relative[tokens[j].type]) {
  5916. break;
  5917. }
  5918. }
  5919. return setMatcher(i > 1 && elementMatcher(matchers), i > 1 && toSelector(tokens.slice(0, i - 1).concat({ value: tokens[i - 2].type === ' ' ? '*' : '' })).replace(rtrim, '$1'), matcher, i < j && matcherFromTokens(tokens.slice(i, j)), j < len && matcherFromTokens(tokens = tokens.slice(j)), j < len && toSelector(tokens));
  5920. }
  5921. matchers.push(matcher);
  5922. }
  5923. }
  5924. return elementMatcher(matchers);
  5925. }
  5926. function matcherFromGroupMatchers(elementMatchers, setMatchers) {
  5927. var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function (seed, context, xml, results, outermost) {
  5928. var elem, j, matcher, matchedCount = 0, i = '0', unmatched = seed && [], setMatched = [], contextBackup = outermostContext, elems = seed || byElement && Expr.find.TAG('*', outermost), dirrunsUnique = dirruns += contextBackup == null ? 1 : Math.random() || 0.1, len = elems.length;
  5929. if (outermost) {
  5930. outermostContext = context !== document$1 && context;
  5931. }
  5932. for (; i !== len && (elem = elems[i]) != null; i++) {
  5933. if (byElement && elem) {
  5934. j = 0;
  5935. while (matcher = elementMatchers[j++]) {
  5936. if (matcher(elem, context, xml)) {
  5937. results.push(elem);
  5938. break;
  5939. }
  5940. }
  5941. if (outermost) {
  5942. dirruns = dirrunsUnique;
  5943. }
  5944. }
  5945. if (bySet) {
  5946. if (elem = !matcher && elem) {
  5947. matchedCount--;
  5948. }
  5949. if (seed) {
  5950. unmatched.push(elem);
  5951. }
  5952. }
  5953. }
  5954. matchedCount += i;
  5955. if (bySet && i !== matchedCount) {
  5956. j = 0;
  5957. while (matcher = setMatchers[j++]) {
  5958. matcher(unmatched, setMatched, context, xml);
  5959. }
  5960. if (seed) {
  5961. if (matchedCount > 0) {
  5962. while (i--) {
  5963. if (!(unmatched[i] || setMatched[i])) {
  5964. setMatched[i] = pop.call(results);
  5965. }
  5966. }
  5967. }
  5968. setMatched = condense(setMatched);
  5969. }
  5970. push.apply(results, setMatched);
  5971. if (outermost && !seed && setMatched.length > 0 && matchedCount + setMatchers.length > 1) {
  5972. Sizzle.uniqueSort(results);
  5973. }
  5974. }
  5975. if (outermost) {
  5976. dirruns = dirrunsUnique;
  5977. outermostContext = contextBackup;
  5978. }
  5979. return unmatched;
  5980. };
  5981. return bySet ? markFunction(superMatcher) : superMatcher;
  5982. }
  5983. compile = Sizzle.compile = function (selector, match) {
  5984. var i, setMatchers = [], elementMatchers = [], cached = compilerCache[selector + ' '];
  5985. if (!cached) {
  5986. if (!match) {
  5987. match = tokenize(selector);
  5988. }
  5989. i = match.length;
  5990. while (i--) {
  5991. cached = matcherFromTokens(match[i]);
  5992. if (cached[expando]) {
  5993. setMatchers.push(cached);
  5994. } else {
  5995. elementMatchers.push(cached);
  5996. }
  5997. }
  5998. cached = compilerCache(selector, matcherFromGroupMatchers(elementMatchers, setMatchers));
  5999. cached.selector = selector;
  6000. }
  6001. return cached;
  6002. };
  6003. select = Sizzle.select = function (selector, context, results, seed) {
  6004. var i, tokens, token, type, find, compiled = typeof selector === 'function' && selector, match = !seed && tokenize(selector = compiled.selector || selector);
  6005. results = results || [];
  6006. if (match.length === 1) {
  6007. tokens = match[0] = match[0].slice(0);
  6008. if (tokens.length > 2 && (token = tokens[0]).type === 'ID' && support.getById && context.nodeType === 9 && documentIsHTML && Expr.relative[tokens[1].type]) {
  6009. context = (Expr.find.ID(token.matches[0].replace(runescape, funescape), context) || [])[0];
  6010. if (!context) {
  6011. return results;
  6012. } else if (compiled) {
  6013. context = context.parentNode;
  6014. }
  6015. selector = selector.slice(tokens.shift().value.length);
  6016. }
  6017. i = matchExpr.needsContext.test(selector) ? 0 : tokens.length;
  6018. while (i--) {
  6019. token = tokens[i];
  6020. if (Expr.relative[type = token.type]) {
  6021. break;
  6022. }
  6023. if (find = Expr.find[type]) {
  6024. if (seed = find(token.matches[0].replace(runescape, funescape), rsibling.test(tokens[0].type) && testContext(context.parentNode) || context)) {
  6025. tokens.splice(i, 1);
  6026. selector = seed.length && toSelector(tokens);
  6027. if (!selector) {
  6028. push.apply(results, seed);
  6029. return results;
  6030. }
  6031. break;
  6032. }
  6033. }
  6034. }
  6035. }
  6036. (compiled || compile(selector, match))(seed, context, !documentIsHTML, results, rsibling.test(selector) && testContext(context.parentNode) || context);
  6037. return results;
  6038. };
  6039. support.sortStable = expando.split('').sort(sortOrder).join('') === expando;
  6040. support.detectDuplicates = !!hasDuplicate;
  6041. setDocument();
  6042. support.sortDetached = true;
  6043. var doc = document, push$1 = Array.prototype.push, slice$1 = Array.prototype.slice;
  6044. var rquickExpr$1 = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/;
  6045. var Event = EventUtils.Event;
  6046. var skipUniques = Tools.makeMap('children,contents,next,prev');
  6047. var isDefined = function (obj) {
  6048. return typeof obj !== 'undefined';
  6049. };
  6050. var isString$1 = function (obj) {
  6051. return typeof obj === 'string';
  6052. };
  6053. var isWindow = function (obj) {
  6054. return obj && obj === obj.window;
  6055. };
  6056. var createFragment = function (html, fragDoc) {
  6057. fragDoc = fragDoc || doc;
  6058. var container = fragDoc.createElement('div');
  6059. var frag = fragDoc.createDocumentFragment();
  6060. container.innerHTML = html;
  6061. var node;
  6062. while (node = container.firstChild) {
  6063. frag.appendChild(node);
  6064. }
  6065. return frag;
  6066. };
  6067. var domManipulate = function (targetNodes, sourceItem, callback, reverse) {
  6068. var i;
  6069. if (isString$1(sourceItem)) {
  6070. sourceItem = createFragment(sourceItem, getElementDocument(targetNodes[0]));
  6071. } else if (sourceItem.length && !sourceItem.nodeType) {
  6072. sourceItem = DomQuery.makeArray(sourceItem);
  6073. if (reverse) {
  6074. for (i = sourceItem.length - 1; i >= 0; i--) {
  6075. domManipulate(targetNodes, sourceItem[i], callback, reverse);
  6076. }
  6077. } else {
  6078. for (i = 0; i < sourceItem.length; i++) {
  6079. domManipulate(targetNodes, sourceItem[i], callback, reverse);
  6080. }
  6081. }
  6082. return targetNodes;
  6083. }
  6084. if (sourceItem.nodeType) {
  6085. i = targetNodes.length;
  6086. while (i--) {
  6087. callback.call(targetNodes[i], sourceItem);
  6088. }
  6089. }
  6090. return targetNodes;
  6091. };
  6092. var hasClass = function (node, className) {
  6093. return node && className && (' ' + node.className + ' ').indexOf(' ' + className + ' ') !== -1;
  6094. };
  6095. var wrap$1 = function (elements, wrapper, all) {
  6096. var lastParent, newWrapper;
  6097. wrapper = DomQuery(wrapper)[0];
  6098. elements.each(function () {
  6099. var self = this;
  6100. if (!all || lastParent !== self.parentNode) {
  6101. lastParent = self.parentNode;
  6102. newWrapper = wrapper.cloneNode(false);
  6103. self.parentNode.insertBefore(newWrapper, self);
  6104. newWrapper.appendChild(self);
  6105. } else {
  6106. newWrapper.appendChild(self);
  6107. }
  6108. });
  6109. return elements;
  6110. };
  6111. var numericCssMap = Tools.makeMap('fillOpacity fontWeight lineHeight opacity orphans widows zIndex zoom', ' ');
  6112. var booleanMap = Tools.makeMap('checked compact declare defer disabled ismap multiple nohref noshade nowrap readonly selected', ' ');
  6113. var propFix = {
  6114. for: 'htmlFor',
  6115. class: 'className',
  6116. readonly: 'readOnly'
  6117. };
  6118. var cssFix = { float: 'cssFloat' };
  6119. var attrHooks = {}, cssHooks = {};
  6120. var DomQueryConstructor = function (selector, context) {
  6121. return new DomQuery.fn.init(selector, context);
  6122. };
  6123. var inArray$1 = function (item, array) {
  6124. var i;
  6125. if (array.indexOf) {
  6126. return array.indexOf(item);
  6127. }
  6128. i = array.length;
  6129. while (i--) {
  6130. if (array[i] === item) {
  6131. return i;
  6132. }
  6133. }
  6134. return -1;
  6135. };
  6136. var whiteSpaceRegExp$2 = /^\s*|\s*$/g;
  6137. var trim$3 = function (str) {
  6138. return str === null || str === undefined ? '' : ('' + str).replace(whiteSpaceRegExp$2, '');
  6139. };
  6140. var each$4 = function (obj, callback) {
  6141. var length, key, i, value;
  6142. if (obj) {
  6143. length = obj.length;
  6144. if (length === undefined) {
  6145. for (key in obj) {
  6146. if (obj.hasOwnProperty(key)) {
  6147. value = obj[key];
  6148. if (callback.call(value, key, value) === false) {
  6149. break;
  6150. }
  6151. }
  6152. }
  6153. } else {
  6154. for (i = 0; i < length; i++) {
  6155. value = obj[i];
  6156. if (callback.call(value, i, value) === false) {
  6157. break;
  6158. }
  6159. }
  6160. }
  6161. }
  6162. return obj;
  6163. };
  6164. var grep = function (array, callback) {
  6165. var out = [];
  6166. each$4(array, function (i, item) {
  6167. if (callback(item, i)) {
  6168. out.push(item);
  6169. }
  6170. });
  6171. return out;
  6172. };
  6173. var getElementDocument = function (element) {
  6174. if (!element) {
  6175. return doc;
  6176. }
  6177. if (element.nodeType === 9) {
  6178. return element;
  6179. }
  6180. return element.ownerDocument;
  6181. };
  6182. DomQueryConstructor.fn = DomQueryConstructor.prototype = {
  6183. constructor: DomQueryConstructor,
  6184. selector: '',
  6185. context: null,
  6186. length: 0,
  6187. init: function (selector, context) {
  6188. var self = this;
  6189. var match, node;
  6190. if (!selector) {
  6191. return self;
  6192. }
  6193. if (selector.nodeType) {
  6194. self.context = self[0] = selector;
  6195. self.length = 1;
  6196. return self;
  6197. }
  6198. if (context && context.nodeType) {
  6199. self.context = context;
  6200. } else {
  6201. if (context) {
  6202. return DomQuery(selector).attr(context);
  6203. }
  6204. self.context = context = document;
  6205. }
  6206. if (isString$1(selector)) {
  6207. self.selector = selector;
  6208. if (selector.charAt(0) === '<' && selector.charAt(selector.length - 1) === '>' && selector.length >= 3) {
  6209. match = [
  6210. null,
  6211. selector,
  6212. null
  6213. ];
  6214. } else {
  6215. match = rquickExpr$1.exec(selector);
  6216. }
  6217. if (match) {
  6218. if (match[1]) {
  6219. node = createFragment(selector, getElementDocument(context)).firstChild;
  6220. while (node) {
  6221. push$1.call(self, node);
  6222. node = node.nextSibling;
  6223. }
  6224. } else {
  6225. node = getElementDocument(context).getElementById(match[2]);
  6226. if (!node) {
  6227. return self;
  6228. }
  6229. if (node.id !== match[2]) {
  6230. return self.find(selector);
  6231. }
  6232. self.length = 1;
  6233. self[0] = node;
  6234. }
  6235. } else {
  6236. return DomQuery(context).find(selector);
  6237. }
  6238. } else {
  6239. this.add(selector, false);
  6240. }
  6241. return self;
  6242. },
  6243. toArray: function () {
  6244. return Tools.toArray(this);
  6245. },
  6246. add: function (items, sort) {
  6247. var self = this;
  6248. var nodes, i;
  6249. if (isString$1(items)) {
  6250. return self.add(DomQuery(items));
  6251. }
  6252. if (sort !== false) {
  6253. nodes = DomQuery.unique(self.toArray().concat(DomQuery.makeArray(items)));
  6254. self.length = nodes.length;
  6255. for (i = 0; i < nodes.length; i++) {
  6256. self[i] = nodes[i];
  6257. }
  6258. } else {
  6259. push$1.apply(self, DomQuery.makeArray(items));
  6260. }
  6261. return self;
  6262. },
  6263. attr: function (name, value) {
  6264. var self = this;
  6265. var hook;
  6266. if (typeof name === 'object') {
  6267. each$4(name, function (name, value) {
  6268. self.attr(name, value);
  6269. });
  6270. } else if (isDefined(value)) {
  6271. this.each(function () {
  6272. var hook;
  6273. if (this.nodeType === 1) {
  6274. hook = attrHooks[name];
  6275. if (hook && hook.set) {
  6276. hook.set(this, value);
  6277. return;
  6278. }
  6279. if (value === null) {
  6280. this.removeAttribute(name, 2);
  6281. } else {
  6282. this.setAttribute(name, value, 2);
  6283. }
  6284. }
  6285. });
  6286. } else {
  6287. if (self[0] && self[0].nodeType === 1) {
  6288. hook = attrHooks[name];
  6289. if (hook && hook.get) {
  6290. return hook.get(self[0], name);
  6291. }
  6292. if (booleanMap[name]) {
  6293. return self.prop(name) ? name : undefined;
  6294. }
  6295. value = self[0].getAttribute(name, 2);
  6296. if (value === null) {
  6297. value = undefined;
  6298. }
  6299. }
  6300. return value;
  6301. }
  6302. return self;
  6303. },
  6304. removeAttr: function (name) {
  6305. return this.attr(name, null);
  6306. },
  6307. prop: function (name, value) {
  6308. var self = this;
  6309. name = propFix[name] || name;
  6310. if (typeof name === 'object') {
  6311. each$4(name, function (name, value) {
  6312. self.prop(name, value);
  6313. });
  6314. } else if (isDefined(value)) {
  6315. this.each(function () {
  6316. if (this.nodeType === 1) {
  6317. this[name] = value;
  6318. }
  6319. });
  6320. } else {
  6321. if (self[0] && self[0].nodeType && name in self[0]) {
  6322. return self[0][name];
  6323. }
  6324. return value;
  6325. }
  6326. return self;
  6327. },
  6328. css: function (name, value) {
  6329. var self = this;
  6330. var elm, hook;
  6331. var camel = function (name) {
  6332. return name.replace(/-(\D)/g, function (a, b) {
  6333. return b.toUpperCase();
  6334. });
  6335. };
  6336. var dashed = function (name) {
  6337. return name.replace(/[A-Z]/g, function (a) {
  6338. return '-' + a;
  6339. });
  6340. };
  6341. if (typeof name === 'object') {
  6342. each$4(name, function (name, value) {
  6343. self.css(name, value);
  6344. });
  6345. } else {
  6346. if (isDefined(value)) {
  6347. name = camel(name);
  6348. if (typeof value === 'number' && !numericCssMap[name]) {
  6349. value = value.toString() + 'px';
  6350. }
  6351. self.each(function () {
  6352. var style = this.style;
  6353. hook = cssHooks[name];
  6354. if (hook && hook.set) {
  6355. hook.set(this, value);
  6356. return;
  6357. }
  6358. try {
  6359. this.style[cssFix[name] || name] = value;
  6360. } catch (ex) {
  6361. }
  6362. if (value === null || value === '') {
  6363. if (style.removeProperty) {
  6364. style.removeProperty(dashed(name));
  6365. } else {
  6366. style.removeAttribute(name);
  6367. }
  6368. }
  6369. });
  6370. } else {
  6371. elm = self[0];
  6372. hook = cssHooks[name];
  6373. if (hook && hook.get) {
  6374. return hook.get(elm);
  6375. }
  6376. if (elm.ownerDocument.defaultView) {
  6377. try {
  6378. return elm.ownerDocument.defaultView.getComputedStyle(elm, null).getPropertyValue(dashed(name));
  6379. } catch (ex) {
  6380. return undefined;
  6381. }
  6382. } else if (elm.currentStyle) {
  6383. return elm.currentStyle[camel(name)];
  6384. } else {
  6385. return '';
  6386. }
  6387. }
  6388. }
  6389. return self;
  6390. },
  6391. remove: function () {
  6392. var self = this;
  6393. var node, i = this.length;
  6394. while (i--) {
  6395. node = self[i];
  6396. Event.clean(node);
  6397. if (node.parentNode) {
  6398. node.parentNode.removeChild(node);
  6399. }
  6400. }
  6401. return this;
  6402. },
  6403. empty: function () {
  6404. var self = this;
  6405. var node, i = this.length;
  6406. while (i--) {
  6407. node = self[i];
  6408. while (node.firstChild) {
  6409. node.removeChild(node.firstChild);
  6410. }
  6411. }
  6412. return this;
  6413. },
  6414. html: function (value) {
  6415. var self = this;
  6416. var i;
  6417. if (isDefined(value)) {
  6418. i = self.length;
  6419. try {
  6420. while (i--) {
  6421. self[i].innerHTML = value;
  6422. }
  6423. } catch (ex) {
  6424. DomQuery(self[i]).empty().append(value);
  6425. }
  6426. return self;
  6427. }
  6428. return self[0] ? self[0].innerHTML : '';
  6429. },
  6430. text: function (value) {
  6431. var self = this;
  6432. var i;
  6433. if (isDefined(value)) {
  6434. i = self.length;
  6435. while (i--) {
  6436. if ('innerText' in self[i]) {
  6437. self[i].innerText = value;
  6438. } else {
  6439. self[0].textContent = value;
  6440. }
  6441. }
  6442. return self;
  6443. }
  6444. return self[0] ? self[0].innerText || self[0].textContent : '';
  6445. },
  6446. append: function () {
  6447. return domManipulate(this, arguments, function (node) {
  6448. if (this.nodeType === 1 || this.host && this.host.nodeType === 1) {
  6449. this.appendChild(node);
  6450. }
  6451. });
  6452. },
  6453. prepend: function () {
  6454. return domManipulate(this, arguments, function (node) {
  6455. if (this.nodeType === 1 || this.host && this.host.nodeType === 1) {
  6456. this.insertBefore(node, this.firstChild);
  6457. }
  6458. }, true);
  6459. },
  6460. before: function () {
  6461. var self = this;
  6462. if (self[0] && self[0].parentNode) {
  6463. return domManipulate(self, arguments, function (node) {
  6464. this.parentNode.insertBefore(node, this);
  6465. });
  6466. }
  6467. return self;
  6468. },
  6469. after: function () {
  6470. var self = this;
  6471. if (self[0] && self[0].parentNode) {
  6472. return domManipulate(self, arguments, function (node) {
  6473. this.parentNode.insertBefore(node, this.nextSibling);
  6474. }, true);
  6475. }
  6476. return self;
  6477. },
  6478. appendTo: function (val) {
  6479. DomQuery(val).append(this);
  6480. return this;
  6481. },
  6482. prependTo: function (val) {
  6483. DomQuery(val).prepend(this);
  6484. return this;
  6485. },
  6486. replaceWith: function (content) {
  6487. return this.before(content).remove();
  6488. },
  6489. wrap: function (content) {
  6490. return wrap$1(this, content);
  6491. },
  6492. wrapAll: function (content) {
  6493. return wrap$1(this, content, true);
  6494. },
  6495. wrapInner: function (content) {
  6496. this.each(function () {
  6497. DomQuery(this).contents().wrapAll(content);
  6498. });
  6499. return this;
  6500. },
  6501. unwrap: function () {
  6502. return this.parent().each(function () {
  6503. DomQuery(this).replaceWith(this.childNodes);
  6504. });
  6505. },
  6506. clone: function () {
  6507. var result = [];
  6508. this.each(function () {
  6509. result.push(this.cloneNode(true));
  6510. });
  6511. return DomQuery(result);
  6512. },
  6513. addClass: function (className) {
  6514. return this.toggleClass(className, true);
  6515. },
  6516. removeClass: function (className) {
  6517. return this.toggleClass(className, false);
  6518. },
  6519. toggleClass: function (className, state) {
  6520. var self = this;
  6521. if (typeof className !== 'string') {
  6522. return self;
  6523. }
  6524. if (className.indexOf(' ') !== -1) {
  6525. each$4(className.split(' '), function () {
  6526. self.toggleClass(this, state);
  6527. });
  6528. } else {
  6529. self.each(function (index, node) {
  6530. var classState = hasClass(node, className);
  6531. if (classState !== state) {
  6532. var existingClassName = node.className;
  6533. if (classState) {
  6534. node.className = trim$3((' ' + existingClassName + ' ').replace(' ' + className + ' ', ' '));
  6535. } else {
  6536. node.className += existingClassName ? ' ' + className : className;
  6537. }
  6538. }
  6539. });
  6540. }
  6541. return self;
  6542. },
  6543. hasClass: function (className) {
  6544. return hasClass(this[0], className);
  6545. },
  6546. each: function (callback) {
  6547. return each$4(this, callback);
  6548. },
  6549. on: function (name, callback) {
  6550. return this.each(function () {
  6551. Event.bind(this, name, callback);
  6552. });
  6553. },
  6554. off: function (name, callback) {
  6555. return this.each(function () {
  6556. Event.unbind(this, name, callback);
  6557. });
  6558. },
  6559. trigger: function (name) {
  6560. return this.each(function () {
  6561. if (typeof name === 'object') {
  6562. Event.fire(this, name.type, name);
  6563. } else {
  6564. Event.fire(this, name);
  6565. }
  6566. });
  6567. },
  6568. show: function () {
  6569. return this.css('display', '');
  6570. },
  6571. hide: function () {
  6572. return this.css('display', 'none');
  6573. },
  6574. slice: function () {
  6575. return new DomQuery(slice$1.apply(this, arguments));
  6576. },
  6577. eq: function (index) {
  6578. return index === -1 ? this.slice(index) : this.slice(index, +index + 1);
  6579. },
  6580. first: function () {
  6581. return this.eq(0);
  6582. },
  6583. last: function () {
  6584. return this.eq(-1);
  6585. },
  6586. find: function (selector) {
  6587. var i, l;
  6588. var ret = [];
  6589. for (i = 0, l = this.length; i < l; i++) {
  6590. DomQuery.find(selector, this[i], ret);
  6591. }
  6592. return DomQuery(ret);
  6593. },
  6594. filter: function (selector) {
  6595. if (typeof selector === 'function') {
  6596. return DomQuery(grep(this.toArray(), function (item, i) {
  6597. return selector(i, item);
  6598. }));
  6599. }
  6600. return DomQuery(DomQuery.filter(selector, this.toArray()));
  6601. },
  6602. closest: function (selector) {
  6603. var result = [];
  6604. if (selector instanceof DomQuery) {
  6605. selector = selector[0];
  6606. }
  6607. this.each(function (i, node) {
  6608. while (node) {
  6609. if (typeof selector === 'string' && DomQuery(node).is(selector)) {
  6610. result.push(node);
  6611. break;
  6612. } else if (node === selector) {
  6613. result.push(node);
  6614. break;
  6615. }
  6616. node = node.parentNode;
  6617. }
  6618. });
  6619. return DomQuery(result);
  6620. },
  6621. offset: function (offset) {
  6622. var elm, doc, docElm;
  6623. var x = 0, y = 0, pos;
  6624. if (!offset) {
  6625. elm = this[0];
  6626. if (elm) {
  6627. doc = elm.ownerDocument;
  6628. docElm = doc.documentElement;
  6629. if (elm.getBoundingClientRect) {
  6630. pos = elm.getBoundingClientRect();
  6631. x = pos.left + (docElm.scrollLeft || doc.body.scrollLeft) - docElm.clientLeft;
  6632. y = pos.top + (docElm.scrollTop || doc.body.scrollTop) - docElm.clientTop;
  6633. }
  6634. }
  6635. return {
  6636. left: x,
  6637. top: y
  6638. };
  6639. }
  6640. return this.css(offset);
  6641. },
  6642. push: push$1,
  6643. sort: Array.prototype.sort,
  6644. splice: Array.prototype.splice
  6645. };
  6646. Tools.extend(DomQueryConstructor, {
  6647. extend: Tools.extend,
  6648. makeArray: function (object) {
  6649. if (isWindow(object) || object.nodeType) {
  6650. return [object];
  6651. }
  6652. return Tools.toArray(object);
  6653. },
  6654. inArray: inArray$1,
  6655. isArray: Tools.isArray,
  6656. each: each$4,
  6657. trim: trim$3,
  6658. grep: grep,
  6659. find: Sizzle,
  6660. expr: Sizzle.selectors,
  6661. unique: Sizzle.uniqueSort,
  6662. text: Sizzle.getText,
  6663. contains: Sizzle.contains,
  6664. filter: function (expr, elems, not) {
  6665. var i = elems.length;
  6666. if (not) {
  6667. expr = ':not(' + expr + ')';
  6668. }
  6669. while (i--) {
  6670. if (elems[i].nodeType !== 1) {
  6671. elems.splice(i, 1);
  6672. }
  6673. }
  6674. if (elems.length === 1) {
  6675. elems = DomQuery.find.matchesSelector(elems[0], expr) ? [elems[0]] : [];
  6676. } else {
  6677. elems = DomQuery.find.matches(expr, elems);
  6678. }
  6679. return elems;
  6680. }
  6681. });
  6682. var dir = function (el, prop, until) {
  6683. var matched = [];
  6684. var cur = el[prop];
  6685. if (typeof until !== 'string' && until instanceof DomQuery) {
  6686. until = until[0];
  6687. }
  6688. while (cur && cur.nodeType !== 9) {
  6689. if (until !== undefined) {
  6690. if (cur === until) {
  6691. break;
  6692. }
  6693. if (typeof until === 'string' && DomQuery(cur).is(until)) {
  6694. break;
  6695. }
  6696. }
  6697. if (cur.nodeType === 1) {
  6698. matched.push(cur);
  6699. }
  6700. cur = cur[prop];
  6701. }
  6702. return matched;
  6703. };
  6704. var sibling = function (node, siblingName, nodeType, until) {
  6705. var result = [];
  6706. if (until instanceof DomQuery) {
  6707. until = until[0];
  6708. }
  6709. for (; node; node = node[siblingName]) {
  6710. if (nodeType && node.nodeType !== nodeType) {
  6711. continue;
  6712. }
  6713. if (until !== undefined) {
  6714. if (node === until) {
  6715. break;
  6716. }
  6717. if (typeof until === 'string' && DomQuery(node).is(until)) {
  6718. break;
  6719. }
  6720. }
  6721. result.push(node);
  6722. }
  6723. return result;
  6724. };
  6725. var firstSibling = function (node, siblingName, nodeType) {
  6726. for (node = node[siblingName]; node; node = node[siblingName]) {
  6727. if (node.nodeType === nodeType) {
  6728. return node;
  6729. }
  6730. }
  6731. return null;
  6732. };
  6733. each$4({
  6734. parent: function (node) {
  6735. var parent = node.parentNode;
  6736. return parent && parent.nodeType !== 11 ? parent : null;
  6737. },
  6738. parents: function (node) {
  6739. return dir(node, 'parentNode');
  6740. },
  6741. next: function (node) {
  6742. return firstSibling(node, 'nextSibling', 1);
  6743. },
  6744. prev: function (node) {
  6745. return firstSibling(node, 'previousSibling', 1);
  6746. },
  6747. children: function (node) {
  6748. return sibling(node.firstChild, 'nextSibling', 1);
  6749. },
  6750. contents: function (node) {
  6751. return Tools.toArray((node.nodeName === 'iframe' ? node.contentDocument || node.contentWindow.document : node).childNodes);
  6752. }
  6753. }, function (name, fn) {
  6754. DomQueryConstructor.fn[name] = function (selector) {
  6755. var self = this;
  6756. var result = [];
  6757. self.each(function () {
  6758. var nodes = fn.call(result, this, selector, result);
  6759. if (nodes) {
  6760. if (DomQuery.isArray(nodes)) {
  6761. result.push.apply(result, nodes);
  6762. } else {
  6763. result.push(nodes);
  6764. }
  6765. }
  6766. });
  6767. if (this.length > 1) {
  6768. if (!skipUniques[name]) {
  6769. result = DomQuery.unique(result);
  6770. }
  6771. if (name.indexOf('parents') === 0) {
  6772. result = result.reverse();
  6773. }
  6774. }
  6775. var wrappedResult = DomQuery(result);
  6776. if (selector) {
  6777. return wrappedResult.filter(selector);
  6778. }
  6779. return wrappedResult;
  6780. };
  6781. });
  6782. each$4({
  6783. parentsUntil: function (node, until) {
  6784. return dir(node, 'parentNode', until);
  6785. },
  6786. nextUntil: function (node, until) {
  6787. return sibling(node, 'nextSibling', 1, until).slice(1);
  6788. },
  6789. prevUntil: function (node, until) {
  6790. return sibling(node, 'previousSibling', 1, until).slice(1);
  6791. }
  6792. }, function (name, fn) {
  6793. DomQueryConstructor.fn[name] = function (selector, filter) {
  6794. var self = this;
  6795. var result = [];
  6796. self.each(function () {
  6797. var nodes = fn.call(result, this, selector, result);
  6798. if (nodes) {
  6799. if (DomQuery.isArray(nodes)) {
  6800. result.push.apply(result, nodes);
  6801. } else {
  6802. result.push(nodes);
  6803. }
  6804. }
  6805. });
  6806. if (this.length > 1) {
  6807. result = DomQuery.unique(result);
  6808. if (name.indexOf('parents') === 0 || name === 'prevUntil') {
  6809. result = result.reverse();
  6810. }
  6811. }
  6812. var wrappedResult = DomQuery(result);
  6813. if (filter) {
  6814. return wrappedResult.filter(filter);
  6815. }
  6816. return wrappedResult;
  6817. };
  6818. });
  6819. DomQueryConstructor.fn.is = function (selector) {
  6820. return !!selector && this.filter(selector).length > 0;
  6821. };
  6822. DomQueryConstructor.fn.init.prototype = DomQueryConstructor.fn;
  6823. DomQueryConstructor.overrideDefaults = function (callback) {
  6824. var defaults;
  6825. var sub = function (selector, context) {
  6826. defaults = defaults || callback();
  6827. if (arguments.length === 0) {
  6828. selector = defaults.element;
  6829. }
  6830. if (!context) {
  6831. context = defaults.context;
  6832. }
  6833. return new sub.fn.init(selector, context);
  6834. };
  6835. DomQuery.extend(sub, this);
  6836. return sub;
  6837. };
  6838. DomQueryConstructor.attrHooks = attrHooks;
  6839. DomQueryConstructor.cssHooks = cssHooks;
  6840. var DomQuery = DomQueryConstructor;
  6841. var each$5 = Tools.each;
  6842. var grep$1 = Tools.grep;
  6843. var isIE = Env.ie;
  6844. var simpleSelectorRe = /^([a-z0-9],?)+$/i;
  6845. var setupAttrHooks = function (styles, settings, getContext) {
  6846. var keepValues = settings.keep_values;
  6847. var keepUrlHook = {
  6848. set: function ($elm, value, name) {
  6849. if (settings.url_converter) {
  6850. value = settings.url_converter.call(settings.url_converter_scope || getContext(), value, name, $elm[0]);
  6851. }
  6852. $elm.attr('data-mce-' + name, value).attr(name, value);
  6853. },
  6854. get: function ($elm, name) {
  6855. return $elm.attr('data-mce-' + name) || $elm.attr(name);
  6856. }
  6857. };
  6858. var attrHooks = {
  6859. style: {
  6860. set: function ($elm, value) {
  6861. if (value !== null && typeof value === 'object') {
  6862. $elm.css(value);
  6863. return;
  6864. }
  6865. if (keepValues) {
  6866. $elm.attr('data-mce-style', value);
  6867. }
  6868. if (value !== null && typeof value === 'string') {
  6869. $elm.removeAttr('style');
  6870. $elm.css(styles.parse(value));
  6871. } else {
  6872. $elm.attr('style', value);
  6873. }
  6874. },
  6875. get: function ($elm) {
  6876. var value = $elm.attr('data-mce-style') || $elm.attr('style');
  6877. value = styles.serialize(styles.parse(value), $elm[0].nodeName);
  6878. return value;
  6879. }
  6880. }
  6881. };
  6882. if (keepValues) {
  6883. attrHooks.href = attrHooks.src = keepUrlHook;
  6884. }
  6885. return attrHooks;
  6886. };
  6887. var updateInternalStyleAttr = function (styles, $elm) {
  6888. var rawValue = $elm.attr('style');
  6889. var value = styles.serialize(styles.parse(rawValue), $elm[0].nodeName);
  6890. if (!value) {
  6891. value = null;
  6892. }
  6893. $elm.attr('data-mce-style', value);
  6894. };
  6895. var findNodeIndex = function (node, normalized) {
  6896. var idx = 0, lastNodeType, nodeType;
  6897. if (node) {
  6898. for (lastNodeType = node.nodeType, node = node.previousSibling; node; node = node.previousSibling) {
  6899. nodeType = node.nodeType;
  6900. if (normalized && nodeType === 3) {
  6901. if (nodeType === lastNodeType || !node.nodeValue.length) {
  6902. continue;
  6903. }
  6904. }
  6905. idx++;
  6906. lastNodeType = nodeType;
  6907. }
  6908. }
  6909. return idx;
  6910. };
  6911. function DOMUtils(doc, settings) {
  6912. var _this = this;
  6913. if (settings === void 0) {
  6914. settings = {};
  6915. }
  6916. var addedStyles = {};
  6917. var win = window;
  6918. var files = {};
  6919. var counter = 0;
  6920. var stdMode = true;
  6921. var boxModel = true;
  6922. var styleSheetLoader = instance.forElement(SugarElement.fromDom(doc), {
  6923. contentCssCors: settings.contentCssCors,
  6924. referrerPolicy: settings.referrerPolicy
  6925. });
  6926. var boundEvents = [];
  6927. var schema = settings.schema ? settings.schema : Schema({});
  6928. var styles = Styles({
  6929. url_converter: settings.url_converter,
  6930. url_converter_scope: settings.url_converter_scope
  6931. }, settings.schema);
  6932. var events = settings.ownEvents ? new EventUtils() : EventUtils.Event;
  6933. var blockElementsMap = schema.getBlockElements();
  6934. var $ = DomQuery.overrideDefaults(function () {
  6935. return {
  6936. context: doc,
  6937. element: self.getRoot()
  6938. };
  6939. });
  6940. var isBlock = function (node) {
  6941. if (typeof node === 'string') {
  6942. return !!blockElementsMap[node];
  6943. } else if (node) {
  6944. var type = node.nodeType;
  6945. if (type) {
  6946. return !!(type === 1 && blockElementsMap[node.nodeName]);
  6947. }
  6948. }
  6949. return false;
  6950. };
  6951. var get = function (elm) {
  6952. return elm && doc && isString(elm) ? doc.getElementById(elm) : elm;
  6953. };
  6954. var $$ = function (elm) {
  6955. return $(typeof elm === 'string' ? get(elm) : elm);
  6956. };
  6957. var getAttrib = function (elm, name, defaultVal) {
  6958. var hook, value;
  6959. var $elm = $$(elm);
  6960. if ($elm.length) {
  6961. hook = attrHooks[name];
  6962. if (hook && hook.get) {
  6963. value = hook.get($elm, name);
  6964. } else {
  6965. value = $elm.attr(name);
  6966. }
  6967. }
  6968. if (typeof value === 'undefined') {
  6969. value = defaultVal || '';
  6970. }
  6971. return value;
  6972. };
  6973. var getAttribs = function (elm) {
  6974. var node = get(elm);
  6975. if (!node) {
  6976. return [];
  6977. }
  6978. return node.attributes;
  6979. };
  6980. var setAttrib = function (elm, name, value) {
  6981. if (value === '') {
  6982. value = null;
  6983. }
  6984. var $elm = $$(elm);
  6985. var originalValue = $elm.attr(name);
  6986. if (!$elm.length) {
  6987. return;
  6988. }
  6989. var hook = attrHooks[name];
  6990. if (hook && hook.set) {
  6991. hook.set($elm, value, name);
  6992. } else {
  6993. $elm.attr(name, value);
  6994. }
  6995. if (originalValue !== value && settings.onSetAttrib) {
  6996. settings.onSetAttrib({
  6997. attrElm: $elm,
  6998. attrName: name,
  6999. attrValue: value
  7000. });
  7001. }
  7002. };
  7003. var clone = function (node, deep) {
  7004. if (!isIE || node.nodeType !== 1 || deep) {
  7005. return node.cloneNode(deep);
  7006. } else {
  7007. var clone_1 = doc.createElement(node.nodeName);
  7008. each$5(getAttribs(node), function (attr) {
  7009. setAttrib(clone_1, attr.nodeName, getAttrib(node, attr.nodeName));
  7010. });
  7011. return clone_1;
  7012. }
  7013. };
  7014. var getRoot = function () {
  7015. return settings.root_element || doc.body;
  7016. };
  7017. var getViewPort = function (argWin) {
  7018. var vp = getBounds(argWin);
  7019. return {
  7020. x: vp.x,
  7021. y: vp.y,
  7022. w: vp.width,
  7023. h: vp.height
  7024. };
  7025. };
  7026. var getPos$1 = function (elm, rootElm) {
  7027. return getPos(doc.body, get(elm), rootElm);
  7028. };
  7029. var setStyle = function (elm, name, value) {
  7030. var $elm = isString(name) ? $$(elm).css(name, value) : $$(elm).css(name);
  7031. if (settings.update_styles) {
  7032. updateInternalStyleAttr(styles, $elm);
  7033. }
  7034. };
  7035. var setStyles = function (elm, stylesArg) {
  7036. var $elm = $$(elm).css(stylesArg);
  7037. if (settings.update_styles) {
  7038. updateInternalStyleAttr(styles, $elm);
  7039. }
  7040. };
  7041. var getStyle = function (elm, name, computed) {
  7042. var $elm = $$(elm);
  7043. if (computed) {
  7044. return $elm.css(name);
  7045. }
  7046. name = name.replace(/-(\D)/g, function (a, b) {
  7047. return b.toUpperCase();
  7048. });
  7049. if (name === 'float') {
  7050. name = Env.browser.isIE() ? 'styleFloat' : 'cssFloat';
  7051. }
  7052. return $elm[0] && $elm[0].style ? $elm[0].style[name] : undefined;
  7053. };
  7054. var getSize = function (elm) {
  7055. var w, h;
  7056. elm = get(elm);
  7057. w = getStyle(elm, 'width');
  7058. h = getStyle(elm, 'height');
  7059. if (w.indexOf('px') === -1) {
  7060. w = 0;
  7061. }
  7062. if (h.indexOf('px') === -1) {
  7063. h = 0;
  7064. }
  7065. return {
  7066. w: parseInt(w, 10) || elm.offsetWidth || elm.clientWidth,
  7067. h: parseInt(h, 10) || elm.offsetHeight || elm.clientHeight
  7068. };
  7069. };
  7070. var getRect = function (elm) {
  7071. elm = get(elm);
  7072. var pos = getPos$1(elm);
  7073. var size = getSize(elm);
  7074. return {
  7075. x: pos.x,
  7076. y: pos.y,
  7077. w: size.w,
  7078. h: size.h
  7079. };
  7080. };
  7081. var is = function (elm, selector) {
  7082. var i;
  7083. if (!elm) {
  7084. return false;
  7085. }
  7086. if (!Array.isArray(elm)) {
  7087. if (selector === '*') {
  7088. return elm.nodeType === 1;
  7089. }
  7090. if (simpleSelectorRe.test(selector)) {
  7091. var selectors = selector.toLowerCase().split(/,/);
  7092. var elmName = elm.nodeName.toLowerCase();
  7093. for (i = selectors.length - 1; i >= 0; i--) {
  7094. if (selectors[i] === elmName) {
  7095. return true;
  7096. }
  7097. }
  7098. return false;
  7099. }
  7100. if (elm.nodeType && elm.nodeType !== 1) {
  7101. return false;
  7102. }
  7103. }
  7104. var elms = !Array.isArray(elm) ? [elm] : elm;
  7105. return Sizzle(selector, elms[0].ownerDocument || elms[0], null, elms).length > 0;
  7106. };
  7107. var getParents = function (elm, selector, root, collect) {
  7108. var result = [];
  7109. var selectorVal;
  7110. var node = get(elm);
  7111. collect = collect === undefined;
  7112. root = root || (getRoot().nodeName !== 'BODY' ? getRoot().parentNode : null);
  7113. if (Tools.is(selector, 'string')) {
  7114. selectorVal = selector;
  7115. if (selector === '*') {
  7116. selector = function (node) {
  7117. return node.nodeType === 1;
  7118. };
  7119. } else {
  7120. selector = function (node) {
  7121. return is(node, selectorVal);
  7122. };
  7123. }
  7124. }
  7125. while (node) {
  7126. if (node === root || !node.nodeType || node.nodeType === 9) {
  7127. break;
  7128. }
  7129. if (!selector || typeof selector === 'function' && selector(node)) {
  7130. if (collect) {
  7131. result.push(node);
  7132. } else {
  7133. return [node];
  7134. }
  7135. }
  7136. node = node.parentNode;
  7137. }
  7138. return collect ? result : null;
  7139. };
  7140. var getParent = function (node, selector, root) {
  7141. var parents = getParents(node, selector, root, false);
  7142. return parents && parents.length > 0 ? parents[0] : null;
  7143. };
  7144. var _findSib = function (node, selector, name) {
  7145. var func = selector;
  7146. if (node) {
  7147. if (typeof selector === 'string') {
  7148. func = function (node) {
  7149. return is(node, selector);
  7150. };
  7151. }
  7152. for (node = node[name]; node; node = node[name]) {
  7153. if (typeof func === 'function' && func(node)) {
  7154. return node;
  7155. }
  7156. }
  7157. }
  7158. return null;
  7159. };
  7160. var getNext = function (node, selector) {
  7161. return _findSib(node, selector, 'nextSibling');
  7162. };
  7163. var getPrev = function (node, selector) {
  7164. return _findSib(node, selector, 'previousSibling');
  7165. };
  7166. var select = function (selector, scope) {
  7167. return Sizzle(selector, get(scope) || settings.root_element || doc, []);
  7168. };
  7169. var run = function (elm, func, scope) {
  7170. var result;
  7171. var node = typeof elm === 'string' ? get(elm) : elm;
  7172. if (!node) {
  7173. return false;
  7174. }
  7175. if (Tools.isArray(node) && (node.length || node.length === 0)) {
  7176. result = [];
  7177. each$5(node, function (elm, i) {
  7178. if (elm) {
  7179. result.push(func.call(scope, typeof elm === 'string' ? get(elm) : elm, i));
  7180. }
  7181. });
  7182. return result;
  7183. }
  7184. var context = scope ? scope : _this;
  7185. return func.call(context, node);
  7186. };
  7187. var setAttribs = function (elm, attrs) {
  7188. $$(elm).each(function (i, node) {
  7189. each$5(attrs, function (value, name) {
  7190. setAttrib(node, name, value);
  7191. });
  7192. });
  7193. };
  7194. var setHTML = function (elm, html) {
  7195. var $elm = $$(elm);
  7196. if (isIE) {
  7197. $elm.each(function (i, target) {
  7198. if (target.canHaveHTML === false) {
  7199. return;
  7200. }
  7201. while (target.firstChild) {
  7202. target.removeChild(target.firstChild);
  7203. }
  7204. try {
  7205. target.innerHTML = '<br>' + html;
  7206. target.removeChild(target.firstChild);
  7207. } catch (ex) {
  7208. DomQuery('<div></div>').html('<br>' + html).contents().slice(1).appendTo(target);
  7209. }
  7210. return html;
  7211. });
  7212. } else {
  7213. $elm.html(html);
  7214. }
  7215. };
  7216. var add = function (parentElm, name, attrs, html, create) {
  7217. return run(parentElm, function (parentElm) {
  7218. var newElm = typeof name === 'string' ? doc.createElement(name) : name;
  7219. setAttribs(newElm, attrs);
  7220. if (html) {
  7221. if (typeof html !== 'string' && html.nodeType) {
  7222. newElm.appendChild(html);
  7223. } else if (typeof html === 'string') {
  7224. setHTML(newElm, html);
  7225. }
  7226. }
  7227. return !create ? parentElm.appendChild(newElm) : newElm;
  7228. });
  7229. };
  7230. var create = function (name, attrs, html) {
  7231. return add(doc.createElement(name), name, attrs, html, true);
  7232. };
  7233. var decode = Entities.decode;
  7234. var encode = Entities.encodeAllRaw;
  7235. var createHTML = function (name, attrs, html) {
  7236. var outHtml = '', key;
  7237. outHtml += '<' + name;
  7238. for (key in attrs) {
  7239. if (attrs.hasOwnProperty(key) && attrs[key] !== null && typeof attrs[key] !== 'undefined') {
  7240. outHtml += ' ' + key + '="' + encode(attrs[key]) + '"';
  7241. }
  7242. }
  7243. if (typeof html !== 'undefined') {
  7244. return outHtml + '>' + html + '</' + name + '>';
  7245. }
  7246. return outHtml + ' />';
  7247. };
  7248. var createFragment = function (html) {
  7249. var node;
  7250. var container = doc.createElement('div');
  7251. var frag = doc.createDocumentFragment();
  7252. frag.appendChild(container);
  7253. if (html) {
  7254. container.innerHTML = html;
  7255. }
  7256. while (node = container.firstChild) {
  7257. frag.appendChild(node);
  7258. }
  7259. frag.removeChild(container);
  7260. return frag;
  7261. };
  7262. var remove = function (node, keepChildren) {
  7263. var $node = $$(node);
  7264. if (keepChildren) {
  7265. $node.each(function () {
  7266. var child;
  7267. while (child = this.firstChild) {
  7268. if (child.nodeType === 3 && child.data.length === 0) {
  7269. this.removeChild(child);
  7270. } else {
  7271. this.parentNode.insertBefore(child, this);
  7272. }
  7273. }
  7274. }).remove();
  7275. } else {
  7276. $node.remove();
  7277. }
  7278. return $node.length > 1 ? $node.toArray() : $node[0];
  7279. };
  7280. var removeAllAttribs = function (e) {
  7281. return run(e, function (e) {
  7282. var i;
  7283. var attrs = e.attributes;
  7284. for (i = attrs.length - 1; i >= 0; i--) {
  7285. e.removeAttributeNode(attrs.item(i));
  7286. }
  7287. });
  7288. };
  7289. var parseStyle = function (cssText) {
  7290. return styles.parse(cssText);
  7291. };
  7292. var serializeStyle = function (stylesArg, name) {
  7293. return styles.serialize(stylesArg, name);
  7294. };
  7295. var addStyle = function (cssText) {
  7296. var head, styleElm;
  7297. if (self !== DOMUtils.DOM && doc === document) {
  7298. if (addedStyles[cssText]) {
  7299. return;
  7300. }
  7301. addedStyles[cssText] = true;
  7302. }
  7303. styleElm = doc.getElementById('mceDefaultStyles');
  7304. if (!styleElm) {
  7305. styleElm = doc.createElement('style');
  7306. styleElm.id = 'mceDefaultStyles';
  7307. styleElm.type = 'text/css';
  7308. head = doc.getElementsByTagName('head')[0];
  7309. if (head.firstChild) {
  7310. head.insertBefore(styleElm, head.firstChild);
  7311. } else {
  7312. head.appendChild(styleElm);
  7313. }
  7314. }
  7315. if (styleElm.styleSheet) {
  7316. styleElm.styleSheet.cssText += cssText;
  7317. } else {
  7318. styleElm.appendChild(doc.createTextNode(cssText));
  7319. }
  7320. };
  7321. var loadCSS = function (urls) {
  7322. if (!urls) {
  7323. urls = '';
  7324. }
  7325. each(urls.split(','), function (url) {
  7326. files[url] = true;
  7327. styleSheetLoader.load(url, noop);
  7328. });
  7329. };
  7330. var toggleClass = function (elm, cls, state) {
  7331. $$(elm).toggleClass(cls, state).each(function () {
  7332. if (this.className === '') {
  7333. DomQuery(this).attr('class', null);
  7334. }
  7335. });
  7336. };
  7337. var addClass = function (elm, cls) {
  7338. $$(elm).addClass(cls);
  7339. };
  7340. var removeClass = function (elm, cls) {
  7341. toggleClass(elm, cls, false);
  7342. };
  7343. var hasClass = function (elm, cls) {
  7344. return $$(elm).hasClass(cls);
  7345. };
  7346. var show = function (elm) {
  7347. $$(elm).show();
  7348. };
  7349. var hide = function (elm) {
  7350. $$(elm).hide();
  7351. };
  7352. var isHidden = function (elm) {
  7353. return $$(elm).css('display') === 'none';
  7354. };
  7355. var uniqueId = function (prefix) {
  7356. return (!prefix ? 'mce_' : prefix) + counter++;
  7357. };
  7358. var getOuterHTML = function (elm) {
  7359. var node = typeof elm === 'string' ? get(elm) : elm;
  7360. return isElement$1(node) ? node.outerHTML : DomQuery('<div></div>').append(DomQuery(node).clone()).html();
  7361. };
  7362. var setOuterHTML = function (elm, html) {
  7363. $$(elm).each(function () {
  7364. try {
  7365. if ('outerHTML' in this) {
  7366. this.outerHTML = html;
  7367. return;
  7368. }
  7369. } catch (ex) {
  7370. }
  7371. remove(DomQuery(this).html(html), true);
  7372. });
  7373. };
  7374. var insertAfter = function (node, reference) {
  7375. var referenceNode = get(reference);
  7376. return run(node, function (node) {
  7377. var parent = referenceNode.parentNode;
  7378. var nextSibling = referenceNode.nextSibling;
  7379. if (nextSibling) {
  7380. parent.insertBefore(node, nextSibling);
  7381. } else {
  7382. parent.appendChild(node);
  7383. }
  7384. return node;
  7385. });
  7386. };
  7387. var replace = function (newElm, oldElm, keepChildren) {
  7388. return run(oldElm, function (oldElm) {
  7389. if (Tools.is(oldElm, 'array')) {
  7390. newElm = newElm.cloneNode(true);
  7391. }
  7392. if (keepChildren) {
  7393. each$5(grep$1(oldElm.childNodes), function (node) {
  7394. newElm.appendChild(node);
  7395. });
  7396. }
  7397. return oldElm.parentNode.replaceChild(newElm, oldElm);
  7398. });
  7399. };
  7400. var rename = function (elm, name) {
  7401. var newElm;
  7402. if (elm.nodeName !== name.toUpperCase()) {
  7403. newElm = create(name);
  7404. each$5(getAttribs(elm), function (attrNode) {
  7405. setAttrib(newElm, attrNode.nodeName, getAttrib(elm, attrNode.nodeName));
  7406. });
  7407. replace(newElm, elm, true);
  7408. }
  7409. return newElm || elm;
  7410. };
  7411. var findCommonAncestor = function (a, b) {
  7412. var ps = a, pe;
  7413. while (ps) {
  7414. pe = b;
  7415. while (pe && ps !== pe) {
  7416. pe = pe.parentNode;
  7417. }
  7418. if (ps === pe) {
  7419. break;
  7420. }
  7421. ps = ps.parentNode;
  7422. }
  7423. if (!ps && a.ownerDocument) {
  7424. return a.ownerDocument.documentElement;
  7425. }
  7426. return ps;
  7427. };
  7428. var toHex = function (rgbVal) {
  7429. return styles.toHex(Tools.trim(rgbVal));
  7430. };
  7431. var isNonEmptyElement = function (node) {
  7432. if (isElement$1(node)) {
  7433. var isNamedAnchor = node.nodeName.toLowerCase() === 'a' && !getAttrib(node, 'href') && getAttrib(node, 'id');
  7434. if (getAttrib(node, 'name') || getAttrib(node, 'data-mce-bookmark') || isNamedAnchor) {
  7435. return true;
  7436. }
  7437. }
  7438. return false;
  7439. };
  7440. var isEmpty = function (node, elements) {
  7441. var type, name, brCount = 0;
  7442. if (isNonEmptyElement(node)) {
  7443. return false;
  7444. }
  7445. node = node.firstChild;
  7446. if (node) {
  7447. var walker = new DomTreeWalker(node, node.parentNode);
  7448. var whitespace = schema ? schema.getWhiteSpaceElements() : {};
  7449. elements = elements || (schema ? schema.getNonEmptyElements() : null);
  7450. do {
  7451. type = node.nodeType;
  7452. if (isElement$1(node)) {
  7453. var bogusVal = node.getAttribute('data-mce-bogus');
  7454. if (bogusVal) {
  7455. node = walker.next(bogusVal === 'all');
  7456. continue;
  7457. }
  7458. name = node.nodeName.toLowerCase();
  7459. if (elements && elements[name]) {
  7460. if (name === 'br') {
  7461. brCount++;
  7462. node = walker.next();
  7463. continue;
  7464. }
  7465. return false;
  7466. }
  7467. if (isNonEmptyElement(node)) {
  7468. return false;
  7469. }
  7470. }
  7471. if (type === 8) {
  7472. return false;
  7473. }
  7474. if (type === 3 && !isWhitespaceText(node.nodeValue)) {
  7475. return false;
  7476. }
  7477. if (type === 3 && node.parentNode && whitespace[node.parentNode.nodeName] && isWhitespaceText(node.nodeValue)) {
  7478. return false;
  7479. }
  7480. node = walker.next();
  7481. } while (node);
  7482. }
  7483. return brCount <= 1;
  7484. };
  7485. var createRng = function () {
  7486. return doc.createRange();
  7487. };
  7488. var split = function (parentElm, splitElm, replacementElm) {
  7489. var range = createRng();
  7490. var beforeFragment;
  7491. var afterFragment;
  7492. var parentNode;
  7493. if (parentElm && splitElm) {
  7494. range.setStart(parentElm.parentNode, findNodeIndex(parentElm));
  7495. range.setEnd(splitElm.parentNode, findNodeIndex(splitElm));
  7496. beforeFragment = range.extractContents();
  7497. range = createRng();
  7498. range.setStart(splitElm.parentNode, findNodeIndex(splitElm) + 1);
  7499. range.setEnd(parentElm.parentNode, findNodeIndex(parentElm) + 1);
  7500. afterFragment = range.extractContents();
  7501. parentNode = parentElm.parentNode;
  7502. parentNode.insertBefore(trimNode(self, beforeFragment), parentElm);
  7503. if (replacementElm) {
  7504. parentNode.insertBefore(replacementElm, parentElm);
  7505. } else {
  7506. parentNode.insertBefore(splitElm, parentElm);
  7507. }
  7508. parentNode.insertBefore(trimNode(self, afterFragment), parentElm);
  7509. remove(parentElm);
  7510. return replacementElm || splitElm;
  7511. }
  7512. };
  7513. var bind = function (target, name, func, scope) {
  7514. if (Tools.isArray(target)) {
  7515. var i = target.length;
  7516. var rv = [];
  7517. while (i--) {
  7518. rv[i] = bind(target[i], name, func, scope);
  7519. }
  7520. return rv;
  7521. }
  7522. if (settings.collect && (target === doc || target === win)) {
  7523. boundEvents.push([
  7524. target,
  7525. name,
  7526. func,
  7527. scope
  7528. ]);
  7529. }
  7530. var output = events.bind(target, name, func, scope || self);
  7531. return output;
  7532. };
  7533. var unbind = function (target, name, func) {
  7534. if (Tools.isArray(target)) {
  7535. var i = target.length;
  7536. var rv = [];
  7537. while (i--) {
  7538. rv[i] = unbind(target[i], name, func);
  7539. }
  7540. return rv;
  7541. } else {
  7542. if (boundEvents.length > 0 && (target === doc || target === win)) {
  7543. var i = boundEvents.length;
  7544. while (i--) {
  7545. var item = boundEvents[i];
  7546. if (target === item[0] && (!name || name === item[1]) && (!func || func === item[2])) {
  7547. events.unbind(item[0], item[1], item[2]);
  7548. }
  7549. }
  7550. }
  7551. return events.unbind(target, name, func);
  7552. }
  7553. };
  7554. var fire = function (target, name, evt) {
  7555. return events.fire(target, name, evt);
  7556. };
  7557. var getContentEditable = function (node) {
  7558. if (node && isElement$1(node)) {
  7559. var contentEditable = node.getAttribute('data-mce-contenteditable');
  7560. if (contentEditable && contentEditable !== 'inherit') {
  7561. return contentEditable;
  7562. }
  7563. return node.contentEditable !== 'inherit' ? node.contentEditable : null;
  7564. } else {
  7565. return null;
  7566. }
  7567. };
  7568. var getContentEditableParent = function (node) {
  7569. var root = getRoot();
  7570. var state = null;
  7571. for (; node && node !== root; node = node.parentNode) {
  7572. state = getContentEditable(node);
  7573. if (state !== null) {
  7574. break;
  7575. }
  7576. }
  7577. return state;
  7578. };
  7579. var destroy = function () {
  7580. if (boundEvents.length > 0) {
  7581. var i = boundEvents.length;
  7582. while (i--) {
  7583. var item = boundEvents[i];
  7584. events.unbind(item[0], item[1], item[2]);
  7585. }
  7586. }
  7587. each$1(files, function (_, url) {
  7588. styleSheetLoader.unload(url);
  7589. delete files[url];
  7590. });
  7591. if (Sizzle.setDocument) {
  7592. Sizzle.setDocument();
  7593. }
  7594. };
  7595. var isChildOf = function (node, parent) {
  7596. while (node) {
  7597. if (parent === node) {
  7598. return true;
  7599. }
  7600. node = node.parentNode;
  7601. }
  7602. return false;
  7603. };
  7604. var dumpRng = function (r) {
  7605. return 'startContainer: ' + r.startContainer.nodeName + ', startOffset: ' + r.startOffset + ', endContainer: ' + r.endContainer.nodeName + ', endOffset: ' + r.endOffset;
  7606. };
  7607. var self = {
  7608. doc: doc,
  7609. settings: settings,
  7610. win: win,
  7611. files: files,
  7612. stdMode: stdMode,
  7613. boxModel: boxModel,
  7614. styleSheetLoader: styleSheetLoader,
  7615. boundEvents: boundEvents,
  7616. styles: styles,
  7617. schema: schema,
  7618. events: events,
  7619. isBlock: isBlock,
  7620. $: $,
  7621. $$: $$,
  7622. root: null,
  7623. clone: clone,
  7624. getRoot: getRoot,
  7625. getViewPort: getViewPort,
  7626. getRect: getRect,
  7627. getSize: getSize,
  7628. getParent: getParent,
  7629. getParents: getParents,
  7630. get: get,
  7631. getNext: getNext,
  7632. getPrev: getPrev,
  7633. select: select,
  7634. is: is,
  7635. add: add,
  7636. create: create,
  7637. createHTML: createHTML,
  7638. createFragment: createFragment,
  7639. remove: remove,
  7640. setStyle: setStyle,
  7641. getStyle: getStyle,
  7642. setStyles: setStyles,
  7643. removeAllAttribs: removeAllAttribs,
  7644. setAttrib: setAttrib,
  7645. setAttribs: setAttribs,
  7646. getAttrib: getAttrib,
  7647. getPos: getPos$1,
  7648. parseStyle: parseStyle,
  7649. serializeStyle: serializeStyle,
  7650. addStyle: addStyle,
  7651. loadCSS: loadCSS,
  7652. addClass: addClass,
  7653. removeClass: removeClass,
  7654. hasClass: hasClass,
  7655. toggleClass: toggleClass,
  7656. show: show,
  7657. hide: hide,
  7658. isHidden: isHidden,
  7659. uniqueId: uniqueId,
  7660. setHTML: setHTML,
  7661. getOuterHTML: getOuterHTML,
  7662. setOuterHTML: setOuterHTML,
  7663. decode: decode,
  7664. encode: encode,
  7665. insertAfter: insertAfter,
  7666. replace: replace,
  7667. rename: rename,
  7668. findCommonAncestor: findCommonAncestor,
  7669. toHex: toHex,
  7670. run: run,
  7671. getAttribs: getAttribs,
  7672. isEmpty: isEmpty,
  7673. createRng: createRng,
  7674. nodeIndex: findNodeIndex,
  7675. split: split,
  7676. bind: bind,
  7677. unbind: unbind,
  7678. fire: fire,
  7679. getContentEditable: getContentEditable,
  7680. getContentEditableParent: getContentEditableParent,
  7681. destroy: destroy,
  7682. isChildOf: isChildOf,
  7683. dumpRng: dumpRng
  7684. };
  7685. var attrHooks = setupAttrHooks(styles, settings, function () {
  7686. return self;
  7687. });
  7688. return self;
  7689. }
  7690. (function (DOMUtils) {
  7691. DOMUtils.DOM = DOMUtils(document);
  7692. DOMUtils.nodeIndex = findNodeIndex;
  7693. }(DOMUtils || (DOMUtils = {})));
  7694. var DOMUtils$1 = DOMUtils;
  7695. var DOM = DOMUtils$1.DOM;
  7696. var each$6 = Tools.each, grep$2 = Tools.grep;
  7697. var QUEUED = 0;
  7698. var LOADING = 1;
  7699. var LOADED = 2;
  7700. var FAILED = 3;
  7701. var ScriptLoader = function () {
  7702. function ScriptLoader(settings) {
  7703. if (settings === void 0) {
  7704. settings = {};
  7705. }
  7706. this.states = {};
  7707. this.queue = [];
  7708. this.scriptLoadedCallbacks = {};
  7709. this.queueLoadedCallbacks = [];
  7710. this.loading = 0;
  7711. this.settings = settings;
  7712. }
  7713. ScriptLoader.prototype._setReferrerPolicy = function (referrerPolicy) {
  7714. this.settings.referrerPolicy = referrerPolicy;
  7715. };
  7716. ScriptLoader.prototype.loadScript = function (url, success, failure) {
  7717. var dom = DOM;
  7718. var elm;
  7719. var done = function () {
  7720. dom.remove(id);
  7721. if (elm) {
  7722. elm.onreadystatechange = elm.onload = elm = null;
  7723. }
  7724. success();
  7725. };
  7726. var error = function () {
  7727. if (isFunction(failure)) {
  7728. failure();
  7729. } else {
  7730. if (typeof console !== 'undefined' && console.log) {
  7731. console.log('Failed to load script: ' + url);
  7732. }
  7733. }
  7734. };
  7735. var id = dom.uniqueId();
  7736. elm = document.createElement('script');
  7737. elm.id = id;
  7738. elm.type = 'text/javascript';
  7739. elm.src = Tools._addCacheSuffix(url);
  7740. if (this.settings.referrerPolicy) {
  7741. dom.setAttrib(elm, 'referrerpolicy', this.settings.referrerPolicy);
  7742. }
  7743. elm.onload = done;
  7744. elm.onerror = error;
  7745. (document.getElementsByTagName('head')[0] || document.body).appendChild(elm);
  7746. };
  7747. ScriptLoader.prototype.isDone = function (url) {
  7748. return this.states[url] === LOADED;
  7749. };
  7750. ScriptLoader.prototype.markDone = function (url) {
  7751. this.states[url] = LOADED;
  7752. };
  7753. ScriptLoader.prototype.add = function (url, success, scope, failure) {
  7754. var state = this.states[url];
  7755. if (state === undefined) {
  7756. this.queue.push(url);
  7757. this.states[url] = QUEUED;
  7758. }
  7759. if (success) {
  7760. if (!this.scriptLoadedCallbacks[url]) {
  7761. this.scriptLoadedCallbacks[url] = [];
  7762. }
  7763. this.scriptLoadedCallbacks[url].push({
  7764. success: success,
  7765. failure: failure,
  7766. scope: scope || this
  7767. });
  7768. }
  7769. };
  7770. ScriptLoader.prototype.load = function (url, success, scope, failure) {
  7771. return this.add(url, success, scope, failure);
  7772. };
  7773. ScriptLoader.prototype.remove = function (url) {
  7774. delete this.states[url];
  7775. delete this.scriptLoadedCallbacks[url];
  7776. };
  7777. ScriptLoader.prototype.loadQueue = function (success, scope, failure) {
  7778. this.loadScripts(this.queue, success, scope, failure);
  7779. };
  7780. ScriptLoader.prototype.loadScripts = function (scripts, success, scope, failure) {
  7781. var self = this;
  7782. var failures = [];
  7783. var execCallbacks = function (name, url) {
  7784. each$6(self.scriptLoadedCallbacks[url], function (callback) {
  7785. if (isFunction(callback[name])) {
  7786. callback[name].call(callback.scope);
  7787. }
  7788. });
  7789. self.scriptLoadedCallbacks[url] = undefined;
  7790. };
  7791. self.queueLoadedCallbacks.push({
  7792. success: success,
  7793. failure: failure,
  7794. scope: scope || this
  7795. });
  7796. var loadScripts = function () {
  7797. var loadingScripts = grep$2(scripts);
  7798. scripts.length = 0;
  7799. each$6(loadingScripts, function (url) {
  7800. if (self.states[url] === LOADED) {
  7801. execCallbacks('success', url);
  7802. return;
  7803. }
  7804. if (self.states[url] === FAILED) {
  7805. execCallbacks('failure', url);
  7806. return;
  7807. }
  7808. if (self.states[url] !== LOADING) {
  7809. self.states[url] = LOADING;
  7810. self.loading++;
  7811. self.loadScript(url, function () {
  7812. self.states[url] = LOADED;
  7813. self.loading--;
  7814. execCallbacks('success', url);
  7815. loadScripts();
  7816. }, function () {
  7817. self.states[url] = FAILED;
  7818. self.loading--;
  7819. failures.push(url);
  7820. execCallbacks('failure', url);
  7821. loadScripts();
  7822. });
  7823. }
  7824. });
  7825. if (!self.loading) {
  7826. var notifyCallbacks = self.queueLoadedCallbacks.slice(0);
  7827. self.queueLoadedCallbacks.length = 0;
  7828. each$6(notifyCallbacks, function (callback) {
  7829. if (failures.length === 0) {
  7830. if (isFunction(callback.success)) {
  7831. callback.success.call(callback.scope);
  7832. }
  7833. } else {
  7834. if (isFunction(callback.failure)) {
  7835. callback.failure.call(callback.scope, failures);
  7836. }
  7837. }
  7838. });
  7839. }
  7840. };
  7841. loadScripts();
  7842. };
  7843. ScriptLoader.ScriptLoader = new ScriptLoader();
  7844. return ScriptLoader;
  7845. }();
  7846. var Cell = function (initial) {
  7847. var value = initial;
  7848. var get = function () {
  7849. return value;
  7850. };
  7851. var set = function (v) {
  7852. value = v;
  7853. };
  7854. return {
  7855. get: get,
  7856. set: set
  7857. };
  7858. };
  7859. var isRaw = function (str) {
  7860. return isObject(str) && has(str, 'raw');
  7861. };
  7862. var isTokenised = function (str) {
  7863. return isArray(str) && str.length > 1;
  7864. };
  7865. var data = {};
  7866. var currentCode = Cell('en');
  7867. var getLanguageData = function () {
  7868. return get(data, currentCode.get());
  7869. };
  7870. var getData = function () {
  7871. return map$1(data, function (value) {
  7872. return __assign({}, value);
  7873. });
  7874. };
  7875. var setCode = function (newCode) {
  7876. if (newCode) {
  7877. currentCode.set(newCode);
  7878. }
  7879. };
  7880. var getCode = function () {
  7881. return currentCode.get();
  7882. };
  7883. var add = function (code, items) {
  7884. var langData = data[code];
  7885. if (!langData) {
  7886. data[code] = langData = {};
  7887. }
  7888. each$1(items, function (translation, name) {
  7889. langData[name.toLowerCase()] = translation;
  7890. });
  7891. };
  7892. var translate = function (text) {
  7893. var langData = getLanguageData().getOr({});
  7894. var toString = function (obj) {
  7895. if (isFunction(obj)) {
  7896. return Object.prototype.toString.call(obj);
  7897. }
  7898. return !isEmpty(obj) ? '' + obj : '';
  7899. };
  7900. var isEmpty = function (text) {
  7901. return text === '' || text === null || text === undefined;
  7902. };
  7903. var getLangData = function (text) {
  7904. var textstr = toString(text);
  7905. return get(langData, textstr.toLowerCase()).map(toString).getOr(textstr);
  7906. };
  7907. var removeContext = function (str) {
  7908. return str.replace(/{context:\w+}$/, '');
  7909. };
  7910. if (isEmpty(text)) {
  7911. return '';
  7912. }
  7913. if (isRaw(text)) {
  7914. return toString(text.raw);
  7915. }
  7916. if (isTokenised(text)) {
  7917. var values_1 = text.slice(1);
  7918. var substitued = getLangData(text[0]).replace(/\{([0-9]+)\}/g, function ($1, $2) {
  7919. return has(values_1, $2) ? toString(values_1[$2]) : $1;
  7920. });
  7921. return removeContext(substitued);
  7922. }
  7923. return removeContext(getLangData(text));
  7924. };
  7925. var isRtl = function () {
  7926. return getLanguageData().bind(function (items) {
  7927. return get(items, '_dir');
  7928. }).exists(function (dir) {
  7929. return dir === 'rtl';
  7930. });
  7931. };
  7932. var hasCode = function (code) {
  7933. return has(data, code);
  7934. };
  7935. var I18n = {
  7936. getData: getData,
  7937. setCode: setCode,
  7938. getCode: getCode,
  7939. add: add,
  7940. translate: translate,
  7941. isRtl: isRtl,
  7942. hasCode: hasCode
  7943. };
  7944. function AddOnManager() {
  7945. var _this = this;
  7946. var items = [];
  7947. var urls = {};
  7948. var lookup = {};
  7949. var _listeners = [];
  7950. var runListeners = function (name, state) {
  7951. var matchedListeners = filter(_listeners, function (listener) {
  7952. return listener.name === name && listener.state === state;
  7953. });
  7954. each(matchedListeners, function (listener) {
  7955. return listener.callback();
  7956. });
  7957. };
  7958. var get = function (name) {
  7959. if (lookup[name]) {
  7960. return lookup[name].instance;
  7961. }
  7962. return undefined;
  7963. };
  7964. var dependencies = function (name) {
  7965. var result;
  7966. if (lookup[name]) {
  7967. result = lookup[name].dependencies;
  7968. }
  7969. return result || [];
  7970. };
  7971. var requireLangPack = function (name, languages) {
  7972. if (AddOnManager.languageLoad !== false) {
  7973. waitFor(name, function () {
  7974. var language = I18n.getCode();
  7975. var wrappedLanguages = ',' + (languages || '') + ',';
  7976. if (!language || languages && wrappedLanguages.indexOf(',' + language + ',') === -1) {
  7977. return;
  7978. }
  7979. ScriptLoader.ScriptLoader.add(urls[name] + '/langs/' + language + '.js');
  7980. }, 'loaded');
  7981. }
  7982. };
  7983. var add = function (id, addOn, dependencies) {
  7984. var addOnConstructor = addOn;
  7985. items.push(addOnConstructor);
  7986. lookup[id] = {
  7987. instance: addOnConstructor,
  7988. dependencies: dependencies
  7989. };
  7990. runListeners(id, 'added');
  7991. return addOnConstructor;
  7992. };
  7993. var remove = function (name) {
  7994. delete urls[name];
  7995. delete lookup[name];
  7996. };
  7997. var createUrl = function (baseUrl, dep) {
  7998. if (typeof dep === 'object') {
  7999. return dep;
  8000. }
  8001. return typeof baseUrl === 'string' ? {
  8002. prefix: '',
  8003. resource: dep,
  8004. suffix: ''
  8005. } : {
  8006. prefix: baseUrl.prefix,
  8007. resource: dep,
  8008. suffix: baseUrl.suffix
  8009. };
  8010. };
  8011. var addComponents = function (pluginName, scripts) {
  8012. var pluginUrl = _this.urls[pluginName];
  8013. each(scripts, function (script) {
  8014. ScriptLoader.ScriptLoader.add(pluginUrl + '/' + script);
  8015. });
  8016. };
  8017. var loadDependencies = function (name, addOnUrl, success, scope) {
  8018. var deps = dependencies(name);
  8019. each(deps, function (dep) {
  8020. var newUrl = createUrl(addOnUrl, dep);
  8021. load(newUrl.resource, newUrl, undefined, undefined);
  8022. });
  8023. if (success) {
  8024. if (scope) {
  8025. success.call(scope);
  8026. } else {
  8027. success.call(ScriptLoader);
  8028. }
  8029. }
  8030. };
  8031. var load = function (name, addOnUrl, success, scope, failure) {
  8032. if (urls[name]) {
  8033. return;
  8034. }
  8035. var urlString = typeof addOnUrl === 'string' ? addOnUrl : addOnUrl.prefix + addOnUrl.resource + addOnUrl.suffix;
  8036. if (urlString.indexOf('/') !== 0 && urlString.indexOf('://') === -1) {
  8037. urlString = AddOnManager.baseURL + '/' + urlString;
  8038. }
  8039. urls[name] = urlString.substring(0, urlString.lastIndexOf('/'));
  8040. var done = function () {
  8041. runListeners(name, 'loaded');
  8042. loadDependencies(name, addOnUrl, success, scope);
  8043. };
  8044. if (lookup[name]) {
  8045. done();
  8046. } else {
  8047. ScriptLoader.ScriptLoader.add(urlString, done, scope, failure);
  8048. }
  8049. };
  8050. var waitFor = function (name, callback, state) {
  8051. if (state === void 0) {
  8052. state = 'added';
  8053. }
  8054. if (has(lookup, name) && state === 'added') {
  8055. callback();
  8056. } else if (has(urls, name) && state === 'loaded') {
  8057. callback();
  8058. } else {
  8059. _listeners.push({
  8060. name: name,
  8061. state: state,
  8062. callback: callback
  8063. });
  8064. }
  8065. };
  8066. return {
  8067. items: items,
  8068. urls: urls,
  8069. lookup: lookup,
  8070. _listeners: _listeners,
  8071. get: get,
  8072. dependencies: dependencies,
  8073. requireLangPack: requireLangPack,
  8074. add: add,
  8075. remove: remove,
  8076. createUrl: createUrl,
  8077. addComponents: addComponents,
  8078. load: load,
  8079. waitFor: waitFor
  8080. };
  8081. }
  8082. (function (AddOnManager) {
  8083. AddOnManager.PluginManager = AddOnManager();
  8084. AddOnManager.ThemeManager = AddOnManager();
  8085. }(AddOnManager || (AddOnManager = {})));
  8086. var AddOnManager$1 = AddOnManager;
  8087. var first = function (fn, rate) {
  8088. var timer = null;
  8089. var cancel = function () {
  8090. if (timer !== null) {
  8091. clearTimeout(timer);
  8092. timer = null;
  8093. }
  8094. };
  8095. var throttle = function () {
  8096. var args = [];
  8097. for (var _i = 0; _i < arguments.length; _i++) {
  8098. args[_i] = arguments[_i];
  8099. }
  8100. if (timer === null) {
  8101. timer = setTimeout(function () {
  8102. fn.apply(null, args);
  8103. timer = null;
  8104. }, rate);
  8105. }
  8106. };
  8107. return {
  8108. cancel: cancel,
  8109. throttle: throttle
  8110. };
  8111. };
  8112. var last$2 = function (fn, rate) {
  8113. var timer = null;
  8114. var cancel = function () {
  8115. if (timer !== null) {
  8116. clearTimeout(timer);
  8117. timer = null;
  8118. }
  8119. };
  8120. var throttle = function () {
  8121. var args = [];
  8122. for (var _i = 0; _i < arguments.length; _i++) {
  8123. args[_i] = arguments[_i];
  8124. }
  8125. if (timer !== null) {
  8126. clearTimeout(timer);
  8127. }
  8128. timer = setTimeout(function () {
  8129. fn.apply(null, args);
  8130. timer = null;
  8131. }, rate);
  8132. };
  8133. return {
  8134. cancel: cancel,
  8135. throttle: throttle
  8136. };
  8137. };
  8138. var read = function (element, attr) {
  8139. var value = get$3(element, attr);
  8140. return value === undefined || value === '' ? [] : value.split(' ');
  8141. };
  8142. var add$1 = function (element, attr, id) {
  8143. var old = read(element, attr);
  8144. var nu = old.concat([id]);
  8145. set(element, attr, nu.join(' '));
  8146. return true;
  8147. };
  8148. var remove$2 = function (element, attr, id) {
  8149. var nu = filter(read(element, attr), function (v) {
  8150. return v !== id;
  8151. });
  8152. if (nu.length > 0) {
  8153. set(element, attr, nu.join(' '));
  8154. } else {
  8155. remove$1(element, attr);
  8156. }
  8157. return false;
  8158. };
  8159. var supports = function (element) {
  8160. return element.dom.classList !== undefined;
  8161. };
  8162. var get$5 = function (element) {
  8163. return read(element, 'class');
  8164. };
  8165. var add$2 = function (element, clazz) {
  8166. return add$1(element, 'class', clazz);
  8167. };
  8168. var remove$3 = function (element, clazz) {
  8169. return remove$2(element, 'class', clazz);
  8170. };
  8171. var add$3 = function (element, clazz) {
  8172. if (supports(element)) {
  8173. element.dom.classList.add(clazz);
  8174. } else {
  8175. add$2(element, clazz);
  8176. }
  8177. };
  8178. var cleanClass = function (element) {
  8179. var classList = supports(element) ? element.dom.classList : get$5(element);
  8180. if (classList.length === 0) {
  8181. remove$1(element, 'class');
  8182. }
  8183. };
  8184. var remove$4 = function (element, clazz) {
  8185. if (supports(element)) {
  8186. var classList = element.dom.classList;
  8187. classList.remove(clazz);
  8188. } else {
  8189. remove$3(element, clazz);
  8190. }
  8191. cleanClass(element);
  8192. };
  8193. var has$2 = function (element, clazz) {
  8194. return supports(element) && element.dom.classList.contains(clazz);
  8195. };
  8196. var descendants = function (scope, predicate) {
  8197. var result = [];
  8198. each(children(scope), function (x) {
  8199. if (predicate(x)) {
  8200. result = result.concat([x]);
  8201. }
  8202. result = result.concat(descendants(x, predicate));
  8203. });
  8204. return result;
  8205. };
  8206. var descendants$1 = function (scope, selector) {
  8207. return all(selector, scope);
  8208. };
  8209. var annotation = constant('mce-annotation');
  8210. var dataAnnotation = constant('data-mce-annotation');
  8211. var dataAnnotationId = constant('data-mce-annotation-uid');
  8212. var identify = function (editor, annotationName) {
  8213. var rng = editor.selection.getRng();
  8214. var start = SugarElement.fromDom(rng.startContainer);
  8215. var root = SugarElement.fromDom(editor.getBody());
  8216. var selector = annotationName.fold(function () {
  8217. return '.' + annotation();
  8218. }, function (an) {
  8219. return '[' + dataAnnotation() + '="' + an + '"]';
  8220. });
  8221. var newStart = child(start, rng.startOffset).getOr(start);
  8222. var closest = closest$1(newStart, selector, function (n) {
  8223. return eq$2(n, root);
  8224. });
  8225. var getAttr = function (c, property) {
  8226. if (has$1(c, property)) {
  8227. return Optional.some(get$3(c, property));
  8228. } else {
  8229. return Optional.none();
  8230. }
  8231. };
  8232. return closest.bind(function (c) {
  8233. return getAttr(c, '' + dataAnnotationId()).bind(function (uid) {
  8234. return getAttr(c, '' + dataAnnotation()).map(function (name) {
  8235. var elements = findMarkers(editor, uid);
  8236. return {
  8237. uid: uid,
  8238. name: name,
  8239. elements: elements
  8240. };
  8241. });
  8242. });
  8243. });
  8244. };
  8245. var isAnnotation = function (elem) {
  8246. return isElement(elem) && has$2(elem, annotation());
  8247. };
  8248. var findMarkers = function (editor, uid) {
  8249. var body = SugarElement.fromDom(editor.getBody());
  8250. return descendants$1(body, '[' + dataAnnotationId() + '="' + uid + '"]');
  8251. };
  8252. var findAll = function (editor, name) {
  8253. var body = SugarElement.fromDom(editor.getBody());
  8254. var markers = descendants$1(body, '[' + dataAnnotation() + '="' + name + '"]');
  8255. var directory = {};
  8256. each(markers, function (m) {
  8257. var uid = get$3(m, dataAnnotationId());
  8258. var nodesAlready = directory.hasOwnProperty(uid) ? directory[uid] : [];
  8259. directory[uid] = nodesAlready.concat([m]);
  8260. });
  8261. return directory;
  8262. };
  8263. var setup = function (editor, _registry) {
  8264. var changeCallbacks = Cell({});
  8265. var initData = function () {
  8266. return {
  8267. listeners: [],
  8268. previous: Cell(Optional.none())
  8269. };
  8270. };
  8271. var withCallbacks = function (name, f) {
  8272. updateCallbacks(name, function (data) {
  8273. f(data);
  8274. return data;
  8275. });
  8276. };
  8277. var updateCallbacks = function (name, f) {
  8278. var callbackMap = changeCallbacks.get();
  8279. var data = callbackMap.hasOwnProperty(name) ? callbackMap[name] : initData();
  8280. var outputData = f(data);
  8281. callbackMap[name] = outputData;
  8282. changeCallbacks.set(callbackMap);
  8283. };
  8284. var fireCallbacks = function (name, uid, elements) {
  8285. withCallbacks(name, function (data) {
  8286. each(data.listeners, function (f) {
  8287. return f(true, name, {
  8288. uid: uid,
  8289. nodes: map(elements, function (elem) {
  8290. return elem.dom;
  8291. })
  8292. });
  8293. });
  8294. });
  8295. };
  8296. var fireNoAnnotation = function (name) {
  8297. withCallbacks(name, function (data) {
  8298. each(data.listeners, function (f) {
  8299. return f(false, name);
  8300. });
  8301. });
  8302. };
  8303. var onNodeChange = last$2(function () {
  8304. var callbackMap = changeCallbacks.get();
  8305. var annotations = sort$1(keys(callbackMap));
  8306. each(annotations, function (name) {
  8307. updateCallbacks(name, function (data) {
  8308. var prev = data.previous.get();
  8309. identify(editor, Optional.some(name)).fold(function () {
  8310. if (prev.isSome()) {
  8311. fireNoAnnotation(name);
  8312. data.previous.set(Optional.none());
  8313. }
  8314. }, function (_a) {
  8315. var uid = _a.uid, name = _a.name, elements = _a.elements;
  8316. if (!prev.is(uid)) {
  8317. fireCallbacks(name, uid, elements);
  8318. data.previous.set(Optional.some(uid));
  8319. }
  8320. });
  8321. return {
  8322. previous: data.previous,
  8323. listeners: data.listeners
  8324. };
  8325. });
  8326. });
  8327. }, 30);
  8328. editor.on('remove', function () {
  8329. onNodeChange.cancel();
  8330. });
  8331. editor.on('NodeChange', function () {
  8332. onNodeChange.throttle();
  8333. });
  8334. var addListener = function (name, f) {
  8335. updateCallbacks(name, function (data) {
  8336. return {
  8337. previous: data.previous,
  8338. listeners: data.listeners.concat([f])
  8339. };
  8340. });
  8341. };
  8342. return { addListener: addListener };
  8343. };
  8344. var setup$1 = function (editor, registry) {
  8345. var identifyParserNode = function (span) {
  8346. return Optional.from(span.attr(dataAnnotation())).bind(registry.lookup);
  8347. };
  8348. editor.on('init', function () {
  8349. editor.serializer.addNodeFilter('span', function (spans) {
  8350. each(spans, function (span) {
  8351. identifyParserNode(span).each(function (settings) {
  8352. if (settings.persistent === false) {
  8353. span.unwrap();
  8354. }
  8355. });
  8356. });
  8357. });
  8358. });
  8359. };
  8360. var create$2 = function () {
  8361. var annotations = {};
  8362. var register = function (name, settings) {
  8363. annotations[name] = {
  8364. name: name,
  8365. settings: settings
  8366. };
  8367. };
  8368. var lookup = function (name) {
  8369. return annotations.hasOwnProperty(name) ? Optional.from(annotations[name]).map(function (a) {
  8370. return a.settings;
  8371. }) : Optional.none();
  8372. };
  8373. return {
  8374. register: register,
  8375. lookup: lookup
  8376. };
  8377. };
  8378. var unique = 0;
  8379. var generate$1 = function (prefix) {
  8380. var date = new Date();
  8381. var time = date.getTime();
  8382. var random = Math.floor(Math.random() * 1000000000);
  8383. unique++;
  8384. return prefix + '_' + random + unique + String(time);
  8385. };
  8386. var add$4 = function (element, classes) {
  8387. each(classes, function (x) {
  8388. add$3(element, x);
  8389. });
  8390. };
  8391. var fromHtml$1 = function (html, scope) {
  8392. var doc = scope || document;
  8393. var div = doc.createElement('div');
  8394. div.innerHTML = html;
  8395. return children(SugarElement.fromDom(div));
  8396. };
  8397. var get$6 = function (element) {
  8398. return element.dom.innerHTML;
  8399. };
  8400. var set$1 = function (element, content) {
  8401. var owner$1 = owner(element);
  8402. var docDom = owner$1.dom;
  8403. var fragment = SugarElement.fromDom(docDom.createDocumentFragment());
  8404. var contentElements = fromHtml$1(content, docDom);
  8405. append$1(fragment, contentElements);
  8406. empty(element);
  8407. append(element, fragment);
  8408. };
  8409. var clone$1 = function (original, isDeep) {
  8410. return SugarElement.fromDom(original.dom.cloneNode(isDeep));
  8411. };
  8412. var shallow = function (original) {
  8413. return clone$1(original, false);
  8414. };
  8415. var deep = function (original) {
  8416. return clone$1(original, true);
  8417. };
  8418. var TextWalker = function (startNode, rootNode, isBoundary) {
  8419. if (isBoundary === void 0) {
  8420. isBoundary = never;
  8421. }
  8422. var walker = new DomTreeWalker(startNode, rootNode);
  8423. var walk = function (direction) {
  8424. var next;
  8425. do {
  8426. next = walker[direction]();
  8427. } while (next && !isText$1(next) && !isBoundary(next));
  8428. return Optional.from(next).filter(isText$1);
  8429. };
  8430. return {
  8431. current: function () {
  8432. return Optional.from(walker.current()).filter(isText$1);
  8433. },
  8434. next: function () {
  8435. return walk('next');
  8436. },
  8437. prev: function () {
  8438. return walk('prev');
  8439. },
  8440. prev2: function () {
  8441. return walk('prev2');
  8442. }
  8443. };
  8444. };
  8445. var TextSeeker = function (dom, isBoundary) {
  8446. var isBlockBoundary = isBoundary ? isBoundary : function (node) {
  8447. return dom.isBlock(node) || isBr(node) || isContentEditableFalse(node);
  8448. };
  8449. var walk = function (node, offset, walker, process) {
  8450. if (isText$1(node)) {
  8451. var newOffset = process(node, offset, node.data);
  8452. if (newOffset !== -1) {
  8453. return Optional.some({
  8454. container: node,
  8455. offset: newOffset
  8456. });
  8457. }
  8458. }
  8459. return walker().bind(function (next) {
  8460. return walk(next.container, next.offset, walker, process);
  8461. });
  8462. };
  8463. var backwards = function (node, offset, process, root) {
  8464. var walker = TextWalker(node, root, isBlockBoundary);
  8465. return walk(node, offset, function () {
  8466. return walker.prev().map(function (prev) {
  8467. return {
  8468. container: prev,
  8469. offset: prev.length
  8470. };
  8471. });
  8472. }, process).getOrNull();
  8473. };
  8474. var forwards = function (node, offset, process, root) {
  8475. var walker = TextWalker(node, root, isBlockBoundary);
  8476. return walk(node, offset, function () {
  8477. return walker.next().map(function (next) {
  8478. return {
  8479. container: next,
  8480. offset: 0
  8481. };
  8482. });
  8483. }, process).getOrNull();
  8484. };
  8485. return {
  8486. backwards: backwards,
  8487. forwards: forwards
  8488. };
  8489. };
  8490. var cat = function (arr) {
  8491. var r = [];
  8492. var push = function (x) {
  8493. r.push(x);
  8494. };
  8495. for (var i = 0; i < arr.length; i++) {
  8496. arr[i].each(push);
  8497. }
  8498. return r;
  8499. };
  8500. var lift2 = function (oa, ob, f) {
  8501. return oa.isSome() && ob.isSome() ? Optional.some(f(oa.getOrDie(), ob.getOrDie())) : Optional.none();
  8502. };
  8503. var lift3 = function (oa, ob, oc, f) {
  8504. return oa.isSome() && ob.isSome() && oc.isSome() ? Optional.some(f(oa.getOrDie(), ob.getOrDie(), oc.getOrDie())) : Optional.none();
  8505. };
  8506. var someIf = function (b, a) {
  8507. return b ? Optional.some(a) : Optional.none();
  8508. };
  8509. var round = Math.round;
  8510. var clone$2 = function (rect) {
  8511. if (!rect) {
  8512. return {
  8513. left: 0,
  8514. top: 0,
  8515. bottom: 0,
  8516. right: 0,
  8517. width: 0,
  8518. height: 0
  8519. };
  8520. }
  8521. return {
  8522. left: round(rect.left),
  8523. top: round(rect.top),
  8524. bottom: round(rect.bottom),
  8525. right: round(rect.right),
  8526. width: round(rect.width),
  8527. height: round(rect.height)
  8528. };
  8529. };
  8530. var collapse = function (rect, toStart) {
  8531. rect = clone$2(rect);
  8532. if (toStart) {
  8533. rect.right = rect.left;
  8534. } else {
  8535. rect.left = rect.left + rect.width;
  8536. rect.right = rect.left;
  8537. }
  8538. rect.width = 0;
  8539. return rect;
  8540. };
  8541. var isEqual = function (rect1, rect2) {
  8542. return rect1.left === rect2.left && rect1.top === rect2.top && rect1.bottom === rect2.bottom && rect1.right === rect2.right;
  8543. };
  8544. var isValidOverflow = function (overflowY, rect1, rect2) {
  8545. return overflowY >= 0 && overflowY <= Math.min(rect1.height, rect2.height) / 2;
  8546. };
  8547. var isAbove = function (rect1, rect2) {
  8548. var halfHeight = Math.min(rect2.height / 2, rect1.height / 2);
  8549. if (rect1.bottom - halfHeight < rect2.top) {
  8550. return true;
  8551. }
  8552. if (rect1.top > rect2.bottom) {
  8553. return false;
  8554. }
  8555. return isValidOverflow(rect2.top - rect1.bottom, rect1, rect2);
  8556. };
  8557. var isBelow = function (rect1, rect2) {
  8558. if (rect1.top > rect2.bottom) {
  8559. return true;
  8560. }
  8561. if (rect1.bottom < rect2.top) {
  8562. return false;
  8563. }
  8564. return isValidOverflow(rect2.bottom - rect1.top, rect1, rect2);
  8565. };
  8566. var containsXY = function (rect, clientX, clientY) {
  8567. return clientX >= rect.left && clientX <= rect.right && clientY >= rect.top && clientY <= rect.bottom;
  8568. };
  8569. var getSelectedNode = function (range) {
  8570. var startContainer = range.startContainer, startOffset = range.startOffset;
  8571. if (startContainer.hasChildNodes() && range.endOffset === startOffset + 1) {
  8572. return startContainer.childNodes[startOffset];
  8573. }
  8574. return null;
  8575. };
  8576. var getNode = function (container, offset) {
  8577. if (container.nodeType === 1 && container.hasChildNodes()) {
  8578. if (offset >= container.childNodes.length) {
  8579. offset = container.childNodes.length - 1;
  8580. }
  8581. container = container.childNodes[offset];
  8582. }
  8583. return container;
  8584. };
  8585. var extendingChars = new RegExp('[\u0300-\u036f\u0483-\u0487\u0488-\u0489\u0591-\u05bd\u05bf\u05c1-\u05c2\u05c4-\u05c5\u05c7\u0610-\u061a' + '\u064b-\u065f\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7-\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0' + '\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08e3-\u0902\u093a\u093c' + '\u0941-\u0948\u094d\u0951-\u0957\u0962-\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2-\u09e3' + '\u0a01-\u0a02\u0a3c\u0a41-\u0a42\u0a47-\u0a48\u0a4b-\u0a4d\u0a51\u0a70-\u0a71\u0a75\u0a81-\u0a82\u0abc' + '\u0ac1-\u0ac5\u0ac7-\u0ac8\u0acd\u0ae2-\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57' + '\u0b62-\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c00\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55-\u0c56' + '\u0c62-\u0c63\u0c81\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc-\u0ccd\u0cd5-\u0cd6\u0ce2-\u0ce3\u0d01\u0d3e\u0d41-\u0d44' + '\u0d4d\u0d57\u0d62-\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9' + '\u0ebb-\u0ebc\u0ec8-\u0ecd\u0f18-\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86-\u0f87\u0f8d-\u0f97' + '\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039-\u103a\u103d-\u103e\u1058-\u1059\u105e-\u1060\u1071-\u1074' + '\u1082\u1085-\u1086\u108d\u109d\u135d-\u135f\u1712-\u1714\u1732-\u1734\u1752-\u1753\u1772-\u1773\u17b4-\u17b5' + '\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927-\u1928\u1932\u1939-\u193b\u1a17-\u1a18' + '\u1a1b\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1ab0-\u1abd\u1ABE\u1b00-\u1b03\u1b34' + '\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80-\u1b81\u1ba2-\u1ba5\u1ba8-\u1ba9\u1bab-\u1bad\u1be6\u1be8-\u1be9' + '\u1bed\u1bef-\u1bf1\u1c2c-\u1c33\u1c36-\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1cf4\u1cf8-\u1cf9' + '\u1dc0-\u1df5\u1dfc-\u1dff\u200c-\u200d\u20d0-\u20dc\u20DD-\u20E0\u20e1\u20E2-\u20E4\u20e5-\u20f0\u2cef-\u2cf1' + '\u2d7f\u2de0-\u2dff\u302a-\u302d\u302e-\u302f\u3099-\u309a\ua66f\uA670-\uA672\ua674-\ua67d\ua69e-\ua69f\ua6f0-\ua6f1' + '\ua802\ua806\ua80b\ua825-\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc' + '\ua9e5\uaa29-\uaa2e\uaa31-\uaa32\uaa35-\uaa36\uaa43\uaa4c\uaa7c\uaab0\uaab2-\uaab4\uaab7-\uaab8\uaabe-\uaabf\uaac1' + '\uaaec-\uaaed\uaaf6\uabe5\uabe8\uabed\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\uff9e-\uff9f]');
  8586. var isExtendingChar = function (ch) {
  8587. return typeof ch === 'string' && ch.charCodeAt(0) >= 768 && extendingChars.test(ch);
  8588. };
  8589. var or = function () {
  8590. var args = [];
  8591. for (var _i = 0; _i < arguments.length; _i++) {
  8592. args[_i] = arguments[_i];
  8593. }
  8594. return function (x) {
  8595. for (var i = 0; i < args.length; i++) {
  8596. if (args[i](x)) {
  8597. return true;
  8598. }
  8599. }
  8600. return false;
  8601. };
  8602. };
  8603. var and = function () {
  8604. var args = [];
  8605. for (var _i = 0; _i < arguments.length; _i++) {
  8606. args[_i] = arguments[_i];
  8607. }
  8608. return function (x) {
  8609. for (var i = 0; i < args.length; i++) {
  8610. if (!args[i](x)) {
  8611. return false;
  8612. }
  8613. }
  8614. return true;
  8615. };
  8616. };
  8617. var isElement$3 = isElement$1;
  8618. var isCaretCandidate$1 = isCaretCandidate;
  8619. var isBlock$1 = matchStyleValues('display', 'block table');
  8620. var isFloated = matchStyleValues('float', 'left right');
  8621. var isValidElementCaretCandidate = and(isElement$3, isCaretCandidate$1, not(isFloated));
  8622. var isNotPre = not(matchStyleValues('white-space', 'pre pre-line pre-wrap'));
  8623. var isText$4 = isText$1;
  8624. var isBr$3 = isBr;
  8625. var nodeIndex = DOMUtils$1.nodeIndex;
  8626. var resolveIndex = getNode;
  8627. var createRange = function (doc) {
  8628. return 'createRange' in doc ? doc.createRange() : DOMUtils$1.DOM.createRng();
  8629. };
  8630. var isWhiteSpace = function (chr) {
  8631. return chr && /[\r\n\t ]/.test(chr);
  8632. };
  8633. var isRange = function (rng) {
  8634. return !!rng.setStart && !!rng.setEnd;
  8635. };
  8636. var isHiddenWhiteSpaceRange = function (range) {
  8637. var container = range.startContainer;
  8638. var offset = range.startOffset;
  8639. var text;
  8640. if (isWhiteSpace(range.toString()) && isNotPre(container.parentNode) && isText$1(container)) {
  8641. text = container.data;
  8642. if (isWhiteSpace(text[offset - 1]) || isWhiteSpace(text[offset + 1])) {
  8643. return true;
  8644. }
  8645. }
  8646. return false;
  8647. };
  8648. var getBrClientRect = function (brNode) {
  8649. var doc = brNode.ownerDocument;
  8650. var rng = createRange(doc);
  8651. var nbsp$1 = doc.createTextNode(nbsp);
  8652. var parentNode = brNode.parentNode;
  8653. parentNode.insertBefore(nbsp$1, brNode);
  8654. rng.setStart(nbsp$1, 0);
  8655. rng.setEnd(nbsp$1, 1);
  8656. var clientRect = clone$2(rng.getBoundingClientRect());
  8657. parentNode.removeChild(nbsp$1);
  8658. return clientRect;
  8659. };
  8660. var getBoundingClientRectWebKitText = function (rng) {
  8661. var sc = rng.startContainer;
  8662. var ec = rng.endContainer;
  8663. var so = rng.startOffset;
  8664. var eo = rng.endOffset;
  8665. if (sc === ec && isText$1(ec) && so === 0 && eo === 1) {
  8666. var newRng = rng.cloneRange();
  8667. newRng.setEndAfter(ec);
  8668. return getBoundingClientRect(newRng);
  8669. } else {
  8670. return null;
  8671. }
  8672. };
  8673. var isZeroRect = function (r) {
  8674. return r.left === 0 && r.right === 0 && r.top === 0 && r.bottom === 0;
  8675. };
  8676. var getBoundingClientRect = function (item) {
  8677. var clientRect;
  8678. var clientRects = item.getClientRects();
  8679. if (clientRects.length > 0) {
  8680. clientRect = clone$2(clientRects[0]);
  8681. } else {
  8682. clientRect = clone$2(item.getBoundingClientRect());
  8683. }
  8684. if (!isRange(item) && isBr$3(item) && isZeroRect(clientRect)) {
  8685. return getBrClientRect(item);
  8686. }
  8687. if (isZeroRect(clientRect) && isRange(item)) {
  8688. return getBoundingClientRectWebKitText(item);
  8689. }
  8690. return clientRect;
  8691. };
  8692. var collapseAndInflateWidth = function (clientRect, toStart) {
  8693. var newClientRect = collapse(clientRect, toStart);
  8694. newClientRect.width = 1;
  8695. newClientRect.right = newClientRect.left + 1;
  8696. return newClientRect;
  8697. };
  8698. var getCaretPositionClientRects = function (caretPosition) {
  8699. var clientRects = [];
  8700. var beforeNode, node;
  8701. var addUniqueAndValidRect = function (clientRect) {
  8702. if (clientRect.height === 0) {
  8703. return;
  8704. }
  8705. if (clientRects.length > 0) {
  8706. if (isEqual(clientRect, clientRects[clientRects.length - 1])) {
  8707. return;
  8708. }
  8709. }
  8710. clientRects.push(clientRect);
  8711. };
  8712. var addCharacterOffset = function (container, offset) {
  8713. var range = createRange(container.ownerDocument);
  8714. if (offset < container.data.length) {
  8715. if (isExtendingChar(container.data[offset])) {
  8716. return clientRects;
  8717. }
  8718. if (isExtendingChar(container.data[offset - 1])) {
  8719. range.setStart(container, offset);
  8720. range.setEnd(container, offset + 1);
  8721. if (!isHiddenWhiteSpaceRange(range)) {
  8722. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect(range), false));
  8723. return clientRects;
  8724. }
  8725. }
  8726. }
  8727. if (offset > 0) {
  8728. range.setStart(container, offset - 1);
  8729. range.setEnd(container, offset);
  8730. if (!isHiddenWhiteSpaceRange(range)) {
  8731. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect(range), false));
  8732. }
  8733. }
  8734. if (offset < container.data.length) {
  8735. range.setStart(container, offset);
  8736. range.setEnd(container, offset + 1);
  8737. if (!isHiddenWhiteSpaceRange(range)) {
  8738. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect(range), true));
  8739. }
  8740. }
  8741. };
  8742. if (isText$4(caretPosition.container())) {
  8743. addCharacterOffset(caretPosition.container(), caretPosition.offset());
  8744. return clientRects;
  8745. }
  8746. if (isElement$3(caretPosition.container())) {
  8747. if (caretPosition.isAtEnd()) {
  8748. node = resolveIndex(caretPosition.container(), caretPosition.offset());
  8749. if (isText$4(node)) {
  8750. addCharacterOffset(node, node.data.length);
  8751. }
  8752. if (isValidElementCaretCandidate(node) && !isBr$3(node)) {
  8753. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect(node), false));
  8754. }
  8755. } else {
  8756. node = resolveIndex(caretPosition.container(), caretPosition.offset());
  8757. if (isText$4(node)) {
  8758. addCharacterOffset(node, 0);
  8759. }
  8760. if (isValidElementCaretCandidate(node) && caretPosition.isAtEnd()) {
  8761. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect(node), false));
  8762. return clientRects;
  8763. }
  8764. beforeNode = resolveIndex(caretPosition.container(), caretPosition.offset() - 1);
  8765. if (isValidElementCaretCandidate(beforeNode) && !isBr$3(beforeNode)) {
  8766. if (isBlock$1(beforeNode) || isBlock$1(node) || !isValidElementCaretCandidate(node)) {
  8767. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect(beforeNode), false));
  8768. }
  8769. }
  8770. if (isValidElementCaretCandidate(node)) {
  8771. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect(node), true));
  8772. }
  8773. }
  8774. }
  8775. return clientRects;
  8776. };
  8777. function CaretPosition(container, offset, clientRects) {
  8778. var isAtStart = function () {
  8779. if (isText$4(container)) {
  8780. return offset === 0;
  8781. }
  8782. return offset === 0;
  8783. };
  8784. var isAtEnd = function () {
  8785. if (isText$4(container)) {
  8786. return offset >= container.data.length;
  8787. }
  8788. return offset >= container.childNodes.length;
  8789. };
  8790. var toRange = function () {
  8791. var range = createRange(container.ownerDocument);
  8792. range.setStart(container, offset);
  8793. range.setEnd(container, offset);
  8794. return range;
  8795. };
  8796. var getClientRects = function () {
  8797. if (!clientRects) {
  8798. clientRects = getCaretPositionClientRects(CaretPosition(container, offset));
  8799. }
  8800. return clientRects;
  8801. };
  8802. var isVisible = function () {
  8803. return getClientRects().length > 0;
  8804. };
  8805. var isEqual = function (caretPosition) {
  8806. return caretPosition && container === caretPosition.container() && offset === caretPosition.offset();
  8807. };
  8808. var getNode = function (before) {
  8809. return resolveIndex(container, before ? offset - 1 : offset);
  8810. };
  8811. return {
  8812. container: constant(container),
  8813. offset: constant(offset),
  8814. toRange: toRange,
  8815. getClientRects: getClientRects,
  8816. isVisible: isVisible,
  8817. isAtStart: isAtStart,
  8818. isAtEnd: isAtEnd,
  8819. isEqual: isEqual,
  8820. getNode: getNode
  8821. };
  8822. }
  8823. (function (CaretPosition) {
  8824. CaretPosition.fromRangeStart = function (range) {
  8825. return CaretPosition(range.startContainer, range.startOffset);
  8826. };
  8827. CaretPosition.fromRangeEnd = function (range) {
  8828. return CaretPosition(range.endContainer, range.endOffset);
  8829. };
  8830. CaretPosition.after = function (node) {
  8831. return CaretPosition(node.parentNode, nodeIndex(node) + 1);
  8832. };
  8833. CaretPosition.before = function (node) {
  8834. return CaretPosition(node.parentNode, nodeIndex(node));
  8835. };
  8836. CaretPosition.isAbove = function (pos1, pos2) {
  8837. return lift2(head(pos2.getClientRects()), last(pos1.getClientRects()), isAbove).getOr(false);
  8838. };
  8839. CaretPosition.isBelow = function (pos1, pos2) {
  8840. return lift2(last(pos2.getClientRects()), head(pos1.getClientRects()), isBelow).getOr(false);
  8841. };
  8842. CaretPosition.isAtStart = function (pos) {
  8843. return pos ? pos.isAtStart() : false;
  8844. };
  8845. CaretPosition.isAtEnd = function (pos) {
  8846. return pos ? pos.isAtEnd() : false;
  8847. };
  8848. CaretPosition.isTextPosition = function (pos) {
  8849. return pos ? isText$1(pos.container()) : false;
  8850. };
  8851. CaretPosition.isElementPosition = function (pos) {
  8852. return CaretPosition.isTextPosition(pos) === false;
  8853. };
  8854. }(CaretPosition || (CaretPosition = {})));
  8855. var CaretPosition$1 = CaretPosition;
  8856. var trimEmptyTextNode = function (dom, node) {
  8857. if (isText$1(node) && node.data.length === 0) {
  8858. dom.remove(node);
  8859. }
  8860. };
  8861. var insertNode = function (dom, rng, node) {
  8862. rng.insertNode(node);
  8863. trimEmptyTextNode(dom, node.previousSibling);
  8864. trimEmptyTextNode(dom, node.nextSibling);
  8865. };
  8866. var insertFragment = function (dom, rng, frag) {
  8867. var firstChild = Optional.from(frag.firstChild);
  8868. var lastChild = Optional.from(frag.lastChild);
  8869. rng.insertNode(frag);
  8870. firstChild.each(function (child) {
  8871. return trimEmptyTextNode(dom, child.previousSibling);
  8872. });
  8873. lastChild.each(function (child) {
  8874. return trimEmptyTextNode(dom, child.nextSibling);
  8875. });
  8876. };
  8877. var rangeInsertNode = function (dom, rng, node) {
  8878. if (isDocumentFragment$1(node)) {
  8879. insertFragment(dom, rng, node);
  8880. } else {
  8881. insertNode(dom, rng, node);
  8882. }
  8883. };
  8884. var isText$5 = isText$1;
  8885. var isBogus$2 = isBogus;
  8886. var nodeIndex$1 = DOMUtils$1.nodeIndex;
  8887. var normalizedParent = function (node) {
  8888. var parentNode = node.parentNode;
  8889. if (isBogus$2(parentNode)) {
  8890. return normalizedParent(parentNode);
  8891. }
  8892. return parentNode;
  8893. };
  8894. var getChildNodes = function (node) {
  8895. if (!node) {
  8896. return [];
  8897. }
  8898. return reduce(node.childNodes, function (result, node) {
  8899. if (isBogus$2(node) && node.nodeName !== 'BR') {
  8900. result = result.concat(getChildNodes(node));
  8901. } else {
  8902. result.push(node);
  8903. }
  8904. return result;
  8905. }, []);
  8906. };
  8907. var normalizedTextOffset = function (node, offset) {
  8908. while (node = node.previousSibling) {
  8909. if (!isText$5(node)) {
  8910. break;
  8911. }
  8912. offset += node.data.length;
  8913. }
  8914. return offset;
  8915. };
  8916. var equal$1 = function (a) {
  8917. return function (b) {
  8918. return a === b;
  8919. };
  8920. };
  8921. var normalizedNodeIndex = function (node) {
  8922. var nodes, index;
  8923. nodes = getChildNodes(normalizedParent(node));
  8924. index = findIndex$1(nodes, equal$1(node), node);
  8925. nodes = nodes.slice(0, index + 1);
  8926. var numTextFragments = reduce(nodes, function (result, node, i) {
  8927. if (isText$5(node) && isText$5(nodes[i - 1])) {
  8928. result++;
  8929. }
  8930. return result;
  8931. }, 0);
  8932. nodes = filter$2(nodes, matchNodeNames([node.nodeName]));
  8933. index = findIndex$1(nodes, equal$1(node), node);
  8934. return index - numTextFragments;
  8935. };
  8936. var createPathItem = function (node) {
  8937. var name;
  8938. if (isText$5(node)) {
  8939. name = 'text()';
  8940. } else {
  8941. name = node.nodeName.toLowerCase();
  8942. }
  8943. return name + '[' + normalizedNodeIndex(node) + ']';
  8944. };
  8945. var parentsUntil = function (root, node, predicate) {
  8946. var parents = [];
  8947. for (node = node.parentNode; node !== root; node = node.parentNode) {
  8948. if (predicate && predicate(node)) {
  8949. break;
  8950. }
  8951. parents.push(node);
  8952. }
  8953. return parents;
  8954. };
  8955. var create$3 = function (root, caretPosition) {
  8956. var container, offset, path = [], outputOffset, childNodes, parents;
  8957. container = caretPosition.container();
  8958. offset = caretPosition.offset();
  8959. if (isText$5(container)) {
  8960. outputOffset = normalizedTextOffset(container, offset);
  8961. } else {
  8962. childNodes = container.childNodes;
  8963. if (offset >= childNodes.length) {
  8964. outputOffset = 'after';
  8965. offset = childNodes.length - 1;
  8966. } else {
  8967. outputOffset = 'before';
  8968. }
  8969. container = childNodes[offset];
  8970. }
  8971. path.push(createPathItem(container));
  8972. parents = parentsUntil(root, container);
  8973. parents = filter$2(parents, not(isBogus));
  8974. path = path.concat(map$2(parents, function (node) {
  8975. return createPathItem(node);
  8976. }));
  8977. return path.reverse().join('/') + ',' + outputOffset;
  8978. };
  8979. var resolvePathItem = function (node, name, index) {
  8980. var nodes = getChildNodes(node);
  8981. nodes = filter$2(nodes, function (node, index) {
  8982. return !isText$5(node) || !isText$5(nodes[index - 1]);
  8983. });
  8984. nodes = filter$2(nodes, matchNodeNames([name]));
  8985. return nodes[index];
  8986. };
  8987. var findTextPosition = function (container, offset) {
  8988. var node = container, targetOffset = 0, dataLen;
  8989. while (isText$5(node)) {
  8990. dataLen = node.data.length;
  8991. if (offset >= targetOffset && offset <= targetOffset + dataLen) {
  8992. container = node;
  8993. offset = offset - targetOffset;
  8994. break;
  8995. }
  8996. if (!isText$5(node.nextSibling)) {
  8997. container = node;
  8998. offset = dataLen;
  8999. break;
  9000. }
  9001. targetOffset += dataLen;
  9002. node = node.nextSibling;
  9003. }
  9004. if (isText$5(container) && offset > container.data.length) {
  9005. offset = container.data.length;
  9006. }
  9007. return CaretPosition$1(container, offset);
  9008. };
  9009. var resolve$1 = function (root, path) {
  9010. var offset;
  9011. if (!path) {
  9012. return null;
  9013. }
  9014. var parts = path.split(',');
  9015. var paths = parts[0].split('/');
  9016. offset = parts.length > 1 ? parts[1] : 'before';
  9017. var container = reduce(paths, function (result, value) {
  9018. var match = /([\w\-\(\)]+)\[([0-9]+)\]/.exec(value);
  9019. if (!match) {
  9020. return null;
  9021. }
  9022. if (match[1] === 'text()') {
  9023. match[1] = '#text';
  9024. }
  9025. return resolvePathItem(result, match[1], parseInt(match[2], 10));
  9026. }, root);
  9027. if (!container) {
  9028. return null;
  9029. }
  9030. if (!isText$5(container)) {
  9031. if (offset === 'after') {
  9032. offset = nodeIndex$1(container) + 1;
  9033. } else {
  9034. offset = nodeIndex$1(container);
  9035. }
  9036. return CaretPosition$1(container.parentNode, offset);
  9037. }
  9038. return findTextPosition(container, parseInt(offset, 10));
  9039. };
  9040. var isContentEditableFalse$2 = isContentEditableFalse;
  9041. var getNormalizedTextOffset = function (trim, container, offset) {
  9042. var node, trimmedOffset;
  9043. trimmedOffset = trim(container.data.slice(0, offset)).length;
  9044. for (node = container.previousSibling; node && isText$1(node); node = node.previousSibling) {
  9045. trimmedOffset += trim(node.data).length;
  9046. }
  9047. return trimmedOffset;
  9048. };
  9049. var getPoint = function (dom, trim, normalized, rng, start) {
  9050. var container = rng[start ? 'startContainer' : 'endContainer'];
  9051. var offset = rng[start ? 'startOffset' : 'endOffset'];
  9052. var point = [];
  9053. var childNodes, after = 0;
  9054. var root = dom.getRoot();
  9055. if (isText$1(container)) {
  9056. point.push(normalized ? getNormalizedTextOffset(trim, container, offset) : offset);
  9057. } else {
  9058. childNodes = container.childNodes;
  9059. if (offset >= childNodes.length && childNodes.length) {
  9060. after = 1;
  9061. offset = Math.max(0, childNodes.length - 1);
  9062. }
  9063. point.push(dom.nodeIndex(childNodes[offset], normalized) + after);
  9064. }
  9065. for (; container && container !== root; container = container.parentNode) {
  9066. point.push(dom.nodeIndex(container, normalized));
  9067. }
  9068. return point;
  9069. };
  9070. var getLocation = function (trim, selection, normalized, rng) {
  9071. var dom = selection.dom, bookmark = {};
  9072. bookmark.start = getPoint(dom, trim, normalized, rng, true);
  9073. if (!selection.isCollapsed()) {
  9074. bookmark.end = getPoint(dom, trim, normalized, rng, false);
  9075. }
  9076. return bookmark;
  9077. };
  9078. var findIndex$2 = function (dom, name, element) {
  9079. var count = 0;
  9080. Tools.each(dom.select(name), function (node) {
  9081. if (node.getAttribute('data-mce-bogus') === 'all') {
  9082. return;
  9083. }
  9084. if (node === element) {
  9085. return false;
  9086. }
  9087. count++;
  9088. });
  9089. return count;
  9090. };
  9091. var moveEndPoint = function (rng, start) {
  9092. var container, offset, childNodes;
  9093. var prefix = start ? 'start' : 'end';
  9094. container = rng[prefix + 'Container'];
  9095. offset = rng[prefix + 'Offset'];
  9096. if (isElement$1(container) && container.nodeName === 'TR') {
  9097. childNodes = container.childNodes;
  9098. container = childNodes[Math.min(start ? offset : offset - 1, childNodes.length - 1)];
  9099. if (container) {
  9100. offset = start ? 0 : container.childNodes.length;
  9101. rng['set' + (start ? 'Start' : 'End')](container, offset);
  9102. }
  9103. }
  9104. };
  9105. var normalizeTableCellSelection = function (rng) {
  9106. moveEndPoint(rng, true);
  9107. moveEndPoint(rng, false);
  9108. return rng;
  9109. };
  9110. var findSibling = function (node, offset) {
  9111. var sibling;
  9112. if (isElement$1(node)) {
  9113. node = getNode(node, offset);
  9114. if (isContentEditableFalse$2(node)) {
  9115. return node;
  9116. }
  9117. }
  9118. if (isCaretContainer(node)) {
  9119. if (isText$1(node) && isCaretContainerBlock(node)) {
  9120. node = node.parentNode;
  9121. }
  9122. sibling = node.previousSibling;
  9123. if (isContentEditableFalse$2(sibling)) {
  9124. return sibling;
  9125. }
  9126. sibling = node.nextSibling;
  9127. if (isContentEditableFalse$2(sibling)) {
  9128. return sibling;
  9129. }
  9130. }
  9131. };
  9132. var findAdjacentContentEditableFalseElm = function (rng) {
  9133. return findSibling(rng.startContainer, rng.startOffset) || findSibling(rng.endContainer, rng.endOffset);
  9134. };
  9135. var getOffsetBookmark = function (trim, normalized, selection) {
  9136. var element = selection.getNode();
  9137. var name = element ? element.nodeName : null;
  9138. var rng = selection.getRng();
  9139. if (isContentEditableFalse$2(element) || name === 'IMG') {
  9140. return {
  9141. name: name,
  9142. index: findIndex$2(selection.dom, name, element)
  9143. };
  9144. }
  9145. var sibling = findAdjacentContentEditableFalseElm(rng);
  9146. if (sibling) {
  9147. name = sibling.tagName;
  9148. return {
  9149. name: name,
  9150. index: findIndex$2(selection.dom, name, sibling)
  9151. };
  9152. }
  9153. return getLocation(trim, selection, normalized, rng);
  9154. };
  9155. var getCaretBookmark = function (selection) {
  9156. var rng = selection.getRng();
  9157. return {
  9158. start: create$3(selection.dom.getRoot(), CaretPosition$1.fromRangeStart(rng)),
  9159. end: create$3(selection.dom.getRoot(), CaretPosition$1.fromRangeEnd(rng))
  9160. };
  9161. };
  9162. var getRangeBookmark = function (selection) {
  9163. return { rng: selection.getRng() };
  9164. };
  9165. var createBookmarkSpan = function (dom, id, filled) {
  9166. var args = {
  9167. 'data-mce-type': 'bookmark',
  9168. id: id,
  9169. 'style': 'overflow:hidden;line-height:0px'
  9170. };
  9171. return filled ? dom.create('span', args, '&#xFEFF;') : dom.create('span', args);
  9172. };
  9173. var getPersistentBookmark = function (selection, filled) {
  9174. var dom = selection.dom;
  9175. var rng = selection.getRng();
  9176. var id = dom.uniqueId();
  9177. var collapsed = selection.isCollapsed();
  9178. var element = selection.getNode();
  9179. var name = element.nodeName;
  9180. if (name === 'IMG') {
  9181. return {
  9182. name: name,
  9183. index: findIndex$2(dom, name, element)
  9184. };
  9185. }
  9186. var rng2 = normalizeTableCellSelection(rng.cloneRange());
  9187. if (!collapsed) {
  9188. rng2.collapse(false);
  9189. var endBookmarkNode = createBookmarkSpan(dom, id + '_end', filled);
  9190. rangeInsertNode(dom, rng2, endBookmarkNode);
  9191. }
  9192. rng = normalizeTableCellSelection(rng);
  9193. rng.collapse(true);
  9194. var startBookmarkNode = createBookmarkSpan(dom, id + '_start', filled);
  9195. rangeInsertNode(dom, rng, startBookmarkNode);
  9196. selection.moveToBookmark({
  9197. id: id,
  9198. keep: true
  9199. });
  9200. return { id: id };
  9201. };
  9202. var getBookmark = function (selection, type, normalized) {
  9203. if (type === 2) {
  9204. return getOffsetBookmark(trim$2, normalized, selection);
  9205. } else if (type === 3) {
  9206. return getCaretBookmark(selection);
  9207. } else if (type) {
  9208. return getRangeBookmark(selection);
  9209. } else {
  9210. return getPersistentBookmark(selection, false);
  9211. }
  9212. };
  9213. var getUndoBookmark = curry(getOffsetBookmark, identity, true);
  9214. var DOM$1 = DOMUtils$1.DOM;
  9215. var defaultPreviewStyles = 'font-family font-size font-weight font-style text-decoration text-transform color background-color border border-radius outline text-shadow';
  9216. var getBodySetting = function (editor, name, defaultValue) {
  9217. var value = editor.getParam(name, defaultValue);
  9218. if (value.indexOf('=') !== -1) {
  9219. var bodyObj = editor.getParam(name, '', 'hash');
  9220. return bodyObj.hasOwnProperty(editor.id) ? bodyObj[editor.id] : defaultValue;
  9221. } else {
  9222. return value;
  9223. }
  9224. };
  9225. var getIframeAttrs = function (editor) {
  9226. return editor.getParam('iframe_attrs', {});
  9227. };
  9228. var getDocType = function (editor) {
  9229. return editor.getParam('doctype', '<!DOCTYPE html>');
  9230. };
  9231. var getDocumentBaseUrl = function (editor) {
  9232. return editor.getParam('document_base_url', '');
  9233. };
  9234. var getBodyId = function (editor) {
  9235. return getBodySetting(editor, 'body_id', 'tinymce');
  9236. };
  9237. var getBodyClass = function (editor) {
  9238. return getBodySetting(editor, 'body_class', '');
  9239. };
  9240. var getContentSecurityPolicy = function (editor) {
  9241. return editor.getParam('content_security_policy', '');
  9242. };
  9243. var shouldPutBrInPre = function (editor) {
  9244. return editor.getParam('br_in_pre', true);
  9245. };
  9246. var getForcedRootBlock = function (editor) {
  9247. if (editor.getParam('force_p_newlines', false)) {
  9248. return 'p';
  9249. }
  9250. var block = editor.getParam('forced_root_block', 'p');
  9251. if (block === false) {
  9252. return '';
  9253. } else if (block === true) {
  9254. return 'p';
  9255. } else {
  9256. return block;
  9257. }
  9258. };
  9259. var getForcedRootBlockAttrs = function (editor) {
  9260. return editor.getParam('forced_root_block_attrs', {});
  9261. };
  9262. var getBrNewLineSelector = function (editor) {
  9263. return editor.getParam('br_newline_selector', '.mce-toc h2,figcaption,caption');
  9264. };
  9265. var getNoNewLineSelector = function (editor) {
  9266. return editor.getParam('no_newline_selector', '');
  9267. };
  9268. var shouldKeepStyles = function (editor) {
  9269. return editor.getParam('keep_styles', true);
  9270. };
  9271. var shouldEndContainerOnEmptyBlock = function (editor) {
  9272. return editor.getParam('end_container_on_empty_block', false);
  9273. };
  9274. var getFontStyleValues = function (editor) {
  9275. return Tools.explode(editor.getParam('font_size_style_values', 'xx-small,x-small,small,medium,large,x-large,xx-large'));
  9276. };
  9277. var getFontSizeClasses = function (editor) {
  9278. return Tools.explode(editor.getParam('font_size_classes', ''));
  9279. };
  9280. var getImagesDataImgFilter = function (editor) {
  9281. return editor.getParam('images_dataimg_filter', always, 'function');
  9282. };
  9283. var isAutomaticUploadsEnabled = function (editor) {
  9284. return editor.getParam('automatic_uploads', true, 'boolean');
  9285. };
  9286. var shouldReuseFileName = function (editor) {
  9287. return editor.getParam('images_reuse_filename', false, 'boolean');
  9288. };
  9289. var shouldReplaceBlobUris = function (editor) {
  9290. return editor.getParam('images_replace_blob_uris', true, 'boolean');
  9291. };
  9292. var getIconPackName = function (editor) {
  9293. return editor.getParam('icons', '', 'string');
  9294. };
  9295. var getIconsUrl = function (editor) {
  9296. return editor.getParam('icons_url', '', 'string');
  9297. };
  9298. var getImageUploadUrl = function (editor) {
  9299. return editor.getParam('images_upload_url', '', 'string');
  9300. };
  9301. var getImageUploadBasePath = function (editor) {
  9302. return editor.getParam('images_upload_base_path', '', 'string');
  9303. };
  9304. var getImagesUploadCredentials = function (editor) {
  9305. return editor.getParam('images_upload_credentials', false, 'boolean');
  9306. };
  9307. var getImagesUploadHandler = function (editor) {
  9308. return editor.getParam('images_upload_handler', null, 'function');
  9309. };
  9310. var shouldUseContentCssCors = function (editor) {
  9311. return editor.getParam('content_css_cors', false, 'boolean');
  9312. };
  9313. var getReferrerPolicy = function (editor) {
  9314. return editor.getParam('referrer_policy', '', 'string');
  9315. };
  9316. var getLanguageCode = function (editor) {
  9317. return editor.getParam('language', 'en', 'string');
  9318. };
  9319. var getLanguageUrl = function (editor) {
  9320. return editor.getParam('language_url', '', 'string');
  9321. };
  9322. var shouldIndentUseMargin = function (editor) {
  9323. return editor.getParam('indent_use_margin', false);
  9324. };
  9325. var getIndentation = function (editor) {
  9326. return editor.getParam('indentation', '40px', 'string');
  9327. };
  9328. var getContentCss = function (editor) {
  9329. var contentCss = editor.getParam('content_css');
  9330. if (isString(contentCss)) {
  9331. return map(contentCss.split(','), trim);
  9332. } else if (isArray(contentCss)) {
  9333. return contentCss;
  9334. } else if (contentCss === false || editor.inline) {
  9335. return [];
  9336. } else {
  9337. return ['default'];
  9338. }
  9339. };
  9340. var getDirectionality = function (editor) {
  9341. return editor.getParam('directionality', I18n.isRtl() ? 'rtl' : undefined);
  9342. };
  9343. var getInlineBoundarySelector = function (editor) {
  9344. return editor.getParam('inline_boundaries_selector', 'a[href],code,.mce-annotation', 'string');
  9345. };
  9346. var getObjectResizing = function (editor) {
  9347. var selector = editor.getParam('object_resizing');
  9348. if (selector === false || Env.iOS) {
  9349. return false;
  9350. } else {
  9351. return isString(selector) ? selector : 'table,img,figure.image,div';
  9352. }
  9353. };
  9354. var getResizeImgProportional = function (editor) {
  9355. return editor.getParam('resize_img_proportional', true, 'boolean');
  9356. };
  9357. var getPlaceholder = function (editor) {
  9358. return editor.getParam('placeholder', DOM$1.getAttrib(editor.getElement(), 'placeholder'), 'string');
  9359. };
  9360. var getEventRoot = function (editor) {
  9361. return editor.getParam('event_root');
  9362. };
  9363. var getServiceMessage = function (editor) {
  9364. return editor.getParam('service_message');
  9365. };
  9366. var getTheme = function (editor) {
  9367. return editor.getParam('theme');
  9368. };
  9369. var shouldValidate = function (editor) {
  9370. return editor.getParam('validate');
  9371. };
  9372. var isInlineBoundariesEnabled = function (editor) {
  9373. return editor.getParam('inline_boundaries') !== false;
  9374. };
  9375. var getFormats = function (editor) {
  9376. return editor.getParam('formats');
  9377. };
  9378. var getPreviewStyles = function (editor) {
  9379. var style = editor.getParam('preview_styles', defaultPreviewStyles);
  9380. if (isString(style)) {
  9381. return style;
  9382. } else {
  9383. return '';
  9384. }
  9385. };
  9386. var getCustomUiSelector = function (editor) {
  9387. return editor.getParam('custom_ui_selector', '', 'string');
  9388. };
  9389. var getThemeUrl = function (editor) {
  9390. return editor.getParam('theme_url');
  9391. };
  9392. var isInline$1 = function (editor) {
  9393. return editor.getParam('inline');
  9394. };
  9395. var hasHiddenInput = function (editor) {
  9396. return editor.getParam('hidden_input');
  9397. };
  9398. var shouldPatchSubmit = function (editor) {
  9399. return editor.getParam('submit_patch');
  9400. };
  9401. var isEncodingXml = function (editor) {
  9402. return editor.getParam('encoding') === 'xml';
  9403. };
  9404. var shouldAddFormSubmitTrigger = function (editor) {
  9405. return editor.getParam('add_form_submit_trigger');
  9406. };
  9407. var shouldAddUnloadTrigger = function (editor) {
  9408. return editor.getParam('add_unload_trigger');
  9409. };
  9410. var hasForcedRootBlock = function (editor) {
  9411. return getForcedRootBlock(editor) !== '';
  9412. };
  9413. var getCustomUndoRedoLevels = function (editor) {
  9414. return editor.getParam('custom_undo_redo_levels', 0, 'number');
  9415. };
  9416. var shouldDisableNodeChange = function (editor) {
  9417. return editor.getParam('disable_nodechange');
  9418. };
  9419. var isReadOnly = function (editor) {
  9420. return editor.getParam('readonly');
  9421. };
  9422. var hasContentCssCors = function (editor) {
  9423. return editor.getParam('content_css_cors');
  9424. };
  9425. var getPlugins = function (editor) {
  9426. return editor.getParam('plugins', '', 'string');
  9427. };
  9428. var getExternalPlugins = function (editor) {
  9429. return editor.getParam('external_plugins');
  9430. };
  9431. var shouldBlockUnsupportedDrop = function (editor) {
  9432. return editor.getParam('block_unsupported_drop', true, 'boolean');
  9433. };
  9434. var isElement$4 = isElement$1;
  9435. var isText$6 = isText$1;
  9436. var removeNode = function (node) {
  9437. var parentNode = node.parentNode;
  9438. if (parentNode) {
  9439. parentNode.removeChild(node);
  9440. }
  9441. };
  9442. var trimCount = function (text) {
  9443. var trimmedText = trim$2(text);
  9444. return {
  9445. count: text.length - trimmedText.length,
  9446. text: trimmedText
  9447. };
  9448. };
  9449. var deleteZwspChars = function (caretContainer) {
  9450. var idx;
  9451. while ((idx = caretContainer.data.lastIndexOf(ZWSP)) !== -1) {
  9452. caretContainer.deleteData(idx, 1);
  9453. }
  9454. };
  9455. var removeUnchanged = function (caretContainer, pos) {
  9456. remove$5(caretContainer);
  9457. return pos;
  9458. };
  9459. var removeTextAndReposition = function (caretContainer, pos) {
  9460. var before = trimCount(caretContainer.data.substr(0, pos.offset()));
  9461. var after = trimCount(caretContainer.data.substr(pos.offset()));
  9462. var text = before.text + after.text;
  9463. if (text.length > 0) {
  9464. deleteZwspChars(caretContainer);
  9465. return CaretPosition$1(caretContainer, pos.offset() - before.count);
  9466. } else {
  9467. return pos;
  9468. }
  9469. };
  9470. var removeElementAndReposition = function (caretContainer, pos) {
  9471. var parentNode = pos.container();
  9472. var newPosition = indexOf(from$1(parentNode.childNodes), caretContainer).map(function (index) {
  9473. return index < pos.offset() ? CaretPosition$1(parentNode, pos.offset() - 1) : pos;
  9474. }).getOr(pos);
  9475. remove$5(caretContainer);
  9476. return newPosition;
  9477. };
  9478. var removeTextCaretContainer = function (caretContainer, pos) {
  9479. return isText$6(caretContainer) && pos.container() === caretContainer ? removeTextAndReposition(caretContainer, pos) : removeUnchanged(caretContainer, pos);
  9480. };
  9481. var removeElementCaretContainer = function (caretContainer, pos) {
  9482. return pos.container() === caretContainer.parentNode ? removeElementAndReposition(caretContainer, pos) : removeUnchanged(caretContainer, pos);
  9483. };
  9484. var removeAndReposition = function (container, pos) {
  9485. return CaretPosition$1.isTextPosition(pos) ? removeTextCaretContainer(container, pos) : removeElementCaretContainer(container, pos);
  9486. };
  9487. var remove$5 = function (caretContainerNode) {
  9488. if (isElement$4(caretContainerNode) && isCaretContainer(caretContainerNode)) {
  9489. if (hasContent(caretContainerNode)) {
  9490. caretContainerNode.removeAttribute('data-mce-caret');
  9491. } else {
  9492. removeNode(caretContainerNode);
  9493. }
  9494. }
  9495. if (isText$6(caretContainerNode)) {
  9496. deleteZwspChars(caretContainerNode);
  9497. if (caretContainerNode.data.length === 0) {
  9498. removeNode(caretContainerNode);
  9499. }
  9500. }
  9501. };
  9502. var browser$2 = detect$3().browser;
  9503. var isContentEditableFalse$3 = isContentEditableFalse;
  9504. var isMedia$1 = isMedia;
  9505. var isTableCell$2 = isTableCell;
  9506. var inlineFakeCaretSelector = '*[contentEditable=false],video,audio,embed,object';
  9507. var getAbsoluteClientRect = function (root, element, before) {
  9508. var clientRect = collapse(element.getBoundingClientRect(), before);
  9509. var docElm, scrollX, scrollY, margin, rootRect;
  9510. if (root.tagName === 'BODY') {
  9511. docElm = root.ownerDocument.documentElement;
  9512. scrollX = root.scrollLeft || docElm.scrollLeft;
  9513. scrollY = root.scrollTop || docElm.scrollTop;
  9514. } else {
  9515. rootRect = root.getBoundingClientRect();
  9516. scrollX = root.scrollLeft - rootRect.left;
  9517. scrollY = root.scrollTop - rootRect.top;
  9518. }
  9519. clientRect.left += scrollX;
  9520. clientRect.right += scrollX;
  9521. clientRect.top += scrollY;
  9522. clientRect.bottom += scrollY;
  9523. clientRect.width = 1;
  9524. margin = element.offsetWidth - element.clientWidth;
  9525. if (margin > 0) {
  9526. if (before) {
  9527. margin *= -1;
  9528. }
  9529. clientRect.left += margin;
  9530. clientRect.right += margin;
  9531. }
  9532. return clientRect;
  9533. };
  9534. var trimInlineCaretContainers = function (root) {
  9535. var fakeCaretTargetNodes = descendants$1(SugarElement.fromDom(root), inlineFakeCaretSelector);
  9536. for (var i = 0; i < fakeCaretTargetNodes.length; i++) {
  9537. var node = fakeCaretTargetNodes[i].dom;
  9538. var sibling = node.previousSibling;
  9539. if (endsWithCaretContainer(sibling)) {
  9540. var data = sibling.data;
  9541. if (data.length === 1) {
  9542. sibling.parentNode.removeChild(sibling);
  9543. } else {
  9544. sibling.deleteData(data.length - 1, 1);
  9545. }
  9546. }
  9547. sibling = node.nextSibling;
  9548. if (startsWithCaretContainer(sibling)) {
  9549. var data = sibling.data;
  9550. if (data.length === 1) {
  9551. sibling.parentNode.removeChild(sibling);
  9552. } else {
  9553. sibling.deleteData(0, 1);
  9554. }
  9555. }
  9556. }
  9557. };
  9558. var FakeCaret = function (editor, root, isBlock, hasFocus) {
  9559. var lastVisualCaret = Cell(Optional.none());
  9560. var cursorInterval, caretContainerNode;
  9561. var rootBlock = getForcedRootBlock(editor);
  9562. var caretBlock = rootBlock.length > 0 ? rootBlock : 'p';
  9563. var show = function (before, element) {
  9564. var clientRect, rng;
  9565. hide();
  9566. if (isTableCell$2(element)) {
  9567. return null;
  9568. }
  9569. if (isBlock(element)) {
  9570. caretContainerNode = insertBlock(caretBlock, element, before);
  9571. clientRect = getAbsoluteClientRect(root, element, before);
  9572. DomQuery(caretContainerNode).css('top', clientRect.top);
  9573. var caret = DomQuery('<div class="mce-visual-caret" data-mce-bogus="all"></div>').css(clientRect).appendTo(root)[0];
  9574. lastVisualCaret.set(Optional.some({
  9575. caret: caret,
  9576. element: element,
  9577. before: before
  9578. }));
  9579. lastVisualCaret.get().each(function (caretState) {
  9580. if (before) {
  9581. DomQuery(caretState.caret).addClass('mce-visual-caret-before');
  9582. }
  9583. });
  9584. startBlink();
  9585. rng = element.ownerDocument.createRange();
  9586. rng.setStart(caretContainerNode, 0);
  9587. rng.setEnd(caretContainerNode, 0);
  9588. } else {
  9589. caretContainerNode = insertInline(element, before);
  9590. rng = element.ownerDocument.createRange();
  9591. if (isInlineFakeCaretTarget(caretContainerNode.nextSibling)) {
  9592. rng.setStart(caretContainerNode, 0);
  9593. rng.setEnd(caretContainerNode, 0);
  9594. } else {
  9595. rng.setStart(caretContainerNode, 1);
  9596. rng.setEnd(caretContainerNode, 1);
  9597. }
  9598. return rng;
  9599. }
  9600. return rng;
  9601. };
  9602. var hide = function () {
  9603. trimInlineCaretContainers(root);
  9604. if (caretContainerNode) {
  9605. remove$5(caretContainerNode);
  9606. caretContainerNode = null;
  9607. }
  9608. lastVisualCaret.get().each(function (caretState) {
  9609. DomQuery(caretState.caret).remove();
  9610. lastVisualCaret.set(Optional.none());
  9611. });
  9612. if (cursorInterval) {
  9613. Delay.clearInterval(cursorInterval);
  9614. cursorInterval = null;
  9615. }
  9616. };
  9617. var startBlink = function () {
  9618. cursorInterval = Delay.setInterval(function () {
  9619. if (hasFocus()) {
  9620. DomQuery('div.mce-visual-caret', root).toggleClass('mce-visual-caret-hidden');
  9621. } else {
  9622. DomQuery('div.mce-visual-caret', root).addClass('mce-visual-caret-hidden');
  9623. }
  9624. }, 500);
  9625. };
  9626. var reposition = function () {
  9627. lastVisualCaret.get().each(function (caretState) {
  9628. var clientRect = getAbsoluteClientRect(root, caretState.element, caretState.before);
  9629. DomQuery(caretState.caret).css(__assign({}, clientRect));
  9630. });
  9631. };
  9632. var destroy = function () {
  9633. return Delay.clearInterval(cursorInterval);
  9634. };
  9635. var getCss = function () {
  9636. return '.mce-visual-caret {' + 'position: absolute;' + 'background-color: black;' + 'background-color: currentcolor;' + '}' + '.mce-visual-caret-hidden {' + 'display: none;' + '}' + '*[data-mce-caret] {' + 'position: absolute;' + 'left: -1000px;' + 'right: auto;' + 'top: 0;' + 'margin: 0;' + 'padding: 0;' + '}';
  9637. };
  9638. return {
  9639. show: show,
  9640. hide: hide,
  9641. getCss: getCss,
  9642. reposition: reposition,
  9643. destroy: destroy
  9644. };
  9645. };
  9646. var isFakeCaretTableBrowser = function () {
  9647. return browser$2.isIE() || browser$2.isEdge() || browser$2.isFirefox();
  9648. };
  9649. var isInlineFakeCaretTarget = function (node) {
  9650. return isContentEditableFalse$3(node) || isMedia$1(node);
  9651. };
  9652. var isFakeCaretTarget = function (node) {
  9653. return isInlineFakeCaretTarget(node) || isTable(node) && isFakeCaretTableBrowser();
  9654. };
  9655. var isContentEditableFalse$4 = isContentEditableFalse;
  9656. var isMedia$2 = isMedia;
  9657. var isBlockLike = matchStyleValues('display', 'block table table-cell table-caption list-item');
  9658. var isCaretContainer$2 = isCaretContainer;
  9659. var isCaretContainerBlock$1 = isCaretContainerBlock;
  9660. var isElement$5 = isElement$1;
  9661. var isCaretCandidate$2 = isCaretCandidate;
  9662. var isForwards = function (direction) {
  9663. return direction > 0;
  9664. };
  9665. var isBackwards = function (direction) {
  9666. return direction < 0;
  9667. };
  9668. var skipCaretContainers = function (walk, shallow) {
  9669. var node;
  9670. while (node = walk(shallow)) {
  9671. if (!isCaretContainerBlock$1(node)) {
  9672. return node;
  9673. }
  9674. }
  9675. return null;
  9676. };
  9677. var findNode = function (node, direction, predicateFn, rootNode, shallow) {
  9678. var walker = new DomTreeWalker(node, rootNode);
  9679. var isCefOrCaretContainer = isContentEditableFalse$4(node) || isCaretContainerBlock$1(node);
  9680. if (isBackwards(direction)) {
  9681. if (isCefOrCaretContainer) {
  9682. node = skipCaretContainers(walker.prev, true);
  9683. if (predicateFn(node)) {
  9684. return node;
  9685. }
  9686. }
  9687. while (node = skipCaretContainers(walker.prev, shallow)) {
  9688. if (predicateFn(node)) {
  9689. return node;
  9690. }
  9691. }
  9692. }
  9693. if (isForwards(direction)) {
  9694. if (isCefOrCaretContainer) {
  9695. node = skipCaretContainers(walker.next, true);
  9696. if (predicateFn(node)) {
  9697. return node;
  9698. }
  9699. }
  9700. while (node = skipCaretContainers(walker.next, shallow)) {
  9701. if (predicateFn(node)) {
  9702. return node;
  9703. }
  9704. }
  9705. }
  9706. return null;
  9707. };
  9708. var getParentBlock = function (node, rootNode) {
  9709. while (node && node !== rootNode) {
  9710. if (isBlockLike(node)) {
  9711. return node;
  9712. }
  9713. node = node.parentNode;
  9714. }
  9715. return null;
  9716. };
  9717. var isInSameBlock = function (caretPosition1, caretPosition2, rootNode) {
  9718. return getParentBlock(caretPosition1.container(), rootNode) === getParentBlock(caretPosition2.container(), rootNode);
  9719. };
  9720. var getChildNodeAtRelativeOffset = function (relativeOffset, caretPosition) {
  9721. if (!caretPosition) {
  9722. return null;
  9723. }
  9724. var container = caretPosition.container();
  9725. var offset = caretPosition.offset();
  9726. if (!isElement$5(container)) {
  9727. return null;
  9728. }
  9729. return container.childNodes[offset + relativeOffset];
  9730. };
  9731. var beforeAfter = function (before, node) {
  9732. var range = node.ownerDocument.createRange();
  9733. if (before) {
  9734. range.setStartBefore(node);
  9735. range.setEndBefore(node);
  9736. } else {
  9737. range.setStartAfter(node);
  9738. range.setEndAfter(node);
  9739. }
  9740. return range;
  9741. };
  9742. var isNodesInSameBlock = function (root, node1, node2) {
  9743. return getParentBlock(node1, root) === getParentBlock(node2, root);
  9744. };
  9745. var lean = function (left, root, node) {
  9746. var sibling, siblingName;
  9747. if (left) {
  9748. siblingName = 'previousSibling';
  9749. } else {
  9750. siblingName = 'nextSibling';
  9751. }
  9752. while (node && node !== root) {
  9753. sibling = node[siblingName];
  9754. if (isCaretContainer$2(sibling)) {
  9755. sibling = sibling[siblingName];
  9756. }
  9757. if (isContentEditableFalse$4(sibling) || isMedia$2(sibling)) {
  9758. if (isNodesInSameBlock(root, sibling, node)) {
  9759. return sibling;
  9760. }
  9761. break;
  9762. }
  9763. if (isCaretCandidate$2(sibling)) {
  9764. break;
  9765. }
  9766. node = node.parentNode;
  9767. }
  9768. return null;
  9769. };
  9770. var before$2 = curry(beforeAfter, true);
  9771. var after$1 = curry(beforeAfter, false);
  9772. var normalizeRange = function (direction, root, range) {
  9773. var node, container, location;
  9774. var leanLeft = curry(lean, true, root);
  9775. var leanRight = curry(lean, false, root);
  9776. container = range.startContainer;
  9777. var offset = range.startOffset;
  9778. if (isCaretContainerBlock(container)) {
  9779. if (!isElement$5(container)) {
  9780. container = container.parentNode;
  9781. }
  9782. location = container.getAttribute('data-mce-caret');
  9783. if (location === 'before') {
  9784. node = container.nextSibling;
  9785. if (isFakeCaretTarget(node)) {
  9786. return before$2(node);
  9787. }
  9788. }
  9789. if (location === 'after') {
  9790. node = container.previousSibling;
  9791. if (isFakeCaretTarget(node)) {
  9792. return after$1(node);
  9793. }
  9794. }
  9795. }
  9796. if (!range.collapsed) {
  9797. return range;
  9798. }
  9799. if (isText$1(container)) {
  9800. if (isCaretContainer$2(container)) {
  9801. if (direction === 1) {
  9802. node = leanRight(container);
  9803. if (node) {
  9804. return before$2(node);
  9805. }
  9806. node = leanLeft(container);
  9807. if (node) {
  9808. return after$1(node);
  9809. }
  9810. }
  9811. if (direction === -1) {
  9812. node = leanLeft(container);
  9813. if (node) {
  9814. return after$1(node);
  9815. }
  9816. node = leanRight(container);
  9817. if (node) {
  9818. return before$2(node);
  9819. }
  9820. }
  9821. return range;
  9822. }
  9823. if (endsWithCaretContainer(container) && offset >= container.data.length - 1) {
  9824. if (direction === 1) {
  9825. node = leanRight(container);
  9826. if (node) {
  9827. return before$2(node);
  9828. }
  9829. }
  9830. return range;
  9831. }
  9832. if (startsWithCaretContainer(container) && offset <= 1) {
  9833. if (direction === -1) {
  9834. node = leanLeft(container);
  9835. if (node) {
  9836. return after$1(node);
  9837. }
  9838. }
  9839. return range;
  9840. }
  9841. if (offset === container.data.length) {
  9842. node = leanRight(container);
  9843. if (node) {
  9844. return before$2(node);
  9845. }
  9846. return range;
  9847. }
  9848. if (offset === 0) {
  9849. node = leanLeft(container);
  9850. if (node) {
  9851. return after$1(node);
  9852. }
  9853. return range;
  9854. }
  9855. }
  9856. return range;
  9857. };
  9858. var getRelativeCefElm = function (forward, caretPosition) {
  9859. return Optional.from(getChildNodeAtRelativeOffset(forward ? 0 : -1, caretPosition)).filter(isContentEditableFalse$4);
  9860. };
  9861. var getNormalizedRangeEndPoint = function (direction, root, range) {
  9862. var normalizedRange = normalizeRange(direction, root, range);
  9863. if (direction === -1) {
  9864. return CaretPosition.fromRangeStart(normalizedRange);
  9865. }
  9866. return CaretPosition.fromRangeEnd(normalizedRange);
  9867. };
  9868. var getElementFromPosition = function (pos) {
  9869. return Optional.from(pos.getNode()).map(SugarElement.fromDom);
  9870. };
  9871. var getElementFromPrevPosition = function (pos) {
  9872. return Optional.from(pos.getNode(true)).map(SugarElement.fromDom);
  9873. };
  9874. var getVisualCaretPosition = function (walkFn, caretPosition) {
  9875. while (caretPosition = walkFn(caretPosition)) {
  9876. if (caretPosition.isVisible()) {
  9877. return caretPosition;
  9878. }
  9879. }
  9880. return caretPosition;
  9881. };
  9882. var isMoveInsideSameBlock = function (from, to) {
  9883. var inSameBlock = isInSameBlock(from, to);
  9884. if (!inSameBlock && isBr(from.getNode())) {
  9885. return true;
  9886. }
  9887. return inSameBlock;
  9888. };
  9889. var HDirection;
  9890. (function (HDirection) {
  9891. HDirection[HDirection['Backwards'] = -1] = 'Backwards';
  9892. HDirection[HDirection['Forwards'] = 1] = 'Forwards';
  9893. }(HDirection || (HDirection = {})));
  9894. var isContentEditableFalse$5 = isContentEditableFalse;
  9895. var isText$7 = isText$1;
  9896. var isElement$6 = isElement$1;
  9897. var isBr$4 = isBr;
  9898. var isCaretCandidate$3 = isCaretCandidate;
  9899. var isAtomic$1 = isAtomic;
  9900. var isEditableCaretCandidate$1 = isEditableCaretCandidate;
  9901. var getParents = function (node, root) {
  9902. var parents = [];
  9903. while (node && node !== root) {
  9904. parents.push(node);
  9905. node = node.parentNode;
  9906. }
  9907. return parents;
  9908. };
  9909. var nodeAtIndex = function (container, offset) {
  9910. if (container.hasChildNodes() && offset < container.childNodes.length) {
  9911. return container.childNodes[offset];
  9912. }
  9913. return null;
  9914. };
  9915. var getCaretCandidatePosition = function (direction, node) {
  9916. if (isForwards(direction)) {
  9917. if (isCaretCandidate$3(node.previousSibling) && !isText$7(node.previousSibling)) {
  9918. return CaretPosition$1.before(node);
  9919. }
  9920. if (isText$7(node)) {
  9921. return CaretPosition$1(node, 0);
  9922. }
  9923. }
  9924. if (isBackwards(direction)) {
  9925. if (isCaretCandidate$3(node.nextSibling) && !isText$7(node.nextSibling)) {
  9926. return CaretPosition$1.after(node);
  9927. }
  9928. if (isText$7(node)) {
  9929. return CaretPosition$1(node, node.data.length);
  9930. }
  9931. }
  9932. if (isBackwards(direction)) {
  9933. if (isBr$4(node)) {
  9934. return CaretPosition$1.before(node);
  9935. }
  9936. return CaretPosition$1.after(node);
  9937. }
  9938. return CaretPosition$1.before(node);
  9939. };
  9940. var moveForwardFromBr = function (root, nextNode) {
  9941. var nextSibling = nextNode.nextSibling;
  9942. if (nextSibling && isCaretCandidate$3(nextSibling)) {
  9943. if (isText$7(nextSibling)) {
  9944. return CaretPosition$1(nextSibling, 0);
  9945. } else {
  9946. return CaretPosition$1.before(nextSibling);
  9947. }
  9948. } else {
  9949. return findCaretPosition(HDirection.Forwards, CaretPosition$1.after(nextNode), root);
  9950. }
  9951. };
  9952. var findCaretPosition = function (direction, startPos, root) {
  9953. var node, nextNode, innerNode;
  9954. var caretPosition;
  9955. if (!isElement$6(root) || !startPos) {
  9956. return null;
  9957. }
  9958. if (startPos.isEqual(CaretPosition$1.after(root)) && root.lastChild) {
  9959. caretPosition = CaretPosition$1.after(root.lastChild);
  9960. if (isBackwards(direction) && isCaretCandidate$3(root.lastChild) && isElement$6(root.lastChild)) {
  9961. return isBr$4(root.lastChild) ? CaretPosition$1.before(root.lastChild) : caretPosition;
  9962. }
  9963. } else {
  9964. caretPosition = startPos;
  9965. }
  9966. var container = caretPosition.container();
  9967. var offset = caretPosition.offset();
  9968. if (isText$7(container)) {
  9969. if (isBackwards(direction) && offset > 0) {
  9970. return CaretPosition$1(container, --offset);
  9971. }
  9972. if (isForwards(direction) && offset < container.length) {
  9973. return CaretPosition$1(container, ++offset);
  9974. }
  9975. node = container;
  9976. } else {
  9977. if (isBackwards(direction) && offset > 0) {
  9978. nextNode = nodeAtIndex(container, offset - 1);
  9979. if (isCaretCandidate$3(nextNode)) {
  9980. if (!isAtomic$1(nextNode)) {
  9981. innerNode = findNode(nextNode, direction, isEditableCaretCandidate$1, nextNode);
  9982. if (innerNode) {
  9983. if (isText$7(innerNode)) {
  9984. return CaretPosition$1(innerNode, innerNode.data.length);
  9985. }
  9986. return CaretPosition$1.after(innerNode);
  9987. }
  9988. }
  9989. if (isText$7(nextNode)) {
  9990. return CaretPosition$1(nextNode, nextNode.data.length);
  9991. }
  9992. return CaretPosition$1.before(nextNode);
  9993. }
  9994. }
  9995. if (isForwards(direction) && offset < container.childNodes.length) {
  9996. nextNode = nodeAtIndex(container, offset);
  9997. if (isCaretCandidate$3(nextNode)) {
  9998. if (isBr$4(nextNode)) {
  9999. return moveForwardFromBr(root, nextNode);
  10000. }
  10001. if (!isAtomic$1(nextNode)) {
  10002. innerNode = findNode(nextNode, direction, isEditableCaretCandidate$1, nextNode);
  10003. if (innerNode) {
  10004. if (isText$7(innerNode)) {
  10005. return CaretPosition$1(innerNode, 0);
  10006. }
  10007. return CaretPosition$1.before(innerNode);
  10008. }
  10009. }
  10010. if (isText$7(nextNode)) {
  10011. return CaretPosition$1(nextNode, 0);
  10012. }
  10013. return CaretPosition$1.after(nextNode);
  10014. }
  10015. }
  10016. node = nextNode ? nextNode : caretPosition.getNode();
  10017. }
  10018. if (isForwards(direction) && caretPosition.isAtEnd() || isBackwards(direction) && caretPosition.isAtStart()) {
  10019. node = findNode(node, direction, always, root, true);
  10020. if (isEditableCaretCandidate$1(node, root)) {
  10021. return getCaretCandidatePosition(direction, node);
  10022. }
  10023. }
  10024. nextNode = findNode(node, direction, isEditableCaretCandidate$1, root);
  10025. var rootContentEditableFalseElm = last$1(filter(getParents(container, root), isContentEditableFalse$5));
  10026. if (rootContentEditableFalseElm && (!nextNode || !rootContentEditableFalseElm.contains(nextNode))) {
  10027. if (isForwards(direction)) {
  10028. caretPosition = CaretPosition$1.after(rootContentEditableFalseElm);
  10029. } else {
  10030. caretPosition = CaretPosition$1.before(rootContentEditableFalseElm);
  10031. }
  10032. return caretPosition;
  10033. }
  10034. if (nextNode) {
  10035. return getCaretCandidatePosition(direction, nextNode);
  10036. }
  10037. return null;
  10038. };
  10039. var CaretWalker = function (root) {
  10040. return {
  10041. next: function (caretPosition) {
  10042. return findCaretPosition(HDirection.Forwards, caretPosition, root);
  10043. },
  10044. prev: function (caretPosition) {
  10045. return findCaretPosition(HDirection.Backwards, caretPosition, root);
  10046. }
  10047. };
  10048. };
  10049. var walkToPositionIn = function (forward, root, start) {
  10050. var position = forward ? CaretPosition$1.before(start) : CaretPosition$1.after(start);
  10051. return fromPosition(forward, root, position);
  10052. };
  10053. var afterElement = function (node) {
  10054. return isBr(node) ? CaretPosition$1.before(node) : CaretPosition$1.after(node);
  10055. };
  10056. var isBeforeOrStart = function (position) {
  10057. if (CaretPosition$1.isTextPosition(position)) {
  10058. return position.offset() === 0;
  10059. } else {
  10060. return isCaretCandidate(position.getNode());
  10061. }
  10062. };
  10063. var isAfterOrEnd = function (position) {
  10064. if (CaretPosition$1.isTextPosition(position)) {
  10065. var container = position.container();
  10066. return position.offset() === container.data.length;
  10067. } else {
  10068. return isCaretCandidate(position.getNode(true));
  10069. }
  10070. };
  10071. var isBeforeAfterSameElement = function (from, to) {
  10072. return !CaretPosition$1.isTextPosition(from) && !CaretPosition$1.isTextPosition(to) && from.getNode() === to.getNode(true);
  10073. };
  10074. var isAtBr = function (position) {
  10075. return !CaretPosition$1.isTextPosition(position) && isBr(position.getNode());
  10076. };
  10077. var shouldSkipPosition = function (forward, from, to) {
  10078. if (forward) {
  10079. return !isBeforeAfterSameElement(from, to) && !isAtBr(from) && isAfterOrEnd(from) && isBeforeOrStart(to);
  10080. } else {
  10081. return !isBeforeAfterSameElement(to, from) && isBeforeOrStart(from) && isAfterOrEnd(to);
  10082. }
  10083. };
  10084. var fromPosition = function (forward, root, pos) {
  10085. var walker = CaretWalker(root);
  10086. return Optional.from(forward ? walker.next(pos) : walker.prev(pos));
  10087. };
  10088. var navigate = function (forward, root, from) {
  10089. return fromPosition(forward, root, from).bind(function (to) {
  10090. if (isInSameBlock(from, to, root) && shouldSkipPosition(forward, from, to)) {
  10091. return fromPosition(forward, root, to);
  10092. } else {
  10093. return Optional.some(to);
  10094. }
  10095. });
  10096. };
  10097. var navigateIgnore = function (forward, root, from, ignoreFilter) {
  10098. return navigate(forward, root, from).bind(function (pos) {
  10099. return ignoreFilter(pos) ? navigateIgnore(forward, root, pos, ignoreFilter) : Optional.some(pos);
  10100. });
  10101. };
  10102. var positionIn = function (forward, element) {
  10103. var startNode = forward ? element.firstChild : element.lastChild;
  10104. if (isText$1(startNode)) {
  10105. return Optional.some(CaretPosition$1(startNode, forward ? 0 : startNode.data.length));
  10106. } else if (startNode) {
  10107. if (isCaretCandidate(startNode)) {
  10108. return Optional.some(forward ? CaretPosition$1.before(startNode) : afterElement(startNode));
  10109. } else {
  10110. return walkToPositionIn(forward, element, startNode);
  10111. }
  10112. } else {
  10113. return Optional.none();
  10114. }
  10115. };
  10116. var nextPosition = curry(fromPosition, true);
  10117. var prevPosition = curry(fromPosition, false);
  10118. var firstPositionIn = curry(positionIn, true);
  10119. var lastPositionIn = curry(positionIn, false);
  10120. var CARET_ID = '_mce_caret';
  10121. var isCaretNode = function (node) {
  10122. return isElement$1(node) && node.id === CARET_ID;
  10123. };
  10124. var getParentCaretContainer = function (body, node) {
  10125. while (node && node !== body) {
  10126. if (node.id === CARET_ID) {
  10127. return node;
  10128. }
  10129. node = node.parentNode;
  10130. }
  10131. return null;
  10132. };
  10133. var isStringPathBookmark = function (bookmark) {
  10134. return typeof bookmark.start === 'string';
  10135. };
  10136. var isRangeBookmark = function (bookmark) {
  10137. return bookmark.hasOwnProperty('rng');
  10138. };
  10139. var isIdBookmark = function (bookmark) {
  10140. return bookmark.hasOwnProperty('id');
  10141. };
  10142. var isIndexBookmark = function (bookmark) {
  10143. return bookmark.hasOwnProperty('name');
  10144. };
  10145. var isPathBookmark = function (bookmark) {
  10146. return Tools.isArray(bookmark.start);
  10147. };
  10148. var addBogus = function (dom, node) {
  10149. if (isElement$1(node) && dom.isBlock(node) && !node.innerHTML && !Env.ie) {
  10150. node.innerHTML = '<br data-mce-bogus="1" />';
  10151. }
  10152. return node;
  10153. };
  10154. var resolveCaretPositionBookmark = function (dom, bookmark) {
  10155. var pos;
  10156. var rng = dom.createRng();
  10157. pos = resolve$1(dom.getRoot(), bookmark.start);
  10158. rng.setStart(pos.container(), pos.offset());
  10159. pos = resolve$1(dom.getRoot(), bookmark.end);
  10160. rng.setEnd(pos.container(), pos.offset());
  10161. return rng;
  10162. };
  10163. var insertZwsp = function (node, rng) {
  10164. var textNode = node.ownerDocument.createTextNode(ZWSP);
  10165. node.appendChild(textNode);
  10166. rng.setStart(textNode, 0);
  10167. rng.setEnd(textNode, 0);
  10168. };
  10169. var isEmpty$1 = function (node) {
  10170. return node.hasChildNodes() === false;
  10171. };
  10172. var tryFindRangePosition = function (node, rng) {
  10173. return lastPositionIn(node).fold(function () {
  10174. return false;
  10175. }, function (pos) {
  10176. rng.setStart(pos.container(), pos.offset());
  10177. rng.setEnd(pos.container(), pos.offset());
  10178. return true;
  10179. });
  10180. };
  10181. var padEmptyCaretContainer = function (root, node, rng) {
  10182. if (isEmpty$1(node) && getParentCaretContainer(root, node)) {
  10183. insertZwsp(node, rng);
  10184. return true;
  10185. } else {
  10186. return false;
  10187. }
  10188. };
  10189. var setEndPoint = function (dom, start, bookmark, rng) {
  10190. var point = bookmark[start ? 'start' : 'end'];
  10191. var i, node, offset, children;
  10192. var root = dom.getRoot();
  10193. if (point) {
  10194. offset = point[0];
  10195. for (node = root, i = point.length - 1; i >= 1; i--) {
  10196. children = node.childNodes;
  10197. if (padEmptyCaretContainer(root, node, rng)) {
  10198. return true;
  10199. }
  10200. if (point[i] > children.length - 1) {
  10201. if (padEmptyCaretContainer(root, node, rng)) {
  10202. return true;
  10203. }
  10204. return tryFindRangePosition(node, rng);
  10205. }
  10206. node = children[point[i]];
  10207. }
  10208. if (node.nodeType === 3) {
  10209. offset = Math.min(point[0], node.nodeValue.length);
  10210. }
  10211. if (node.nodeType === 1) {
  10212. offset = Math.min(point[0], node.childNodes.length);
  10213. }
  10214. if (start) {
  10215. rng.setStart(node, offset);
  10216. } else {
  10217. rng.setEnd(node, offset);
  10218. }
  10219. }
  10220. return true;
  10221. };
  10222. var isValidTextNode = function (node) {
  10223. return isText$1(node) && node.data.length > 0;
  10224. };
  10225. var restoreEndPoint = function (dom, suffix, bookmark) {
  10226. var marker = dom.get(bookmark.id + '_' + suffix), node, idx, next, prev;
  10227. var keep = bookmark.keep;
  10228. var container, offset;
  10229. if (marker) {
  10230. node = marker.parentNode;
  10231. if (suffix === 'start') {
  10232. if (!keep) {
  10233. idx = dom.nodeIndex(marker);
  10234. } else {
  10235. if (marker.hasChildNodes()) {
  10236. node = marker.firstChild;
  10237. idx = 1;
  10238. } else if (isValidTextNode(marker.nextSibling)) {
  10239. node = marker.nextSibling;
  10240. idx = 0;
  10241. } else if (isValidTextNode(marker.previousSibling)) {
  10242. node = marker.previousSibling;
  10243. idx = marker.previousSibling.data.length;
  10244. } else {
  10245. node = marker.parentNode;
  10246. idx = dom.nodeIndex(marker) + 1;
  10247. }
  10248. }
  10249. container = node;
  10250. offset = idx;
  10251. } else {
  10252. if (!keep) {
  10253. idx = dom.nodeIndex(marker);
  10254. } else {
  10255. if (marker.hasChildNodes()) {
  10256. node = marker.firstChild;
  10257. idx = 1;
  10258. } else if (isValidTextNode(marker.previousSibling)) {
  10259. node = marker.previousSibling;
  10260. idx = marker.previousSibling.data.length;
  10261. } else {
  10262. node = marker.parentNode;
  10263. idx = dom.nodeIndex(marker);
  10264. }
  10265. }
  10266. container = node;
  10267. offset = idx;
  10268. }
  10269. if (!keep) {
  10270. prev = marker.previousSibling;
  10271. next = marker.nextSibling;
  10272. Tools.each(Tools.grep(marker.childNodes), function (node) {
  10273. if (isText$1(node)) {
  10274. node.nodeValue = node.nodeValue.replace(/\uFEFF/g, '');
  10275. }
  10276. });
  10277. while (marker = dom.get(bookmark.id + '_' + suffix)) {
  10278. dom.remove(marker, true);
  10279. }
  10280. if (prev && next && prev.nodeType === next.nodeType && isText$1(prev) && !Env.opera) {
  10281. idx = prev.nodeValue.length;
  10282. prev.appendData(next.nodeValue);
  10283. dom.remove(next);
  10284. container = prev;
  10285. offset = idx;
  10286. }
  10287. }
  10288. return Optional.some(CaretPosition$1(container, offset));
  10289. } else {
  10290. return Optional.none();
  10291. }
  10292. };
  10293. var resolvePaths = function (dom, bookmark) {
  10294. var rng = dom.createRng();
  10295. if (setEndPoint(dom, true, bookmark, rng) && setEndPoint(dom, false, bookmark, rng)) {
  10296. return Optional.some(rng);
  10297. } else {
  10298. return Optional.none();
  10299. }
  10300. };
  10301. var resolveId = function (dom, bookmark) {
  10302. var startPos = restoreEndPoint(dom, 'start', bookmark);
  10303. var endPos = restoreEndPoint(dom, 'end', bookmark);
  10304. return lift2(startPos, endPos.or(startPos), function (spos, epos) {
  10305. var rng = dom.createRng();
  10306. rng.setStart(addBogus(dom, spos.container()), spos.offset());
  10307. rng.setEnd(addBogus(dom, epos.container()), epos.offset());
  10308. return rng;
  10309. });
  10310. };
  10311. var resolveIndex$1 = function (dom, bookmark) {
  10312. return Optional.from(dom.select(bookmark.name)[bookmark.index]).map(function (elm) {
  10313. var rng = dom.createRng();
  10314. rng.selectNode(elm);
  10315. return rng;
  10316. });
  10317. };
  10318. var resolve$2 = function (selection, bookmark) {
  10319. var dom = selection.dom;
  10320. if (bookmark) {
  10321. if (isPathBookmark(bookmark)) {
  10322. return resolvePaths(dom, bookmark);
  10323. } else if (isStringPathBookmark(bookmark)) {
  10324. return Optional.some(resolveCaretPositionBookmark(dom, bookmark));
  10325. } else if (isIdBookmark(bookmark)) {
  10326. return resolveId(dom, bookmark);
  10327. } else if (isIndexBookmark(bookmark)) {
  10328. return resolveIndex$1(dom, bookmark);
  10329. } else if (isRangeBookmark(bookmark)) {
  10330. return Optional.some(bookmark.rng);
  10331. }
  10332. }
  10333. return Optional.none();
  10334. };
  10335. var getBookmark$1 = function (selection, type, normalized) {
  10336. return getBookmark(selection, type, normalized);
  10337. };
  10338. var moveToBookmark = function (selection, bookmark) {
  10339. resolve$2(selection, bookmark).each(function (rng) {
  10340. selection.setRng(rng);
  10341. });
  10342. };
  10343. var isBookmarkNode$1 = function (node) {
  10344. return isElement$1(node) && node.tagName === 'SPAN' && node.getAttribute('data-mce-type') === 'bookmark';
  10345. };
  10346. var is$2 = function (expected) {
  10347. return function (actual) {
  10348. return expected === actual;
  10349. };
  10350. };
  10351. var isNbsp = is$2(nbsp);
  10352. var isWhiteSpace$1 = function (chr) {
  10353. return chr !== '' && ' \f\n\r\t\x0B'.indexOf(chr) !== -1;
  10354. };
  10355. var isContent$1 = function (chr) {
  10356. return !isWhiteSpace$1(chr) && !isNbsp(chr);
  10357. };
  10358. var isNode = function (node) {
  10359. return !!node.nodeType;
  10360. };
  10361. var isInlineBlock = function (node) {
  10362. return node && /^(IMG)$/.test(node.nodeName);
  10363. };
  10364. var moveStart = function (dom, selection, rng) {
  10365. var offset = rng.startOffset;
  10366. var container = rng.startContainer, walker, node, nodes;
  10367. if (rng.startContainer === rng.endContainer) {
  10368. if (isInlineBlock(rng.startContainer.childNodes[rng.startOffset])) {
  10369. return;
  10370. }
  10371. }
  10372. if (container.nodeType === 1) {
  10373. nodes = container.childNodes;
  10374. if (offset < nodes.length) {
  10375. container = nodes[offset];
  10376. walker = new DomTreeWalker(container, dom.getParent(container, dom.isBlock));
  10377. } else {
  10378. container = nodes[nodes.length - 1];
  10379. walker = new DomTreeWalker(container, dom.getParent(container, dom.isBlock));
  10380. walker.next(true);
  10381. }
  10382. for (node = walker.current(); node; node = walker.next()) {
  10383. if (node.nodeType === 3 && !isWhiteSpaceNode(node)) {
  10384. rng.setStart(node, 0);
  10385. selection.setRng(rng);
  10386. return;
  10387. }
  10388. }
  10389. }
  10390. };
  10391. var getNonWhiteSpaceSibling = function (node, next, inc) {
  10392. if (node) {
  10393. var nextName = next ? 'nextSibling' : 'previousSibling';
  10394. for (node = inc ? node : node[nextName]; node; node = node[nextName]) {
  10395. if (node.nodeType === 1 || !isWhiteSpaceNode(node)) {
  10396. return node;
  10397. }
  10398. }
  10399. }
  10400. };
  10401. var isTextBlock$1 = function (editor, name) {
  10402. if (isNode(name)) {
  10403. name = name.nodeName;
  10404. }
  10405. return !!editor.schema.getTextBlockElements()[name.toLowerCase()];
  10406. };
  10407. var isValid = function (ed, parent, child) {
  10408. return ed.schema.isValidChild(parent, child);
  10409. };
  10410. var isWhiteSpaceNode = function (node) {
  10411. return node && isText$1(node) && /^([\t \r\n]+|)$/.test(node.nodeValue);
  10412. };
  10413. var isEmptyTextNode = function (node) {
  10414. return node && isText$1(node) && node.length === 0;
  10415. };
  10416. var replaceVars = function (value, vars) {
  10417. if (typeof value !== 'string') {
  10418. value = value(vars);
  10419. } else if (vars) {
  10420. value = value.replace(/%(\w+)/g, function (str, name) {
  10421. return vars[name] || str;
  10422. });
  10423. }
  10424. return value;
  10425. };
  10426. var isEq = function (str1, str2) {
  10427. str1 = str1 || '';
  10428. str2 = str2 || '';
  10429. str1 = '' + (str1.nodeName || str1);
  10430. str2 = '' + (str2.nodeName || str2);
  10431. return str1.toLowerCase() === str2.toLowerCase();
  10432. };
  10433. var normalizeStyleValue = function (dom, value, name) {
  10434. if (name === 'color' || name === 'backgroundColor') {
  10435. value = dom.toHex(value);
  10436. }
  10437. if (name === 'fontWeight' && value === 700) {
  10438. value = 'bold';
  10439. }
  10440. if (name === 'fontFamily') {
  10441. value = value.replace(/[\'\"]/g, '').replace(/,\s+/g, ',');
  10442. }
  10443. return '' + value;
  10444. };
  10445. var getStyle = function (dom, node, name) {
  10446. return normalizeStyleValue(dom, dom.getStyle(node, name), name);
  10447. };
  10448. var getTextDecoration = function (dom, node) {
  10449. var decoration;
  10450. dom.getParent(node, function (n) {
  10451. decoration = dom.getStyle(n, 'text-decoration');
  10452. return decoration && decoration !== 'none';
  10453. });
  10454. return decoration;
  10455. };
  10456. var getParents$1 = function (dom, node, selector) {
  10457. return dom.getParents(node, selector, dom.getRoot());
  10458. };
  10459. var isVariableFormatName = function (editor, formatName) {
  10460. var hasVariableValues = function (format) {
  10461. var isVariableValue = function (val) {
  10462. return val.length > 1 && val.charAt(0) === '%';
  10463. };
  10464. return exists([
  10465. 'styles',
  10466. 'attributes'
  10467. ], function (key) {
  10468. return get(format, key).exists(function (field) {
  10469. var fieldValues = isArray(field) ? field : values(field);
  10470. return exists(fieldValues, isVariableValue);
  10471. });
  10472. });
  10473. };
  10474. return exists(editor.formatter.get(formatName), hasVariableValues);
  10475. };
  10476. var areSimilarFormats = function (editor, formatName, otherFormatName) {
  10477. var validKeys = [
  10478. 'inline',
  10479. 'block',
  10480. 'selector',
  10481. 'attributes',
  10482. 'styles',
  10483. 'classes'
  10484. ];
  10485. var filterObj = function (format) {
  10486. return filter$1(format, function (_, key) {
  10487. return exists(validKeys, function (validKey) {
  10488. return validKey === key;
  10489. });
  10490. });
  10491. };
  10492. return exists(editor.formatter.get(formatName), function (fmt1) {
  10493. var filteredFmt1 = filterObj(fmt1);
  10494. return exists(editor.formatter.get(otherFormatName), function (fmt2) {
  10495. var filteredFmt2 = filterObj(fmt2);
  10496. return equal(filteredFmt1, filteredFmt2);
  10497. });
  10498. });
  10499. };
  10500. var isBookmarkNode$2 = isBookmarkNode$1;
  10501. var getParents$2 = getParents$1;
  10502. var isWhiteSpaceNode$1 = isWhiteSpaceNode;
  10503. var isTextBlock$2 = isTextBlock$1;
  10504. var isBogusBr = function (node) {
  10505. return node.nodeName === 'BR' && node.getAttribute('data-mce-bogus') && !node.nextSibling;
  10506. };
  10507. var findParentContentEditable = function (dom, node) {
  10508. var parent = node;
  10509. while (parent) {
  10510. if (isElement$1(parent) && dom.getContentEditable(parent)) {
  10511. return dom.getContentEditable(parent) === 'false' ? parent : node;
  10512. }
  10513. parent = parent.parentNode;
  10514. }
  10515. return node;
  10516. };
  10517. var walkText = function (start, node, offset, predicate) {
  10518. var str = node.data;
  10519. for (var i = offset; start ? i >= 0 : i < str.length; start ? i-- : i++) {
  10520. if (predicate(str.charAt(i))) {
  10521. return start ? i + 1 : i;
  10522. }
  10523. }
  10524. return -1;
  10525. };
  10526. var findSpace = function (start, node, offset) {
  10527. return walkText(start, node, offset, function (c) {
  10528. return isNbsp(c) || isWhiteSpace$1(c);
  10529. });
  10530. };
  10531. var findContent = function (start, node, offset) {
  10532. return walkText(start, node, offset, isContent$1);
  10533. };
  10534. var findWordEndPoint = function (dom, body, container, offset, start, includeTrailingSpaces) {
  10535. var lastTextNode;
  10536. var rootNode = dom.getParent(container, dom.isBlock) || body;
  10537. var walk = function (container, offset, pred) {
  10538. var textSeeker = TextSeeker(dom);
  10539. var walker = start ? textSeeker.backwards : textSeeker.forwards;
  10540. return Optional.from(walker(container, offset, function (text, textOffset) {
  10541. if (isBookmarkNode$2(text.parentNode)) {
  10542. return -1;
  10543. } else {
  10544. lastTextNode = text;
  10545. return pred(start, text, textOffset);
  10546. }
  10547. }, rootNode));
  10548. };
  10549. var spaceResult = walk(container, offset, findSpace);
  10550. return spaceResult.bind(function (result) {
  10551. return includeTrailingSpaces ? walk(result.container, result.offset + (start ? -1 : 0), findContent) : Optional.some(result);
  10552. }).orThunk(function () {
  10553. return lastTextNode ? Optional.some({
  10554. container: lastTextNode,
  10555. offset: start ? 0 : lastTextNode.length
  10556. }) : Optional.none();
  10557. });
  10558. };
  10559. var findSelectorEndPoint = function (dom, format, rng, container, siblingName) {
  10560. if (isText$1(container) && container.nodeValue.length === 0 && container[siblingName]) {
  10561. container = container[siblingName];
  10562. }
  10563. var parents = getParents$2(dom, container);
  10564. for (var i = 0; i < parents.length; i++) {
  10565. for (var y = 0; y < format.length; y++) {
  10566. var curFormat = format[y];
  10567. if ('collapsed' in curFormat && curFormat.collapsed !== rng.collapsed) {
  10568. continue;
  10569. }
  10570. if (dom.is(parents[i], curFormat.selector)) {
  10571. return parents[i];
  10572. }
  10573. }
  10574. }
  10575. return container;
  10576. };
  10577. var findBlockEndPoint = function (editor, format, container, siblingName) {
  10578. var node;
  10579. var dom = editor.dom;
  10580. var root = dom.getRoot();
  10581. if (!format[0].wrapper) {
  10582. node = dom.getParent(container, format[0].block, root);
  10583. }
  10584. if (!node) {
  10585. var scopeRoot = dom.getParent(container, 'LI,TD,TH');
  10586. node = dom.getParent(isText$1(container) ? container.parentNode : container, function (node) {
  10587. return node !== root && isTextBlock$2(editor, node);
  10588. }, scopeRoot);
  10589. }
  10590. if (node && format[0].wrapper) {
  10591. node = getParents$2(dom, node, 'ul,ol').reverse()[0] || node;
  10592. }
  10593. if (!node) {
  10594. node = container;
  10595. while (node[siblingName] && !dom.isBlock(node[siblingName])) {
  10596. node = node[siblingName];
  10597. if (isEq(node, 'br')) {
  10598. break;
  10599. }
  10600. }
  10601. }
  10602. return node || container;
  10603. };
  10604. var findParentContainer = function (dom, format, startContainer, startOffset, endContainer, endOffset, start) {
  10605. var container, parent, sibling;
  10606. container = parent = start ? startContainer : endContainer;
  10607. var siblingName = start ? 'previousSibling' : 'nextSibling';
  10608. var root = dom.getRoot();
  10609. if (isText$1(container) && !isWhiteSpaceNode$1(container)) {
  10610. if (start ? startOffset > 0 : endOffset < container.nodeValue.length) {
  10611. return container;
  10612. }
  10613. }
  10614. while (true) {
  10615. if (!format[0].block_expand && dom.isBlock(parent)) {
  10616. return parent;
  10617. }
  10618. for (sibling = parent[siblingName]; sibling; sibling = sibling[siblingName]) {
  10619. if (!isBookmarkNode$2(sibling) && !isWhiteSpaceNode$1(sibling) && !isBogusBr(sibling)) {
  10620. return parent;
  10621. }
  10622. }
  10623. if (parent === root || parent.parentNode === root) {
  10624. container = parent;
  10625. break;
  10626. }
  10627. parent = parent.parentNode;
  10628. }
  10629. return container;
  10630. };
  10631. var expandRng = function (editor, rng, format, includeTrailingSpace) {
  10632. if (includeTrailingSpace === void 0) {
  10633. includeTrailingSpace = false;
  10634. }
  10635. var startContainer = rng.startContainer, startOffset = rng.startOffset, endContainer = rng.endContainer, endOffset = rng.endOffset;
  10636. var dom = editor.dom;
  10637. if (isElement$1(startContainer) && startContainer.hasChildNodes()) {
  10638. startContainer = getNode(startContainer, startOffset);
  10639. if (isText$1(startContainer)) {
  10640. startOffset = 0;
  10641. }
  10642. }
  10643. if (isElement$1(endContainer) && endContainer.hasChildNodes()) {
  10644. endContainer = getNode(endContainer, rng.collapsed ? endOffset : endOffset - 1);
  10645. if (isText$1(endContainer)) {
  10646. endOffset = endContainer.nodeValue.length;
  10647. }
  10648. }
  10649. startContainer = findParentContentEditable(dom, startContainer);
  10650. endContainer = findParentContentEditable(dom, endContainer);
  10651. if (isBookmarkNode$2(startContainer.parentNode) || isBookmarkNode$2(startContainer)) {
  10652. startContainer = isBookmarkNode$2(startContainer) ? startContainer : startContainer.parentNode;
  10653. if (rng.collapsed) {
  10654. startContainer = startContainer.previousSibling || startContainer;
  10655. } else {
  10656. startContainer = startContainer.nextSibling || startContainer;
  10657. }
  10658. if (isText$1(startContainer)) {
  10659. startOffset = rng.collapsed ? startContainer.length : 0;
  10660. }
  10661. }
  10662. if (isBookmarkNode$2(endContainer.parentNode) || isBookmarkNode$2(endContainer)) {
  10663. endContainer = isBookmarkNode$2(endContainer) ? endContainer : endContainer.parentNode;
  10664. if (rng.collapsed) {
  10665. endContainer = endContainer.nextSibling || endContainer;
  10666. } else {
  10667. endContainer = endContainer.previousSibling || endContainer;
  10668. }
  10669. if (isText$1(endContainer)) {
  10670. endOffset = rng.collapsed ? 0 : endContainer.length;
  10671. }
  10672. }
  10673. if (rng.collapsed) {
  10674. var startPoint = findWordEndPoint(dom, editor.getBody(), startContainer, startOffset, true, includeTrailingSpace);
  10675. startPoint.each(function (_a) {
  10676. var container = _a.container, offset = _a.offset;
  10677. startContainer = container;
  10678. startOffset = offset;
  10679. });
  10680. var endPoint = findWordEndPoint(dom, editor.getBody(), endContainer, endOffset, false, includeTrailingSpace);
  10681. endPoint.each(function (_a) {
  10682. var container = _a.container, offset = _a.offset;
  10683. endContainer = container;
  10684. endOffset = offset;
  10685. });
  10686. }
  10687. if (format[0].inline || format[0].block_expand) {
  10688. if (!format[0].inline || (!isText$1(startContainer) || startOffset === 0)) {
  10689. startContainer = findParentContainer(dom, format, startContainer, startOffset, endContainer, endOffset, true);
  10690. }
  10691. if (!format[0].inline || (!isText$1(endContainer) || endOffset === endContainer.nodeValue.length)) {
  10692. endContainer = findParentContainer(dom, format, startContainer, startOffset, endContainer, endOffset, false);
  10693. }
  10694. }
  10695. if (format[0].selector && format[0].expand !== false && !format[0].inline) {
  10696. startContainer = findSelectorEndPoint(dom, format, rng, startContainer, 'previousSibling');
  10697. endContainer = findSelectorEndPoint(dom, format, rng, endContainer, 'nextSibling');
  10698. }
  10699. if (format[0].block || format[0].selector) {
  10700. startContainer = findBlockEndPoint(editor, format, startContainer, 'previousSibling');
  10701. endContainer = findBlockEndPoint(editor, format, endContainer, 'nextSibling');
  10702. if (format[0].block) {
  10703. if (!dom.isBlock(startContainer)) {
  10704. startContainer = findParentContainer(dom, format, startContainer, startOffset, endContainer, endOffset, true);
  10705. }
  10706. if (!dom.isBlock(endContainer)) {
  10707. endContainer = findParentContainer(dom, format, startContainer, startOffset, endContainer, endOffset, false);
  10708. }
  10709. }
  10710. }
  10711. if (isElement$1(startContainer)) {
  10712. startOffset = dom.nodeIndex(startContainer);
  10713. startContainer = startContainer.parentNode;
  10714. }
  10715. if (isElement$1(endContainer)) {
  10716. endOffset = dom.nodeIndex(endContainer) + 1;
  10717. endContainer = endContainer.parentNode;
  10718. }
  10719. return {
  10720. startContainer: startContainer,
  10721. startOffset: startOffset,
  10722. endContainer: endContainer,
  10723. endOffset: endOffset
  10724. };
  10725. };
  10726. var clampToExistingChildren = function (container, index) {
  10727. var childNodes = container.childNodes;
  10728. if (index >= childNodes.length) {
  10729. index = childNodes.length - 1;
  10730. } else if (index < 0) {
  10731. index = 0;
  10732. }
  10733. return childNodes[index] || container;
  10734. };
  10735. var getEndChild = function (container, index) {
  10736. return clampToExistingChildren(container, index - 1);
  10737. };
  10738. var walk$1 = function (dom, rng, callback) {
  10739. var startContainer = rng.startContainer;
  10740. var startOffset = rng.startOffset;
  10741. var endContainer = rng.endContainer;
  10742. var endOffset = rng.endOffset;
  10743. var exclude = function (nodes) {
  10744. var node;
  10745. node = nodes[0];
  10746. if (node.nodeType === 3 && node === startContainer && startOffset >= node.nodeValue.length) {
  10747. nodes.splice(0, 1);
  10748. }
  10749. node = nodes[nodes.length - 1];
  10750. if (endOffset === 0 && nodes.length > 0 && node === endContainer && node.nodeType === 3) {
  10751. nodes.splice(nodes.length - 1, 1);
  10752. }
  10753. return nodes;
  10754. };
  10755. var collectSiblings = function (node, name, endNode) {
  10756. var siblings = [];
  10757. for (; node && node !== endNode; node = node[name]) {
  10758. siblings.push(node);
  10759. }
  10760. return siblings;
  10761. };
  10762. var findEndPoint = function (node, root) {
  10763. do {
  10764. if (node.parentNode === root) {
  10765. return node;
  10766. }
  10767. node = node.parentNode;
  10768. } while (node);
  10769. };
  10770. var walkBoundary = function (startNode, endNode, next) {
  10771. var siblingName = next ? 'nextSibling' : 'previousSibling';
  10772. for (var node = startNode, parent_1 = node.parentNode; node && node !== endNode; node = parent_1) {
  10773. parent_1 = node.parentNode;
  10774. var siblings_1 = collectSiblings(node === startNode ? node : node[siblingName], siblingName);
  10775. if (siblings_1.length) {
  10776. if (!next) {
  10777. siblings_1.reverse();
  10778. }
  10779. callback(exclude(siblings_1));
  10780. }
  10781. }
  10782. };
  10783. if (startContainer.nodeType === 1 && startContainer.hasChildNodes()) {
  10784. startContainer = clampToExistingChildren(startContainer, startOffset);
  10785. }
  10786. if (endContainer.nodeType === 1 && endContainer.hasChildNodes()) {
  10787. endContainer = getEndChild(endContainer, endOffset);
  10788. }
  10789. if (startContainer === endContainer) {
  10790. return callback(exclude([startContainer]));
  10791. }
  10792. var ancestor = dom.findCommonAncestor(startContainer, endContainer);
  10793. for (var node = startContainer; node; node = node.parentNode) {
  10794. if (node === endContainer) {
  10795. return walkBoundary(startContainer, ancestor, true);
  10796. }
  10797. if (node === ancestor) {
  10798. break;
  10799. }
  10800. }
  10801. for (var node = endContainer; node; node = node.parentNode) {
  10802. if (node === startContainer) {
  10803. return walkBoundary(endContainer, ancestor);
  10804. }
  10805. if (node === ancestor) {
  10806. break;
  10807. }
  10808. }
  10809. var startPoint = findEndPoint(startContainer, ancestor) || startContainer;
  10810. var endPoint = findEndPoint(endContainer, ancestor) || endContainer;
  10811. walkBoundary(startContainer, startPoint, true);
  10812. var siblings = collectSiblings(startPoint === startContainer ? startPoint : startPoint.nextSibling, 'nextSibling', endPoint === endContainer ? endPoint.nextSibling : endPoint);
  10813. if (siblings.length) {
  10814. callback(exclude(siblings));
  10815. }
  10816. walkBoundary(endContainer, endPoint);
  10817. };
  10818. var getRanges = function (selection) {
  10819. var ranges = [];
  10820. if (selection) {
  10821. for (var i = 0; i < selection.rangeCount; i++) {
  10822. ranges.push(selection.getRangeAt(i));
  10823. }
  10824. }
  10825. return ranges;
  10826. };
  10827. var getSelectedNodes = function (ranges) {
  10828. return bind(ranges, function (range) {
  10829. var node = getSelectedNode(range);
  10830. return node ? [SugarElement.fromDom(node)] : [];
  10831. });
  10832. };
  10833. var hasMultipleRanges = function (selection) {
  10834. return getRanges(selection).length > 1;
  10835. };
  10836. var getCellsFromRanges = function (ranges) {
  10837. return filter(getSelectedNodes(ranges), isTableCell$1);
  10838. };
  10839. var getCellsFromElement = function (elm) {
  10840. return descendants$1(elm, 'td[data-mce-selected],th[data-mce-selected]');
  10841. };
  10842. var getCellsFromElementOrRanges = function (ranges, element) {
  10843. var selectedCells = getCellsFromElement(element);
  10844. return selectedCells.length > 0 ? selectedCells : getCellsFromRanges(ranges);
  10845. };
  10846. var getCellsFromEditor = function (editor) {
  10847. return getCellsFromElementOrRanges(getRanges(editor.selection.getSel()), SugarElement.fromDom(editor.getBody()));
  10848. };
  10849. var getStartNode = function (rng) {
  10850. var sc = rng.startContainer, so = rng.startOffset;
  10851. if (isText$1(sc)) {
  10852. return so === 0 ? Optional.some(SugarElement.fromDom(sc)) : Optional.none();
  10853. } else {
  10854. return Optional.from(sc.childNodes[so]).map(SugarElement.fromDom);
  10855. }
  10856. };
  10857. var getEndNode = function (rng) {
  10858. var ec = rng.endContainer, eo = rng.endOffset;
  10859. if (isText$1(ec)) {
  10860. return eo === ec.data.length ? Optional.some(SugarElement.fromDom(ec)) : Optional.none();
  10861. } else {
  10862. return Optional.from(ec.childNodes[eo - 1]).map(SugarElement.fromDom);
  10863. }
  10864. };
  10865. var getFirstChildren = function (node) {
  10866. return firstChild(node).fold(constant([node]), function (child) {
  10867. return [node].concat(getFirstChildren(child));
  10868. });
  10869. };
  10870. var getLastChildren = function (node) {
  10871. return lastChild(node).fold(constant([node]), function (child) {
  10872. if (name(child) === 'br') {
  10873. return prevSibling(child).map(function (sibling) {
  10874. return [node].concat(getLastChildren(sibling));
  10875. }).getOr([]);
  10876. } else {
  10877. return [node].concat(getLastChildren(child));
  10878. }
  10879. });
  10880. };
  10881. var hasAllContentsSelected = function (elm, rng) {
  10882. return lift2(getStartNode(rng), getEndNode(rng), function (startNode, endNode) {
  10883. var start = find(getFirstChildren(elm), curry(eq$2, startNode));
  10884. var end = find(getLastChildren(elm), curry(eq$2, endNode));
  10885. return start.isSome() && end.isSome();
  10886. }).getOr(false);
  10887. };
  10888. var moveEndPoint$1 = function (dom, rng, node, start) {
  10889. var root = node, walker = new DomTreeWalker(node, root);
  10890. var moveCaretBeforeOnEnterElementsMap = filter$1(dom.schema.getMoveCaretBeforeOnEnterElements(), function (_, name) {
  10891. return !contains([
  10892. 'td',
  10893. 'th',
  10894. 'table'
  10895. ], name.toLowerCase());
  10896. });
  10897. do {
  10898. if (isText$1(node) && Tools.trim(node.nodeValue).length !== 0) {
  10899. if (start) {
  10900. rng.setStart(node, 0);
  10901. } else {
  10902. rng.setEnd(node, node.nodeValue.length);
  10903. }
  10904. return;
  10905. }
  10906. if (moveCaretBeforeOnEnterElementsMap[node.nodeName]) {
  10907. if (start) {
  10908. rng.setStartBefore(node);
  10909. } else {
  10910. if (node.nodeName === 'BR') {
  10911. rng.setEndBefore(node);
  10912. } else {
  10913. rng.setEndAfter(node);
  10914. }
  10915. }
  10916. return;
  10917. }
  10918. } while (node = start ? walker.next() : walker.prev());
  10919. if (root.nodeName === 'BODY') {
  10920. if (start) {
  10921. rng.setStart(root, 0);
  10922. } else {
  10923. rng.setEnd(root, root.childNodes.length);
  10924. }
  10925. }
  10926. };
  10927. var hasAnyRanges = function (editor) {
  10928. var sel = editor.selection.getSel();
  10929. return sel && sel.rangeCount > 0;
  10930. };
  10931. var runOnRanges = function (editor, executor) {
  10932. var fakeSelectionNodes = getCellsFromEditor(editor);
  10933. if (fakeSelectionNodes.length > 0) {
  10934. each(fakeSelectionNodes, function (elem) {
  10935. var node = elem.dom;
  10936. var fakeNodeRng = editor.dom.createRng();
  10937. fakeNodeRng.setStartBefore(node);
  10938. fakeNodeRng.setEndAfter(node);
  10939. executor(fakeNodeRng, true);
  10940. });
  10941. } else {
  10942. executor(editor.selection.getRng(), false);
  10943. }
  10944. };
  10945. var preserve = function (selection, fillBookmark, executor) {
  10946. var bookmark = getPersistentBookmark(selection, fillBookmark);
  10947. executor(bookmark);
  10948. selection.moveToBookmark(bookmark);
  10949. };
  10950. function NodeValue (is, name) {
  10951. var get = function (element) {
  10952. if (!is(element)) {
  10953. throw new Error('Can only get ' + name + ' value of a ' + name + ' node');
  10954. }
  10955. return getOption(element).getOr('');
  10956. };
  10957. var getOption = function (element) {
  10958. return is(element) ? Optional.from(element.dom.nodeValue) : Optional.none();
  10959. };
  10960. var set = function (element, value) {
  10961. if (!is(element)) {
  10962. throw new Error('Can only set raw ' + name + ' value of a ' + name + ' node');
  10963. }
  10964. element.dom.nodeValue = value;
  10965. };
  10966. return {
  10967. get: get,
  10968. getOption: getOption,
  10969. set: set
  10970. };
  10971. }
  10972. var api = NodeValue(isText, 'text');
  10973. var get$7 = function (element) {
  10974. return api.get(element);
  10975. };
  10976. var isZeroWidth = function (elem) {
  10977. return isText(elem) && get$7(elem) === ZWSP;
  10978. };
  10979. var context = function (editor, elem, wrapName, nodeName) {
  10980. return parent(elem).fold(function () {
  10981. return 'skipping';
  10982. }, function (parent) {
  10983. if (nodeName === 'br' || isZeroWidth(elem)) {
  10984. return 'valid';
  10985. } else if (isAnnotation(elem)) {
  10986. return 'existing';
  10987. } else if (isCaretNode(elem.dom)) {
  10988. return 'caret';
  10989. } else if (!isValid(editor, wrapName, nodeName) || !isValid(editor, name(parent), wrapName)) {
  10990. return 'invalid-child';
  10991. } else {
  10992. return 'valid';
  10993. }
  10994. });
  10995. };
  10996. var applyWordGrab = function (editor, rng) {
  10997. var r = expandRng(editor, rng, [{ inline: true }]);
  10998. rng.setStart(r.startContainer, r.startOffset);
  10999. rng.setEnd(r.endContainer, r.endOffset);
  11000. editor.selection.setRng(rng);
  11001. };
  11002. var makeAnnotation = function (eDoc, _a, annotationName, decorate) {
  11003. var _b = _a.uid, uid = _b === void 0 ? generate$1('mce-annotation') : _b, data = __rest(_a, ['uid']);
  11004. var master = SugarElement.fromTag('span', eDoc);
  11005. add$3(master, annotation());
  11006. set(master, '' + dataAnnotationId(), uid);
  11007. set(master, '' + dataAnnotation(), annotationName);
  11008. var _c = decorate(uid, data), _d = _c.attributes, attributes = _d === void 0 ? {} : _d, _e = _c.classes, classes = _e === void 0 ? [] : _e;
  11009. setAll(master, attributes);
  11010. add$4(master, classes);
  11011. return master;
  11012. };
  11013. var annotate = function (editor, rng, annotationName, decorate, data) {
  11014. var newWrappers = [];
  11015. var master = makeAnnotation(editor.getDoc(), data, annotationName, decorate);
  11016. var wrapper = Cell(Optional.none());
  11017. var finishWrapper = function () {
  11018. wrapper.set(Optional.none());
  11019. };
  11020. var getOrOpenWrapper = function () {
  11021. return wrapper.get().getOrThunk(function () {
  11022. var nu = shallow(master);
  11023. newWrappers.push(nu);
  11024. wrapper.set(Optional.some(nu));
  11025. return nu;
  11026. });
  11027. };
  11028. var processElements = function (elems) {
  11029. each(elems, processElement);
  11030. };
  11031. var processElement = function (elem) {
  11032. var ctx = context(editor, elem, 'span', name(elem));
  11033. switch (ctx) {
  11034. case 'invalid-child': {
  11035. finishWrapper();
  11036. var children$1 = children(elem);
  11037. processElements(children$1);
  11038. finishWrapper();
  11039. break;
  11040. }
  11041. case 'valid': {
  11042. var w = getOrOpenWrapper();
  11043. wrap(elem, w);
  11044. break;
  11045. }
  11046. }
  11047. };
  11048. var processNodes = function (nodes) {
  11049. var elems = map(nodes, SugarElement.fromDom);
  11050. processElements(elems);
  11051. };
  11052. walk$1(editor.dom, rng, function (nodes) {
  11053. finishWrapper();
  11054. processNodes(nodes);
  11055. });
  11056. return newWrappers;
  11057. };
  11058. var annotateWithBookmark = function (editor, name, settings, data) {
  11059. editor.undoManager.transact(function () {
  11060. var selection = editor.selection;
  11061. var initialRng = selection.getRng();
  11062. var hasFakeSelection = getCellsFromEditor(editor).length > 0;
  11063. if (initialRng.collapsed && !hasFakeSelection) {
  11064. applyWordGrab(editor, initialRng);
  11065. }
  11066. if (selection.getRng().collapsed && !hasFakeSelection) {
  11067. var wrapper = makeAnnotation(editor.getDoc(), data, name, settings.decorate);
  11068. set$1(wrapper, nbsp);
  11069. selection.getRng().insertNode(wrapper.dom);
  11070. selection.select(wrapper.dom);
  11071. } else {
  11072. preserve(selection, false, function () {
  11073. runOnRanges(editor, function (selectionRng) {
  11074. annotate(editor, selectionRng, name, settings.decorate, data);
  11075. });
  11076. });
  11077. }
  11078. });
  11079. };
  11080. var Annotator = function (editor) {
  11081. var registry = create$2();
  11082. setup$1(editor, registry);
  11083. var changes = setup(editor);
  11084. return {
  11085. register: function (name, settings) {
  11086. registry.register(name, settings);
  11087. },
  11088. annotate: function (name, data) {
  11089. registry.lookup(name).each(function (settings) {
  11090. annotateWithBookmark(editor, name, settings, data);
  11091. });
  11092. },
  11093. annotationChanged: function (name, callback) {
  11094. changes.addListener(name, callback);
  11095. },
  11096. remove: function (name) {
  11097. identify(editor, Optional.some(name)).each(function (_a) {
  11098. var elements = _a.elements;
  11099. each(elements, unwrap);
  11100. });
  11101. },
  11102. getAll: function (name) {
  11103. var directory = findAll(editor, name);
  11104. return map$1(directory, function (elems) {
  11105. return map(elems, function (elem) {
  11106. return elem.dom;
  11107. });
  11108. });
  11109. }
  11110. };
  11111. };
  11112. function BookmarkManager(selection) {
  11113. return {
  11114. getBookmark: curry(getBookmark$1, selection),
  11115. moveToBookmark: curry(moveToBookmark, selection)
  11116. };
  11117. }
  11118. (function (BookmarkManager) {
  11119. BookmarkManager.isBookmarkNode = isBookmarkNode$1;
  11120. }(BookmarkManager || (BookmarkManager = {})));
  11121. var BookmarkManager$1 = BookmarkManager;
  11122. var getContentEditableRoot = function (root, node) {
  11123. while (node && node !== root) {
  11124. if (isContentEditableTrue(node) || isContentEditableFalse(node)) {
  11125. return node;
  11126. }
  11127. node = node.parentNode;
  11128. }
  11129. return null;
  11130. };
  11131. var isXYWithinRange = function (clientX, clientY, range) {
  11132. if (range.collapsed) {
  11133. return false;
  11134. }
  11135. if (Env.browser.isIE() && range.startOffset === range.endOffset - 1 && range.startContainer === range.endContainer) {
  11136. var elm = range.startContainer.childNodes[range.startOffset];
  11137. if (isElement$1(elm)) {
  11138. return exists(elm.getClientRects(), function (rect) {
  11139. return containsXY(rect, clientX, clientY);
  11140. });
  11141. }
  11142. }
  11143. return exists(range.getClientRects(), function (rect) {
  11144. return containsXY(rect, clientX, clientY);
  11145. });
  11146. };
  11147. var firePreProcess = function (editor, args) {
  11148. return editor.fire('PreProcess', args);
  11149. };
  11150. var firePostProcess = function (editor, args) {
  11151. return editor.fire('PostProcess', args);
  11152. };
  11153. var fireRemove = function (editor) {
  11154. return editor.fire('remove');
  11155. };
  11156. var fireDetach = function (editor) {
  11157. return editor.fire('detach');
  11158. };
  11159. var fireSwitchMode = function (editor, mode) {
  11160. return editor.fire('SwitchMode', { mode: mode });
  11161. };
  11162. var fireObjectResizeStart = function (editor, target, width, height, origin) {
  11163. editor.fire('ObjectResizeStart', {
  11164. target: target,
  11165. width: width,
  11166. height: height,
  11167. origin: origin
  11168. });
  11169. };
  11170. var fireObjectResized = function (editor, target, width, height, origin) {
  11171. editor.fire('ObjectResized', {
  11172. target: target,
  11173. width: width,
  11174. height: height,
  11175. origin: origin
  11176. });
  11177. };
  11178. var firePreInit = function (editor) {
  11179. return editor.fire('PreInit');
  11180. };
  11181. var firePostRender = function (editor) {
  11182. return editor.fire('PostRender');
  11183. };
  11184. var fireInit = function (editor) {
  11185. return editor.fire('Init');
  11186. };
  11187. var firePlaceholderToggle = function (editor, state) {
  11188. return editor.fire('PlaceholderToggle', { state: state });
  11189. };
  11190. var fireError = function (editor, errorType, error) {
  11191. return editor.fire(errorType, error);
  11192. };
  11193. var VK = {
  11194. BACKSPACE: 8,
  11195. DELETE: 46,
  11196. DOWN: 40,
  11197. ENTER: 13,
  11198. LEFT: 37,
  11199. RIGHT: 39,
  11200. SPACEBAR: 32,
  11201. TAB: 9,
  11202. UP: 38,
  11203. END: 35,
  11204. HOME: 36,
  11205. modifierPressed: function (e) {
  11206. return e.shiftKey || e.ctrlKey || e.altKey || this.metaKeyPressed(e);
  11207. },
  11208. metaKeyPressed: function (e) {
  11209. return Env.mac ? e.metaKey : e.ctrlKey && !e.altKey;
  11210. }
  11211. };
  11212. var isContentEditableFalse$6 = isContentEditableFalse;
  11213. var ControlSelection = function (selection, editor) {
  11214. var dom = editor.dom, each = Tools.each;
  11215. var selectedElm, selectedElmGhost, resizeHelper, selectedHandle;
  11216. var startX, startY, selectedElmX, selectedElmY, startW, startH, ratio, resizeStarted;
  11217. var width, height;
  11218. var editableDoc = editor.getDoc(), rootDocument = document;
  11219. var abs = Math.abs, round = Math.round, rootElement = editor.getBody();
  11220. var startScrollWidth, startScrollHeight;
  11221. var resizeHandles = {
  11222. nw: [
  11223. 0,
  11224. 0,
  11225. -1,
  11226. -1
  11227. ],
  11228. ne: [
  11229. 1,
  11230. 0,
  11231. 1,
  11232. -1
  11233. ],
  11234. se: [
  11235. 1,
  11236. 1,
  11237. 1,
  11238. 1
  11239. ],
  11240. sw: [
  11241. 0,
  11242. 1,
  11243. -1,
  11244. 1
  11245. ]
  11246. };
  11247. var isImage = function (elm) {
  11248. return elm && (elm.nodeName === 'IMG' || editor.dom.is(elm, 'figure.image'));
  11249. };
  11250. var isEventOnImageOutsideRange = function (evt, range) {
  11251. if (evt.type === 'longpress' || evt.type.indexOf('touch') === 0) {
  11252. var touch = evt.touches[0];
  11253. return isImage(evt.target) && !isXYWithinRange(touch.clientX, touch.clientY, range);
  11254. } else {
  11255. return isImage(evt.target) && !isXYWithinRange(evt.clientX, evt.clientY, range);
  11256. }
  11257. };
  11258. var contextMenuSelectImage = function (evt) {
  11259. var target = evt.target;
  11260. if (isEventOnImageOutsideRange(evt, editor.selection.getRng()) && !evt.isDefaultPrevented()) {
  11261. editor.selection.select(target);
  11262. }
  11263. };
  11264. var getResizeTarget = function (elm) {
  11265. return editor.dom.is(elm, 'figure.image') ? elm.querySelector('img') : elm;
  11266. };
  11267. var isResizable = function (elm) {
  11268. var selector = getObjectResizing(editor);
  11269. if (!selector) {
  11270. return false;
  11271. }
  11272. if (elm.getAttribute('data-mce-resize') === 'false') {
  11273. return false;
  11274. }
  11275. if (elm === editor.getBody()) {
  11276. return false;
  11277. }
  11278. return is$1(SugarElement.fromDom(elm), selector);
  11279. };
  11280. var setGhostElmSize = function (ghostElm, width, height) {
  11281. dom.setStyles(getResizeTarget(ghostElm), {
  11282. width: width,
  11283. height: height
  11284. });
  11285. };
  11286. var resizeGhostElement = function (e) {
  11287. var deltaX, deltaY, proportional;
  11288. var resizeHelperX, resizeHelperY;
  11289. deltaX = e.screenX - startX;
  11290. deltaY = e.screenY - startY;
  11291. width = deltaX * selectedHandle[2] + startW;
  11292. height = deltaY * selectedHandle[3] + startH;
  11293. width = width < 5 ? 5 : width;
  11294. height = height < 5 ? 5 : height;
  11295. if (isImage(selectedElm) && getResizeImgProportional(editor) !== false) {
  11296. proportional = !VK.modifierPressed(e);
  11297. } else {
  11298. proportional = VK.modifierPressed(e);
  11299. }
  11300. if (proportional) {
  11301. if (abs(deltaX) > abs(deltaY)) {
  11302. height = round(width * ratio);
  11303. width = round(height / ratio);
  11304. } else {
  11305. width = round(height / ratio);
  11306. height = round(width * ratio);
  11307. }
  11308. }
  11309. setGhostElmSize(selectedElmGhost, width, height);
  11310. resizeHelperX = selectedHandle.startPos.x + deltaX;
  11311. resizeHelperY = selectedHandle.startPos.y + deltaY;
  11312. resizeHelperX = resizeHelperX > 0 ? resizeHelperX : 0;
  11313. resizeHelperY = resizeHelperY > 0 ? resizeHelperY : 0;
  11314. dom.setStyles(resizeHelper, {
  11315. left: resizeHelperX,
  11316. top: resizeHelperY,
  11317. display: 'block'
  11318. });
  11319. resizeHelper.innerHTML = width + ' &times; ' + height;
  11320. if (selectedHandle[2] < 0 && selectedElmGhost.clientWidth <= width) {
  11321. dom.setStyle(selectedElmGhost, 'left', selectedElmX + (startW - width));
  11322. }
  11323. if (selectedHandle[3] < 0 && selectedElmGhost.clientHeight <= height) {
  11324. dom.setStyle(selectedElmGhost, 'top', selectedElmY + (startH - height));
  11325. }
  11326. deltaX = rootElement.scrollWidth - startScrollWidth;
  11327. deltaY = rootElement.scrollHeight - startScrollHeight;
  11328. if (deltaX + deltaY !== 0) {
  11329. dom.setStyles(resizeHelper, {
  11330. left: resizeHelperX - deltaX,
  11331. top: resizeHelperY - deltaY
  11332. });
  11333. }
  11334. if (!resizeStarted) {
  11335. fireObjectResizeStart(editor, selectedElm, startW, startH, 'corner-' + selectedHandle.name);
  11336. resizeStarted = true;
  11337. }
  11338. };
  11339. var endGhostResize = function () {
  11340. var wasResizeStarted = resizeStarted;
  11341. resizeStarted = false;
  11342. var setSizeProp = function (name, value) {
  11343. if (value) {
  11344. if (selectedElm.style[name] || !editor.schema.isValid(selectedElm.nodeName.toLowerCase(), name)) {
  11345. dom.setStyle(getResizeTarget(selectedElm), name, value);
  11346. } else {
  11347. dom.setAttrib(getResizeTarget(selectedElm), name, '' + value);
  11348. }
  11349. }
  11350. };
  11351. if (wasResizeStarted) {
  11352. setSizeProp('width', width);
  11353. setSizeProp('height', height);
  11354. }
  11355. dom.unbind(editableDoc, 'mousemove', resizeGhostElement);
  11356. dom.unbind(editableDoc, 'mouseup', endGhostResize);
  11357. if (rootDocument !== editableDoc) {
  11358. dom.unbind(rootDocument, 'mousemove', resizeGhostElement);
  11359. dom.unbind(rootDocument, 'mouseup', endGhostResize);
  11360. }
  11361. dom.remove(selectedElmGhost);
  11362. dom.remove(resizeHelper);
  11363. showResizeRect(selectedElm);
  11364. if (wasResizeStarted) {
  11365. fireObjectResized(editor, selectedElm, width, height, 'corner-' + selectedHandle.name);
  11366. dom.setAttrib(selectedElm, 'style', dom.getAttrib(selectedElm, 'style'));
  11367. }
  11368. editor.nodeChanged();
  11369. };
  11370. var showResizeRect = function (targetElm) {
  11371. hideResizeRect();
  11372. unbindResizeHandleEvents();
  11373. var position = dom.getPos(targetElm, rootElement);
  11374. var selectedElmX = position.x;
  11375. var selectedElmY = position.y;
  11376. var rect = targetElm.getBoundingClientRect();
  11377. var targetWidth = rect.width || rect.right - rect.left;
  11378. var targetHeight = rect.height || rect.bottom - rect.top;
  11379. if (selectedElm !== targetElm) {
  11380. selectedElm = targetElm;
  11381. width = height = 0;
  11382. }
  11383. var e = editor.fire('ObjectSelected', { target: targetElm });
  11384. if (isResizable(targetElm) && !e.isDefaultPrevented()) {
  11385. each(resizeHandles, function (handle, name) {
  11386. var handleElm;
  11387. var startDrag = function (e) {
  11388. startX = e.screenX;
  11389. startY = e.screenY;
  11390. startW = getResizeTarget(selectedElm).clientWidth;
  11391. startH = getResizeTarget(selectedElm).clientHeight;
  11392. ratio = startH / startW;
  11393. selectedHandle = handle;
  11394. selectedHandle.name = name;
  11395. selectedHandle.startPos = {
  11396. x: targetWidth * handle[0] + selectedElmX,
  11397. y: targetHeight * handle[1] + selectedElmY
  11398. };
  11399. startScrollWidth = rootElement.scrollWidth;
  11400. startScrollHeight = rootElement.scrollHeight;
  11401. selectedElmGhost = selectedElm.cloneNode(true);
  11402. dom.addClass(selectedElmGhost, 'mce-clonedresizable');
  11403. dom.setAttrib(selectedElmGhost, 'data-mce-bogus', 'all');
  11404. selectedElmGhost.contentEditable = false;
  11405. selectedElmGhost.unSelectabe = true;
  11406. dom.setStyles(selectedElmGhost, {
  11407. left: selectedElmX,
  11408. top: selectedElmY,
  11409. margin: 0
  11410. });
  11411. setGhostElmSize(selectedElmGhost, targetWidth, targetHeight);
  11412. selectedElmGhost.removeAttribute('data-mce-selected');
  11413. rootElement.appendChild(selectedElmGhost);
  11414. dom.bind(editableDoc, 'mousemove', resizeGhostElement);
  11415. dom.bind(editableDoc, 'mouseup', endGhostResize);
  11416. if (rootDocument !== editableDoc) {
  11417. dom.bind(rootDocument, 'mousemove', resizeGhostElement);
  11418. dom.bind(rootDocument, 'mouseup', endGhostResize);
  11419. }
  11420. resizeHelper = dom.add(rootElement, 'div', {
  11421. 'class': 'mce-resize-helper',
  11422. 'data-mce-bogus': 'all'
  11423. }, startW + ' &times; ' + startH);
  11424. };
  11425. handleElm = dom.get('mceResizeHandle' + name);
  11426. if (handleElm) {
  11427. dom.remove(handleElm);
  11428. }
  11429. handleElm = dom.add(rootElement, 'div', {
  11430. 'id': 'mceResizeHandle' + name,
  11431. 'data-mce-bogus': 'all',
  11432. 'class': 'mce-resizehandle',
  11433. 'unselectable': true,
  11434. 'style': 'cursor:' + name + '-resize; margin:0; padding:0'
  11435. });
  11436. if (Env.ie === 11) {
  11437. handleElm.contentEditable = false;
  11438. }
  11439. dom.bind(handleElm, 'mousedown', function (e) {
  11440. e.stopImmediatePropagation();
  11441. e.preventDefault();
  11442. startDrag(e);
  11443. });
  11444. handle.elm = handleElm;
  11445. dom.setStyles(handleElm, {
  11446. left: targetWidth * handle[0] + selectedElmX - handleElm.offsetWidth / 2,
  11447. top: targetHeight * handle[1] + selectedElmY - handleElm.offsetHeight / 2
  11448. });
  11449. });
  11450. } else {
  11451. hideResizeRect();
  11452. }
  11453. selectedElm.setAttribute('data-mce-selected', '1');
  11454. };
  11455. var hideResizeRect = function () {
  11456. unbindResizeHandleEvents();
  11457. if (selectedElm) {
  11458. selectedElm.removeAttribute('data-mce-selected');
  11459. }
  11460. each$1(resizeHandles, function (value, name) {
  11461. var handleElm = dom.get('mceResizeHandle' + name);
  11462. if (handleElm) {
  11463. dom.unbind(handleElm);
  11464. dom.remove(handleElm);
  11465. }
  11466. });
  11467. };
  11468. var updateResizeRect = function (e) {
  11469. var startElm, controlElm;
  11470. var isChildOrEqual = function (node, parent) {
  11471. if (node) {
  11472. do {
  11473. if (node === parent) {
  11474. return true;
  11475. }
  11476. } while (node = node.parentNode);
  11477. }
  11478. };
  11479. if (resizeStarted || editor.removed) {
  11480. return;
  11481. }
  11482. each(dom.select('img[data-mce-selected],hr[data-mce-selected]'), function (img) {
  11483. img.removeAttribute('data-mce-selected');
  11484. });
  11485. controlElm = e.type === 'mousedown' ? e.target : selection.getNode();
  11486. controlElm = dom.$(controlElm).closest('table,img,figure.image,hr')[0];
  11487. if (isChildOrEqual(controlElm, rootElement)) {
  11488. disableGeckoResize();
  11489. startElm = selection.getStart(true);
  11490. if (isChildOrEqual(startElm, controlElm) && isChildOrEqual(selection.getEnd(true), controlElm)) {
  11491. showResizeRect(controlElm);
  11492. return;
  11493. }
  11494. }
  11495. hideResizeRect();
  11496. };
  11497. var isWithinContentEditableFalse = function (elm) {
  11498. return isContentEditableFalse$6(getContentEditableRoot(editor.getBody(), elm));
  11499. };
  11500. var unbindResizeHandleEvents = function () {
  11501. each$1(resizeHandles, function (handle) {
  11502. if (handle.elm) {
  11503. dom.unbind(handle.elm);
  11504. delete handle.elm;
  11505. }
  11506. });
  11507. };
  11508. var disableGeckoResize = function () {
  11509. try {
  11510. editor.getDoc().execCommand('enableObjectResizing', false, 'false');
  11511. } catch (ex) {
  11512. }
  11513. };
  11514. editor.on('init', function () {
  11515. disableGeckoResize();
  11516. if (Env.browser.isIE() || Env.browser.isEdge()) {
  11517. editor.on('mousedown click', function (e) {
  11518. var target = e.target, nodeName = target.nodeName;
  11519. if (!resizeStarted && /^(TABLE|IMG|HR)$/.test(nodeName) && !isWithinContentEditableFalse(target)) {
  11520. if (e.button !== 2) {
  11521. editor.selection.select(target, nodeName === 'TABLE');
  11522. }
  11523. if (e.type === 'mousedown') {
  11524. editor.nodeChanged();
  11525. }
  11526. }
  11527. });
  11528. var handleMSControlSelect_1 = function (e) {
  11529. var delayedSelect = function (node) {
  11530. Delay.setEditorTimeout(editor, function () {
  11531. return editor.selection.select(node);
  11532. });
  11533. };
  11534. if (isWithinContentEditableFalse(e.target) || isMedia(e.target)) {
  11535. e.preventDefault();
  11536. delayedSelect(e.target);
  11537. return;
  11538. }
  11539. if (/^(TABLE|IMG|HR)$/.test(e.target.nodeName)) {
  11540. e.preventDefault();
  11541. if (e.target.tagName === 'IMG') {
  11542. delayedSelect(e.target);
  11543. }
  11544. }
  11545. };
  11546. dom.bind(rootElement, 'mscontrolselect', handleMSControlSelect_1);
  11547. editor.on('remove', function () {
  11548. return dom.unbind(rootElement, 'mscontrolselect', handleMSControlSelect_1);
  11549. });
  11550. }
  11551. var throttledUpdateResizeRect = Delay.throttle(function (e) {
  11552. if (!editor.composing) {
  11553. updateResizeRect(e);
  11554. }
  11555. });
  11556. editor.on('nodechange ResizeEditor ResizeWindow ResizeContent drop FullscreenStateChanged', throttledUpdateResizeRect);
  11557. editor.on('keyup compositionend', function (e) {
  11558. if (selectedElm && selectedElm.nodeName === 'TABLE') {
  11559. throttledUpdateResizeRect(e);
  11560. }
  11561. });
  11562. editor.on('hide blur', hideResizeRect);
  11563. editor.on('contextmenu longpress', contextMenuSelectImage, true);
  11564. });
  11565. editor.on('remove', unbindResizeHandleEvents);
  11566. var destroy = function () {
  11567. selectedElm = selectedElmGhost = null;
  11568. };
  11569. return {
  11570. isResizable: isResizable,
  11571. showResizeRect: showResizeRect,
  11572. hideResizeRect: hideResizeRect,
  11573. updateResizeRect: updateResizeRect,
  11574. destroy: destroy
  11575. };
  11576. };
  11577. var hasCeProperty = function (node) {
  11578. return isContentEditableTrue(node) || isContentEditableFalse(node);
  11579. };
  11580. var findParent = function (node, rootNode, predicate) {
  11581. while (node && node !== rootNode) {
  11582. if (predicate(node)) {
  11583. return node;
  11584. }
  11585. node = node.parentNode;
  11586. }
  11587. return null;
  11588. };
  11589. var findClosestIeRange = function (clientX, clientY, doc) {
  11590. var rects;
  11591. var element = doc.elementFromPoint(clientX, clientY);
  11592. var rng = doc.body.createTextRange();
  11593. if (!element || element.tagName === 'HTML') {
  11594. element = doc.body;
  11595. }
  11596. rng.moveToElementText(element);
  11597. rects = Tools.toArray(rng.getClientRects());
  11598. rects = rects.sort(function (a, b) {
  11599. a = Math.abs(Math.max(a.top - clientY, a.bottom - clientY));
  11600. b = Math.abs(Math.max(b.top - clientY, b.bottom - clientY));
  11601. return a - b;
  11602. });
  11603. if (rects.length > 0) {
  11604. clientY = (rects[0].bottom + rects[0].top) / 2;
  11605. try {
  11606. rng.moveToPoint(clientX, clientY);
  11607. rng.collapse(true);
  11608. return rng;
  11609. } catch (ex) {
  11610. }
  11611. }
  11612. return null;
  11613. };
  11614. var moveOutOfContentEditableFalse = function (rng, rootNode) {
  11615. var parentElement = rng && rng.parentElement ? rng.parentElement() : null;
  11616. return isContentEditableFalse(findParent(parentElement, rootNode, hasCeProperty)) ? null : rng;
  11617. };
  11618. var fromPoint$1 = function (clientX, clientY, doc) {
  11619. var rng, point;
  11620. var pointDoc = doc;
  11621. if (pointDoc.caretPositionFromPoint) {
  11622. point = pointDoc.caretPositionFromPoint(clientX, clientY);
  11623. if (point) {
  11624. rng = doc.createRange();
  11625. rng.setStart(point.offsetNode, point.offset);
  11626. rng.collapse(true);
  11627. }
  11628. } else if (doc.caretRangeFromPoint) {
  11629. rng = doc.caretRangeFromPoint(clientX, clientY);
  11630. } else if (pointDoc.body.createTextRange) {
  11631. rng = pointDoc.body.createTextRange();
  11632. try {
  11633. rng.moveToPoint(clientX, clientY);
  11634. rng.collapse(true);
  11635. } catch (ex) {
  11636. rng = findClosestIeRange(clientX, clientY, doc);
  11637. }
  11638. return moveOutOfContentEditableFalse(rng, doc.body);
  11639. }
  11640. return rng;
  11641. };
  11642. var isEq$1 = function (rng1, rng2) {
  11643. return rng1 && rng2 && (rng1.startContainer === rng2.startContainer && rng1.startOffset === rng2.startOffset) && (rng1.endContainer === rng2.endContainer && rng1.endOffset === rng2.endOffset);
  11644. };
  11645. var findParent$1 = function (node, rootNode, predicate) {
  11646. while (node && node !== rootNode) {
  11647. if (predicate(node)) {
  11648. return node;
  11649. }
  11650. node = node.parentNode;
  11651. }
  11652. return null;
  11653. };
  11654. var hasParent = function (node, rootNode, predicate) {
  11655. return findParent$1(node, rootNode, predicate) !== null;
  11656. };
  11657. var hasParentWithName = function (node, rootNode, name) {
  11658. return hasParent(node, rootNode, function (node) {
  11659. return node.nodeName === name;
  11660. });
  11661. };
  11662. var isTable$3 = function (node) {
  11663. return node && node.nodeName === 'TABLE';
  11664. };
  11665. var isTableCell$3 = function (node) {
  11666. return node && /^(TD|TH|CAPTION)$/.test(node.nodeName);
  11667. };
  11668. var isCeFalseCaretContainer = function (node, rootNode) {
  11669. return isCaretContainer(node) && hasParent(node, rootNode, isCaretNode) === false;
  11670. };
  11671. var hasBrBeforeAfter = function (dom, node, left) {
  11672. var walker = new DomTreeWalker(node, dom.getParent(node.parentNode, dom.isBlock) || dom.getRoot());
  11673. while (node = walker[left ? 'prev' : 'next']()) {
  11674. if (isBr(node)) {
  11675. return true;
  11676. }
  11677. }
  11678. };
  11679. var isPrevNode = function (node, name) {
  11680. return node.previousSibling && node.previousSibling.nodeName === name;
  11681. };
  11682. var hasContentEditableFalseParent = function (body, node) {
  11683. while (node && node !== body) {
  11684. if (isContentEditableFalse(node)) {
  11685. return true;
  11686. }
  11687. node = node.parentNode;
  11688. }
  11689. return false;
  11690. };
  11691. var findTextNodeRelative = function (dom, isAfterNode, collapsed, left, startNode) {
  11692. var lastInlineElement;
  11693. var body = dom.getRoot();
  11694. var node;
  11695. var nonEmptyElementsMap = dom.schema.getNonEmptyElements();
  11696. var parentBlockContainer = dom.getParent(startNode.parentNode, dom.isBlock) || body;
  11697. if (left && isBr(startNode) && isAfterNode && dom.isEmpty(parentBlockContainer)) {
  11698. return Optional.some(CaretPosition(startNode.parentNode, dom.nodeIndex(startNode)));
  11699. }
  11700. var walker = new DomTreeWalker(startNode, parentBlockContainer);
  11701. while (node = walker[left ? 'prev' : 'next']()) {
  11702. if (dom.getContentEditableParent(node) === 'false' || isCeFalseCaretContainer(node, body)) {
  11703. return Optional.none();
  11704. }
  11705. if (isText$1(node) && node.nodeValue.length > 0) {
  11706. if (hasParentWithName(node, body, 'A') === false) {
  11707. return Optional.some(CaretPosition(node, left ? node.nodeValue.length : 0));
  11708. }
  11709. return Optional.none();
  11710. }
  11711. if (dom.isBlock(node) || nonEmptyElementsMap[node.nodeName.toLowerCase()]) {
  11712. return Optional.none();
  11713. }
  11714. lastInlineElement = node;
  11715. }
  11716. if (collapsed && lastInlineElement) {
  11717. return Optional.some(CaretPosition(lastInlineElement, 0));
  11718. }
  11719. return Optional.none();
  11720. };
  11721. var normalizeEndPoint = function (dom, collapsed, start, rng) {
  11722. var container, offset;
  11723. var body = dom.getRoot();
  11724. var node;
  11725. var directionLeft, normalized = false;
  11726. container = rng[(start ? 'start' : 'end') + 'Container'];
  11727. offset = rng[(start ? 'start' : 'end') + 'Offset'];
  11728. var isAfterNode = isElement$1(container) && offset === container.childNodes.length;
  11729. var nonEmptyElementsMap = dom.schema.getNonEmptyElements();
  11730. directionLeft = start;
  11731. if (isCaretContainer(container)) {
  11732. return Optional.none();
  11733. }
  11734. if (isElement$1(container) && offset > container.childNodes.length - 1) {
  11735. directionLeft = false;
  11736. }
  11737. if (isDocument$1(container)) {
  11738. container = body;
  11739. offset = 0;
  11740. }
  11741. if (container === body) {
  11742. if (directionLeft) {
  11743. node = container.childNodes[offset > 0 ? offset - 1 : 0];
  11744. if (node) {
  11745. if (isCaretContainer(node)) {
  11746. return Optional.none();
  11747. }
  11748. if (nonEmptyElementsMap[node.nodeName] || isTable$3(node)) {
  11749. return Optional.none();
  11750. }
  11751. }
  11752. }
  11753. if (container.hasChildNodes()) {
  11754. offset = Math.min(!directionLeft && offset > 0 ? offset - 1 : offset, container.childNodes.length - 1);
  11755. container = container.childNodes[offset];
  11756. offset = isText$1(container) && isAfterNode ? container.data.length : 0;
  11757. if (!collapsed && container === body.lastChild && isTable$3(container)) {
  11758. return Optional.none();
  11759. }
  11760. if (hasContentEditableFalseParent(body, container) || isCaretContainer(container)) {
  11761. return Optional.none();
  11762. }
  11763. if (container.hasChildNodes() && isTable$3(container) === false) {
  11764. node = container;
  11765. var walker = new DomTreeWalker(container, body);
  11766. do {
  11767. if (isContentEditableFalse(node) || isCaretContainer(node)) {
  11768. normalized = false;
  11769. break;
  11770. }
  11771. if (isText$1(node) && node.nodeValue.length > 0) {
  11772. offset = directionLeft ? 0 : node.nodeValue.length;
  11773. container = node;
  11774. normalized = true;
  11775. break;
  11776. }
  11777. if (nonEmptyElementsMap[node.nodeName.toLowerCase()] && !isTableCell$3(node)) {
  11778. offset = dom.nodeIndex(node);
  11779. container = node.parentNode;
  11780. if (!directionLeft) {
  11781. offset++;
  11782. }
  11783. normalized = true;
  11784. break;
  11785. }
  11786. } while (node = directionLeft ? walker.next() : walker.prev());
  11787. }
  11788. }
  11789. }
  11790. if (collapsed) {
  11791. if (isText$1(container) && offset === 0) {
  11792. findTextNodeRelative(dom, isAfterNode, collapsed, true, container).each(function (pos) {
  11793. container = pos.container();
  11794. offset = pos.offset();
  11795. normalized = true;
  11796. });
  11797. }
  11798. if (isElement$1(container)) {
  11799. node = container.childNodes[offset];
  11800. if (!node) {
  11801. node = container.childNodes[offset - 1];
  11802. }
  11803. if (node && isBr(node) && !isPrevNode(node, 'A') && !hasBrBeforeAfter(dom, node, false) && !hasBrBeforeAfter(dom, node, true)) {
  11804. findTextNodeRelative(dom, isAfterNode, collapsed, true, node).each(function (pos) {
  11805. container = pos.container();
  11806. offset = pos.offset();
  11807. normalized = true;
  11808. });
  11809. }
  11810. }
  11811. }
  11812. if (directionLeft && !collapsed && isText$1(container) && offset === container.nodeValue.length) {
  11813. findTextNodeRelative(dom, isAfterNode, collapsed, false, container).each(function (pos) {
  11814. container = pos.container();
  11815. offset = pos.offset();
  11816. normalized = true;
  11817. });
  11818. }
  11819. return normalized ? Optional.some(CaretPosition(container, offset)) : Optional.none();
  11820. };
  11821. var normalize = function (dom, rng) {
  11822. var collapsed = rng.collapsed, normRng = rng.cloneRange();
  11823. var startPos = CaretPosition.fromRangeStart(rng);
  11824. normalizeEndPoint(dom, collapsed, true, normRng).each(function (pos) {
  11825. if (!collapsed || !CaretPosition.isAbove(startPos, pos)) {
  11826. normRng.setStart(pos.container(), pos.offset());
  11827. }
  11828. });
  11829. if (!collapsed) {
  11830. normalizeEndPoint(dom, collapsed, false, normRng).each(function (pos) {
  11831. normRng.setEnd(pos.container(), pos.offset());
  11832. });
  11833. }
  11834. if (collapsed) {
  11835. normRng.collapse(true);
  11836. }
  11837. return isEq$1(rng, normRng) ? Optional.none() : Optional.some(normRng);
  11838. };
  11839. var splitText = function (node, offset) {
  11840. return node.splitText(offset);
  11841. };
  11842. var split$1 = function (rng) {
  11843. var startContainer = rng.startContainer, startOffset = rng.startOffset, endContainer = rng.endContainer, endOffset = rng.endOffset;
  11844. if (startContainer === endContainer && isText$1(startContainer)) {
  11845. if (startOffset > 0 && startOffset < startContainer.nodeValue.length) {
  11846. endContainer = splitText(startContainer, startOffset);
  11847. startContainer = endContainer.previousSibling;
  11848. if (endOffset > startOffset) {
  11849. endOffset = endOffset - startOffset;
  11850. startContainer = endContainer = splitText(endContainer, endOffset).previousSibling;
  11851. endOffset = endContainer.nodeValue.length;
  11852. startOffset = 0;
  11853. } else {
  11854. endOffset = 0;
  11855. }
  11856. }
  11857. } else {
  11858. if (isText$1(startContainer) && startOffset > 0 && startOffset < startContainer.nodeValue.length) {
  11859. startContainer = splitText(startContainer, startOffset);
  11860. startOffset = 0;
  11861. }
  11862. if (isText$1(endContainer) && endOffset > 0 && endOffset < endContainer.nodeValue.length) {
  11863. endContainer = splitText(endContainer, endOffset).previousSibling;
  11864. endOffset = endContainer.nodeValue.length;
  11865. }
  11866. }
  11867. return {
  11868. startContainer: startContainer,
  11869. startOffset: startOffset,
  11870. endContainer: endContainer,
  11871. endOffset: endOffset
  11872. };
  11873. };
  11874. function RangeUtils(dom) {
  11875. var walk = function (rng, callback) {
  11876. return walk$1(dom, rng, callback);
  11877. };
  11878. var split = split$1;
  11879. var normalize$1 = function (rng) {
  11880. return normalize(dom, rng).fold(never, function (normalizedRng) {
  11881. rng.setStart(normalizedRng.startContainer, normalizedRng.startOffset);
  11882. rng.setEnd(normalizedRng.endContainer, normalizedRng.endOffset);
  11883. return true;
  11884. });
  11885. };
  11886. return {
  11887. walk: walk,
  11888. split: split,
  11889. normalize: normalize$1
  11890. };
  11891. }
  11892. (function (RangeUtils) {
  11893. RangeUtils.compareRanges = isEq$1;
  11894. RangeUtils.getCaretRangeFromPoint = fromPoint$1;
  11895. RangeUtils.getSelectedNode = getSelectedNode;
  11896. RangeUtils.getNode = getNode;
  11897. }(RangeUtils || (RangeUtils = {})));
  11898. var RangeUtils$1 = RangeUtils;
  11899. function Dimension (name, getOffset) {
  11900. var set = function (element, h) {
  11901. if (!isNumber(h) && !h.match(/^[0-9]+$/)) {
  11902. throw new Error(name + '.set accepts only positive integer values. Value was ' + h);
  11903. }
  11904. var dom = element.dom;
  11905. if (isSupported$1(dom)) {
  11906. dom.style[name] = h + 'px';
  11907. }
  11908. };
  11909. var get = function (element) {
  11910. var r = getOffset(element);
  11911. if (r <= 0 || r === null) {
  11912. var css = get$4(element, name);
  11913. return parseFloat(css) || 0;
  11914. }
  11915. return r;
  11916. };
  11917. var getOuter = get;
  11918. var aggregate = function (element, properties) {
  11919. return foldl(properties, function (acc, property) {
  11920. var val = get$4(element, property);
  11921. var value = val === undefined ? 0 : parseInt(val, 10);
  11922. return isNaN(value) ? acc : acc + value;
  11923. }, 0);
  11924. };
  11925. var max = function (element, value, properties) {
  11926. var cumulativeInclusions = aggregate(element, properties);
  11927. var absoluteMax = value > cumulativeInclusions ? value - cumulativeInclusions : 0;
  11928. return absoluteMax;
  11929. };
  11930. return {
  11931. set: set,
  11932. get: get,
  11933. getOuter: getOuter,
  11934. aggregate: aggregate,
  11935. max: max
  11936. };
  11937. }
  11938. var api$1 = Dimension('height', function (element) {
  11939. var dom = element.dom;
  11940. return inBody(element) ? dom.getBoundingClientRect().height : dom.offsetHeight;
  11941. });
  11942. var get$8 = function (element) {
  11943. return api$1.get(element);
  11944. };
  11945. var walkUp = function (navigation, doc) {
  11946. var frame = navigation.view(doc);
  11947. return frame.fold(constant([]), function (f) {
  11948. var parent = navigation.owner(f);
  11949. var rest = walkUp(navigation, parent);
  11950. return [f].concat(rest);
  11951. });
  11952. };
  11953. var pathTo = function (element, navigation) {
  11954. var d = navigation.owner(element);
  11955. return walkUp(navigation, d);
  11956. };
  11957. var view = function (doc) {
  11958. var _a;
  11959. var element = doc.dom === document ? Optional.none() : Optional.from((_a = doc.dom.defaultView) === null || _a === void 0 ? void 0 : _a.frameElement);
  11960. return element.map(SugarElement.fromDom);
  11961. };
  11962. var owner$1 = function (element) {
  11963. return documentOrOwner(element);
  11964. };
  11965. var Navigation = /*#__PURE__*/Object.freeze({
  11966. __proto__: null,
  11967. view: view,
  11968. owner: owner$1
  11969. });
  11970. var find$2 = function (element) {
  11971. var doc = SugarElement.fromDom(document);
  11972. var scroll = get$1(doc);
  11973. var frames = pathTo(element, Navigation);
  11974. var offset = viewport(element);
  11975. var r = foldr(frames, function (b, a) {
  11976. var loc = viewport(a);
  11977. return {
  11978. left: b.left + loc.left,
  11979. top: b.top + loc.top
  11980. };
  11981. }, {
  11982. left: 0,
  11983. top: 0
  11984. });
  11985. return SugarPosition(r.left + offset.left + scroll.left, r.top + offset.top + scroll.top);
  11986. };
  11987. var excludeFromDescend = function (element) {
  11988. return name(element) === 'textarea';
  11989. };
  11990. var fireScrollIntoViewEvent = function (editor, data) {
  11991. var scrollEvent = editor.fire('ScrollIntoView', data);
  11992. return scrollEvent.isDefaultPrevented();
  11993. };
  11994. var fireAfterScrollIntoViewEvent = function (editor, data) {
  11995. editor.fire('AfterScrollIntoView', data);
  11996. };
  11997. var descend = function (element, offset) {
  11998. var children$1 = children(element);
  11999. if (children$1.length === 0 || excludeFromDescend(element)) {
  12000. return {
  12001. element: element,
  12002. offset: offset
  12003. };
  12004. } else if (offset < children$1.length && !excludeFromDescend(children$1[offset])) {
  12005. return {
  12006. element: children$1[offset],
  12007. offset: 0
  12008. };
  12009. } else {
  12010. var last = children$1[children$1.length - 1];
  12011. if (excludeFromDescend(last)) {
  12012. return {
  12013. element: element,
  12014. offset: offset
  12015. };
  12016. } else {
  12017. if (name(last) === 'img') {
  12018. return {
  12019. element: last,
  12020. offset: 1
  12021. };
  12022. } else if (isText(last)) {
  12023. return {
  12024. element: last,
  12025. offset: get$7(last).length
  12026. };
  12027. } else {
  12028. return {
  12029. element: last,
  12030. offset: children(last).length
  12031. };
  12032. }
  12033. }
  12034. }
  12035. };
  12036. var markerInfo = function (element, cleanupFun) {
  12037. var pos = absolute(element);
  12038. var height = get$8(element);
  12039. return {
  12040. element: element,
  12041. bottom: pos.top + height,
  12042. height: height,
  12043. pos: pos,
  12044. cleanup: cleanupFun
  12045. };
  12046. };
  12047. var createMarker = function (element, offset) {
  12048. var startPoint = descend(element, offset);
  12049. var span = SugarElement.fromHtml('<span data-mce-bogus="all">' + ZWSP + '</span>');
  12050. before(startPoint.element, span);
  12051. return markerInfo(span, function () {
  12052. return remove(span);
  12053. });
  12054. };
  12055. var elementMarker = function (element) {
  12056. return markerInfo(SugarElement.fromDom(element), noop);
  12057. };
  12058. var withMarker = function (editor, f, rng, alignToTop) {
  12059. preserveWith(editor, function (_s, _e) {
  12060. return applyWithMarker(editor, f, rng, alignToTop);
  12061. }, rng);
  12062. };
  12063. var withScrollEvents = function (editor, doc, f, marker, alignToTop) {
  12064. var data = {
  12065. elm: marker.element.dom,
  12066. alignToTop: alignToTop
  12067. };
  12068. if (fireScrollIntoViewEvent(editor, data)) {
  12069. return;
  12070. }
  12071. var scrollTop = get$1(doc).top;
  12072. f(doc, scrollTop, marker, alignToTop);
  12073. fireAfterScrollIntoViewEvent(editor, data);
  12074. };
  12075. var applyWithMarker = function (editor, f, rng, alignToTop) {
  12076. var body = SugarElement.fromDom(editor.getBody());
  12077. var doc = SugarElement.fromDom(editor.getDoc());
  12078. reflow(body);
  12079. var marker = createMarker(SugarElement.fromDom(rng.startContainer), rng.startOffset);
  12080. withScrollEvents(editor, doc, f, marker, alignToTop);
  12081. marker.cleanup();
  12082. };
  12083. var withElement = function (editor, element, f, alignToTop) {
  12084. var doc = SugarElement.fromDom(editor.getDoc());
  12085. withScrollEvents(editor, doc, f, elementMarker(element), alignToTop);
  12086. };
  12087. var preserveWith = function (editor, f, rng) {
  12088. var startElement = rng.startContainer;
  12089. var startOffset = rng.startOffset;
  12090. var endElement = rng.endContainer;
  12091. var endOffset = rng.endOffset;
  12092. f(SugarElement.fromDom(startElement), SugarElement.fromDom(endElement));
  12093. var newRng = editor.dom.createRng();
  12094. newRng.setStart(startElement, startOffset);
  12095. newRng.setEnd(endElement, endOffset);
  12096. editor.selection.setRng(rng);
  12097. };
  12098. var scrollToMarker = function (marker, viewHeight, alignToTop, doc) {
  12099. var pos = marker.pos;
  12100. if (alignToTop) {
  12101. to(pos.left, pos.top, doc);
  12102. } else {
  12103. var y = pos.top - viewHeight + marker.height;
  12104. to(pos.left, y, doc);
  12105. }
  12106. };
  12107. var intoWindowIfNeeded = function (doc, scrollTop, viewHeight, marker, alignToTop) {
  12108. var viewportBottom = viewHeight + scrollTop;
  12109. var markerTop = marker.pos.top;
  12110. var markerBottom = marker.bottom;
  12111. var largerThanViewport = markerBottom - markerTop >= viewHeight;
  12112. if (markerTop < scrollTop) {
  12113. scrollToMarker(marker, viewHeight, alignToTop !== false, doc);
  12114. } else if (markerTop > viewportBottom) {
  12115. var align = largerThanViewport ? alignToTop !== false : alignToTop === true;
  12116. scrollToMarker(marker, viewHeight, align, doc);
  12117. } else if (markerBottom > viewportBottom && !largerThanViewport) {
  12118. scrollToMarker(marker, viewHeight, alignToTop === true, doc);
  12119. }
  12120. };
  12121. var intoWindow = function (doc, scrollTop, marker, alignToTop) {
  12122. var viewHeight = doc.dom.defaultView.innerHeight;
  12123. intoWindowIfNeeded(doc, scrollTop, viewHeight, marker, alignToTop);
  12124. };
  12125. var intoFrame = function (doc, scrollTop, marker, alignToTop) {
  12126. var frameViewHeight = doc.dom.defaultView.innerHeight;
  12127. intoWindowIfNeeded(doc, scrollTop, frameViewHeight, marker, alignToTop);
  12128. var op = find$2(marker.element);
  12129. var viewportBounds = getBounds(window);
  12130. if (op.top < viewportBounds.y) {
  12131. intoView(marker.element, alignToTop !== false);
  12132. } else if (op.top > viewportBounds.bottom) {
  12133. intoView(marker.element, alignToTop === true);
  12134. }
  12135. };
  12136. var rangeIntoWindow = function (editor, rng, alignToTop) {
  12137. return withMarker(editor, intoWindow, rng, alignToTop);
  12138. };
  12139. var elementIntoWindow = function (editor, element, alignToTop) {
  12140. return withElement(editor, element, intoWindow, alignToTop);
  12141. };
  12142. var rangeIntoFrame = function (editor, rng, alignToTop) {
  12143. return withMarker(editor, intoFrame, rng, alignToTop);
  12144. };
  12145. var elementIntoFrame = function (editor, element, alignToTop) {
  12146. return withElement(editor, element, intoFrame, alignToTop);
  12147. };
  12148. var scrollElementIntoView = function (editor, element, alignToTop) {
  12149. var scroller = editor.inline ? elementIntoWindow : elementIntoFrame;
  12150. scroller(editor, element, alignToTop);
  12151. };
  12152. var scrollRangeIntoView = function (editor, rng, alignToTop) {
  12153. var scroller = editor.inline ? rangeIntoWindow : rangeIntoFrame;
  12154. scroller(editor, rng, alignToTop);
  12155. };
  12156. var getDocument = function () {
  12157. return SugarElement.fromDom(document);
  12158. };
  12159. var focus = function (element) {
  12160. return element.dom.focus();
  12161. };
  12162. var hasFocus = function (element) {
  12163. var root = getRootNode(element).dom;
  12164. return element.dom === root.activeElement;
  12165. };
  12166. var active = function (root) {
  12167. if (root === void 0) {
  12168. root = getDocument();
  12169. }
  12170. return Optional.from(root.dom.activeElement).map(SugarElement.fromDom);
  12171. };
  12172. var search = function (element) {
  12173. return active(getRootNode(element)).filter(function (e) {
  12174. return element.dom.contains(e.dom);
  12175. });
  12176. };
  12177. var create$4 = function (start, soffset, finish, foffset) {
  12178. return {
  12179. start: start,
  12180. soffset: soffset,
  12181. finish: finish,
  12182. foffset: foffset
  12183. };
  12184. };
  12185. var SimRange = { create: create$4 };
  12186. var adt = Adt.generate([
  12187. { before: ['element'] },
  12188. {
  12189. on: [
  12190. 'element',
  12191. 'offset'
  12192. ]
  12193. },
  12194. { after: ['element'] }
  12195. ]);
  12196. var cata = function (subject, onBefore, onOn, onAfter) {
  12197. return subject.fold(onBefore, onOn, onAfter);
  12198. };
  12199. var getStart = function (situ) {
  12200. return situ.fold(identity, identity, identity);
  12201. };
  12202. var before$3 = adt.before;
  12203. var on = adt.on;
  12204. var after$2 = adt.after;
  12205. var Situ = {
  12206. before: before$3,
  12207. on: on,
  12208. after: after$2,
  12209. cata: cata,
  12210. getStart: getStart
  12211. };
  12212. var adt$1 = Adt.generate([
  12213. { domRange: ['rng'] },
  12214. {
  12215. relative: [
  12216. 'startSitu',
  12217. 'finishSitu'
  12218. ]
  12219. },
  12220. {
  12221. exact: [
  12222. 'start',
  12223. 'soffset',
  12224. 'finish',
  12225. 'foffset'
  12226. ]
  12227. }
  12228. ]);
  12229. var exactFromRange = function (simRange) {
  12230. return adt$1.exact(simRange.start, simRange.soffset, simRange.finish, simRange.foffset);
  12231. };
  12232. var getStart$1 = function (selection) {
  12233. return selection.match({
  12234. domRange: function (rng) {
  12235. return SugarElement.fromDom(rng.startContainer);
  12236. },
  12237. relative: function (startSitu, _finishSitu) {
  12238. return Situ.getStart(startSitu);
  12239. },
  12240. exact: function (start, _soffset, _finish, _foffset) {
  12241. return start;
  12242. }
  12243. });
  12244. };
  12245. var domRange = adt$1.domRange;
  12246. var relative = adt$1.relative;
  12247. var exact = adt$1.exact;
  12248. var getWin = function (selection) {
  12249. var start = getStart$1(selection);
  12250. return defaultView(start);
  12251. };
  12252. var range = SimRange.create;
  12253. var SimSelection = {
  12254. domRange: domRange,
  12255. relative: relative,
  12256. exact: exact,
  12257. exactFromRange: exactFromRange,
  12258. getWin: getWin,
  12259. range: range
  12260. };
  12261. var browser$3 = detect$3().browser;
  12262. var clamp = function (offset, element) {
  12263. var max = isText(element) ? get$7(element).length : children(element).length + 1;
  12264. if (offset > max) {
  12265. return max;
  12266. } else if (offset < 0) {
  12267. return 0;
  12268. }
  12269. return offset;
  12270. };
  12271. var normalizeRng = function (rng) {
  12272. return SimSelection.range(rng.start, clamp(rng.soffset, rng.start), rng.finish, clamp(rng.foffset, rng.finish));
  12273. };
  12274. var isOrContains = function (root, elm) {
  12275. return !isRestrictedNode(elm.dom) && (contains$2(root, elm) || eq$2(root, elm));
  12276. };
  12277. var isRngInRoot = function (root) {
  12278. return function (rng) {
  12279. return isOrContains(root, rng.start) && isOrContains(root, rng.finish);
  12280. };
  12281. };
  12282. var shouldStore = function (editor) {
  12283. return editor.inline === true || browser$3.isIE();
  12284. };
  12285. var nativeRangeToSelectionRange = function (r) {
  12286. return SimSelection.range(SugarElement.fromDom(r.startContainer), r.startOffset, SugarElement.fromDom(r.endContainer), r.endOffset);
  12287. };
  12288. var readRange = function (win) {
  12289. var selection = win.getSelection();
  12290. var rng = !selection || selection.rangeCount === 0 ? Optional.none() : Optional.from(selection.getRangeAt(0));
  12291. return rng.map(nativeRangeToSelectionRange);
  12292. };
  12293. var getBookmark$2 = function (root) {
  12294. var win = defaultView(root);
  12295. return readRange(win.dom).filter(isRngInRoot(root));
  12296. };
  12297. var validate = function (root, bookmark) {
  12298. return Optional.from(bookmark).filter(isRngInRoot(root)).map(normalizeRng);
  12299. };
  12300. var bookmarkToNativeRng = function (bookmark) {
  12301. var rng = document.createRange();
  12302. try {
  12303. rng.setStart(bookmark.start.dom, bookmark.soffset);
  12304. rng.setEnd(bookmark.finish.dom, bookmark.foffset);
  12305. return Optional.some(rng);
  12306. } catch (_) {
  12307. return Optional.none();
  12308. }
  12309. };
  12310. var store = function (editor) {
  12311. var newBookmark = shouldStore(editor) ? getBookmark$2(SugarElement.fromDom(editor.getBody())) : Optional.none();
  12312. editor.bookmark = newBookmark.isSome() ? newBookmark : editor.bookmark;
  12313. };
  12314. var storeNative = function (editor, rng) {
  12315. var root = SugarElement.fromDom(editor.getBody());
  12316. var range = shouldStore(editor) ? Optional.from(rng) : Optional.none();
  12317. var newBookmark = range.map(nativeRangeToSelectionRange).filter(isRngInRoot(root));
  12318. editor.bookmark = newBookmark.isSome() ? newBookmark : editor.bookmark;
  12319. };
  12320. var getRng = function (editor) {
  12321. var bookmark = editor.bookmark ? editor.bookmark : Optional.none();
  12322. return bookmark.bind(function (x) {
  12323. return validate(SugarElement.fromDom(editor.getBody()), x);
  12324. }).bind(bookmarkToNativeRng);
  12325. };
  12326. var restore = function (editor) {
  12327. getRng(editor).each(function (rng) {
  12328. return editor.selection.setRng(rng);
  12329. });
  12330. };
  12331. var isEditorUIElement = function (elm) {
  12332. var className = elm.className.toString();
  12333. return className.indexOf('tox-') !== -1 || className.indexOf('mce-') !== -1;
  12334. };
  12335. var FocusManager = { isEditorUIElement: isEditorUIElement };
  12336. var isManualNodeChange = function (e) {
  12337. return e.type === 'nodechange' && e.selectionChange;
  12338. };
  12339. var registerPageMouseUp = function (editor, throttledStore) {
  12340. var mouseUpPage = function () {
  12341. throttledStore.throttle();
  12342. };
  12343. DOMUtils$1.DOM.bind(document, 'mouseup', mouseUpPage);
  12344. editor.on('remove', function () {
  12345. DOMUtils$1.DOM.unbind(document, 'mouseup', mouseUpPage);
  12346. });
  12347. };
  12348. var registerFocusOut = function (editor) {
  12349. editor.on('focusout', function () {
  12350. store(editor);
  12351. });
  12352. };
  12353. var registerMouseUp = function (editor, throttledStore) {
  12354. editor.on('mouseup touchend', function (_e) {
  12355. throttledStore.throttle();
  12356. });
  12357. };
  12358. var registerEditorEvents = function (editor, throttledStore) {
  12359. var browser = detect$3().browser;
  12360. if (browser.isIE()) {
  12361. registerFocusOut(editor);
  12362. } else {
  12363. registerMouseUp(editor, throttledStore);
  12364. }
  12365. editor.on('keyup NodeChange', function (e) {
  12366. if (!isManualNodeChange(e)) {
  12367. store(editor);
  12368. }
  12369. });
  12370. };
  12371. var register = function (editor) {
  12372. var throttledStore = first(function () {
  12373. store(editor);
  12374. }, 0);
  12375. editor.on('init', function () {
  12376. if (editor.inline) {
  12377. registerPageMouseUp(editor, throttledStore);
  12378. }
  12379. registerEditorEvents(editor, throttledStore);
  12380. });
  12381. editor.on('remove', function () {
  12382. throttledStore.cancel();
  12383. });
  12384. };
  12385. var documentFocusInHandler;
  12386. var DOM$2 = DOMUtils$1.DOM;
  12387. var isEditorUIElement$1 = function (elm) {
  12388. return FocusManager.isEditorUIElement(elm);
  12389. };
  12390. var isEditorContentAreaElement = function (elm) {
  12391. var classList = elm.classList;
  12392. if (classList !== undefined) {
  12393. return classList.contains('tox-edit-area') || classList.contains('tox-edit-area__iframe') || classList.contains('mce-content-body');
  12394. } else {
  12395. return false;
  12396. }
  12397. };
  12398. var isUIElement = function (editor, elm) {
  12399. var customSelector = getCustomUiSelector(editor);
  12400. var parent = DOM$2.getParent(elm, function (elm) {
  12401. return isEditorUIElement$1(elm) || (customSelector ? editor.dom.is(elm, customSelector) : false);
  12402. });
  12403. return parent !== null;
  12404. };
  12405. var getActiveElement = function (editor) {
  12406. try {
  12407. var root = getRootNode(SugarElement.fromDom(editor.getElement()));
  12408. return active(root).fold(function () {
  12409. return document.body;
  12410. }, function (x) {
  12411. return x.dom;
  12412. });
  12413. } catch (ex) {
  12414. return document.body;
  12415. }
  12416. };
  12417. var registerEvents = function (editorManager, e) {
  12418. var editor = e.editor;
  12419. register(editor);
  12420. editor.on('focusin', function () {
  12421. var self = this;
  12422. var focusedEditor = editorManager.focusedEditor;
  12423. if (focusedEditor !== self) {
  12424. if (focusedEditor) {
  12425. focusedEditor.fire('blur', { focusedEditor: self });
  12426. }
  12427. editorManager.setActive(self);
  12428. editorManager.focusedEditor = self;
  12429. self.fire('focus', { blurredEditor: focusedEditor });
  12430. self.focus(true);
  12431. }
  12432. });
  12433. editor.on('focusout', function () {
  12434. var self = this;
  12435. Delay.setEditorTimeout(self, function () {
  12436. var focusedEditor = editorManager.focusedEditor;
  12437. if (!isUIElement(self, getActiveElement(self)) && focusedEditor === self) {
  12438. self.fire('blur', { focusedEditor: null });
  12439. editorManager.focusedEditor = null;
  12440. }
  12441. });
  12442. });
  12443. if (!documentFocusInHandler) {
  12444. documentFocusInHandler = function (e) {
  12445. var activeEditor = editorManager.activeEditor;
  12446. if (activeEditor) {
  12447. getOriginalEventTarget(e).each(function (target) {
  12448. if (target.ownerDocument === document) {
  12449. if (target !== document.body && !isUIElement(activeEditor, target) && editorManager.focusedEditor === activeEditor) {
  12450. activeEditor.fire('blur', { focusedEditor: null });
  12451. editorManager.focusedEditor = null;
  12452. }
  12453. }
  12454. });
  12455. }
  12456. };
  12457. DOM$2.bind(document, 'focusin', documentFocusInHandler);
  12458. }
  12459. };
  12460. var unregisterDocumentEvents = function (editorManager, e) {
  12461. if (editorManager.focusedEditor === e.editor) {
  12462. editorManager.focusedEditor = null;
  12463. }
  12464. if (!editorManager.activeEditor) {
  12465. DOM$2.unbind(document, 'focusin', documentFocusInHandler);
  12466. documentFocusInHandler = null;
  12467. }
  12468. };
  12469. var setup$2 = function (editorManager) {
  12470. editorManager.on('AddEditor', curry(registerEvents, editorManager));
  12471. editorManager.on('RemoveEditor', curry(unregisterDocumentEvents, editorManager));
  12472. };
  12473. var getContentEditableHost = function (editor, node) {
  12474. return editor.dom.getParent(node, function (node) {
  12475. return editor.dom.getContentEditable(node) === 'true';
  12476. });
  12477. };
  12478. var getCollapsedNode = function (rng) {
  12479. return rng.collapsed ? Optional.from(getNode(rng.startContainer, rng.startOffset)).map(SugarElement.fromDom) : Optional.none();
  12480. };
  12481. var getFocusInElement = function (root, rng) {
  12482. return getCollapsedNode(rng).bind(function (node) {
  12483. if (isTableSection(node)) {
  12484. return Optional.some(node);
  12485. } else if (contains$2(root, node) === false) {
  12486. return Optional.some(root);
  12487. } else {
  12488. return Optional.none();
  12489. }
  12490. });
  12491. };
  12492. var normalizeSelection = function (editor, rng) {
  12493. getFocusInElement(SugarElement.fromDom(editor.getBody()), rng).bind(function (elm) {
  12494. return firstPositionIn(elm.dom);
  12495. }).fold(function () {
  12496. editor.selection.normalize();
  12497. return;
  12498. }, function (caretPos) {
  12499. return editor.selection.setRng(caretPos.toRange());
  12500. });
  12501. };
  12502. var focusBody = function (body) {
  12503. if (body.setActive) {
  12504. try {
  12505. body.setActive();
  12506. } catch (ex) {
  12507. body.focus();
  12508. }
  12509. } else {
  12510. body.focus();
  12511. }
  12512. };
  12513. var hasElementFocus = function (elm) {
  12514. return hasFocus(elm) || search(elm).isSome();
  12515. };
  12516. var hasIframeFocus = function (editor) {
  12517. return editor.iframeElement && hasFocus(SugarElement.fromDom(editor.iframeElement));
  12518. };
  12519. var hasInlineFocus = function (editor) {
  12520. var rawBody = editor.getBody();
  12521. return rawBody && hasElementFocus(SugarElement.fromDom(rawBody));
  12522. };
  12523. var hasUiFocus = function (editor) {
  12524. return active().filter(function (elem) {
  12525. return !isEditorContentAreaElement(elem.dom) && isUIElement(editor, elem.dom);
  12526. }).isSome();
  12527. };
  12528. var hasFocus$1 = function (editor) {
  12529. return editor.inline ? hasInlineFocus(editor) : hasIframeFocus(editor);
  12530. };
  12531. var hasEditorOrUiFocus = function (editor) {
  12532. return hasFocus$1(editor) || hasUiFocus(editor);
  12533. };
  12534. var focusEditor = function (editor) {
  12535. var selection = editor.selection;
  12536. var body = editor.getBody();
  12537. var rng = selection.getRng();
  12538. editor.quirks.refreshContentEditable();
  12539. if (editor.bookmark !== undefined && hasFocus$1(editor) === false) {
  12540. getRng(editor).each(function (bookmarkRng) {
  12541. editor.selection.setRng(bookmarkRng);
  12542. rng = bookmarkRng;
  12543. });
  12544. }
  12545. var contentEditableHost = getContentEditableHost(editor, selection.getNode());
  12546. if (editor.$.contains(body, contentEditableHost)) {
  12547. focusBody(contentEditableHost);
  12548. normalizeSelection(editor, rng);
  12549. activateEditor(editor);
  12550. return;
  12551. }
  12552. if (!editor.inline) {
  12553. if (!Env.opera) {
  12554. focusBody(body);
  12555. }
  12556. editor.getWin().focus();
  12557. }
  12558. if (Env.gecko || editor.inline) {
  12559. focusBody(body);
  12560. normalizeSelection(editor, rng);
  12561. }
  12562. activateEditor(editor);
  12563. };
  12564. var activateEditor = function (editor) {
  12565. return editor.editorManager.setActive(editor);
  12566. };
  12567. var focus$1 = function (editor, skipFocus) {
  12568. if (editor.removed) {
  12569. return;
  12570. }
  12571. skipFocus ? activateEditor(editor) : focusEditor(editor);
  12572. };
  12573. var getEndpointElement = function (root, rng, start, real, resolve) {
  12574. var container = start ? rng.startContainer : rng.endContainer;
  12575. var offset = start ? rng.startOffset : rng.endOffset;
  12576. return Optional.from(container).map(SugarElement.fromDom).map(function (elm) {
  12577. return !real || !rng.collapsed ? child(elm, resolve(elm, offset)).getOr(elm) : elm;
  12578. }).bind(function (elm) {
  12579. return isElement(elm) ? Optional.some(elm) : parent(elm).filter(isElement);
  12580. }).map(function (elm) {
  12581. return elm.dom;
  12582. }).getOr(root);
  12583. };
  12584. var getStart$2 = function (root, rng, real) {
  12585. return getEndpointElement(root, rng, true, real, function (elm, offset) {
  12586. return Math.min(childNodesCount(elm), offset);
  12587. });
  12588. };
  12589. var getEnd = function (root, rng, real) {
  12590. return getEndpointElement(root, rng, false, real, function (elm, offset) {
  12591. return offset > 0 ? offset - 1 : offset;
  12592. });
  12593. };
  12594. var skipEmptyTextNodes = function (node, forwards) {
  12595. var orig = node;
  12596. while (node && isText$1(node) && node.length === 0) {
  12597. node = forwards ? node.nextSibling : node.previousSibling;
  12598. }
  12599. return node || orig;
  12600. };
  12601. var getNode$1 = function (root, rng) {
  12602. var elm, startContainer, endContainer;
  12603. if (!rng) {
  12604. return root;
  12605. }
  12606. startContainer = rng.startContainer;
  12607. endContainer = rng.endContainer;
  12608. var startOffset = rng.startOffset;
  12609. var endOffset = rng.endOffset;
  12610. elm = rng.commonAncestorContainer;
  12611. if (!rng.collapsed) {
  12612. if (startContainer === endContainer) {
  12613. if (endOffset - startOffset < 2) {
  12614. if (startContainer.hasChildNodes()) {
  12615. elm = startContainer.childNodes[startOffset];
  12616. }
  12617. }
  12618. }
  12619. if (startContainer.nodeType === 3 && endContainer.nodeType === 3) {
  12620. if (startContainer.length === startOffset) {
  12621. startContainer = skipEmptyTextNodes(startContainer.nextSibling, true);
  12622. } else {
  12623. startContainer = startContainer.parentNode;
  12624. }
  12625. if (endOffset === 0) {
  12626. endContainer = skipEmptyTextNodes(endContainer.previousSibling, false);
  12627. } else {
  12628. endContainer = endContainer.parentNode;
  12629. }
  12630. if (startContainer && startContainer === endContainer) {
  12631. return startContainer;
  12632. }
  12633. }
  12634. }
  12635. if (elm && elm.nodeType === 3) {
  12636. return elm.parentNode;
  12637. }
  12638. return elm;
  12639. };
  12640. var getSelectedBlocks = function (dom, rng, startElm, endElm) {
  12641. var node;
  12642. var selectedBlocks = [];
  12643. var root = dom.getRoot();
  12644. startElm = dom.getParent(startElm || getStart$2(root, rng, rng.collapsed), dom.isBlock);
  12645. endElm = dom.getParent(endElm || getEnd(root, rng, rng.collapsed), dom.isBlock);
  12646. if (startElm && startElm !== root) {
  12647. selectedBlocks.push(startElm);
  12648. }
  12649. if (startElm && endElm && startElm !== endElm) {
  12650. node = startElm;
  12651. var walker = new DomTreeWalker(startElm, root);
  12652. while ((node = walker.next()) && node !== endElm) {
  12653. if (dom.isBlock(node)) {
  12654. selectedBlocks.push(node);
  12655. }
  12656. }
  12657. }
  12658. if (endElm && startElm !== endElm && endElm !== root) {
  12659. selectedBlocks.push(endElm);
  12660. }
  12661. return selectedBlocks;
  12662. };
  12663. var select$1 = function (dom, node, content) {
  12664. return Optional.from(node).map(function (node) {
  12665. var idx = dom.nodeIndex(node);
  12666. var rng = dom.createRng();
  12667. rng.setStart(node.parentNode, idx);
  12668. rng.setEnd(node.parentNode, idx + 1);
  12669. if (content) {
  12670. moveEndPoint$1(dom, rng, node, true);
  12671. moveEndPoint$1(dom, rng, node, false);
  12672. }
  12673. return rng;
  12674. });
  12675. };
  12676. var processRanges = function (editor, ranges) {
  12677. return map(ranges, function (range) {
  12678. var evt = editor.fire('GetSelectionRange', { range: range });
  12679. return evt.range !== range ? evt.range : range;
  12680. });
  12681. };
  12682. var typeLookup = {
  12683. '#text': 3,
  12684. '#comment': 8,
  12685. '#cdata': 4,
  12686. '#pi': 7,
  12687. '#doctype': 10,
  12688. '#document-fragment': 11
  12689. };
  12690. var walk$2 = function (node, root, prev) {
  12691. var startName = prev ? 'lastChild' : 'firstChild';
  12692. var siblingName = prev ? 'prev' : 'next';
  12693. if (node[startName]) {
  12694. return node[startName];
  12695. }
  12696. if (node !== root) {
  12697. var sibling = node[siblingName];
  12698. if (sibling) {
  12699. return sibling;
  12700. }
  12701. for (var parent_1 = node.parent; parent_1 && parent_1 !== root; parent_1 = parent_1.parent) {
  12702. sibling = parent_1[siblingName];
  12703. if (sibling) {
  12704. return sibling;
  12705. }
  12706. }
  12707. }
  12708. };
  12709. var isEmptyTextNode$1 = function (node) {
  12710. if (!isWhitespaceText(node.value)) {
  12711. return false;
  12712. }
  12713. var parentNode = node.parent;
  12714. if (parentNode && (parentNode.name !== 'span' || parentNode.attr('style')) && /^[ ]+$/.test(node.value)) {
  12715. return false;
  12716. }
  12717. return true;
  12718. };
  12719. var isNonEmptyElement = function (node) {
  12720. var isNamedAnchor = node.name === 'a' && !node.attr('href') && node.attr('id');
  12721. return node.attr('name') || node.attr('id') && !node.firstChild || node.attr('data-mce-bookmark') || isNamedAnchor;
  12722. };
  12723. var AstNode = function () {
  12724. function AstNode(name, type) {
  12725. this.name = name;
  12726. this.type = type;
  12727. if (type === 1) {
  12728. this.attributes = [];
  12729. this.attributes.map = {};
  12730. }
  12731. }
  12732. AstNode.create = function (name, attrs) {
  12733. var node = new AstNode(name, typeLookup[name] || 1);
  12734. if (attrs) {
  12735. each$1(attrs, function (value, attrName) {
  12736. node.attr(attrName, value);
  12737. });
  12738. }
  12739. return node;
  12740. };
  12741. AstNode.prototype.replace = function (node) {
  12742. var self = this;
  12743. if (node.parent) {
  12744. node.remove();
  12745. }
  12746. self.insert(node, self);
  12747. self.remove();
  12748. return self;
  12749. };
  12750. AstNode.prototype.attr = function (name, value) {
  12751. var self = this;
  12752. var attrs;
  12753. if (typeof name !== 'string') {
  12754. if (name !== undefined && name !== null) {
  12755. each$1(name, function (value, key) {
  12756. self.attr(key, value);
  12757. });
  12758. }
  12759. return self;
  12760. }
  12761. if (attrs = self.attributes) {
  12762. if (value !== undefined) {
  12763. if (value === null) {
  12764. if (name in attrs.map) {
  12765. delete attrs.map[name];
  12766. var i = attrs.length;
  12767. while (i--) {
  12768. if (attrs[i].name === name) {
  12769. attrs.splice(i, 1);
  12770. return self;
  12771. }
  12772. }
  12773. }
  12774. return self;
  12775. }
  12776. if (name in attrs.map) {
  12777. var i = attrs.length;
  12778. while (i--) {
  12779. if (attrs[i].name === name) {
  12780. attrs[i].value = value;
  12781. break;
  12782. }
  12783. }
  12784. } else {
  12785. attrs.push({
  12786. name: name,
  12787. value: value
  12788. });
  12789. }
  12790. attrs.map[name] = value;
  12791. return self;
  12792. }
  12793. return attrs.map[name];
  12794. }
  12795. };
  12796. AstNode.prototype.clone = function () {
  12797. var self = this;
  12798. var clone = new AstNode(self.name, self.type);
  12799. var selfAttrs;
  12800. if (selfAttrs = self.attributes) {
  12801. var cloneAttrs = [];
  12802. cloneAttrs.map = {};
  12803. for (var i = 0, l = selfAttrs.length; i < l; i++) {
  12804. var selfAttr = selfAttrs[i];
  12805. if (selfAttr.name !== 'id') {
  12806. cloneAttrs[cloneAttrs.length] = {
  12807. name: selfAttr.name,
  12808. value: selfAttr.value
  12809. };
  12810. cloneAttrs.map[selfAttr.name] = selfAttr.value;
  12811. }
  12812. }
  12813. clone.attributes = cloneAttrs;
  12814. }
  12815. clone.value = self.value;
  12816. clone.shortEnded = self.shortEnded;
  12817. return clone;
  12818. };
  12819. AstNode.prototype.wrap = function (wrapper) {
  12820. var self = this;
  12821. self.parent.insert(wrapper, self);
  12822. wrapper.append(self);
  12823. return self;
  12824. };
  12825. AstNode.prototype.unwrap = function () {
  12826. var self = this;
  12827. for (var node = self.firstChild; node;) {
  12828. var next = node.next;
  12829. self.insert(node, self, true);
  12830. node = next;
  12831. }
  12832. self.remove();
  12833. };
  12834. AstNode.prototype.remove = function () {
  12835. var self = this, parent = self.parent, next = self.next, prev = self.prev;
  12836. if (parent) {
  12837. if (parent.firstChild === self) {
  12838. parent.firstChild = next;
  12839. if (next) {
  12840. next.prev = null;
  12841. }
  12842. } else {
  12843. prev.next = next;
  12844. }
  12845. if (parent.lastChild === self) {
  12846. parent.lastChild = prev;
  12847. if (prev) {
  12848. prev.next = null;
  12849. }
  12850. } else {
  12851. next.prev = prev;
  12852. }
  12853. self.parent = self.next = self.prev = null;
  12854. }
  12855. return self;
  12856. };
  12857. AstNode.prototype.append = function (node) {
  12858. var self = this;
  12859. if (node.parent) {
  12860. node.remove();
  12861. }
  12862. var last = self.lastChild;
  12863. if (last) {
  12864. last.next = node;
  12865. node.prev = last;
  12866. self.lastChild = node;
  12867. } else {
  12868. self.lastChild = self.firstChild = node;
  12869. }
  12870. node.parent = self;
  12871. return node;
  12872. };
  12873. AstNode.prototype.insert = function (node, refNode, before) {
  12874. if (node.parent) {
  12875. node.remove();
  12876. }
  12877. var parent = refNode.parent || this;
  12878. if (before) {
  12879. if (refNode === parent.firstChild) {
  12880. parent.firstChild = node;
  12881. } else {
  12882. refNode.prev.next = node;
  12883. }
  12884. node.prev = refNode.prev;
  12885. node.next = refNode;
  12886. refNode.prev = node;
  12887. } else {
  12888. if (refNode === parent.lastChild) {
  12889. parent.lastChild = node;
  12890. } else {
  12891. refNode.next.prev = node;
  12892. }
  12893. node.next = refNode.next;
  12894. node.prev = refNode;
  12895. refNode.next = node;
  12896. }
  12897. node.parent = parent;
  12898. return node;
  12899. };
  12900. AstNode.prototype.getAll = function (name) {
  12901. var self = this;
  12902. var collection = [];
  12903. for (var node = self.firstChild; node; node = walk$2(node, self)) {
  12904. if (node.name === name) {
  12905. collection.push(node);
  12906. }
  12907. }
  12908. return collection;
  12909. };
  12910. AstNode.prototype.empty = function () {
  12911. var self = this;
  12912. if (self.firstChild) {
  12913. var nodes = [];
  12914. for (var node = self.firstChild; node; node = walk$2(node, self)) {
  12915. nodes.push(node);
  12916. }
  12917. var i = nodes.length;
  12918. while (i--) {
  12919. var node = nodes[i];
  12920. node.parent = node.firstChild = node.lastChild = node.next = node.prev = null;
  12921. }
  12922. }
  12923. self.firstChild = self.lastChild = null;
  12924. return self;
  12925. };
  12926. AstNode.prototype.isEmpty = function (elements, whitespace, predicate) {
  12927. if (whitespace === void 0) {
  12928. whitespace = {};
  12929. }
  12930. var self = this;
  12931. var node = self.firstChild;
  12932. if (isNonEmptyElement(self)) {
  12933. return false;
  12934. }
  12935. if (node) {
  12936. do {
  12937. if (node.type === 1) {
  12938. if (node.attr('data-mce-bogus')) {
  12939. continue;
  12940. }
  12941. if (elements[node.name]) {
  12942. return false;
  12943. }
  12944. if (isNonEmptyElement(node)) {
  12945. return false;
  12946. }
  12947. }
  12948. if (node.type === 8) {
  12949. return false;
  12950. }
  12951. if (node.type === 3 && !isEmptyTextNode$1(node)) {
  12952. return false;
  12953. }
  12954. if (node.type === 3 && node.parent && whitespace[node.parent.name] && isWhitespaceText(node.value)) {
  12955. return false;
  12956. }
  12957. if (predicate && predicate(node)) {
  12958. return false;
  12959. }
  12960. } while (node = walk$2(node, self));
  12961. }
  12962. return true;
  12963. };
  12964. AstNode.prototype.walk = function (prev) {
  12965. return walk$2(this, null, prev);
  12966. };
  12967. return AstNode;
  12968. }();
  12969. var makeMap$3 = Tools.makeMap;
  12970. var Writer = function (settings) {
  12971. var html = [];
  12972. settings = settings || {};
  12973. var indent = settings.indent;
  12974. var indentBefore = makeMap$3(settings.indent_before || '');
  12975. var indentAfter = makeMap$3(settings.indent_after || '');
  12976. var encode = Entities.getEncodeFunc(settings.entity_encoding || 'raw', settings.entities);
  12977. var htmlOutput = settings.element_format === 'html';
  12978. return {
  12979. start: function (name, attrs, empty) {
  12980. var i, l, attr, value;
  12981. if (indent && indentBefore[name] && html.length > 0) {
  12982. value = html[html.length - 1];
  12983. if (value.length > 0 && value !== '\n') {
  12984. html.push('\n');
  12985. }
  12986. }
  12987. html.push('<', name);
  12988. if (attrs) {
  12989. for (i = 0, l = attrs.length; i < l; i++) {
  12990. attr = attrs[i];
  12991. html.push(' ', attr.name, '="', encode(attr.value, true), '"');
  12992. }
  12993. }
  12994. if (!empty || htmlOutput) {
  12995. html[html.length] = '>';
  12996. } else {
  12997. html[html.length] = ' />';
  12998. }
  12999. if (empty && indent && indentAfter[name] && html.length > 0) {
  13000. value = html[html.length - 1];
  13001. if (value.length > 0 && value !== '\n') {
  13002. html.push('\n');
  13003. }
  13004. }
  13005. },
  13006. end: function (name) {
  13007. var value;
  13008. html.push('</', name, '>');
  13009. if (indent && indentAfter[name] && html.length > 0) {
  13010. value = html[html.length - 1];
  13011. if (value.length > 0 && value !== '\n') {
  13012. html.push('\n');
  13013. }
  13014. }
  13015. },
  13016. text: function (text, raw) {
  13017. if (text.length > 0) {
  13018. html[html.length] = raw ? text : encode(text);
  13019. }
  13020. },
  13021. cdata: function (text) {
  13022. html.push('<![CDATA[', text, ']]>');
  13023. },
  13024. comment: function (text) {
  13025. html.push('<!--', text, '-->');
  13026. },
  13027. pi: function (name, text) {
  13028. if (text) {
  13029. html.push('<?', name, ' ', encode(text), '?>');
  13030. } else {
  13031. html.push('<?', name, '?>');
  13032. }
  13033. if (indent) {
  13034. html.push('\n');
  13035. }
  13036. },
  13037. doctype: function (text) {
  13038. html.push('<!DOCTYPE', text, '>', indent ? '\n' : '');
  13039. },
  13040. reset: function () {
  13041. html.length = 0;
  13042. },
  13043. getContent: function () {
  13044. return html.join('').replace(/\n$/, '');
  13045. }
  13046. };
  13047. };
  13048. var HtmlSerializer = function (settings, schema) {
  13049. if (schema === void 0) {
  13050. schema = Schema();
  13051. }
  13052. var writer = Writer(settings);
  13053. settings = settings || {};
  13054. settings.validate = 'validate' in settings ? settings.validate : true;
  13055. var serialize = function (node) {
  13056. var validate = settings.validate;
  13057. var handlers = {
  13058. 3: function (node) {
  13059. writer.text(node.value, node.raw);
  13060. },
  13061. 8: function (node) {
  13062. writer.comment(node.value);
  13063. },
  13064. 7: function (node) {
  13065. writer.pi(node.name, node.value);
  13066. },
  13067. 10: function (node) {
  13068. writer.doctype(node.value);
  13069. },
  13070. 4: function (node) {
  13071. writer.cdata(node.value);
  13072. },
  13073. 11: function (node) {
  13074. if (node = node.firstChild) {
  13075. do {
  13076. walk(node);
  13077. } while (node = node.next);
  13078. }
  13079. }
  13080. };
  13081. writer.reset();
  13082. var walk = function (node) {
  13083. var handler = handlers[node.type];
  13084. var name, isEmpty, attrs, attrName, attrValue, sortedAttrs, i, l, elementRule;
  13085. if (!handler) {
  13086. name = node.name;
  13087. isEmpty = node.shortEnded;
  13088. attrs = node.attributes;
  13089. if (validate && attrs && attrs.length > 1) {
  13090. sortedAttrs = [];
  13091. sortedAttrs.map = {};
  13092. elementRule = schema.getElementRule(node.name);
  13093. if (elementRule) {
  13094. for (i = 0, l = elementRule.attributesOrder.length; i < l; i++) {
  13095. attrName = elementRule.attributesOrder[i];
  13096. if (attrName in attrs.map) {
  13097. attrValue = attrs.map[attrName];
  13098. sortedAttrs.map[attrName] = attrValue;
  13099. sortedAttrs.push({
  13100. name: attrName,
  13101. value: attrValue
  13102. });
  13103. }
  13104. }
  13105. for (i = 0, l = attrs.length; i < l; i++) {
  13106. attrName = attrs[i].name;
  13107. if (!(attrName in sortedAttrs.map)) {
  13108. attrValue = attrs.map[attrName];
  13109. sortedAttrs.map[attrName] = attrValue;
  13110. sortedAttrs.push({
  13111. name: attrName,
  13112. value: attrValue
  13113. });
  13114. }
  13115. }
  13116. attrs = sortedAttrs;
  13117. }
  13118. }
  13119. writer.start(node.name, attrs, isEmpty);
  13120. if (!isEmpty) {
  13121. if (node = node.firstChild) {
  13122. do {
  13123. walk(node);
  13124. } while (node = node.next);
  13125. }
  13126. writer.end(name);
  13127. }
  13128. } else {
  13129. handler(node);
  13130. }
  13131. };
  13132. if (node.type === 1 && !settings.inner) {
  13133. walk(node);
  13134. } else {
  13135. handlers[11](node);
  13136. }
  13137. return writer.getContent();
  13138. };
  13139. return { serialize: serialize };
  13140. };
  13141. var extractBase64DataUris = function (html) {
  13142. var dataImageUri = /data:[^;]+;base64,([a-z0-9\+\/=]+)/gi;
  13143. var chunks = [];
  13144. var uris = {};
  13145. var prefix = generate$1('img');
  13146. var matches;
  13147. var index = 0;
  13148. var count = 0;
  13149. while (matches = dataImageUri.exec(html)) {
  13150. var uri = matches[0];
  13151. var imageId = prefix + '_' + count++;
  13152. uris[imageId] = uri;
  13153. if (index < matches.index) {
  13154. chunks.push(html.substr(index, matches.index - index));
  13155. }
  13156. chunks.push(imageId);
  13157. index = matches.index + uri.length;
  13158. }
  13159. if (index === 0) {
  13160. return {
  13161. prefix: prefix,
  13162. uris: uris,
  13163. html: html
  13164. };
  13165. } else {
  13166. if (index < html.length) {
  13167. chunks.push(html.substr(index));
  13168. }
  13169. return {
  13170. prefix: prefix,
  13171. uris: uris,
  13172. html: chunks.join('')
  13173. };
  13174. }
  13175. };
  13176. var restoreDataUris = function (html, result) {
  13177. return html.replace(new RegExp(result.prefix + '_[0-9]+', 'g'), function (imageId) {
  13178. return get(result.uris, imageId).getOr(imageId);
  13179. });
  13180. };
  13181. var parseDataUri = function (uri) {
  13182. var matches = /data:([^;]+);base64,([a-z0-9\+\/=]+)/i.exec(uri);
  13183. if (matches) {
  13184. return Optional.some({
  13185. type: matches[1],
  13186. data: decodeURIComponent(matches[2])
  13187. });
  13188. } else {
  13189. return Optional.none();
  13190. }
  13191. };
  13192. var isValidPrefixAttrName = function (name) {
  13193. return name.indexOf('data-') === 0 || name.indexOf('aria-') === 0;
  13194. };
  13195. var isInvalidUri = function (settings, uri) {
  13196. if (settings.allow_html_data_urls) {
  13197. return false;
  13198. } else if (/^data:image\//i.test(uri)) {
  13199. return settings.allow_svg_data_urls === false && /^data:image\/svg\+xml/i.test(uri);
  13200. } else {
  13201. return /^data:/i.test(uri);
  13202. }
  13203. };
  13204. var findEndTagIndex = function (schema, html, startIndex) {
  13205. var count = 1, index, matches;
  13206. var shortEndedElements = schema.getShortEndedElements();
  13207. var tokenRegExp = /<([!?\/])?([A-Za-z0-9\-_\:\.]+)((?:\s+[^"\'>]+(?:(?:"[^"]*")|(?:\'[^\']*\')|[^>]*))*|\/|\s+)>/g;
  13208. tokenRegExp.lastIndex = index = startIndex;
  13209. while (matches = tokenRegExp.exec(html)) {
  13210. index = tokenRegExp.lastIndex;
  13211. if (matches[1] === '/') {
  13212. count--;
  13213. } else if (!matches[1]) {
  13214. if (matches[2] in shortEndedElements) {
  13215. continue;
  13216. }
  13217. count++;
  13218. }
  13219. if (count === 0) {
  13220. break;
  13221. }
  13222. }
  13223. return index;
  13224. };
  13225. var isConditionalComment = function (html, startIndex) {
  13226. return /^\s*\[if [\w\W]+\]>.*<!\[endif\](--!?)?>/.test(html.substr(startIndex));
  13227. };
  13228. var findCommentEndIndex = function (html, isBogus, startIndex) {
  13229. if (startIndex === void 0) {
  13230. startIndex = 0;
  13231. }
  13232. var lcHtml = html.toLowerCase();
  13233. if (lcHtml.indexOf('[if ', startIndex) !== -1 && isConditionalComment(lcHtml, startIndex)) {
  13234. var endIfIndex = lcHtml.indexOf('[endif]', startIndex);
  13235. return lcHtml.indexOf('>', endIfIndex);
  13236. } else {
  13237. if (isBogus) {
  13238. var endIndex = lcHtml.indexOf('>', startIndex);
  13239. return endIndex !== -1 ? endIndex : lcHtml.length;
  13240. } else {
  13241. var endCommentRegexp = /--!?>/;
  13242. endCommentRegexp.lastIndex = startIndex;
  13243. var match = endCommentRegexp.exec(html);
  13244. return match ? match.index + match[0].length : lcHtml.length;
  13245. }
  13246. }
  13247. };
  13248. var checkBogusAttribute = function (regExp, attrString) {
  13249. var matches = regExp.exec(attrString);
  13250. if (matches) {
  13251. var name_1 = matches[1];
  13252. var value = matches[2];
  13253. return typeof name_1 === 'string' && name_1.toLowerCase() === 'data-mce-bogus' ? value : null;
  13254. } else {
  13255. return null;
  13256. }
  13257. };
  13258. function SaxParser(settings, schema) {
  13259. if (schema === void 0) {
  13260. schema = Schema();
  13261. }
  13262. var noop = function () {
  13263. };
  13264. settings = settings || {};
  13265. if (settings.fix_self_closing !== false) {
  13266. settings.fix_self_closing = true;
  13267. }
  13268. var comment = settings.comment ? settings.comment : noop;
  13269. var cdata = settings.cdata ? settings.cdata : noop;
  13270. var text = settings.text ? settings.text : noop;
  13271. var start = settings.start ? settings.start : noop;
  13272. var end = settings.end ? settings.end : noop;
  13273. var pi = settings.pi ? settings.pi : noop;
  13274. var doctype = settings.doctype ? settings.doctype : noop;
  13275. var parseInternal = function (base64Extract, format) {
  13276. if (format === void 0) {
  13277. format = 'html';
  13278. }
  13279. var html = base64Extract.html;
  13280. var matches, index = 0, value, endRegExp;
  13281. var stack = [];
  13282. var attrList, i, textData, name;
  13283. var isInternalElement, isShortEnded;
  13284. var elementRule, isValidElement, attr, attribsValue, validAttributesMap, validAttributePatterns;
  13285. var attributesRequired, attributesDefault, attributesForced;
  13286. var anyAttributesRequired, attrValue, idCount = 0;
  13287. var decode = Entities.decode;
  13288. var filteredUrlAttrs = Tools.makeMap('src,href,data,background,formaction,poster,xlink:href');
  13289. var scriptUriRegExp = /((java|vb)script|mhtml):/i;
  13290. var parsingMode = format === 'html' ? 0 : 1;
  13291. var processEndTag = function (name) {
  13292. var pos, i;
  13293. pos = stack.length;
  13294. while (pos--) {
  13295. if (stack[pos].name === name) {
  13296. break;
  13297. }
  13298. }
  13299. if (pos >= 0) {
  13300. for (i = stack.length - 1; i >= pos; i--) {
  13301. name = stack[i];
  13302. if (name.valid) {
  13303. end(name.name);
  13304. }
  13305. }
  13306. stack.length = pos;
  13307. }
  13308. };
  13309. var processText = function (value, raw) {
  13310. return text(restoreDataUris(value, base64Extract), raw);
  13311. };
  13312. var processComment = function (value) {
  13313. if (value === '') {
  13314. return;
  13315. }
  13316. if (value.charAt(0) === '>') {
  13317. value = ' ' + value;
  13318. }
  13319. if (!settings.allow_conditional_comments && value.substr(0, 3).toLowerCase() === '[if') {
  13320. value = ' ' + value;
  13321. }
  13322. comment(restoreDataUris(value, base64Extract));
  13323. };
  13324. var processAttr = function (value) {
  13325. return get(base64Extract.uris, value).getOr(value);
  13326. };
  13327. var processMalformedComment = function (value, startIndex) {
  13328. var startTag = value || '';
  13329. var isBogus = !startsWith(startTag, '--');
  13330. var endIndex = findCommentEndIndex(html, isBogus, startIndex);
  13331. value = html.substr(startIndex, endIndex - startIndex);
  13332. processComment(isBogus ? startTag + value : value);
  13333. return endIndex + 1;
  13334. };
  13335. var parseAttribute = function (match, name, value, val2, val3) {
  13336. var attrRule, i;
  13337. var trimRegExp = /[\s\u0000-\u001F]+/g;
  13338. name = name.toLowerCase();
  13339. value = processAttr(name in fillAttrsMap ? name : decode(value || val2 || val3 || ''));
  13340. if (validate && !isInternalElement && isValidPrefixAttrName(name) === false) {
  13341. attrRule = validAttributesMap[name];
  13342. if (!attrRule && validAttributePatterns) {
  13343. i = validAttributePatterns.length;
  13344. while (i--) {
  13345. attrRule = validAttributePatterns[i];
  13346. if (attrRule.pattern.test(name)) {
  13347. break;
  13348. }
  13349. }
  13350. if (i === -1) {
  13351. attrRule = null;
  13352. }
  13353. }
  13354. if (!attrRule) {
  13355. return;
  13356. }
  13357. if (attrRule.validValues && !(value in attrRule.validValues)) {
  13358. return;
  13359. }
  13360. }
  13361. if (filteredUrlAttrs[name] && !settings.allow_script_urls) {
  13362. var uri = value.replace(trimRegExp, '');
  13363. try {
  13364. uri = decodeURIComponent(uri);
  13365. } catch (ex) {
  13366. uri = unescape(uri);
  13367. }
  13368. if (scriptUriRegExp.test(uri)) {
  13369. return;
  13370. }
  13371. if (isInvalidUri(settings, uri)) {
  13372. return;
  13373. }
  13374. }
  13375. if (isInternalElement && (name in filteredUrlAttrs || name.indexOf('on') === 0)) {
  13376. return;
  13377. }
  13378. attrList.map[name] = value;
  13379. attrList.push({
  13380. name: name,
  13381. value: value
  13382. });
  13383. };
  13384. var tokenRegExp = new RegExp('<(?:' + '(?:!--([\\w\\W]*?)--!?>)|' + '(?:!\\[CDATA\\[([\\w\\W]*?)\\]\\]>)|' + '(?:![Dd][Oo][Cc][Tt][Yy][Pp][Ee]([\\w\\W]*?)>)|' + '(?:!(--)?)|' + '(?:\\?([^\\s\\/<>]+) ?([\\w\\W]*?)[?/]>)|' + '(?:\\/([A-Za-z][A-Za-z0-9\\-_\\:\\.]*)>)|' + '(?:([A-Za-z][A-Za-z0-9\\-_\\:\\.]*)((?:\\s+[^"\'>]+(?:(?:"[^"]*")|(?:\'[^\']*\')|[^>]*))*|\\/|\\s+)>)' + ')', 'g');
  13385. var attrRegExp = /([\w:\-]+)(?:\s*=\s*(?:(?:\"((?:[^\"])*)\")|(?:\'((?:[^\'])*)\')|([^>\s]+)))?/g;
  13386. var shortEndedElements = schema.getShortEndedElements();
  13387. var selfClosing = settings.self_closing_elements || schema.getSelfClosingElements();
  13388. var fillAttrsMap = schema.getBoolAttrs();
  13389. var validate = settings.validate;
  13390. var removeInternalElements = settings.remove_internals;
  13391. var fixSelfClosing = settings.fix_self_closing;
  13392. var specialElements = schema.getSpecialElements();
  13393. var processHtml = html + '>';
  13394. while (matches = tokenRegExp.exec(processHtml)) {
  13395. var matchText = matches[0];
  13396. if (index < matches.index) {
  13397. processText(decode(html.substr(index, matches.index - index)));
  13398. }
  13399. if (value = matches[7]) {
  13400. value = value.toLowerCase();
  13401. if (value.charAt(0) === ':') {
  13402. value = value.substr(1);
  13403. }
  13404. processEndTag(value);
  13405. } else if (value = matches[8]) {
  13406. if (matches.index + matchText.length > html.length) {
  13407. processText(decode(html.substr(matches.index)));
  13408. index = matches.index + matchText.length;
  13409. continue;
  13410. }
  13411. value = value.toLowerCase();
  13412. if (value.charAt(0) === ':') {
  13413. value = value.substr(1);
  13414. }
  13415. isShortEnded = value in shortEndedElements;
  13416. if (fixSelfClosing && selfClosing[value] && stack.length > 0 && stack[stack.length - 1].name === value) {
  13417. processEndTag(value);
  13418. }
  13419. var bogusValue = checkBogusAttribute(attrRegExp, matches[9]);
  13420. if (bogusValue !== null) {
  13421. if (bogusValue === 'all') {
  13422. index = findEndTagIndex(schema, html, tokenRegExp.lastIndex);
  13423. tokenRegExp.lastIndex = index;
  13424. continue;
  13425. }
  13426. isValidElement = false;
  13427. }
  13428. if (!validate || (elementRule = schema.getElementRule(value))) {
  13429. isValidElement = true;
  13430. if (validate) {
  13431. validAttributesMap = elementRule.attributes;
  13432. validAttributePatterns = elementRule.attributePatterns;
  13433. }
  13434. if (attribsValue = matches[9]) {
  13435. isInternalElement = attribsValue.indexOf('data-mce-type') !== -1;
  13436. if (isInternalElement && removeInternalElements) {
  13437. isValidElement = false;
  13438. }
  13439. attrList = [];
  13440. attrList.map = {};
  13441. attribsValue.replace(attrRegExp, parseAttribute);
  13442. } else {
  13443. attrList = [];
  13444. attrList.map = {};
  13445. }
  13446. if (validate && !isInternalElement) {
  13447. attributesRequired = elementRule.attributesRequired;
  13448. attributesDefault = elementRule.attributesDefault;
  13449. attributesForced = elementRule.attributesForced;
  13450. anyAttributesRequired = elementRule.removeEmptyAttrs;
  13451. if (anyAttributesRequired && !attrList.length) {
  13452. isValidElement = false;
  13453. }
  13454. if (attributesForced) {
  13455. i = attributesForced.length;
  13456. while (i--) {
  13457. attr = attributesForced[i];
  13458. name = attr.name;
  13459. attrValue = attr.value;
  13460. if (attrValue === '{$uid}') {
  13461. attrValue = 'mce_' + idCount++;
  13462. }
  13463. attrList.map[name] = attrValue;
  13464. attrList.push({
  13465. name: name,
  13466. value: attrValue
  13467. });
  13468. }
  13469. }
  13470. if (attributesDefault) {
  13471. i = attributesDefault.length;
  13472. while (i--) {
  13473. attr = attributesDefault[i];
  13474. name = attr.name;
  13475. if (!(name in attrList.map)) {
  13476. attrValue = attr.value;
  13477. if (attrValue === '{$uid}') {
  13478. attrValue = 'mce_' + idCount++;
  13479. }
  13480. attrList.map[name] = attrValue;
  13481. attrList.push({
  13482. name: name,
  13483. value: attrValue
  13484. });
  13485. }
  13486. }
  13487. }
  13488. if (attributesRequired) {
  13489. i = attributesRequired.length;
  13490. while (i--) {
  13491. if (attributesRequired[i] in attrList.map) {
  13492. break;
  13493. }
  13494. }
  13495. if (i === -1) {
  13496. isValidElement = false;
  13497. }
  13498. }
  13499. if (attr = attrList.map['data-mce-bogus']) {
  13500. if (attr === 'all') {
  13501. index = findEndTagIndex(schema, html, tokenRegExp.lastIndex);
  13502. tokenRegExp.lastIndex = index;
  13503. continue;
  13504. }
  13505. isValidElement = false;
  13506. }
  13507. }
  13508. if (isValidElement) {
  13509. start(value, attrList, isShortEnded);
  13510. }
  13511. } else {
  13512. isValidElement = false;
  13513. }
  13514. if (endRegExp = specialElements[value]) {
  13515. endRegExp.lastIndex = index = matches.index + matchText.length;
  13516. if (matches = endRegExp.exec(html)) {
  13517. if (isValidElement) {
  13518. textData = html.substr(index, matches.index - index);
  13519. }
  13520. index = matches.index + matches[0].length;
  13521. } else {
  13522. textData = html.substr(index);
  13523. index = html.length;
  13524. }
  13525. if (isValidElement) {
  13526. if (textData.length > 0) {
  13527. processText(textData, true);
  13528. }
  13529. end(value);
  13530. }
  13531. tokenRegExp.lastIndex = index;
  13532. continue;
  13533. }
  13534. if (!isShortEnded) {
  13535. if (!attribsValue || attribsValue.indexOf('/') !== attribsValue.length - 1) {
  13536. stack.push({
  13537. name: value,
  13538. valid: isValidElement
  13539. });
  13540. } else if (isValidElement) {
  13541. end(value);
  13542. }
  13543. }
  13544. } else if (value = matches[1]) {
  13545. processComment(value);
  13546. } else if (value = matches[2]) {
  13547. var isValidCdataSection = parsingMode === 1 || settings.preserve_cdata || stack.length > 0 && schema.isValidChild(stack[stack.length - 1].name, '#cdata');
  13548. if (isValidCdataSection) {
  13549. cdata(value);
  13550. } else {
  13551. index = processMalformedComment('', matches.index + 2);
  13552. tokenRegExp.lastIndex = index;
  13553. continue;
  13554. }
  13555. } else if (value = matches[3]) {
  13556. doctype(value);
  13557. } else if ((value = matches[4]) || matchText === '<!') {
  13558. index = processMalformedComment(value, matches.index + matchText.length);
  13559. tokenRegExp.lastIndex = index;
  13560. continue;
  13561. } else if (value = matches[5]) {
  13562. if (parsingMode === 1) {
  13563. pi(value, matches[6]);
  13564. } else {
  13565. index = processMalformedComment('?', matches.index + 2);
  13566. tokenRegExp.lastIndex = index;
  13567. continue;
  13568. }
  13569. }
  13570. index = matches.index + matchText.length;
  13571. }
  13572. if (index < html.length) {
  13573. processText(decode(html.substr(index)));
  13574. }
  13575. for (i = stack.length - 1; i >= 0; i--) {
  13576. value = stack[i];
  13577. if (value.valid) {
  13578. end(value.name);
  13579. }
  13580. }
  13581. };
  13582. var parse = function (html, format) {
  13583. if (format === void 0) {
  13584. format = 'html';
  13585. }
  13586. parseInternal(extractBase64DataUris(html), format);
  13587. };
  13588. return { parse: parse };
  13589. }
  13590. (function (SaxParser) {
  13591. SaxParser.findEndTag = findEndTagIndex;
  13592. }(SaxParser || (SaxParser = {})));
  13593. var SaxParser$1 = SaxParser;
  13594. var trimHtml = function (tempAttrs, html) {
  13595. var trimContentRegExp = new RegExp(['\\s?(' + tempAttrs.join('|') + ')="[^"]+"'].join('|'), 'gi');
  13596. return html.replace(trimContentRegExp, '');
  13597. };
  13598. var trimInternal = function (serializer, html) {
  13599. var content = html;
  13600. var bogusAllRegExp = /<(\w+) [^>]*data-mce-bogus="all"[^>]*>/g;
  13601. var endTagIndex, index, matchLength, matches;
  13602. var schema = serializer.schema;
  13603. content = trimHtml(serializer.getTempAttrs(), content);
  13604. var shortEndedElements = schema.getShortEndedElements();
  13605. while (matches = bogusAllRegExp.exec(content)) {
  13606. index = bogusAllRegExp.lastIndex;
  13607. matchLength = matches[0].length;
  13608. if (shortEndedElements[matches[1]]) {
  13609. endTagIndex = index;
  13610. } else {
  13611. endTagIndex = SaxParser$1.findEndTag(schema, content, index);
  13612. }
  13613. content = content.substring(0, index - matchLength) + content.substring(endTagIndex);
  13614. bogusAllRegExp.lastIndex = index - matchLength;
  13615. }
  13616. return trim$2(content);
  13617. };
  13618. var trimExternal = trimInternal;
  13619. var trimEmptyContents = function (editor, html) {
  13620. var blockName = getForcedRootBlock(editor);
  13621. var emptyRegExp = new RegExp('^(<' + blockName + '[^>]*>(&nbsp;|&#160;|\\s|\xA0|<br \\/>|)<\\/' + blockName + '>[\r\n]*|<br \\/>[\r\n]*)$');
  13622. return html.replace(emptyRegExp, '');
  13623. };
  13624. var getContentFromBody = function (editor, args, format, body) {
  13625. var content;
  13626. args.format = format;
  13627. args.get = true;
  13628. args.getInner = true;
  13629. if (!args.no_events) {
  13630. editor.fire('BeforeGetContent', args);
  13631. }
  13632. if (args.format === 'raw') {
  13633. content = Tools.trim(trimExternal(editor.serializer, body.innerHTML));
  13634. } else if (args.format === 'text') {
  13635. content = trim$2(body.innerText || body.textContent);
  13636. } else if (args.format === 'tree') {
  13637. return editor.serializer.serialize(body, args);
  13638. } else {
  13639. content = trimEmptyContents(editor, editor.serializer.serialize(body, args));
  13640. }
  13641. if (args.format !== 'text' && !isWsPreserveElement(SugarElement.fromDom(body))) {
  13642. args.content = Tools.trim(content);
  13643. } else {
  13644. args.content = content;
  13645. }
  13646. if (!args.no_events) {
  13647. editor.fire('GetContent', args);
  13648. }
  13649. return args.content;
  13650. };
  13651. var getContentInternal = function (editor, args, format) {
  13652. return Optional.from(editor.getBody()).fold(constant(args.format === 'tree' ? new AstNode('body', 11) : ''), function (body) {
  13653. return getContentFromBody(editor, args, format, body);
  13654. });
  13655. };
  13656. var each$7 = Tools.each;
  13657. var ElementUtils = function (dom) {
  13658. this.compare = function (node1, node2) {
  13659. if (node1.nodeName !== node2.nodeName) {
  13660. return false;
  13661. }
  13662. var getAttribs = function (node) {
  13663. var attribs = {};
  13664. each$7(dom.getAttribs(node), function (attr) {
  13665. var name = attr.nodeName.toLowerCase();
  13666. if (name.indexOf('_') !== 0 && name !== 'style' && name.indexOf('data-') !== 0) {
  13667. attribs[name] = dom.getAttrib(node, name);
  13668. }
  13669. });
  13670. return attribs;
  13671. };
  13672. var compareObjects = function (obj1, obj2) {
  13673. var value, name;
  13674. for (name in obj1) {
  13675. if (obj1.hasOwnProperty(name)) {
  13676. value = obj2[name];
  13677. if (typeof value === 'undefined') {
  13678. return false;
  13679. }
  13680. if (obj1[name] !== value) {
  13681. return false;
  13682. }
  13683. delete obj2[name];
  13684. }
  13685. }
  13686. for (name in obj2) {
  13687. if (obj2.hasOwnProperty(name)) {
  13688. return false;
  13689. }
  13690. }
  13691. return true;
  13692. };
  13693. if (!compareObjects(getAttribs(node1), getAttribs(node2))) {
  13694. return false;
  13695. }
  13696. if (!compareObjects(dom.parseStyle(dom.getAttrib(node1, 'style')), dom.parseStyle(dom.getAttrib(node2, 'style')))) {
  13697. return false;
  13698. }
  13699. return !isBookmarkNode$1(node1) && !isBookmarkNode$1(node2);
  13700. };
  13701. };
  13702. var isChar = function (forward, predicate, pos) {
  13703. return Optional.from(pos.container()).filter(isText$1).exists(function (text) {
  13704. var delta = forward ? 0 : -1;
  13705. return predicate(text.data.charAt(pos.offset() + delta));
  13706. });
  13707. };
  13708. var isBeforeSpace = curry(isChar, true, isWhiteSpace$1);
  13709. var isAfterSpace = curry(isChar, false, isWhiteSpace$1);
  13710. var isEmptyText = function (pos) {
  13711. var container = pos.container();
  13712. return isText$1(container) && (container.data.length === 0 || isZwsp$1(container.data) && BookmarkManager$1.isBookmarkNode(container.parentNode));
  13713. };
  13714. var matchesElementPosition = function (before, predicate) {
  13715. return function (pos) {
  13716. return Optional.from(getChildNodeAtRelativeOffset(before ? 0 : -1, pos)).filter(predicate).isSome();
  13717. };
  13718. };
  13719. var isImageBlock = function (node) {
  13720. return isImg(node) && get$4(SugarElement.fromDom(node), 'display') === 'block';
  13721. };
  13722. var isCefNode = function (node) {
  13723. return isContentEditableFalse(node) && !isBogusAll(node);
  13724. };
  13725. var isBeforeImageBlock = matchesElementPosition(true, isImageBlock);
  13726. var isAfterImageBlock = matchesElementPosition(false, isImageBlock);
  13727. var isBeforeMedia = matchesElementPosition(true, isMedia);
  13728. var isAfterMedia = matchesElementPosition(false, isMedia);
  13729. var isBeforeTable = matchesElementPosition(true, isTable);
  13730. var isAfterTable = matchesElementPosition(false, isTable);
  13731. var isBeforeContentEditableFalse = matchesElementPosition(true, isCefNode);
  13732. var isAfterContentEditableFalse = matchesElementPosition(false, isCefNode);
  13733. var getLastChildren$1 = function (elm) {
  13734. var children = [];
  13735. var rawNode = elm.dom;
  13736. while (rawNode) {
  13737. children.push(SugarElement.fromDom(rawNode));
  13738. rawNode = rawNode.lastChild;
  13739. }
  13740. return children;
  13741. };
  13742. var removeTrailingBr = function (elm) {
  13743. var allBrs = descendants$1(elm, 'br');
  13744. var brs = filter(getLastChildren$1(elm).slice(-1), isBr$1);
  13745. if (allBrs.length === brs.length) {
  13746. each(brs, remove);
  13747. }
  13748. };
  13749. var fillWithPaddingBr = function (elm) {
  13750. empty(elm);
  13751. append(elm, SugarElement.fromHtml('<br data-mce-bogus="1">'));
  13752. };
  13753. var trimBlockTrailingBr = function (elm) {
  13754. lastChild(elm).each(function (lastChild) {
  13755. prevSibling(lastChild).each(function (lastChildPrevSibling) {
  13756. if (isBlock(elm) && isBr$1(lastChild) && isBlock(lastChildPrevSibling)) {
  13757. remove(lastChild);
  13758. }
  13759. });
  13760. });
  13761. };
  13762. var dropLast = function (xs) {
  13763. return xs.slice(0, -1);
  13764. };
  13765. var parentsUntil$1 = function (start, root, predicate) {
  13766. if (contains$2(root, start)) {
  13767. return dropLast(parents(start, function (elm) {
  13768. return predicate(elm) || eq$2(elm, root);
  13769. }));
  13770. } else {
  13771. return [];
  13772. }
  13773. };
  13774. var parents$1 = function (start, root) {
  13775. return parentsUntil$1(start, root, never);
  13776. };
  13777. var parentsAndSelf = function (start, root) {
  13778. return [start].concat(parents$1(start, root));
  13779. };
  13780. var navigateIgnoreEmptyTextNodes = function (forward, root, from) {
  13781. return navigateIgnore(forward, root, from, isEmptyText);
  13782. };
  13783. var getClosestBlock = function (root, pos) {
  13784. return find(parentsAndSelf(SugarElement.fromDom(pos.container()), root), isBlock);
  13785. };
  13786. var isAtBeforeAfterBlockBoundary = function (forward, root, pos) {
  13787. return navigateIgnoreEmptyTextNodes(forward, root.dom, pos).forall(function (newPos) {
  13788. return getClosestBlock(root, pos).fold(function () {
  13789. return isInSameBlock(newPos, pos, root.dom) === false;
  13790. }, function (fromBlock) {
  13791. return isInSameBlock(newPos, pos, root.dom) === false && contains$2(fromBlock, SugarElement.fromDom(newPos.container()));
  13792. });
  13793. });
  13794. };
  13795. var isAtBlockBoundary = function (forward, root, pos) {
  13796. return getClosestBlock(root, pos).fold(function () {
  13797. return navigateIgnoreEmptyTextNodes(forward, root.dom, pos).forall(function (newPos) {
  13798. return isInSameBlock(newPos, pos, root.dom) === false;
  13799. });
  13800. }, function (parent) {
  13801. return navigateIgnoreEmptyTextNodes(forward, parent.dom, pos).isNone();
  13802. });
  13803. };
  13804. var isAtStartOfBlock = curry(isAtBlockBoundary, false);
  13805. var isAtEndOfBlock = curry(isAtBlockBoundary, true);
  13806. var isBeforeBlock = curry(isAtBeforeAfterBlockBoundary, false);
  13807. var isAfterBlock = curry(isAtBeforeAfterBlockBoundary, true);
  13808. var isBr$5 = function (pos) {
  13809. return getElementFromPosition(pos).exists(isBr$1);
  13810. };
  13811. var findBr = function (forward, root, pos) {
  13812. var parentBlocks = filter(parentsAndSelf(SugarElement.fromDom(pos.container()), root), isBlock);
  13813. var scope = head(parentBlocks).getOr(root);
  13814. return fromPosition(forward, scope.dom, pos).filter(isBr$5);
  13815. };
  13816. var isBeforeBr = function (root, pos) {
  13817. return getElementFromPosition(pos).exists(isBr$1) || findBr(true, root, pos).isSome();
  13818. };
  13819. var isAfterBr = function (root, pos) {
  13820. return getElementFromPrevPosition(pos).exists(isBr$1) || findBr(false, root, pos).isSome();
  13821. };
  13822. var findPreviousBr = curry(findBr, false);
  13823. var findNextBr = curry(findBr, true);
  13824. var isInMiddleOfText = function (pos) {
  13825. return CaretPosition.isTextPosition(pos) && !pos.isAtStart() && !pos.isAtEnd();
  13826. };
  13827. var getClosestBlock$1 = function (root, pos) {
  13828. var parentBlocks = filter(parentsAndSelf(SugarElement.fromDom(pos.container()), root), isBlock);
  13829. return head(parentBlocks).getOr(root);
  13830. };
  13831. var hasSpaceBefore = function (root, pos) {
  13832. if (isInMiddleOfText(pos)) {
  13833. return isAfterSpace(pos);
  13834. } else {
  13835. return isAfterSpace(pos) || prevPosition(getClosestBlock$1(root, pos).dom, pos).exists(isAfterSpace);
  13836. }
  13837. };
  13838. var hasSpaceAfter = function (root, pos) {
  13839. if (isInMiddleOfText(pos)) {
  13840. return isBeforeSpace(pos);
  13841. } else {
  13842. return isBeforeSpace(pos) || nextPosition(getClosestBlock$1(root, pos).dom, pos).exists(isBeforeSpace);
  13843. }
  13844. };
  13845. var isPreValue = function (value) {
  13846. return contains([
  13847. 'pre',
  13848. 'pre-wrap'
  13849. ], value);
  13850. };
  13851. var isInPre = function (pos) {
  13852. return getElementFromPosition(pos).bind(function (elm) {
  13853. return closest(elm, isElement);
  13854. }).exists(function (elm) {
  13855. return isPreValue(get$4(elm, 'white-space'));
  13856. });
  13857. };
  13858. var isAtBeginningOfBody = function (root, pos) {
  13859. return prevPosition(root.dom, pos).isNone();
  13860. };
  13861. var isAtEndOfBody = function (root, pos) {
  13862. return nextPosition(root.dom, pos).isNone();
  13863. };
  13864. var isAtLineBoundary = function (root, pos) {
  13865. return isAtBeginningOfBody(root, pos) || isAtEndOfBody(root, pos) || isAtStartOfBlock(root, pos) || isAtEndOfBlock(root, pos) || isAfterBr(root, pos) || isBeforeBr(root, pos);
  13866. };
  13867. var needsToHaveNbsp = function (root, pos) {
  13868. if (isInPre(pos)) {
  13869. return false;
  13870. } else {
  13871. return isAtLineBoundary(root, pos) || hasSpaceBefore(root, pos) || hasSpaceAfter(root, pos);
  13872. }
  13873. };
  13874. var needsToBeNbspLeft = function (root, pos) {
  13875. if (isInPre(pos)) {
  13876. return false;
  13877. } else {
  13878. return isAtStartOfBlock(root, pos) || isBeforeBlock(root, pos) || isAfterBr(root, pos) || hasSpaceBefore(root, pos);
  13879. }
  13880. };
  13881. var leanRight = function (pos) {
  13882. var container = pos.container();
  13883. var offset = pos.offset();
  13884. if (isText$1(container) && offset < container.data.length) {
  13885. return CaretPosition(container, offset + 1);
  13886. } else {
  13887. return pos;
  13888. }
  13889. };
  13890. var needsToBeNbspRight = function (root, pos) {
  13891. if (isInPre(pos)) {
  13892. return false;
  13893. } else {
  13894. return isAtEndOfBlock(root, pos) || isAfterBlock(root, pos) || isBeforeBr(root, pos) || hasSpaceAfter(root, pos);
  13895. }
  13896. };
  13897. var needsToBeNbsp = function (root, pos) {
  13898. return needsToBeNbspLeft(root, pos) || needsToBeNbspRight(root, leanRight(pos));
  13899. };
  13900. var isNbspAt = function (text, offset) {
  13901. return isNbsp(text.charAt(offset));
  13902. };
  13903. var hasNbsp = function (pos) {
  13904. var container = pos.container();
  13905. return isText$1(container) && contains$1(container.data, nbsp);
  13906. };
  13907. var normalizeNbspMiddle = function (text) {
  13908. var chars = text.split('');
  13909. return map(chars, function (chr, i) {
  13910. if (isNbsp(chr) && i > 0 && i < chars.length - 1 && isContent$1(chars[i - 1]) && isContent$1(chars[i + 1])) {
  13911. return ' ';
  13912. } else {
  13913. return chr;
  13914. }
  13915. }).join('');
  13916. };
  13917. var normalizeNbspAtStart = function (root, node) {
  13918. var text = node.data;
  13919. var firstPos = CaretPosition(node, 0);
  13920. if (isNbspAt(text, 0) && !needsToBeNbsp(root, firstPos)) {
  13921. node.data = ' ' + text.slice(1);
  13922. return true;
  13923. } else {
  13924. return false;
  13925. }
  13926. };
  13927. var normalizeNbspInMiddleOfTextNode = function (node) {
  13928. var text = node.data;
  13929. var newText = normalizeNbspMiddle(text);
  13930. if (newText !== text) {
  13931. node.data = newText;
  13932. return true;
  13933. } else {
  13934. return false;
  13935. }
  13936. };
  13937. var normalizeNbspAtEnd = function (root, node) {
  13938. var text = node.data;
  13939. var lastPos = CaretPosition(node, text.length - 1);
  13940. if (isNbspAt(text, text.length - 1) && !needsToBeNbsp(root, lastPos)) {
  13941. node.data = text.slice(0, -1) + ' ';
  13942. return true;
  13943. } else {
  13944. return false;
  13945. }
  13946. };
  13947. var normalizeNbsps = function (root, pos) {
  13948. return Optional.some(pos).filter(hasNbsp).bind(function (pos) {
  13949. var container = pos.container();
  13950. var normalized = normalizeNbspAtStart(root, container) || normalizeNbspInMiddleOfTextNode(container) || normalizeNbspAtEnd(root, container);
  13951. return normalized ? Optional.some(pos) : Optional.none();
  13952. });
  13953. };
  13954. var normalizeNbspsInEditor = function (editor) {
  13955. var root = SugarElement.fromDom(editor.getBody());
  13956. if (editor.selection.isCollapsed()) {
  13957. normalizeNbsps(root, CaretPosition.fromRangeStart(editor.selection.getRng())).each(function (pos) {
  13958. editor.selection.setRng(pos.toRange());
  13959. });
  13960. }
  13961. };
  13962. var normalizeContent = function (content, isStartOfContent, isEndOfContent) {
  13963. var result = foldl(content, function (acc, c) {
  13964. if (isWhiteSpace$1(c) || isNbsp(c)) {
  13965. if (acc.previousCharIsSpace || acc.str === '' && isStartOfContent || acc.str.length === content.length - 1 && isEndOfContent) {
  13966. return {
  13967. previousCharIsSpace: false,
  13968. str: acc.str + nbsp
  13969. };
  13970. } else {
  13971. return {
  13972. previousCharIsSpace: true,
  13973. str: acc.str + ' '
  13974. };
  13975. }
  13976. } else {
  13977. return {
  13978. previousCharIsSpace: false,
  13979. str: acc.str + c
  13980. };
  13981. }
  13982. }, {
  13983. previousCharIsSpace: false,
  13984. str: ''
  13985. });
  13986. return result.str;
  13987. };
  13988. var normalize$1 = function (node, offset, count) {
  13989. if (count === 0) {
  13990. return;
  13991. }
  13992. var elm = SugarElement.fromDom(node);
  13993. var root = ancestor(elm, isBlock).getOr(elm);
  13994. var whitespace = node.data.slice(offset, offset + count);
  13995. var isEndOfContent = offset + count >= node.data.length && needsToBeNbspRight(root, CaretPosition$1(node, node.data.length));
  13996. var isStartOfContent = offset === 0 && needsToBeNbspLeft(root, CaretPosition$1(node, 0));
  13997. node.replaceData(offset, count, normalizeContent(whitespace, isStartOfContent, isEndOfContent));
  13998. };
  13999. var normalizeWhitespaceAfter = function (node, offset) {
  14000. var content = node.data.slice(offset);
  14001. var whitespaceCount = content.length - lTrim(content).length;
  14002. return normalize$1(node, offset, whitespaceCount);
  14003. };
  14004. var normalizeWhitespaceBefore = function (node, offset) {
  14005. var content = node.data.slice(0, offset);
  14006. var whitespaceCount = content.length - rTrim(content).length;
  14007. return normalize$1(node, offset - whitespaceCount, whitespaceCount);
  14008. };
  14009. var mergeTextNodes = function (prevNode, nextNode, normalizeWhitespace, mergeToPrev) {
  14010. if (mergeToPrev === void 0) {
  14011. mergeToPrev = true;
  14012. }
  14013. var whitespaceOffset = rTrim(prevNode.data).length;
  14014. var newNode = mergeToPrev ? prevNode : nextNode;
  14015. var removeNode = mergeToPrev ? nextNode : prevNode;
  14016. if (mergeToPrev) {
  14017. newNode.appendData(removeNode.data);
  14018. } else {
  14019. newNode.insertData(0, removeNode.data);
  14020. }
  14021. remove(SugarElement.fromDom(removeNode));
  14022. if (normalizeWhitespace) {
  14023. normalizeWhitespaceAfter(newNode, whitespaceOffset);
  14024. }
  14025. return newNode;
  14026. };
  14027. var needsReposition = function (pos, elm) {
  14028. var container = pos.container();
  14029. var offset = pos.offset();
  14030. return CaretPosition$1.isTextPosition(pos) === false && container === elm.parentNode && offset > CaretPosition$1.before(elm).offset();
  14031. };
  14032. var reposition = function (elm, pos) {
  14033. return needsReposition(pos, elm) ? CaretPosition$1(pos.container(), pos.offset() - 1) : pos;
  14034. };
  14035. var beforeOrStartOf = function (node) {
  14036. return isText$1(node) ? CaretPosition$1(node, 0) : CaretPosition$1.before(node);
  14037. };
  14038. var afterOrEndOf = function (node) {
  14039. return isText$1(node) ? CaretPosition$1(node, node.data.length) : CaretPosition$1.after(node);
  14040. };
  14041. var getPreviousSiblingCaretPosition = function (elm) {
  14042. if (isCaretCandidate(elm.previousSibling)) {
  14043. return Optional.some(afterOrEndOf(elm.previousSibling));
  14044. } else {
  14045. return elm.previousSibling ? lastPositionIn(elm.previousSibling) : Optional.none();
  14046. }
  14047. };
  14048. var getNextSiblingCaretPosition = function (elm) {
  14049. if (isCaretCandidate(elm.nextSibling)) {
  14050. return Optional.some(beforeOrStartOf(elm.nextSibling));
  14051. } else {
  14052. return elm.nextSibling ? firstPositionIn(elm.nextSibling) : Optional.none();
  14053. }
  14054. };
  14055. var findCaretPositionBackwardsFromElm = function (rootElement, elm) {
  14056. var startPosition = CaretPosition$1.before(elm.previousSibling ? elm.previousSibling : elm.parentNode);
  14057. return prevPosition(rootElement, startPosition).fold(function () {
  14058. return nextPosition(rootElement, CaretPosition$1.after(elm));
  14059. }, Optional.some);
  14060. };
  14061. var findCaretPositionForwardsFromElm = function (rootElement, elm) {
  14062. return nextPosition(rootElement, CaretPosition$1.after(elm)).fold(function () {
  14063. return prevPosition(rootElement, CaretPosition$1.before(elm));
  14064. }, Optional.some);
  14065. };
  14066. var findCaretPositionBackwards = function (rootElement, elm) {
  14067. return getPreviousSiblingCaretPosition(elm).orThunk(function () {
  14068. return getNextSiblingCaretPosition(elm);
  14069. }).orThunk(function () {
  14070. return findCaretPositionBackwardsFromElm(rootElement, elm);
  14071. });
  14072. };
  14073. var findCaretPositionForward = function (rootElement, elm) {
  14074. return getNextSiblingCaretPosition(elm).orThunk(function () {
  14075. return getPreviousSiblingCaretPosition(elm);
  14076. }).orThunk(function () {
  14077. return findCaretPositionForwardsFromElm(rootElement, elm);
  14078. });
  14079. };
  14080. var findCaretPosition$1 = function (forward, rootElement, elm) {
  14081. return forward ? findCaretPositionForward(rootElement, elm) : findCaretPositionBackwards(rootElement, elm);
  14082. };
  14083. var findCaretPosOutsideElmAfterDelete = function (forward, rootElement, elm) {
  14084. return findCaretPosition$1(forward, rootElement, elm).map(curry(reposition, elm));
  14085. };
  14086. var setSelection = function (editor, forward, pos) {
  14087. pos.fold(function () {
  14088. editor.focus();
  14089. }, function (pos) {
  14090. editor.selection.setRng(pos.toRange(), forward);
  14091. });
  14092. };
  14093. var eqRawNode = function (rawNode) {
  14094. return function (elm) {
  14095. return elm.dom === rawNode;
  14096. };
  14097. };
  14098. var isBlock$2 = function (editor, elm) {
  14099. return elm && has(editor.schema.getBlockElements(), name(elm));
  14100. };
  14101. var paddEmptyBlock = function (elm) {
  14102. if (isEmpty(elm)) {
  14103. var br = SugarElement.fromHtml('<br data-mce-bogus="1">');
  14104. empty(elm);
  14105. append(elm, br);
  14106. return Optional.some(CaretPosition$1.before(br.dom));
  14107. } else {
  14108. return Optional.none();
  14109. }
  14110. };
  14111. var deleteNormalized = function (elm, afterDeletePosOpt, normalizeWhitespace) {
  14112. var prevTextOpt = prevSibling(elm).filter(isText);
  14113. var nextTextOpt = nextSibling(elm).filter(isText);
  14114. remove(elm);
  14115. return lift3(prevTextOpt, nextTextOpt, afterDeletePosOpt, function (prev, next, pos) {
  14116. var prevNode = prev.dom, nextNode = next.dom;
  14117. var offset = prevNode.data.length;
  14118. mergeTextNodes(prevNode, nextNode, normalizeWhitespace);
  14119. return pos.container() === nextNode ? CaretPosition$1(prevNode, offset) : pos;
  14120. }).orThunk(function () {
  14121. if (normalizeWhitespace) {
  14122. prevTextOpt.each(function (elm) {
  14123. return normalizeWhitespaceBefore(elm.dom, elm.dom.length);
  14124. });
  14125. nextTextOpt.each(function (elm) {
  14126. return normalizeWhitespaceAfter(elm.dom, 0);
  14127. });
  14128. }
  14129. return afterDeletePosOpt;
  14130. });
  14131. };
  14132. var isInlineElement = function (editor, element) {
  14133. return has(editor.schema.getTextInlineElements(), name(element));
  14134. };
  14135. var deleteElement = function (editor, forward, elm, moveCaret) {
  14136. if (moveCaret === void 0) {
  14137. moveCaret = true;
  14138. }
  14139. var afterDeletePos = findCaretPosOutsideElmAfterDelete(forward, editor.getBody(), elm.dom);
  14140. var parentBlock = ancestor(elm, curry(isBlock$2, editor), eqRawNode(editor.getBody()));
  14141. var normalizedAfterDeletePos = deleteNormalized(elm, afterDeletePos, isInlineElement(editor, elm));
  14142. if (editor.dom.isEmpty(editor.getBody())) {
  14143. editor.setContent('');
  14144. editor.selection.setCursorLocation();
  14145. } else {
  14146. parentBlock.bind(paddEmptyBlock).fold(function () {
  14147. if (moveCaret) {
  14148. setSelection(editor, forward, normalizedAfterDeletePos);
  14149. }
  14150. }, function (paddPos) {
  14151. if (moveCaret) {
  14152. setSelection(editor, forward, Optional.some(paddPos));
  14153. }
  14154. });
  14155. }
  14156. };
  14157. var tableCellRng = function (start, end) {
  14158. return {
  14159. start: start,
  14160. end: end
  14161. };
  14162. };
  14163. var tableSelection = function (rng, table, cells) {
  14164. return {
  14165. rng: rng,
  14166. table: table,
  14167. cells: cells
  14168. };
  14169. };
  14170. var deleteAction = Adt.generate([
  14171. { removeTable: ['element'] },
  14172. { emptyCells: ['cells'] },
  14173. {
  14174. deleteCellSelection: [
  14175. 'rng',
  14176. 'cell'
  14177. ]
  14178. }
  14179. ]);
  14180. var isRootFromElement = function (root) {
  14181. return function (cur) {
  14182. return eq$2(root, cur);
  14183. };
  14184. };
  14185. var getClosestCell = function (container, isRoot) {
  14186. return closest$1(SugarElement.fromDom(container), 'td,th', isRoot);
  14187. };
  14188. var getClosestTable = function (cell, isRoot) {
  14189. return ancestor$1(cell, 'table', isRoot);
  14190. };
  14191. var isExpandedCellRng = function (cellRng) {
  14192. return !eq$2(cellRng.start, cellRng.end);
  14193. };
  14194. var getTableFromCellRng = function (cellRng, isRoot) {
  14195. return getClosestTable(cellRng.start, isRoot).bind(function (startParentTable) {
  14196. return getClosestTable(cellRng.end, isRoot).bind(function (endParentTable) {
  14197. return someIf(eq$2(startParentTable, endParentTable), startParentTable);
  14198. });
  14199. });
  14200. };
  14201. var isSingleCellTable = function (cellRng, isRoot) {
  14202. return !isExpandedCellRng(cellRng) && getTableFromCellRng(cellRng, isRoot).exists(function (table) {
  14203. var rows = table.dom.rows;
  14204. return rows.length === 1 && rows[0].cells.length === 1;
  14205. });
  14206. };
  14207. var getTableCells = function (table) {
  14208. return descendants$1(table, 'td,th');
  14209. };
  14210. var getCellRng = function (rng, isRoot) {
  14211. var startCell = getClosestCell(rng.startContainer, isRoot);
  14212. var endCell = getClosestCell(rng.endContainer, isRoot);
  14213. return lift2(startCell, endCell, tableCellRng);
  14214. };
  14215. var getCellRangeFromStartTable = function (cellRng, isRoot) {
  14216. return getClosestTable(cellRng.start, isRoot).bind(function (table) {
  14217. return last(getTableCells(table)).map(function (endCell) {
  14218. return tableCellRng(cellRng.start, endCell);
  14219. });
  14220. });
  14221. };
  14222. var partialSelection = function (isRoot, rng) {
  14223. var startCell = getClosestCell(rng.startContainer, isRoot);
  14224. var endCell = getClosestCell(rng.endContainer, isRoot);
  14225. return rng.collapsed ? Optional.none() : lift2(startCell, endCell, tableCellRng).fold(function () {
  14226. return startCell.fold(function () {
  14227. return endCell.bind(function (endCell) {
  14228. return getClosestTable(endCell, isRoot).bind(function (table) {
  14229. return head(getTableCells(table)).map(function (startCell) {
  14230. return tableCellRng(startCell, endCell);
  14231. });
  14232. });
  14233. });
  14234. }, function (startCell) {
  14235. return getClosestTable(startCell, isRoot).bind(function (table) {
  14236. return last(getTableCells(table)).map(function (endCell) {
  14237. return tableCellRng(startCell, endCell);
  14238. });
  14239. });
  14240. });
  14241. }, function (cellRng) {
  14242. return isWithinSameTable(isRoot, cellRng) ? Optional.none() : getCellRangeFromStartTable(cellRng, isRoot);
  14243. });
  14244. };
  14245. var isWithinSameTable = function (isRoot, cellRng) {
  14246. return getTableFromCellRng(cellRng, isRoot).isSome();
  14247. };
  14248. var getTableSelectionFromCellRng = function (cellRng, isRoot) {
  14249. return getTableFromCellRng(cellRng, isRoot).map(function (table) {
  14250. return tableSelection(cellRng, table, getTableCells(table));
  14251. });
  14252. };
  14253. var getTableSelection = function (optCellRng, rng, isRoot) {
  14254. return optCellRng.filter(function (cellRng) {
  14255. return isExpandedCellRng(cellRng) && isWithinSameTable(isRoot, cellRng);
  14256. }).orThunk(function () {
  14257. return partialSelection(isRoot, rng);
  14258. }).bind(function (cRng) {
  14259. return getTableSelectionFromCellRng(cRng, isRoot);
  14260. });
  14261. };
  14262. var getCellIndex = function (cells, cell) {
  14263. return findIndex(cells, function (x) {
  14264. return eq$2(x, cell);
  14265. });
  14266. };
  14267. var getSelectedCells = function (tableSelection) {
  14268. return lift2(getCellIndex(tableSelection.cells, tableSelection.rng.start), getCellIndex(tableSelection.cells, tableSelection.rng.end), function (startIndex, endIndex) {
  14269. return tableSelection.cells.slice(startIndex, endIndex + 1);
  14270. });
  14271. };
  14272. var isSingleCellTableContentSelected = function (optCellRng, rng, isRoot) {
  14273. return optCellRng.filter(function (cellRng) {
  14274. return isSingleCellTable(cellRng, isRoot) && hasAllContentsSelected(cellRng.start, rng);
  14275. }).map(function (cellRng) {
  14276. return cellRng.start;
  14277. });
  14278. };
  14279. var getAction = function (tableSelection) {
  14280. return getSelectedCells(tableSelection).map(function (selected) {
  14281. var cells = tableSelection.cells;
  14282. return selected.length === cells.length ? deleteAction.removeTable(tableSelection.table) : deleteAction.emptyCells(selected);
  14283. });
  14284. };
  14285. var getActionFromRange = function (root, rng) {
  14286. var isRoot = isRootFromElement(root);
  14287. var optCellRng = getCellRng(rng, isRoot);
  14288. return isSingleCellTableContentSelected(optCellRng, rng, isRoot).map(function (cell) {
  14289. return deleteAction.deleteCellSelection(rng, cell);
  14290. }).orThunk(function () {
  14291. return getTableSelection(optCellRng, rng, isRoot).bind(getAction);
  14292. });
  14293. };
  14294. var freefallRtl = function (root) {
  14295. var child = isComment(root) ? prevSibling(root) : lastChild(root);
  14296. return child.bind(freefallRtl).orThunk(function () {
  14297. return Optional.some(root);
  14298. });
  14299. };
  14300. var emptyCells = function (editor, cells) {
  14301. each(cells, fillWithPaddingBr);
  14302. editor.selection.setCursorLocation(cells[0].dom, 0);
  14303. return true;
  14304. };
  14305. var deleteCellContents = function (editor, rng, cell) {
  14306. rng.deleteContents();
  14307. var lastNode = freefallRtl(cell).getOr(cell);
  14308. var lastBlock = SugarElement.fromDom(editor.dom.getParent(lastNode.dom, editor.dom.isBlock));
  14309. if (isEmpty(lastBlock)) {
  14310. fillWithPaddingBr(lastBlock);
  14311. editor.selection.setCursorLocation(lastBlock.dom, 0);
  14312. }
  14313. if (!eq$2(cell, lastBlock)) {
  14314. var additionalCleanupNodes = parent(lastBlock).is(cell) ? [] : siblings(lastBlock);
  14315. each(additionalCleanupNodes.concat(children(cell)), function (node) {
  14316. if (!eq$2(node, lastBlock) && !contains$2(node, lastBlock)) {
  14317. remove(node);
  14318. }
  14319. });
  14320. }
  14321. return true;
  14322. };
  14323. var deleteTableElement = function (editor, table) {
  14324. deleteElement(editor, false, table);
  14325. return true;
  14326. };
  14327. var deleteCellRange = function (editor, rootElm, rng) {
  14328. return getActionFromRange(rootElm, rng).map(function (action) {
  14329. return action.fold(curry(deleteTableElement, editor), curry(emptyCells, editor), curry(deleteCellContents, editor));
  14330. });
  14331. };
  14332. var deleteCaptionRange = function (editor, caption) {
  14333. return emptyElement(editor, caption);
  14334. };
  14335. var deleteTableRange = function (editor, rootElm, rng, startElm) {
  14336. return getParentCaption(rootElm, startElm).fold(function () {
  14337. return deleteCellRange(editor, rootElm, rng);
  14338. }, function (caption) {
  14339. return deleteCaptionRange(editor, caption);
  14340. }).getOr(false);
  14341. };
  14342. var deleteRange = function (editor, startElm) {
  14343. var rootNode = SugarElement.fromDom(editor.getBody());
  14344. var rng = editor.selection.getRng();
  14345. var selectedCells = getCellsFromEditor(editor);
  14346. return selectedCells.length !== 0 ? emptyCells(editor, selectedCells) : deleteTableRange(editor, rootNode, rng, startElm);
  14347. };
  14348. var getParentCell = function (rootElm, elm) {
  14349. return find(parentsAndSelf(elm, rootElm), isTableCell$1);
  14350. };
  14351. var getParentCaption = function (rootElm, elm) {
  14352. return find(parentsAndSelf(elm, rootElm), function (elm) {
  14353. return name(elm) === 'caption';
  14354. });
  14355. };
  14356. var deleteBetweenCells = function (editor, rootElm, forward, fromCell, from) {
  14357. return navigate(forward, editor.getBody(), from).bind(function (to) {
  14358. return getParentCell(rootElm, SugarElement.fromDom(to.getNode())).map(function (toCell) {
  14359. return eq$2(toCell, fromCell) === false;
  14360. });
  14361. });
  14362. };
  14363. var emptyElement = function (editor, elm) {
  14364. fillWithPaddingBr(elm);
  14365. editor.selection.setCursorLocation(elm.dom, 0);
  14366. return Optional.some(true);
  14367. };
  14368. var isDeleteOfLastCharPos = function (fromCaption, forward, from, to) {
  14369. return firstPositionIn(fromCaption.dom).bind(function (first) {
  14370. return lastPositionIn(fromCaption.dom).map(function (last) {
  14371. return forward ? from.isEqual(first) && to.isEqual(last) : from.isEqual(last) && to.isEqual(first);
  14372. });
  14373. }).getOr(true);
  14374. };
  14375. var emptyCaretCaption = function (editor, elm) {
  14376. return emptyElement(editor, elm);
  14377. };
  14378. var validateCaretCaption = function (rootElm, fromCaption, to) {
  14379. return getParentCaption(rootElm, SugarElement.fromDom(to.getNode())).map(function (toCaption) {
  14380. return eq$2(toCaption, fromCaption) === false;
  14381. });
  14382. };
  14383. var deleteCaretInsideCaption = function (editor, rootElm, forward, fromCaption, from) {
  14384. return navigate(forward, editor.getBody(), from).bind(function (to) {
  14385. return isDeleteOfLastCharPos(fromCaption, forward, from, to) ? emptyCaretCaption(editor, fromCaption) : validateCaretCaption(rootElm, fromCaption, to);
  14386. }).or(Optional.some(true));
  14387. };
  14388. var deleteCaretCells = function (editor, forward, rootElm, startElm) {
  14389. var from = CaretPosition$1.fromRangeStart(editor.selection.getRng());
  14390. return getParentCell(rootElm, startElm).bind(function (fromCell) {
  14391. return isEmpty(fromCell) ? emptyElement(editor, fromCell) : deleteBetweenCells(editor, rootElm, forward, fromCell, from);
  14392. }).getOr(false);
  14393. };
  14394. var deleteCaretCaption = function (editor, forward, rootElm, fromCaption) {
  14395. var from = CaretPosition$1.fromRangeStart(editor.selection.getRng());
  14396. return isEmpty(fromCaption) ? emptyElement(editor, fromCaption) : deleteCaretInsideCaption(editor, rootElm, forward, fromCaption, from);
  14397. };
  14398. var isNearTable = function (forward, pos) {
  14399. return forward ? isBeforeTable(pos) : isAfterTable(pos);
  14400. };
  14401. var isBeforeOrAfterTable = function (editor, forward) {
  14402. var fromPos = CaretPosition$1.fromRangeStart(editor.selection.getRng());
  14403. return isNearTable(forward, fromPos) || fromPosition(forward, editor.getBody(), fromPos).exists(function (pos) {
  14404. return isNearTable(forward, pos);
  14405. });
  14406. };
  14407. var deleteCaret = function (editor, forward, startElm) {
  14408. var rootElm = SugarElement.fromDom(editor.getBody());
  14409. return getParentCaption(rootElm, startElm).fold(function () {
  14410. return deleteCaretCells(editor, forward, rootElm, startElm) || isBeforeOrAfterTable(editor, forward);
  14411. }, function (fromCaption) {
  14412. return deleteCaretCaption(editor, forward, rootElm, fromCaption).getOr(false);
  14413. });
  14414. };
  14415. var backspaceDelete = function (editor, forward) {
  14416. var startElm = SugarElement.fromDom(editor.selection.getStart(true));
  14417. var cells = getCellsFromEditor(editor);
  14418. return editor.selection.isCollapsed() && cells.length === 0 ? deleteCaret(editor, forward, startElm) : deleteRange(editor, startElm);
  14419. };
  14420. var createRange$1 = function (sc, so, ec, eo) {
  14421. var rng = document.createRange();
  14422. rng.setStart(sc, so);
  14423. rng.setEnd(ec, eo);
  14424. return rng;
  14425. };
  14426. var normalizeBlockSelectionRange = function (rng) {
  14427. var startPos = CaretPosition$1.fromRangeStart(rng);
  14428. var endPos = CaretPosition$1.fromRangeEnd(rng);
  14429. var rootNode = rng.commonAncestorContainer;
  14430. return fromPosition(false, rootNode, endPos).map(function (newEndPos) {
  14431. if (!isInSameBlock(startPos, endPos, rootNode) && isInSameBlock(startPos, newEndPos, rootNode)) {
  14432. return createRange$1(startPos.container(), startPos.offset(), newEndPos.container(), newEndPos.offset());
  14433. } else {
  14434. return rng;
  14435. }
  14436. }).getOr(rng);
  14437. };
  14438. var normalize$2 = function (rng) {
  14439. return rng.collapsed ? rng : normalizeBlockSelectionRange(rng);
  14440. };
  14441. var hasOnlyOneChild = function (node) {
  14442. return node.firstChild && node.firstChild === node.lastChild;
  14443. };
  14444. var isPaddingNode = function (node) {
  14445. return node.name === 'br' || node.value === nbsp;
  14446. };
  14447. var isPaddedEmptyBlock = function (schema, node) {
  14448. var blockElements = schema.getBlockElements();
  14449. return blockElements[node.name] && hasOnlyOneChild(node) && isPaddingNode(node.firstChild);
  14450. };
  14451. var isEmptyFragmentElement = function (schema, node) {
  14452. var nonEmptyElements = schema.getNonEmptyElements();
  14453. return node && (node.isEmpty(nonEmptyElements) || isPaddedEmptyBlock(schema, node));
  14454. };
  14455. var isListFragment = function (schema, fragment) {
  14456. var firstChild = fragment.firstChild;
  14457. var lastChild = fragment.lastChild;
  14458. if (firstChild && firstChild.name === 'meta') {
  14459. firstChild = firstChild.next;
  14460. }
  14461. if (lastChild && lastChild.attr('id') === 'mce_marker') {
  14462. lastChild = lastChild.prev;
  14463. }
  14464. if (isEmptyFragmentElement(schema, lastChild)) {
  14465. lastChild = lastChild.prev;
  14466. }
  14467. if (!firstChild || firstChild !== lastChild) {
  14468. return false;
  14469. }
  14470. return firstChild.name === 'ul' || firstChild.name === 'ol';
  14471. };
  14472. var cleanupDomFragment = function (domFragment) {
  14473. var firstChild = domFragment.firstChild;
  14474. var lastChild = domFragment.lastChild;
  14475. if (firstChild && firstChild.nodeName === 'META') {
  14476. firstChild.parentNode.removeChild(firstChild);
  14477. }
  14478. if (lastChild && lastChild.id === 'mce_marker') {
  14479. lastChild.parentNode.removeChild(lastChild);
  14480. }
  14481. return domFragment;
  14482. };
  14483. var toDomFragment = function (dom, serializer, fragment) {
  14484. var html = serializer.serialize(fragment);
  14485. var domFragment = dom.createFragment(html);
  14486. return cleanupDomFragment(domFragment);
  14487. };
  14488. var listItems$1 = function (elm) {
  14489. return Tools.grep(elm.childNodes, function (child) {
  14490. return child.nodeName === 'LI';
  14491. });
  14492. };
  14493. var isPadding = function (node) {
  14494. return node.data === nbsp || isBr(node);
  14495. };
  14496. var isListItemPadded = function (node) {
  14497. return node && node.firstChild && node.firstChild === node.lastChild && isPadding(node.firstChild);
  14498. };
  14499. var isEmptyOrPadded = function (elm) {
  14500. return !elm.firstChild || isListItemPadded(elm);
  14501. };
  14502. var trimListItems = function (elms) {
  14503. return elms.length > 0 && isEmptyOrPadded(elms[elms.length - 1]) ? elms.slice(0, -1) : elms;
  14504. };
  14505. var getParentLi = function (dom, node) {
  14506. var parentBlock = dom.getParent(node, dom.isBlock);
  14507. return parentBlock && parentBlock.nodeName === 'LI' ? parentBlock : null;
  14508. };
  14509. var isParentBlockLi = function (dom, node) {
  14510. return !!getParentLi(dom, node);
  14511. };
  14512. var getSplit = function (parentNode, rng) {
  14513. var beforeRng = rng.cloneRange();
  14514. var afterRng = rng.cloneRange();
  14515. beforeRng.setStartBefore(parentNode);
  14516. afterRng.setEndAfter(parentNode);
  14517. return [
  14518. beforeRng.cloneContents(),
  14519. afterRng.cloneContents()
  14520. ];
  14521. };
  14522. var findFirstIn = function (node, rootNode) {
  14523. var caretPos = CaretPosition$1.before(node);
  14524. var caretWalker = CaretWalker(rootNode);
  14525. var newCaretPos = caretWalker.next(caretPos);
  14526. return newCaretPos ? newCaretPos.toRange() : null;
  14527. };
  14528. var findLastOf = function (node, rootNode) {
  14529. var caretPos = CaretPosition$1.after(node);
  14530. var caretWalker = CaretWalker(rootNode);
  14531. var newCaretPos = caretWalker.prev(caretPos);
  14532. return newCaretPos ? newCaretPos.toRange() : null;
  14533. };
  14534. var insertMiddle = function (target, elms, rootNode, rng) {
  14535. var parts = getSplit(target, rng);
  14536. var parentElm = target.parentNode;
  14537. parentElm.insertBefore(parts[0], target);
  14538. Tools.each(elms, function (li) {
  14539. parentElm.insertBefore(li, target);
  14540. });
  14541. parentElm.insertBefore(parts[1], target);
  14542. parentElm.removeChild(target);
  14543. return findLastOf(elms[elms.length - 1], rootNode);
  14544. };
  14545. var insertBefore = function (target, elms, rootNode) {
  14546. var parentElm = target.parentNode;
  14547. Tools.each(elms, function (elm) {
  14548. parentElm.insertBefore(elm, target);
  14549. });
  14550. return findFirstIn(target, rootNode);
  14551. };
  14552. var insertAfter = function (target, elms, rootNode, dom) {
  14553. dom.insertAfter(elms.reverse(), target);
  14554. return findLastOf(elms[0], rootNode);
  14555. };
  14556. var insertAtCaret = function (serializer, dom, rng, fragment) {
  14557. var domFragment = toDomFragment(dom, serializer, fragment);
  14558. var liTarget = getParentLi(dom, rng.startContainer);
  14559. var liElms = trimListItems(listItems$1(domFragment.firstChild));
  14560. var BEGINNING = 1, END = 2;
  14561. var rootNode = dom.getRoot();
  14562. var isAt = function (location) {
  14563. var caretPos = CaretPosition$1.fromRangeStart(rng);
  14564. var caretWalker = CaretWalker(dom.getRoot());
  14565. var newPos = location === BEGINNING ? caretWalker.prev(caretPos) : caretWalker.next(caretPos);
  14566. return newPos ? getParentLi(dom, newPos.getNode()) !== liTarget : true;
  14567. };
  14568. if (isAt(BEGINNING)) {
  14569. return insertBefore(liTarget, liElms, rootNode);
  14570. } else if (isAt(END)) {
  14571. return insertAfter(liTarget, liElms, rootNode, dom);
  14572. }
  14573. return insertMiddle(liTarget, liElms, rootNode, rng);
  14574. };
  14575. var trimOrPadLeftRight = function (dom, rng, html) {
  14576. var root = SugarElement.fromDom(dom.getRoot());
  14577. if (needsToBeNbspLeft(root, CaretPosition$1.fromRangeStart(rng))) {
  14578. html = html.replace(/^ /, '&nbsp;');
  14579. } else {
  14580. html = html.replace(/^&nbsp;/, ' ');
  14581. }
  14582. if (needsToBeNbspRight(root, CaretPosition$1.fromRangeEnd(rng))) {
  14583. html = html.replace(/(&nbsp;| )(<br( \/)>)?$/, '&nbsp;');
  14584. } else {
  14585. html = html.replace(/&nbsp;(<br( \/)?>)?$/, ' ');
  14586. }
  14587. return html;
  14588. };
  14589. var isTableCell$4 = isTableCell;
  14590. var isTableCellContentSelected = function (dom, rng, cell) {
  14591. if (cell !== null) {
  14592. var endCell = dom.getParent(rng.endContainer, isTableCell$4);
  14593. return cell === endCell && hasAllContentsSelected(SugarElement.fromDom(cell), rng);
  14594. } else {
  14595. return false;
  14596. }
  14597. };
  14598. var validInsertion = function (editor, value, parentNode) {
  14599. if (parentNode.getAttribute('data-mce-bogus') === 'all') {
  14600. parentNode.parentNode.insertBefore(editor.dom.createFragment(value), parentNode);
  14601. } else {
  14602. var node = parentNode.firstChild;
  14603. var node2 = parentNode.lastChild;
  14604. if (!node || node === node2 && node.nodeName === 'BR') {
  14605. editor.dom.setHTML(parentNode, value);
  14606. } else {
  14607. editor.selection.setContent(value);
  14608. }
  14609. }
  14610. };
  14611. var trimBrsFromTableCell = function (dom, elm) {
  14612. Optional.from(dom.getParent(elm, 'td,th')).map(SugarElement.fromDom).each(trimBlockTrailingBr);
  14613. };
  14614. var reduceInlineTextElements = function (editor, merge) {
  14615. var textInlineElements = editor.schema.getTextInlineElements();
  14616. var dom = editor.dom;
  14617. if (merge) {
  14618. var root_1 = editor.getBody(), elementUtils_1 = new ElementUtils(dom);
  14619. Tools.each(dom.select('*[data-mce-fragment]'), function (node) {
  14620. for (var testNode = node.parentNode; testNode && testNode !== root_1; testNode = testNode.parentNode) {
  14621. if (textInlineElements[node.nodeName.toLowerCase()] && elementUtils_1.compare(testNode, node)) {
  14622. dom.remove(node, true);
  14623. }
  14624. }
  14625. });
  14626. }
  14627. };
  14628. var markFragmentElements = function (fragment) {
  14629. var node = fragment;
  14630. while (node = node.walk()) {
  14631. if (node.type === 1) {
  14632. node.attr('data-mce-fragment', '1');
  14633. }
  14634. }
  14635. };
  14636. var unmarkFragmentElements = function (elm) {
  14637. Tools.each(elm.getElementsByTagName('*'), function (elm) {
  14638. elm.removeAttribute('data-mce-fragment');
  14639. });
  14640. };
  14641. var isPartOfFragment = function (node) {
  14642. return !!node.getAttribute('data-mce-fragment');
  14643. };
  14644. var canHaveChildren = function (editor, node) {
  14645. return node && !editor.schema.getShortEndedElements()[node.nodeName];
  14646. };
  14647. var moveSelectionToMarker = function (editor, marker) {
  14648. var nextRng;
  14649. var dom = editor.dom, selection = editor.selection;
  14650. var node2;
  14651. var getContentEditableFalseParent = function (node) {
  14652. var root = editor.getBody();
  14653. for (; node && node !== root; node = node.parentNode) {
  14654. if (dom.getContentEditable(node) === 'false') {
  14655. return node;
  14656. }
  14657. }
  14658. return null;
  14659. };
  14660. if (!marker) {
  14661. return;
  14662. }
  14663. selection.scrollIntoView(marker);
  14664. var parentEditableFalseElm = getContentEditableFalseParent(marker);
  14665. if (parentEditableFalseElm) {
  14666. dom.remove(marker);
  14667. selection.select(parentEditableFalseElm);
  14668. return;
  14669. }
  14670. var rng = dom.createRng();
  14671. var node = marker.previousSibling;
  14672. if (node && node.nodeType === 3) {
  14673. rng.setStart(node, node.nodeValue.length);
  14674. if (!Env.ie) {
  14675. node2 = marker.nextSibling;
  14676. if (node2 && node2.nodeType === 3) {
  14677. node.appendData(node2.data);
  14678. node2.parentNode.removeChild(node2);
  14679. }
  14680. }
  14681. } else {
  14682. rng.setStartBefore(marker);
  14683. rng.setEndBefore(marker);
  14684. }
  14685. var findNextCaretRng = function (rng) {
  14686. var caretPos = CaretPosition$1.fromRangeStart(rng);
  14687. var caretWalker = CaretWalker(editor.getBody());
  14688. caretPos = caretWalker.next(caretPos);
  14689. if (caretPos) {
  14690. return caretPos.toRange();
  14691. }
  14692. };
  14693. var parentBlock = dom.getParent(marker, dom.isBlock);
  14694. dom.remove(marker);
  14695. if (parentBlock && dom.isEmpty(parentBlock)) {
  14696. editor.$(parentBlock).empty();
  14697. rng.setStart(parentBlock, 0);
  14698. rng.setEnd(parentBlock, 0);
  14699. if (!isTableCell$4(parentBlock) && !isPartOfFragment(parentBlock) && (nextRng = findNextCaretRng(rng))) {
  14700. rng = nextRng;
  14701. dom.remove(parentBlock);
  14702. } else {
  14703. dom.add(parentBlock, dom.create('br', { 'data-mce-bogus': '1' }));
  14704. }
  14705. }
  14706. selection.setRng(rng);
  14707. };
  14708. var deleteSelectedContent = function (editor) {
  14709. var dom = editor.dom;
  14710. var rng = normalize$2(editor.selection.getRng());
  14711. editor.selection.setRng(rng);
  14712. var startCell = dom.getParent(rng.startContainer, isTableCell$4);
  14713. if (isTableCellContentSelected(dom, rng, startCell)) {
  14714. deleteCellContents(editor, rng, SugarElement.fromDom(startCell));
  14715. } else {
  14716. editor.getDoc().execCommand('Delete', false, null);
  14717. }
  14718. };
  14719. var insertHtmlAtCaret = function (editor, value, details) {
  14720. var parentNode, rootNode, args;
  14721. var marker, rng, node;
  14722. var selection = editor.selection, dom = editor.dom;
  14723. if (/^ | $/.test(value)) {
  14724. value = trimOrPadLeftRight(dom, selection.getRng(), value);
  14725. }
  14726. var parser = editor.parser;
  14727. var merge = details.merge;
  14728. var serializer = HtmlSerializer({ validate: shouldValidate(editor) }, editor.schema);
  14729. var bookmarkHtml = '<span id="mce_marker" data-mce-type="bookmark">&#xFEFF;</span>';
  14730. args = {
  14731. content: value,
  14732. format: 'html',
  14733. selection: true,
  14734. paste: details.paste
  14735. };
  14736. args = editor.fire('BeforeSetContent', args);
  14737. if (args.isDefaultPrevented()) {
  14738. editor.fire('SetContent', {
  14739. content: args.content,
  14740. format: 'html',
  14741. selection: true,
  14742. paste: details.paste
  14743. });
  14744. return;
  14745. }
  14746. value = args.content;
  14747. if (value.indexOf('{$caret}') === -1) {
  14748. value += '{$caret}';
  14749. }
  14750. value = value.replace(/\{\$caret\}/, bookmarkHtml);
  14751. rng = selection.getRng();
  14752. var caretElement = rng.startContainer || (rng.parentElement ? rng.parentElement() : null);
  14753. var body = editor.getBody();
  14754. if (caretElement === body && selection.isCollapsed()) {
  14755. if (dom.isBlock(body.firstChild) && canHaveChildren(editor, body.firstChild) && dom.isEmpty(body.firstChild)) {
  14756. rng = dom.createRng();
  14757. rng.setStart(body.firstChild, 0);
  14758. rng.setEnd(body.firstChild, 0);
  14759. selection.setRng(rng);
  14760. }
  14761. }
  14762. if (!selection.isCollapsed()) {
  14763. deleteSelectedContent(editor);
  14764. }
  14765. parentNode = selection.getNode();
  14766. var parserArgs = {
  14767. context: parentNode.nodeName.toLowerCase(),
  14768. data: details.data,
  14769. insert: true
  14770. };
  14771. var fragment = parser.parse(value, parserArgs);
  14772. if (details.paste === true && isListFragment(editor.schema, fragment) && isParentBlockLi(dom, parentNode)) {
  14773. rng = insertAtCaret(serializer, dom, selection.getRng(), fragment);
  14774. selection.setRng(rng);
  14775. editor.fire('SetContent', args);
  14776. return;
  14777. }
  14778. markFragmentElements(fragment);
  14779. node = fragment.lastChild;
  14780. if (node.attr('id') === 'mce_marker') {
  14781. marker = node;
  14782. for (node = node.prev; node; node = node.walk(true)) {
  14783. if (node.type === 3 || !dom.isBlock(node.name)) {
  14784. if (editor.schema.isValidChild(node.parent.name, 'span')) {
  14785. node.parent.insert(marker, node, node.name === 'br');
  14786. }
  14787. break;
  14788. }
  14789. }
  14790. }
  14791. editor._selectionOverrides.showBlockCaretContainer(parentNode);
  14792. if (!parserArgs.invalid) {
  14793. value = serializer.serialize(fragment);
  14794. validInsertion(editor, value, parentNode);
  14795. } else {
  14796. editor.selection.setContent(bookmarkHtml);
  14797. parentNode = selection.getNode();
  14798. rootNode = editor.getBody();
  14799. if (parentNode.nodeType === 9) {
  14800. parentNode = node = rootNode;
  14801. } else {
  14802. node = parentNode;
  14803. }
  14804. while (node !== rootNode) {
  14805. parentNode = node;
  14806. node = node.parentNode;
  14807. }
  14808. value = parentNode === rootNode ? rootNode.innerHTML : dom.getOuterHTML(parentNode);
  14809. value = serializer.serialize(parser.parse(value.replace(/<span (id="mce_marker"|id=mce_marker).+?<\/span>/i, function () {
  14810. return serializer.serialize(fragment);
  14811. })));
  14812. if (parentNode === rootNode) {
  14813. dom.setHTML(rootNode, value);
  14814. } else {
  14815. dom.setOuterHTML(parentNode, value);
  14816. }
  14817. }
  14818. reduceInlineTextElements(editor, merge);
  14819. moveSelectionToMarker(editor, dom.get('mce_marker'));
  14820. unmarkFragmentElements(editor.getBody());
  14821. trimBrsFromTableCell(dom, selection.getStart());
  14822. editor.fire('SetContent', args);
  14823. editor.addVisual();
  14824. };
  14825. var traverse = function (node, fn) {
  14826. fn(node);
  14827. if (node.firstChild) {
  14828. traverse(node.firstChild, fn);
  14829. }
  14830. if (node.next) {
  14831. traverse(node.next, fn);
  14832. }
  14833. };
  14834. var findMatchingNodes = function (nodeFilters, attributeFilters, node) {
  14835. var nodeMatches = {};
  14836. var attrMatches = {};
  14837. var matches = [];
  14838. if (node.firstChild) {
  14839. traverse(node.firstChild, function (node) {
  14840. each(nodeFilters, function (filter) {
  14841. if (filter.name === node.name) {
  14842. if (nodeMatches[filter.name]) {
  14843. nodeMatches[filter.name].nodes.push(node);
  14844. } else {
  14845. nodeMatches[filter.name] = {
  14846. filter: filter,
  14847. nodes: [node]
  14848. };
  14849. }
  14850. }
  14851. });
  14852. each(attributeFilters, function (filter) {
  14853. if (typeof node.attr(filter.name) === 'string') {
  14854. if (attrMatches[filter.name]) {
  14855. attrMatches[filter.name].nodes.push(node);
  14856. } else {
  14857. attrMatches[filter.name] = {
  14858. filter: filter,
  14859. nodes: [node]
  14860. };
  14861. }
  14862. }
  14863. });
  14864. });
  14865. }
  14866. for (var name_1 in nodeMatches) {
  14867. if (nodeMatches.hasOwnProperty(name_1)) {
  14868. matches.push(nodeMatches[name_1]);
  14869. }
  14870. }
  14871. for (var name_2 in attrMatches) {
  14872. if (attrMatches.hasOwnProperty(name_2)) {
  14873. matches.push(attrMatches[name_2]);
  14874. }
  14875. }
  14876. return matches;
  14877. };
  14878. var filter$3 = function (nodeFilters, attributeFilters, node) {
  14879. var matches = findMatchingNodes(nodeFilters, attributeFilters, node);
  14880. each(matches, function (match) {
  14881. each(match.filter.callbacks, function (callback) {
  14882. callback(match.nodes, match.filter.name, {});
  14883. });
  14884. });
  14885. };
  14886. var defaultFormat = 'html';
  14887. var isTreeNode = function (content) {
  14888. return content instanceof AstNode;
  14889. };
  14890. var moveSelection = function (editor) {
  14891. if (hasFocus$1(editor)) {
  14892. firstPositionIn(editor.getBody()).each(function (pos) {
  14893. var node = pos.getNode();
  14894. var caretPos = isTable(node) ? firstPositionIn(node).getOr(pos) : pos;
  14895. editor.selection.setRng(caretPos.toRange());
  14896. });
  14897. }
  14898. };
  14899. var setEditorHtml = function (editor, html) {
  14900. editor.dom.setHTML(editor.getBody(), html);
  14901. moveSelection(editor);
  14902. };
  14903. var setContentString = function (editor, body, content, args) {
  14904. var forcedRootBlockName, padd;
  14905. if (content.length === 0 || /^\s+$/.test(content)) {
  14906. padd = '<br data-mce-bogus="1">';
  14907. if (body.nodeName === 'TABLE') {
  14908. content = '<tr><td>' + padd + '</td></tr>';
  14909. } else if (/^(UL|OL)$/.test(body.nodeName)) {
  14910. content = '<li>' + padd + '</li>';
  14911. }
  14912. forcedRootBlockName = getForcedRootBlock(editor);
  14913. if (forcedRootBlockName && editor.schema.isValidChild(body.nodeName.toLowerCase(), forcedRootBlockName.toLowerCase())) {
  14914. content = padd;
  14915. content = editor.dom.createHTML(forcedRootBlockName, getForcedRootBlockAttrs(editor), content);
  14916. } else if (!content) {
  14917. content = '<br data-mce-bogus="1">';
  14918. }
  14919. setEditorHtml(editor, content);
  14920. editor.fire('SetContent', args);
  14921. } else {
  14922. if (args.format !== 'raw') {
  14923. content = HtmlSerializer({ validate: editor.validate }, editor.schema).serialize(editor.parser.parse(content, {
  14924. isRootContent: true,
  14925. insert: true
  14926. }));
  14927. }
  14928. args.content = isWsPreserveElement(SugarElement.fromDom(body)) ? content : Tools.trim(content);
  14929. setEditorHtml(editor, args.content);
  14930. if (!args.no_events) {
  14931. editor.fire('SetContent', args);
  14932. }
  14933. }
  14934. return args.content;
  14935. };
  14936. var setContentTree = function (editor, body, content, args) {
  14937. filter$3(editor.parser.getNodeFilters(), editor.parser.getAttributeFilters(), content);
  14938. var html = HtmlSerializer({ validate: editor.validate }, editor.schema).serialize(content);
  14939. args.content = isWsPreserveElement(SugarElement.fromDom(body)) ? html : Tools.trim(html);
  14940. setEditorHtml(editor, args.content);
  14941. if (!args.no_events) {
  14942. editor.fire('SetContent', args);
  14943. }
  14944. return content;
  14945. };
  14946. var setContentInternal = function (editor, content, args) {
  14947. args.format = args.format ? args.format : defaultFormat;
  14948. args.set = true;
  14949. args.content = isTreeNode(content) ? '' : content;
  14950. if (!isTreeNode(content) && !args.no_events) {
  14951. editor.fire('BeforeSetContent', args);
  14952. content = args.content;
  14953. }
  14954. return Optional.from(editor.getBody()).fold(constant(content), function (body) {
  14955. return isTreeNode(content) ? setContentTree(editor, body, content, args) : setContentString(editor, body, content, args);
  14956. });
  14957. };
  14958. var isEq$2 = isEq;
  14959. var matchesUnInheritedFormatSelector = function (ed, node, name) {
  14960. var formatList = ed.formatter.get(name);
  14961. if (formatList) {
  14962. for (var i = 0; i < formatList.length; i++) {
  14963. if (formatList[i].inherit === false && ed.dom.is(node, formatList[i].selector)) {
  14964. return true;
  14965. }
  14966. }
  14967. }
  14968. return false;
  14969. };
  14970. var matchParents = function (editor, node, name, vars) {
  14971. var root = editor.dom.getRoot();
  14972. if (node === root) {
  14973. return false;
  14974. }
  14975. node = editor.dom.getParent(node, function (node) {
  14976. if (matchesUnInheritedFormatSelector(editor, node, name)) {
  14977. return true;
  14978. }
  14979. return node.parentNode === root || !!matchNode(editor, node, name, vars, true);
  14980. });
  14981. return matchNode(editor, node, name, vars);
  14982. };
  14983. var matchName = function (dom, node, format) {
  14984. if (isEq$2(node, format.inline)) {
  14985. return true;
  14986. }
  14987. if (isEq$2(node, format.block)) {
  14988. return true;
  14989. }
  14990. if (format.selector) {
  14991. return node.nodeType === 1 && dom.is(node, format.selector);
  14992. }
  14993. };
  14994. var matchItems = function (dom, node, format, itemName, similar, vars) {
  14995. var key, value;
  14996. var items = format[itemName];
  14997. var i;
  14998. if (format.onmatch) {
  14999. return format.onmatch(node, format, itemName);
  15000. }
  15001. if (items) {
  15002. if (typeof items.length === 'undefined') {
  15003. for (key in items) {
  15004. if (items.hasOwnProperty(key)) {
  15005. if (itemName === 'attributes') {
  15006. value = dom.getAttrib(node, key);
  15007. } else {
  15008. value = getStyle(dom, node, key);
  15009. }
  15010. if (similar && !value && !format.exact) {
  15011. return;
  15012. }
  15013. if ((!similar || format.exact) && !isEq$2(value, normalizeStyleValue(dom, replaceVars(items[key], vars), key))) {
  15014. return;
  15015. }
  15016. }
  15017. }
  15018. } else {
  15019. for (i = 0; i < items.length; i++) {
  15020. if (itemName === 'attributes' ? dom.getAttrib(node, items[i]) : getStyle(dom, node, items[i])) {
  15021. return format;
  15022. }
  15023. }
  15024. }
  15025. }
  15026. return format;
  15027. };
  15028. var matchNode = function (ed, node, name, vars, similar) {
  15029. var formatList = ed.formatter.get(name);
  15030. var format, i, x, classes;
  15031. var dom = ed.dom;
  15032. if (formatList && node) {
  15033. for (i = 0; i < formatList.length; i++) {
  15034. format = formatList[i];
  15035. if (matchName(ed.dom, node, format) && matchItems(dom, node, format, 'attributes', similar, vars) && matchItems(dom, node, format, 'styles', similar, vars)) {
  15036. if (classes = format.classes) {
  15037. for (x = 0; x < classes.length; x++) {
  15038. if (!ed.dom.hasClass(node, classes[x])) {
  15039. return;
  15040. }
  15041. }
  15042. }
  15043. return format;
  15044. }
  15045. }
  15046. }
  15047. };
  15048. var match = function (editor, name, vars, node) {
  15049. if (node) {
  15050. return matchParents(editor, node, name, vars);
  15051. }
  15052. node = editor.selection.getNode();
  15053. if (matchParents(editor, node, name, vars)) {
  15054. return true;
  15055. }
  15056. var startNode = editor.selection.getStart();
  15057. if (startNode !== node) {
  15058. if (matchParents(editor, startNode, name, vars)) {
  15059. return true;
  15060. }
  15061. }
  15062. return false;
  15063. };
  15064. var matchAll = function (editor, names, vars) {
  15065. var matchedFormatNames = [];
  15066. var checkedMap = {};
  15067. var startElement = editor.selection.getStart();
  15068. editor.dom.getParent(startElement, function (node) {
  15069. for (var i = 0; i < names.length; i++) {
  15070. var name_1 = names[i];
  15071. if (!checkedMap[name_1] && matchNode(editor, node, name_1, vars)) {
  15072. checkedMap[name_1] = true;
  15073. matchedFormatNames.push(name_1);
  15074. }
  15075. }
  15076. }, editor.dom.getRoot());
  15077. return matchedFormatNames;
  15078. };
  15079. var canApply = function (editor, name) {
  15080. var formatList = editor.formatter.get(name);
  15081. var startNode, parents, i, x, selector;
  15082. var dom = editor.dom;
  15083. if (formatList) {
  15084. startNode = editor.selection.getStart();
  15085. parents = getParents$1(dom, startNode);
  15086. for (x = formatList.length - 1; x >= 0; x--) {
  15087. selector = formatList[x].selector;
  15088. if (!selector || formatList[x].defaultBlock) {
  15089. return true;
  15090. }
  15091. for (i = parents.length - 1; i >= 0; i--) {
  15092. if (dom.is(parents[i], selector)) {
  15093. return true;
  15094. }
  15095. }
  15096. }
  15097. }
  15098. return false;
  15099. };
  15100. var matchAllOnNode = function (editor, node, formatNames) {
  15101. return foldl(formatNames, function (acc, name) {
  15102. var matchSimilar = isVariableFormatName(editor, name);
  15103. if (editor.formatter.matchNode(node, name, {}, matchSimilar)) {
  15104. return acc.concat([name]);
  15105. } else {
  15106. return acc;
  15107. }
  15108. }, []);
  15109. };
  15110. var ZWSP$1 = ZWSP, CARET_ID$1 = '_mce_caret';
  15111. var importNode = function (ownerDocument, node) {
  15112. return ownerDocument.importNode(node, true);
  15113. };
  15114. var getEmptyCaretContainers = function (node) {
  15115. var nodes = [];
  15116. while (node) {
  15117. if (node.nodeType === 3 && node.nodeValue !== ZWSP$1 || node.childNodes.length > 1) {
  15118. return [];
  15119. }
  15120. if (node.nodeType === 1) {
  15121. nodes.push(node);
  15122. }
  15123. node = node.firstChild;
  15124. }
  15125. return nodes;
  15126. };
  15127. var isCaretContainerEmpty = function (node) {
  15128. return getEmptyCaretContainers(node).length > 0;
  15129. };
  15130. var findFirstTextNode = function (node) {
  15131. if (node) {
  15132. var walker = new DomTreeWalker(node, node);
  15133. for (node = walker.current(); node; node = walker.next()) {
  15134. if (isText$1(node)) {
  15135. return node;
  15136. }
  15137. }
  15138. }
  15139. return null;
  15140. };
  15141. var createCaretContainer = function (fill) {
  15142. var caretContainer = SugarElement.fromTag('span');
  15143. setAll(caretContainer, {
  15144. 'id': CARET_ID$1,
  15145. 'data-mce-bogus': '1',
  15146. 'data-mce-type': 'format-caret'
  15147. });
  15148. if (fill) {
  15149. append(caretContainer, SugarElement.fromText(ZWSP$1));
  15150. }
  15151. return caretContainer;
  15152. };
  15153. var trimZwspFromCaretContainer = function (caretContainerNode) {
  15154. var textNode = findFirstTextNode(caretContainerNode);
  15155. if (textNode && textNode.nodeValue.charAt(0) === ZWSP$1) {
  15156. textNode.deleteData(0, 1);
  15157. }
  15158. return textNode;
  15159. };
  15160. var removeCaretContainerNode = function (editor, node, moveCaret) {
  15161. if (moveCaret === void 0) {
  15162. moveCaret = true;
  15163. }
  15164. var dom = editor.dom, selection = editor.selection;
  15165. if (isCaretContainerEmpty(node)) {
  15166. deleteElement(editor, false, SugarElement.fromDom(node), moveCaret);
  15167. } else {
  15168. var rng = selection.getRng();
  15169. var block = dom.getParent(node, dom.isBlock);
  15170. var startContainer = rng.startContainer;
  15171. var startOffset = rng.startOffset;
  15172. var endContainer = rng.endContainer;
  15173. var endOffset = rng.endOffset;
  15174. var textNode = trimZwspFromCaretContainer(node);
  15175. dom.remove(node, true);
  15176. if (startContainer === textNode && startOffset > 0) {
  15177. rng.setStart(textNode, startOffset - 1);
  15178. }
  15179. if (endContainer === textNode && endOffset > 0) {
  15180. rng.setEnd(textNode, endOffset - 1);
  15181. }
  15182. if (block && dom.isEmpty(block)) {
  15183. fillWithPaddingBr(SugarElement.fromDom(block));
  15184. }
  15185. selection.setRng(rng);
  15186. }
  15187. };
  15188. var removeCaretContainer = function (editor, node, moveCaret) {
  15189. if (moveCaret === void 0) {
  15190. moveCaret = true;
  15191. }
  15192. var dom = editor.dom, selection = editor.selection;
  15193. if (!node) {
  15194. node = getParentCaretContainer(editor.getBody(), selection.getStart());
  15195. if (!node) {
  15196. while (node = dom.get(CARET_ID$1)) {
  15197. removeCaretContainerNode(editor, node, false);
  15198. }
  15199. }
  15200. } else {
  15201. removeCaretContainerNode(editor, node, moveCaret);
  15202. }
  15203. };
  15204. var insertCaretContainerNode = function (editor, caretContainer, formatNode) {
  15205. var dom = editor.dom, block = dom.getParent(formatNode, curry(isTextBlock$1, editor));
  15206. if (block && dom.isEmpty(block)) {
  15207. formatNode.parentNode.replaceChild(caretContainer, formatNode);
  15208. } else {
  15209. removeTrailingBr(SugarElement.fromDom(formatNode));
  15210. if (dom.isEmpty(formatNode)) {
  15211. formatNode.parentNode.replaceChild(caretContainer, formatNode);
  15212. } else {
  15213. dom.insertAfter(caretContainer, formatNode);
  15214. }
  15215. }
  15216. };
  15217. var appendNode = function (parentNode, node) {
  15218. parentNode.appendChild(node);
  15219. return node;
  15220. };
  15221. var insertFormatNodesIntoCaretContainer = function (formatNodes, caretContainer) {
  15222. var innerMostFormatNode = foldr(formatNodes, function (parentNode, formatNode) {
  15223. return appendNode(parentNode, formatNode.cloneNode(false));
  15224. }, caretContainer);
  15225. return appendNode(innerMostFormatNode, innerMostFormatNode.ownerDocument.createTextNode(ZWSP$1));
  15226. };
  15227. var cleanFormatNode = function (editor, caretContainer, formatNode, name, vars, similar) {
  15228. var formatter = editor.formatter;
  15229. var dom = editor.dom;
  15230. var validFormats = filter(keys(formatter.get()), function (formatName) {
  15231. return formatName !== name && !contains$1(formatName, 'removeformat');
  15232. });
  15233. var matchedFormats = matchAllOnNode(editor, formatNode, validFormats);
  15234. var uniqueFormats = filter(matchedFormats, function (fmtName) {
  15235. return !areSimilarFormats(editor, fmtName, name);
  15236. });
  15237. if (uniqueFormats.length > 0) {
  15238. var clonedFormatNode = formatNode.cloneNode(false);
  15239. dom.add(caretContainer, clonedFormatNode);
  15240. formatter.remove(name, vars, clonedFormatNode, similar);
  15241. dom.remove(clonedFormatNode);
  15242. return Optional.some(clonedFormatNode);
  15243. } else {
  15244. return Optional.none();
  15245. }
  15246. };
  15247. var applyCaretFormat = function (editor, name, vars) {
  15248. var caretContainer, textNode;
  15249. var selection = editor.selection;
  15250. var selectionRng = selection.getRng();
  15251. var offset = selectionRng.startOffset;
  15252. var container = selectionRng.startContainer;
  15253. var text = container.nodeValue;
  15254. caretContainer = getParentCaretContainer(editor.getBody(), selection.getStart());
  15255. if (caretContainer) {
  15256. textNode = findFirstTextNode(caretContainer);
  15257. }
  15258. var wordcharRegex = /[^\s\u00a0\u00ad\u200b\ufeff]/;
  15259. if (text && offset > 0 && offset < text.length && wordcharRegex.test(text.charAt(offset)) && wordcharRegex.test(text.charAt(offset - 1))) {
  15260. var bookmark = selection.getBookmark();
  15261. selectionRng.collapse(true);
  15262. var rng = expandRng(editor, selectionRng, editor.formatter.get(name));
  15263. rng = split$1(rng);
  15264. editor.formatter.apply(name, vars, rng);
  15265. selection.moveToBookmark(bookmark);
  15266. } else {
  15267. if (!caretContainer || textNode.nodeValue !== ZWSP$1) {
  15268. caretContainer = importNode(editor.getDoc(), createCaretContainer(true).dom);
  15269. textNode = caretContainer.firstChild;
  15270. selectionRng.insertNode(caretContainer);
  15271. offset = 1;
  15272. editor.formatter.apply(name, vars, caretContainer);
  15273. } else {
  15274. editor.formatter.apply(name, vars, caretContainer);
  15275. }
  15276. selection.setCursorLocation(textNode, offset);
  15277. }
  15278. };
  15279. var removeCaretFormat = function (editor, name, vars, similar) {
  15280. var dom = editor.dom;
  15281. var selection = editor.selection;
  15282. var hasContentAfter, node, formatNode;
  15283. var parents = [];
  15284. var rng = selection.getRng();
  15285. var container = rng.startContainer;
  15286. var offset = rng.startOffset;
  15287. node = container;
  15288. if (container.nodeType === 3) {
  15289. if (offset !== container.nodeValue.length) {
  15290. hasContentAfter = true;
  15291. }
  15292. node = node.parentNode;
  15293. }
  15294. while (node) {
  15295. if (matchNode(editor, node, name, vars, similar)) {
  15296. formatNode = node;
  15297. break;
  15298. }
  15299. if (node.nextSibling) {
  15300. hasContentAfter = true;
  15301. }
  15302. parents.push(node);
  15303. node = node.parentNode;
  15304. }
  15305. if (!formatNode) {
  15306. return;
  15307. }
  15308. if (hasContentAfter) {
  15309. var bookmark = selection.getBookmark();
  15310. rng.collapse(true);
  15311. var expandedRng = expandRng(editor, rng, editor.formatter.get(name), true);
  15312. expandedRng = split$1(expandedRng);
  15313. editor.formatter.remove(name, vars, expandedRng, similar);
  15314. selection.moveToBookmark(bookmark);
  15315. } else {
  15316. var caretContainer = getParentCaretContainer(editor.getBody(), formatNode);
  15317. var newCaretContainer = createCaretContainer(false).dom;
  15318. insertCaretContainerNode(editor, newCaretContainer, caretContainer !== null ? caretContainer : formatNode);
  15319. var cleanedFormatNode = cleanFormatNode(editor, newCaretContainer, formatNode, name, vars, similar);
  15320. var caretTextNode = insertFormatNodesIntoCaretContainer(parents.concat(cleanedFormatNode.toArray()), newCaretContainer);
  15321. removeCaretContainerNode(editor, caretContainer, false);
  15322. selection.setCursorLocation(caretTextNode, 1);
  15323. if (dom.isEmpty(formatNode)) {
  15324. dom.remove(formatNode);
  15325. }
  15326. }
  15327. };
  15328. var disableCaretContainer = function (editor, keyCode) {
  15329. var selection = editor.selection, body = editor.getBody();
  15330. removeCaretContainer(editor, null, false);
  15331. if ((keyCode === 8 || keyCode === 46) && selection.isCollapsed() && selection.getStart().innerHTML === ZWSP$1) {
  15332. removeCaretContainer(editor, getParentCaretContainer(body, selection.getStart()));
  15333. }
  15334. if (keyCode === 37 || keyCode === 39) {
  15335. removeCaretContainer(editor, getParentCaretContainer(body, selection.getStart()));
  15336. }
  15337. };
  15338. var setup$3 = function (editor) {
  15339. editor.on('mouseup keydown', function (e) {
  15340. disableCaretContainer(editor, e.keyCode);
  15341. });
  15342. };
  15343. var replaceWithCaretFormat = function (targetNode, formatNodes) {
  15344. var caretContainer = createCaretContainer(false);
  15345. var innerMost = insertFormatNodesIntoCaretContainer(formatNodes, caretContainer.dom);
  15346. before(SugarElement.fromDom(targetNode), caretContainer);
  15347. remove(SugarElement.fromDom(targetNode));
  15348. return CaretPosition$1(innerMost, 0);
  15349. };
  15350. var isFormatElement = function (editor, element) {
  15351. var inlineElements = editor.schema.getTextInlineElements();
  15352. return inlineElements.hasOwnProperty(name(element)) && !isCaretNode(element.dom) && !isBogus(element.dom);
  15353. };
  15354. var isEmptyCaretFormatElement = function (element) {
  15355. return isCaretNode(element.dom) && isCaretContainerEmpty(element.dom);
  15356. };
  15357. var postProcessHooks = {};
  15358. var filter$4 = filter$2;
  15359. var each$8 = each$2;
  15360. var addPostProcessHook = function (name, hook) {
  15361. var hooks = postProcessHooks[name];
  15362. if (!hooks) {
  15363. postProcessHooks[name] = [];
  15364. }
  15365. postProcessHooks[name].push(hook);
  15366. };
  15367. var postProcess = function (name, editor) {
  15368. each$8(postProcessHooks[name], function (hook) {
  15369. hook(editor);
  15370. });
  15371. };
  15372. addPostProcessHook('pre', function (editor) {
  15373. var rng = editor.selection.getRng();
  15374. var blocks;
  15375. var hasPreSibling = function (pre) {
  15376. return isPre(pre.previousSibling) && indexOf$1(blocks, pre.previousSibling) !== -1;
  15377. };
  15378. var joinPre = function (pre1, pre2) {
  15379. DomQuery(pre2).remove();
  15380. DomQuery(pre1).append('<br><br>').append(pre2.childNodes);
  15381. };
  15382. var isPre = matchNodeNames(['pre']);
  15383. if (!rng.collapsed) {
  15384. blocks = editor.selection.getSelectedBlocks();
  15385. each$8(filter$4(filter$4(blocks, isPre), hasPreSibling), function (pre) {
  15386. joinPre(pre.previousSibling, pre);
  15387. });
  15388. }
  15389. });
  15390. var each$9 = Tools.each;
  15391. var isElementNode = function (node) {
  15392. return isElement$1(node) && !isBookmarkNode$1(node) && !isCaretNode(node) && !isBogus(node);
  15393. };
  15394. var findElementSibling = function (node, siblingName) {
  15395. var sibling;
  15396. for (sibling = node; sibling; sibling = sibling[siblingName]) {
  15397. if (isText$1(sibling) && sibling.nodeValue.length !== 0) {
  15398. return node;
  15399. }
  15400. if (isElement$1(sibling) && !isBookmarkNode$1(sibling)) {
  15401. return sibling;
  15402. }
  15403. }
  15404. return node;
  15405. };
  15406. var mergeSiblingsNodes = function (dom, prev, next) {
  15407. var sibling, tmpSibling;
  15408. var elementUtils = new ElementUtils(dom);
  15409. if (prev && next) {
  15410. prev = findElementSibling(prev, 'previousSibling');
  15411. next = findElementSibling(next, 'nextSibling');
  15412. if (elementUtils.compare(prev, next)) {
  15413. for (sibling = prev.nextSibling; sibling && sibling !== next;) {
  15414. tmpSibling = sibling;
  15415. sibling = sibling.nextSibling;
  15416. prev.appendChild(tmpSibling);
  15417. }
  15418. dom.remove(next);
  15419. Tools.each(Tools.grep(next.childNodes), function (node) {
  15420. prev.appendChild(node);
  15421. });
  15422. return prev;
  15423. }
  15424. }
  15425. return next;
  15426. };
  15427. var mergeSiblings = function (dom, format, vars, node) {
  15428. if (node && format.merge_siblings !== false) {
  15429. var newNode = mergeSiblingsNodes(dom, getNonWhiteSpaceSibling(node), node);
  15430. mergeSiblingsNodes(dom, newNode, getNonWhiteSpaceSibling(newNode, true));
  15431. }
  15432. };
  15433. var clearChildStyles = function (dom, format, node) {
  15434. if (format.clear_child_styles) {
  15435. var selector = format.links ? '*:not(a)' : '*';
  15436. each$9(dom.select(selector, node), function (node) {
  15437. if (isElementNode(node)) {
  15438. each$9(format.styles, function (value, name) {
  15439. dom.setStyle(node, name, '');
  15440. });
  15441. }
  15442. });
  15443. }
  15444. };
  15445. var processChildElements = function (node, filter, process) {
  15446. each$9(node.childNodes, function (node) {
  15447. if (isElementNode(node)) {
  15448. if (filter(node)) {
  15449. process(node);
  15450. }
  15451. if (node.hasChildNodes()) {
  15452. processChildElements(node, filter, process);
  15453. }
  15454. }
  15455. });
  15456. };
  15457. var unwrapEmptySpan = function (dom, node) {
  15458. if (node.nodeName === 'SPAN' && dom.getAttribs(node).length === 0) {
  15459. dom.remove(node, true);
  15460. }
  15461. };
  15462. var hasStyle = function (dom, name) {
  15463. return function (node) {
  15464. return !!(node && getStyle(dom, node, name));
  15465. };
  15466. };
  15467. var applyStyle = function (dom, name, value) {
  15468. return function (node) {
  15469. dom.setStyle(node, name, value);
  15470. if (node.getAttribute('style') === '') {
  15471. node.removeAttribute('style');
  15472. }
  15473. unwrapEmptySpan(dom, node);
  15474. };
  15475. };
  15476. var removeResult = Adt.generate([
  15477. { keep: [] },
  15478. { rename: ['name'] },
  15479. { removed: [] }
  15480. ]);
  15481. var MCE_ATTR_RE = /^(src|href|style)$/;
  15482. var each$a = Tools.each;
  15483. var isEq$3 = isEq;
  15484. var isTableCellOrRow = function (node) {
  15485. return /^(TR|TH|TD)$/.test(node.nodeName);
  15486. };
  15487. var isChildOfInlineParent = function (dom, node, parent) {
  15488. return dom.isChildOf(node, parent) && node !== parent && !dom.isBlock(parent);
  15489. };
  15490. var getContainer = function (ed, rng, start) {
  15491. var container, offset;
  15492. container = rng[start ? 'startContainer' : 'endContainer'];
  15493. offset = rng[start ? 'startOffset' : 'endOffset'];
  15494. if (isElement$1(container)) {
  15495. var lastIdx = container.childNodes.length - 1;
  15496. if (!start && offset) {
  15497. offset--;
  15498. }
  15499. container = container.childNodes[offset > lastIdx ? lastIdx : offset];
  15500. }
  15501. if (isText$1(container) && start && offset >= container.nodeValue.length) {
  15502. container = new DomTreeWalker(container, ed.getBody()).next() || container;
  15503. }
  15504. if (isText$1(container) && !start && offset === 0) {
  15505. container = new DomTreeWalker(container, ed.getBody()).prev() || container;
  15506. }
  15507. return container;
  15508. };
  15509. var normalizeTableSelection = function (node, start) {
  15510. var prop = start ? 'firstChild' : 'lastChild';
  15511. if (isTableCellOrRow(node) && node[prop]) {
  15512. var childNode = node[prop];
  15513. if (node.nodeName === 'TR') {
  15514. return childNode[prop] || childNode;
  15515. } else {
  15516. return childNode;
  15517. }
  15518. }
  15519. return node;
  15520. };
  15521. var wrap$2 = function (dom, node, name, attrs) {
  15522. var wrapper = dom.create(name, attrs);
  15523. node.parentNode.insertBefore(wrapper, node);
  15524. wrapper.appendChild(node);
  15525. return wrapper;
  15526. };
  15527. var wrapWithSiblings = function (dom, node, next, name, attrs) {
  15528. var start = SugarElement.fromDom(node);
  15529. var wrapper = SugarElement.fromDom(dom.create(name, attrs));
  15530. var siblings = next ? nextSiblings(start) : prevSiblings(start);
  15531. append$1(wrapper, siblings);
  15532. if (next) {
  15533. before(start, wrapper);
  15534. prepend(wrapper, start);
  15535. } else {
  15536. after(start, wrapper);
  15537. append(wrapper, start);
  15538. }
  15539. return wrapper.dom;
  15540. };
  15541. var matchName$1 = function (dom, node, format) {
  15542. if (isEq$3(node, format.inline)) {
  15543. return true;
  15544. }
  15545. if (isEq$3(node, format.block)) {
  15546. return true;
  15547. }
  15548. if (format.selector) {
  15549. return isElement$1(node) && dom.is(node, format.selector);
  15550. }
  15551. };
  15552. var isColorFormatAndAnchor = function (node, format) {
  15553. return format.links && node.nodeName === 'A';
  15554. };
  15555. var find$3 = function (dom, node, next, inc) {
  15556. node = getNonWhiteSpaceSibling(node, next, inc);
  15557. return !node || (node.nodeName === 'BR' || dom.isBlock(node));
  15558. };
  15559. var removeNode$1 = function (ed, node, format) {
  15560. var parentNode = node.parentNode;
  15561. var rootBlockElm;
  15562. var dom = ed.dom, forcedRootBlock = getForcedRootBlock(ed);
  15563. if (format.block) {
  15564. if (!forcedRootBlock) {
  15565. if (dom.isBlock(node) && !dom.isBlock(parentNode)) {
  15566. if (!find$3(dom, node, false) && !find$3(dom, node.firstChild, true, true)) {
  15567. node.insertBefore(dom.create('br'), node.firstChild);
  15568. }
  15569. if (!find$3(dom, node, true) && !find$3(dom, node.lastChild, false, true)) {
  15570. node.appendChild(dom.create('br'));
  15571. }
  15572. }
  15573. } else {
  15574. if (parentNode === dom.getRoot()) {
  15575. if (!format.list_block || !isEq$3(node, format.list_block)) {
  15576. each(from$1(node.childNodes), function (node) {
  15577. if (isValid(ed, forcedRootBlock, node.nodeName.toLowerCase())) {
  15578. if (!rootBlockElm) {
  15579. rootBlockElm = wrap$2(dom, node, forcedRootBlock);
  15580. dom.setAttribs(rootBlockElm, ed.settings.forced_root_block_attrs);
  15581. } else {
  15582. rootBlockElm.appendChild(node);
  15583. }
  15584. } else {
  15585. rootBlockElm = 0;
  15586. }
  15587. });
  15588. }
  15589. }
  15590. }
  15591. }
  15592. if (format.selector && format.inline && !isEq$3(format.inline, node)) {
  15593. return;
  15594. }
  15595. dom.remove(node, true);
  15596. };
  15597. var removeFormatInternal = function (ed, format, vars, node, compareNode) {
  15598. var stylesModified;
  15599. var dom = ed.dom;
  15600. if (!matchName$1(dom, node, format) && !isColorFormatAndAnchor(node, format)) {
  15601. return removeResult.keep();
  15602. }
  15603. var elm = node;
  15604. if (format.inline && format.remove === 'all' && isArray(format.preserve_attributes)) {
  15605. var attrsToPreserve = filter(dom.getAttribs(elm), function (attr) {
  15606. return contains(format.preserve_attributes, attr.name.toLowerCase());
  15607. });
  15608. dom.removeAllAttribs(elm);
  15609. each(attrsToPreserve, function (attr) {
  15610. return dom.setAttrib(elm, attr.name, attr.value);
  15611. });
  15612. if (attrsToPreserve.length > 0) {
  15613. return removeResult.rename('span');
  15614. }
  15615. }
  15616. if (format.remove !== 'all') {
  15617. each$a(format.styles, function (value, name) {
  15618. value = normalizeStyleValue(dom, replaceVars(value, vars), name + '');
  15619. if (isNumber(name)) {
  15620. name = value;
  15621. compareNode = null;
  15622. }
  15623. if (format.remove_similar || (!compareNode || isEq$3(getStyle(dom, compareNode, name), value))) {
  15624. dom.setStyle(elm, name, '');
  15625. }
  15626. stylesModified = true;
  15627. });
  15628. if (stylesModified && dom.getAttrib(elm, 'style') === '') {
  15629. elm.removeAttribute('style');
  15630. elm.removeAttribute('data-mce-style');
  15631. }
  15632. each$a(format.attributes, function (value, name) {
  15633. var valueOut;
  15634. value = replaceVars(value, vars);
  15635. if (isNumber(name)) {
  15636. name = value;
  15637. compareNode = null;
  15638. }
  15639. if (format.remove_similar || (!compareNode || isEq$3(dom.getAttrib(compareNode, name), value))) {
  15640. if (name === 'class') {
  15641. value = dom.getAttrib(elm, name);
  15642. if (value) {
  15643. valueOut = '';
  15644. each(value.split(/\s+/), function (cls) {
  15645. if (/mce\-\w+/.test(cls)) {
  15646. valueOut += (valueOut ? ' ' : '') + cls;
  15647. }
  15648. });
  15649. if (valueOut) {
  15650. dom.setAttrib(elm, name, valueOut);
  15651. return;
  15652. }
  15653. }
  15654. }
  15655. if (name === 'class') {
  15656. elm.removeAttribute('className');
  15657. }
  15658. if (MCE_ATTR_RE.test(name)) {
  15659. elm.removeAttribute('data-mce-' + name);
  15660. }
  15661. elm.removeAttribute(name);
  15662. }
  15663. });
  15664. each$a(format.classes, function (value) {
  15665. value = replaceVars(value, vars);
  15666. if (!compareNode || dom.hasClass(compareNode, value)) {
  15667. dom.removeClass(elm, value);
  15668. }
  15669. });
  15670. var attrs = dom.getAttribs(elm);
  15671. for (var i = 0; i < attrs.length; i++) {
  15672. var attrName = attrs[i].nodeName;
  15673. if (attrName.indexOf('_') !== 0 && attrName.indexOf('data-') !== 0) {
  15674. return removeResult.keep();
  15675. }
  15676. }
  15677. }
  15678. if (format.remove !== 'none') {
  15679. removeNode$1(ed, elm, format);
  15680. return removeResult.removed();
  15681. }
  15682. return removeResult.keep();
  15683. };
  15684. var removeFormat = function (ed, format, vars, node, compareNode) {
  15685. return removeFormatInternal(ed, format, vars, node, compareNode).fold(never, function (newName) {
  15686. ed.dom.rename(node, newName);
  15687. return true;
  15688. }, always);
  15689. };
  15690. var findFormatRoot = function (editor, container, name, vars, similar) {
  15691. var formatRoot;
  15692. each(getParents$1(editor.dom, container.parentNode).reverse(), function (parent) {
  15693. if (!formatRoot && parent.id !== '_start' && parent.id !== '_end') {
  15694. var format = matchNode(editor, parent, name, vars, similar);
  15695. if (format && format.split !== false) {
  15696. formatRoot = parent;
  15697. }
  15698. }
  15699. });
  15700. return formatRoot;
  15701. };
  15702. var removeFormatFromClone = function (editor, format, vars, clone) {
  15703. return removeFormatInternal(editor, format, vars, clone, clone).fold(constant(clone), function (newName) {
  15704. var fragment = editor.dom.createFragment();
  15705. fragment.appendChild(clone);
  15706. return editor.dom.rename(clone, newName);
  15707. }, constant(null));
  15708. };
  15709. var wrapAndSplit = function (editor, formatList, formatRoot, container, target, split, format, vars) {
  15710. var clone, lastClone, firstClone;
  15711. var dom = editor.dom;
  15712. if (formatRoot) {
  15713. var formatRootParent = formatRoot.parentNode;
  15714. for (var parent_1 = container.parentNode; parent_1 && parent_1 !== formatRootParent; parent_1 = parent_1.parentNode) {
  15715. clone = dom.clone(parent_1, false);
  15716. for (var i = 0; i < formatList.length; i++) {
  15717. clone = removeFormatFromClone(editor, formatList[i], vars, clone);
  15718. if (clone === null) {
  15719. break;
  15720. }
  15721. }
  15722. if (clone) {
  15723. if (lastClone) {
  15724. clone.appendChild(lastClone);
  15725. }
  15726. if (!firstClone) {
  15727. firstClone = clone;
  15728. }
  15729. lastClone = clone;
  15730. }
  15731. }
  15732. if (split && (!format.mixed || !dom.isBlock(formatRoot))) {
  15733. container = dom.split(formatRoot, container);
  15734. }
  15735. if (lastClone) {
  15736. target.parentNode.insertBefore(lastClone, target);
  15737. firstClone.appendChild(target);
  15738. if (format.inline) {
  15739. mergeSiblings(dom, format, vars, lastClone);
  15740. }
  15741. }
  15742. }
  15743. return container;
  15744. };
  15745. var remove$6 = function (ed, name, vars, node, similar) {
  15746. var formatList = ed.formatter.get(name);
  15747. var format = formatList[0];
  15748. var contentEditable = true;
  15749. var dom = ed.dom;
  15750. var selection = ed.selection;
  15751. var splitToFormatRoot = function (container) {
  15752. var formatRoot = findFormatRoot(ed, container, name, vars, similar);
  15753. return wrapAndSplit(ed, formatList, formatRoot, container, container, true, format, vars);
  15754. };
  15755. var isRemoveBookmarkNode = function (node) {
  15756. return isBookmarkNode$1(node) && isElement$1(node) && (node.id === '_start' || node.id === '_end');
  15757. };
  15758. var process = function (node) {
  15759. var lastContentEditable, hasContentEditableState;
  15760. if (isElement$1(node) && dom.getContentEditable(node)) {
  15761. lastContentEditable = contentEditable;
  15762. contentEditable = dom.getContentEditable(node) === 'true';
  15763. hasContentEditableState = true;
  15764. }
  15765. var children = from$1(node.childNodes);
  15766. if (contentEditable && !hasContentEditableState) {
  15767. for (var i = 0; i < formatList.length; i++) {
  15768. if (removeFormat(ed, formatList[i], vars, node, node)) {
  15769. break;
  15770. }
  15771. }
  15772. }
  15773. if (format.deep) {
  15774. if (children.length) {
  15775. for (var i = 0; i < children.length; i++) {
  15776. process(children[i]);
  15777. }
  15778. if (hasContentEditableState) {
  15779. contentEditable = lastContentEditable;
  15780. }
  15781. }
  15782. }
  15783. };
  15784. var unwrap = function (start) {
  15785. var node = dom.get(start ? '_start' : '_end');
  15786. var out = node[start ? 'firstChild' : 'lastChild'];
  15787. if (isRemoveBookmarkNode(out)) {
  15788. out = out[start ? 'firstChild' : 'lastChild'];
  15789. }
  15790. if (isText$1(out) && out.data.length === 0) {
  15791. out = start ? node.previousSibling || node.nextSibling : node.nextSibling || node.previousSibling;
  15792. }
  15793. dom.remove(node, true);
  15794. return out;
  15795. };
  15796. var removeRngStyle = function (rng) {
  15797. var startContainer, endContainer;
  15798. var expandedRng = expandRng(ed, rng, formatList, true);
  15799. if (format.split) {
  15800. expandedRng = split$1(expandedRng);
  15801. startContainer = getContainer(ed, expandedRng, true);
  15802. endContainer = getContainer(ed, expandedRng);
  15803. if (startContainer !== endContainer) {
  15804. startContainer = normalizeTableSelection(startContainer, true);
  15805. endContainer = normalizeTableSelection(endContainer, false);
  15806. if (isChildOfInlineParent(dom, startContainer, endContainer)) {
  15807. var marker = Optional.from(startContainer.firstChild).getOr(startContainer);
  15808. splitToFormatRoot(wrapWithSiblings(dom, marker, true, 'span', {
  15809. 'id': '_start',
  15810. 'data-mce-type': 'bookmark'
  15811. }));
  15812. unwrap(true);
  15813. return;
  15814. }
  15815. if (isChildOfInlineParent(dom, endContainer, startContainer)) {
  15816. var marker = Optional.from(endContainer.lastChild).getOr(endContainer);
  15817. splitToFormatRoot(wrapWithSiblings(dom, marker, false, 'span', {
  15818. 'id': '_end',
  15819. 'data-mce-type': 'bookmark'
  15820. }));
  15821. unwrap(false);
  15822. return;
  15823. }
  15824. startContainer = wrap$2(dom, startContainer, 'span', {
  15825. 'id': '_start',
  15826. 'data-mce-type': 'bookmark'
  15827. });
  15828. endContainer = wrap$2(dom, endContainer, 'span', {
  15829. 'id': '_end',
  15830. 'data-mce-type': 'bookmark'
  15831. });
  15832. var newRng = dom.createRng();
  15833. newRng.setStartAfter(startContainer);
  15834. newRng.setEndBefore(endContainer);
  15835. walk$1(dom, newRng, function (nodes) {
  15836. each(nodes, function (n) {
  15837. if (!isBookmarkNode$1(n) && !isBookmarkNode$1(n.parentNode)) {
  15838. splitToFormatRoot(n);
  15839. }
  15840. });
  15841. });
  15842. splitToFormatRoot(startContainer);
  15843. splitToFormatRoot(endContainer);
  15844. startContainer = unwrap(true);
  15845. endContainer = unwrap();
  15846. } else {
  15847. startContainer = endContainer = splitToFormatRoot(startContainer);
  15848. }
  15849. expandedRng.startContainer = startContainer.parentNode ? startContainer.parentNode : startContainer;
  15850. expandedRng.startOffset = dom.nodeIndex(startContainer);
  15851. expandedRng.endContainer = endContainer.parentNode ? endContainer.parentNode : endContainer;
  15852. expandedRng.endOffset = dom.nodeIndex(endContainer) + 1;
  15853. }
  15854. walk$1(dom, expandedRng, function (nodes) {
  15855. each(nodes, function (node) {
  15856. process(node);
  15857. var textDecorations = [
  15858. 'underline',
  15859. 'line-through',
  15860. 'overline'
  15861. ];
  15862. each(textDecorations, function (decoration) {
  15863. if (isElement$1(node) && ed.dom.getStyle(node, 'text-decoration') === decoration && node.parentNode && getTextDecoration(dom, node.parentNode) === decoration) {
  15864. removeFormat(ed, {
  15865. deep: false,
  15866. exact: true,
  15867. inline: 'span',
  15868. styles: { textDecoration: decoration }
  15869. }, null, node);
  15870. }
  15871. });
  15872. });
  15873. });
  15874. };
  15875. if (node) {
  15876. if (isNode(node)) {
  15877. var rng = dom.createRng();
  15878. rng.setStartBefore(node);
  15879. rng.setEndAfter(node);
  15880. removeRngStyle(rng);
  15881. } else {
  15882. removeRngStyle(node);
  15883. }
  15884. return;
  15885. }
  15886. if (dom.getContentEditable(selection.getNode()) === 'false') {
  15887. node = selection.getNode();
  15888. for (var i = 0; i < formatList.length; i++) {
  15889. if (formatList[i].ceFalseOverride) {
  15890. if (removeFormat(ed, formatList[i], vars, node, node)) {
  15891. break;
  15892. }
  15893. }
  15894. }
  15895. return;
  15896. }
  15897. if (!selection.isCollapsed() || !format.inline || getCellsFromEditor(ed).length) {
  15898. preserve(selection, true, function () {
  15899. runOnRanges(ed, removeRngStyle);
  15900. });
  15901. if (format.inline && match(ed, name, vars, selection.getStart())) {
  15902. moveStart(dom, selection, selection.getRng());
  15903. }
  15904. ed.nodeChanged();
  15905. } else {
  15906. removeCaretFormat(ed, name, vars, similar);
  15907. }
  15908. };
  15909. var each$b = Tools.each;
  15910. var mergeTextDecorationsAndColor = function (dom, format, vars, node) {
  15911. var processTextDecorationsAndColor = function (n) {
  15912. if (n.nodeType === 1 && n.parentNode && n.parentNode.nodeType === 1) {
  15913. var textDecoration = getTextDecoration(dom, n.parentNode);
  15914. if (dom.getStyle(n, 'color') && textDecoration) {
  15915. dom.setStyle(n, 'text-decoration', textDecoration);
  15916. } else if (dom.getStyle(n, 'text-decoration') === textDecoration) {
  15917. dom.setStyle(n, 'text-decoration', null);
  15918. }
  15919. }
  15920. };
  15921. if (format.styles && (format.styles.color || format.styles.textDecoration)) {
  15922. Tools.walk(node, processTextDecorationsAndColor, 'childNodes');
  15923. processTextDecorationsAndColor(node);
  15924. }
  15925. };
  15926. var mergeBackgroundColorAndFontSize = function (dom, format, vars, node) {
  15927. if (format.styles && format.styles.backgroundColor) {
  15928. processChildElements(node, hasStyle(dom, 'fontSize'), applyStyle(dom, 'backgroundColor', replaceVars(format.styles.backgroundColor, vars)));
  15929. }
  15930. };
  15931. var mergeSubSup = function (dom, format, vars, node) {
  15932. if (format.inline === 'sub' || format.inline === 'sup') {
  15933. processChildElements(node, hasStyle(dom, 'fontSize'), applyStyle(dom, 'fontSize', ''));
  15934. dom.remove(dom.select(format.inline === 'sup' ? 'sub' : 'sup', node), true);
  15935. }
  15936. };
  15937. var mergeWithChildren = function (editor, formatList, vars, node) {
  15938. each$b(formatList, function (format) {
  15939. each$b(editor.dom.select(format.inline, node), function (child) {
  15940. if (!isElementNode(child)) {
  15941. return;
  15942. }
  15943. removeFormat(editor, format, vars, child, format.exact ? child : null);
  15944. });
  15945. clearChildStyles(editor.dom, format, node);
  15946. });
  15947. };
  15948. var mergeWithParents = function (editor, format, name, vars, node) {
  15949. if (matchNode(editor, node.parentNode, name, vars)) {
  15950. if (removeFormat(editor, format, vars, node)) {
  15951. return;
  15952. }
  15953. }
  15954. if (format.merge_with_parents) {
  15955. editor.dom.getParent(node.parentNode, function (parent) {
  15956. if (matchNode(editor, parent, name, vars)) {
  15957. removeFormat(editor, format, vars, node);
  15958. return true;
  15959. }
  15960. });
  15961. }
  15962. };
  15963. var each$c = Tools.each;
  15964. var isElementNode$1 = function (node) {
  15965. return node && node.nodeType === 1 && !isBookmarkNode$1(node) && !isCaretNode(node) && !isBogus(node);
  15966. };
  15967. var applyFormat = function (ed, name, vars, node) {
  15968. var formatList = ed.formatter.get(name);
  15969. var format = formatList[0];
  15970. var rng;
  15971. var isCollapsed = !node && ed.selection.isCollapsed();
  15972. var dom = ed.dom, selection = ed.selection;
  15973. var setElementFormat = function (elm, fmt) {
  15974. fmt = fmt || format;
  15975. if (elm) {
  15976. if (fmt.onformat) {
  15977. fmt.onformat(elm, fmt, vars, node);
  15978. }
  15979. each$c(fmt.styles, function (value, name) {
  15980. dom.setStyle(elm, name, replaceVars(value, vars));
  15981. });
  15982. if (fmt.styles) {
  15983. var styleVal = dom.getAttrib(elm, 'style');
  15984. if (styleVal) {
  15985. dom.setAttrib(elm, 'data-mce-style', styleVal);
  15986. }
  15987. }
  15988. each$c(fmt.attributes, function (value, name) {
  15989. dom.setAttrib(elm, name, replaceVars(value, vars));
  15990. });
  15991. each$c(fmt.classes, function (value) {
  15992. value = replaceVars(value, vars);
  15993. if (!dom.hasClass(elm, value)) {
  15994. dom.addClass(elm, value);
  15995. }
  15996. });
  15997. }
  15998. };
  15999. var applyNodeStyle = function (formatList, node) {
  16000. var found = false;
  16001. if (!format.selector) {
  16002. return false;
  16003. }
  16004. each$c(formatList, function (format) {
  16005. if ('collapsed' in format && format.collapsed !== isCollapsed) {
  16006. return;
  16007. }
  16008. if (dom.is(node, format.selector) && !isCaretNode(node)) {
  16009. setElementFormat(node, format);
  16010. found = true;
  16011. return false;
  16012. }
  16013. });
  16014. return found;
  16015. };
  16016. var applyRngStyle = function (dom, rng, bookmark, nodeSpecific) {
  16017. var newWrappers = [];
  16018. var contentEditable = true;
  16019. var wrapName = format.inline || format.block;
  16020. var wrapElm = dom.create(wrapName);
  16021. setElementFormat(wrapElm);
  16022. walk$1(dom, rng, function (nodes) {
  16023. var currentWrapElm;
  16024. var process = function (node) {
  16025. var hasContentEditableState = false;
  16026. var lastContentEditable = contentEditable;
  16027. var nodeName = node.nodeName.toLowerCase();
  16028. var parentName = node.parentNode.nodeName.toLowerCase();
  16029. if (isElement$1(node) && dom.getContentEditable(node)) {
  16030. lastContentEditable = contentEditable;
  16031. contentEditable = dom.getContentEditable(node) === 'true';
  16032. hasContentEditableState = true;
  16033. }
  16034. if (isEq(nodeName, 'br')) {
  16035. currentWrapElm = 0;
  16036. if (format.block) {
  16037. dom.remove(node);
  16038. }
  16039. return;
  16040. }
  16041. if (format.wrapper && matchNode(ed, node, name, vars)) {
  16042. currentWrapElm = 0;
  16043. return;
  16044. }
  16045. if (contentEditable && !hasContentEditableState && format.block && !format.wrapper && isTextBlock$1(ed, nodeName) && isValid(ed, parentName, wrapName)) {
  16046. var elm = dom.rename(node, wrapName);
  16047. setElementFormat(elm);
  16048. newWrappers.push(elm);
  16049. currentWrapElm = 0;
  16050. return;
  16051. }
  16052. if (format.selector) {
  16053. var found = applyNodeStyle(formatList, node);
  16054. if (!format.inline || found) {
  16055. currentWrapElm = 0;
  16056. return;
  16057. }
  16058. }
  16059. if (contentEditable && !hasContentEditableState && isValid(ed, wrapName, nodeName) && isValid(ed, parentName, wrapName) && !(!nodeSpecific && node.nodeType === 3 && node.nodeValue.length === 1 && node.nodeValue.charCodeAt(0) === 65279) && !isCaretNode(node) && (!format.inline || !dom.isBlock(node))) {
  16060. if (!currentWrapElm) {
  16061. currentWrapElm = dom.clone(wrapElm, false);
  16062. node.parentNode.insertBefore(currentWrapElm, node);
  16063. newWrappers.push(currentWrapElm);
  16064. }
  16065. currentWrapElm.appendChild(node);
  16066. } else {
  16067. currentWrapElm = 0;
  16068. each$c(Tools.grep(node.childNodes), process);
  16069. if (hasContentEditableState) {
  16070. contentEditable = lastContentEditable;
  16071. }
  16072. currentWrapElm = 0;
  16073. }
  16074. };
  16075. each$c(nodes, process);
  16076. });
  16077. if (format.links === true) {
  16078. each$c(newWrappers, function (node) {
  16079. var process = function (node) {
  16080. if (node.nodeName === 'A') {
  16081. setElementFormat(node, format);
  16082. }
  16083. each$c(Tools.grep(node.childNodes), process);
  16084. };
  16085. process(node);
  16086. });
  16087. }
  16088. each$c(newWrappers, function (node) {
  16089. var getChildCount = function (node) {
  16090. var count = 0;
  16091. each$c(node.childNodes, function (node) {
  16092. if (!isEmptyTextNode(node) && !isBookmarkNode$1(node)) {
  16093. count++;
  16094. }
  16095. });
  16096. return count;
  16097. };
  16098. var getChildElementNode = function (root) {
  16099. var child = false;
  16100. each$c(root.childNodes, function (node) {
  16101. if (isElementNode$1(node)) {
  16102. child = node;
  16103. return false;
  16104. }
  16105. });
  16106. return child;
  16107. };
  16108. var mergeStyles = function (node) {
  16109. var clone;
  16110. var child = getChildElementNode(node);
  16111. if (child && !isBookmarkNode$1(child) && matchName(dom, child, format)) {
  16112. clone = dom.clone(child, false);
  16113. setElementFormat(clone);
  16114. dom.replace(clone, node, true);
  16115. dom.remove(child, true);
  16116. }
  16117. return clone || node;
  16118. };
  16119. var childCount = getChildCount(node);
  16120. if ((newWrappers.length > 1 || !dom.isBlock(node)) && childCount === 0) {
  16121. dom.remove(node, true);
  16122. return;
  16123. }
  16124. if (format.inline || format.wrapper) {
  16125. if (!format.exact && childCount === 1) {
  16126. node = mergeStyles(node);
  16127. }
  16128. mergeWithChildren(ed, formatList, vars, node);
  16129. mergeWithParents(ed, format, name, vars, node);
  16130. mergeBackgroundColorAndFontSize(dom, format, vars, node);
  16131. mergeTextDecorationsAndColor(dom, format, vars, node);
  16132. mergeSubSup(dom, format, vars, node);
  16133. mergeSiblings(dom, format, vars, node);
  16134. }
  16135. });
  16136. };
  16137. if (dom.getContentEditable(selection.getNode()) === 'false') {
  16138. node = selection.getNode();
  16139. for (var i = 0, l = formatList.length; i < l; i++) {
  16140. if (formatList[i].ceFalseOverride && dom.is(node, formatList[i].selector)) {
  16141. setElementFormat(node, formatList[i]);
  16142. return;
  16143. }
  16144. }
  16145. return;
  16146. }
  16147. if (format) {
  16148. if (node) {
  16149. if (isNode(node)) {
  16150. if (!applyNodeStyle(formatList, node)) {
  16151. rng = dom.createRng();
  16152. rng.setStartBefore(node);
  16153. rng.setEndAfter(node);
  16154. applyRngStyle(dom, expandRng(ed, rng, formatList), null, true);
  16155. }
  16156. } else {
  16157. applyRngStyle(dom, node, null, true);
  16158. }
  16159. } else {
  16160. if (!isCollapsed || !format.inline || getCellsFromEditor(ed).length) {
  16161. var curSelNode = selection.getNode();
  16162. if (!ed.settings.forced_root_block && formatList[0].defaultBlock && !dom.getParent(curSelNode, dom.isBlock)) {
  16163. applyFormat(ed, formatList[0].defaultBlock);
  16164. }
  16165. selection.setRng(normalize$2(selection.getRng()));
  16166. preserve(selection, true, function (bookmark) {
  16167. runOnRanges(ed, function (selectionRng, fake) {
  16168. var expandedRng = fake ? selectionRng : expandRng(ed, selectionRng, formatList);
  16169. applyRngStyle(dom, expandedRng);
  16170. });
  16171. });
  16172. moveStart(dom, selection, selection.getRng());
  16173. ed.nodeChanged();
  16174. } else {
  16175. applyCaretFormat(ed, name, vars);
  16176. }
  16177. }
  16178. postProcess(name, ed);
  16179. }
  16180. };
  16181. var toggle = function (editor, name, vars, node) {
  16182. var fmt = editor.formatter.get(name);
  16183. if (match(editor, name, vars, node) && (!('toggle' in fmt[0]) || fmt[0].toggle)) {
  16184. remove$6(editor, name, vars, node);
  16185. } else {
  16186. applyFormat(editor, name, vars, node);
  16187. }
  16188. };
  16189. var fromElements = function (elements, scope) {
  16190. var doc = scope || document;
  16191. var fragment = doc.createDocumentFragment();
  16192. each(elements, function (element) {
  16193. fragment.appendChild(element.dom);
  16194. });
  16195. return SugarElement.fromDom(fragment);
  16196. };
  16197. var tableModel = function (element, width, rows) {
  16198. return {
  16199. element: element,
  16200. width: width,
  16201. rows: rows
  16202. };
  16203. };
  16204. var tableRow = function (element, cells) {
  16205. return {
  16206. element: element,
  16207. cells: cells
  16208. };
  16209. };
  16210. var cellPosition = function (x, y) {
  16211. return {
  16212. x: x,
  16213. y: y
  16214. };
  16215. };
  16216. var getSpan = function (td, key) {
  16217. var value = parseInt(get$3(td, key), 10);
  16218. return isNaN(value) ? 1 : value;
  16219. };
  16220. var fillout = function (table, x, y, tr, td) {
  16221. var rowspan = getSpan(td, 'rowspan');
  16222. var colspan = getSpan(td, 'colspan');
  16223. var rows = table.rows;
  16224. for (var y2 = y; y2 < y + rowspan; y2++) {
  16225. if (!rows[y2]) {
  16226. rows[y2] = tableRow(deep(tr), []);
  16227. }
  16228. for (var x2 = x; x2 < x + colspan; x2++) {
  16229. var cells = rows[y2].cells;
  16230. cells[x2] = y2 === y && x2 === x ? td : shallow(td);
  16231. }
  16232. }
  16233. };
  16234. var cellExists = function (table, x, y) {
  16235. var rows = table.rows;
  16236. var cells = rows[y] ? rows[y].cells : [];
  16237. return !!cells[x];
  16238. };
  16239. var skipCellsX = function (table, x, y) {
  16240. while (cellExists(table, x, y)) {
  16241. x++;
  16242. }
  16243. return x;
  16244. };
  16245. var getWidth = function (rows) {
  16246. return foldl(rows, function (acc, row) {
  16247. return row.cells.length > acc ? row.cells.length : acc;
  16248. }, 0);
  16249. };
  16250. var findElementPos = function (table, element) {
  16251. var rows = table.rows;
  16252. for (var y = 0; y < rows.length; y++) {
  16253. var cells = rows[y].cells;
  16254. for (var x = 0; x < cells.length; x++) {
  16255. if (eq$2(cells[x], element)) {
  16256. return Optional.some(cellPosition(x, y));
  16257. }
  16258. }
  16259. }
  16260. return Optional.none();
  16261. };
  16262. var extractRows = function (table, sx, sy, ex, ey) {
  16263. var newRows = [];
  16264. var rows = table.rows;
  16265. for (var y = sy; y <= ey; y++) {
  16266. var cells = rows[y].cells;
  16267. var slice = sx < ex ? cells.slice(sx, ex + 1) : cells.slice(ex, sx + 1);
  16268. newRows.push(tableRow(rows[y].element, slice));
  16269. }
  16270. return newRows;
  16271. };
  16272. var subTable = function (table, startPos, endPos) {
  16273. var sx = startPos.x, sy = startPos.y;
  16274. var ex = endPos.x, ey = endPos.y;
  16275. var newRows = sy < ey ? extractRows(table, sx, sy, ex, ey) : extractRows(table, sx, ey, ex, sy);
  16276. return tableModel(table.element, getWidth(newRows), newRows);
  16277. };
  16278. var createDomTable = function (table, rows) {
  16279. var tableElement = shallow(table.element);
  16280. var tableBody = SugarElement.fromTag('tbody');
  16281. append$1(tableBody, rows);
  16282. append(tableElement, tableBody);
  16283. return tableElement;
  16284. };
  16285. var modelRowsToDomRows = function (table) {
  16286. return map(table.rows, function (row) {
  16287. var cells = map(row.cells, function (cell) {
  16288. var td = deep(cell);
  16289. remove$1(td, 'colspan');
  16290. remove$1(td, 'rowspan');
  16291. return td;
  16292. });
  16293. var tr = shallow(row.element);
  16294. append$1(tr, cells);
  16295. return tr;
  16296. });
  16297. };
  16298. var fromDom$1 = function (tableElm) {
  16299. var table = tableModel(shallow(tableElm), 0, []);
  16300. each(descendants$1(tableElm, 'tr'), function (tr, y) {
  16301. each(descendants$1(tr, 'td,th'), function (td, x) {
  16302. fillout(table, skipCellsX(table, x, y), y, tr, td);
  16303. });
  16304. });
  16305. return tableModel(table.element, getWidth(table.rows), table.rows);
  16306. };
  16307. var toDom = function (table) {
  16308. return createDomTable(table, modelRowsToDomRows(table));
  16309. };
  16310. var subsection = function (table, startElement, endElement) {
  16311. return findElementPos(table, startElement).bind(function (startPos) {
  16312. return findElementPos(table, endElement).map(function (endPos) {
  16313. return subTable(table, startPos, endPos);
  16314. });
  16315. });
  16316. };
  16317. var findParentListContainer = function (parents) {
  16318. return find(parents, function (elm) {
  16319. return name(elm) === 'ul' || name(elm) === 'ol';
  16320. });
  16321. };
  16322. var getFullySelectedListWrappers = function (parents, rng) {
  16323. return find(parents, function (elm) {
  16324. return name(elm) === 'li' && hasAllContentsSelected(elm, rng);
  16325. }).fold(constant([]), function (_li) {
  16326. return findParentListContainer(parents).map(function (listCont) {
  16327. var listElm = SugarElement.fromTag(name(listCont));
  16328. var listStyles = filter$1(getAllRaw(listCont), function (_style, name) {
  16329. return startsWith(name, 'list-style');
  16330. });
  16331. setAll$1(listElm, listStyles);
  16332. return [
  16333. SugarElement.fromTag('li'),
  16334. listElm
  16335. ];
  16336. }).getOr([]);
  16337. });
  16338. };
  16339. var wrap$3 = function (innerElm, elms) {
  16340. var wrapped = foldl(elms, function (acc, elm) {
  16341. append(elm, acc);
  16342. return elm;
  16343. }, innerElm);
  16344. return elms.length > 0 ? fromElements([wrapped]) : wrapped;
  16345. };
  16346. var directListWrappers = function (commonAnchorContainer) {
  16347. if (isListItem(commonAnchorContainer)) {
  16348. return parent(commonAnchorContainer).filter(isList).fold(constant([]), function (listElm) {
  16349. return [
  16350. commonAnchorContainer,
  16351. listElm
  16352. ];
  16353. });
  16354. } else {
  16355. return isList(commonAnchorContainer) ? [commonAnchorContainer] : [];
  16356. }
  16357. };
  16358. var getWrapElements = function (rootNode, rng) {
  16359. var commonAnchorContainer = SugarElement.fromDom(rng.commonAncestorContainer);
  16360. var parents = parentsAndSelf(commonAnchorContainer, rootNode);
  16361. var wrapElements = filter(parents, function (elm) {
  16362. return isInline(elm) || isHeading(elm);
  16363. });
  16364. var listWrappers = getFullySelectedListWrappers(parents, rng);
  16365. var allWrappers = wrapElements.concat(listWrappers.length ? listWrappers : directListWrappers(commonAnchorContainer));
  16366. return map(allWrappers, shallow);
  16367. };
  16368. var emptyFragment = function () {
  16369. return fromElements([]);
  16370. };
  16371. var getFragmentFromRange = function (rootNode, rng) {
  16372. return wrap$3(SugarElement.fromDom(rng.cloneContents()), getWrapElements(rootNode, rng));
  16373. };
  16374. var getParentTable = function (rootElm, cell) {
  16375. return ancestor$1(cell, 'table', curry(eq$2, rootElm));
  16376. };
  16377. var getTableFragment = function (rootNode, selectedTableCells) {
  16378. return getParentTable(rootNode, selectedTableCells[0]).bind(function (tableElm) {
  16379. var firstCell = selectedTableCells[0];
  16380. var lastCell = selectedTableCells[selectedTableCells.length - 1];
  16381. var fullTableModel = fromDom$1(tableElm);
  16382. return subsection(fullTableModel, firstCell, lastCell).map(function (sectionedTableModel) {
  16383. return fromElements([toDom(sectionedTableModel)]);
  16384. });
  16385. }).getOrThunk(emptyFragment);
  16386. };
  16387. var getSelectionFragment = function (rootNode, ranges) {
  16388. return ranges.length > 0 && ranges[0].collapsed ? emptyFragment() : getFragmentFromRange(rootNode, ranges[0]);
  16389. };
  16390. var read$1 = function (rootNode, ranges) {
  16391. var selectedCells = getCellsFromElementOrRanges(ranges, rootNode);
  16392. return selectedCells.length > 0 ? getTableFragment(rootNode, selectedCells) : getSelectionFragment(rootNode, ranges);
  16393. };
  16394. var trimLeadingCollapsibleText = function (text) {
  16395. return text.replace(/^[ \f\n\r\t\v]+/, '');
  16396. };
  16397. var isCollapsibleWhitespace = function (text, index) {
  16398. return index >= 0 && index < text.length && isWhiteSpace$1(text.charAt(index));
  16399. };
  16400. var getInnerText = function (bin) {
  16401. var text = trim$2(bin.innerText);
  16402. return Env.browser.isIE() ? trimLeadingCollapsibleText(text) : text;
  16403. };
  16404. var getTextContent = function (editor) {
  16405. return Optional.from(editor.selection.getRng()).map(function (rng) {
  16406. var bin = editor.dom.add(editor.getBody(), 'div', {
  16407. 'data-mce-bogus': 'all',
  16408. 'style': 'overflow: hidden; opacity: 0;'
  16409. }, rng.cloneContents());
  16410. var text = getInnerText(bin);
  16411. var nonRenderedText = trim$2(bin.textContent);
  16412. editor.dom.remove(bin);
  16413. if (isCollapsibleWhitespace(nonRenderedText, 0) || isCollapsibleWhitespace(nonRenderedText, nonRenderedText.length - 1)) {
  16414. var parentBlock = editor.dom.getParent(rng.commonAncestorContainer, editor.dom.isBlock);
  16415. var parentBlockText = getInnerText(parentBlock);
  16416. var textIndex = parentBlockText.indexOf(text);
  16417. if (textIndex !== -1) {
  16418. var hasProceedingSpace = isCollapsibleWhitespace(parentBlockText, textIndex - 1);
  16419. var hasTrailingSpace = isCollapsibleWhitespace(parentBlockText, textIndex + text.length);
  16420. return (hasProceedingSpace ? ' ' : '') + text + (hasTrailingSpace ? ' ' : '');
  16421. } else {
  16422. return text;
  16423. }
  16424. } else {
  16425. return text;
  16426. }
  16427. }).getOr('');
  16428. };
  16429. var getSerializedContent = function (editor, args) {
  16430. var rng = editor.selection.getRng(), tmpElm = editor.dom.create('body');
  16431. var sel = editor.selection.getSel();
  16432. var ranges = processRanges(editor, getRanges(sel));
  16433. var fragment = args.contextual ? read$1(SugarElement.fromDom(editor.getBody()), ranges).dom : rng.cloneContents();
  16434. if (fragment) {
  16435. tmpElm.appendChild(fragment);
  16436. }
  16437. return editor.selection.serializer.serialize(tmpElm, args);
  16438. };
  16439. var getSelectedContentInternal = function (editor, format, args) {
  16440. if (args === void 0) {
  16441. args = {};
  16442. }
  16443. args.get = true;
  16444. args.format = format;
  16445. args.selection = true;
  16446. args = editor.fire('BeforeGetContent', args);
  16447. if (args.isDefaultPrevented()) {
  16448. editor.fire('GetContent', args);
  16449. return args.content;
  16450. }
  16451. if (args.format === 'text') {
  16452. return getTextContent(editor);
  16453. } else {
  16454. args.getInner = true;
  16455. var content = getSerializedContent(editor, args);
  16456. if (args.format === 'tree') {
  16457. return content;
  16458. } else {
  16459. args.content = editor.selection.isCollapsed() ? '' : content;
  16460. editor.fire('GetContent', args);
  16461. return args.content;
  16462. }
  16463. }
  16464. };
  16465. var KEEP = 0, INSERT = 1, DELETE = 2;
  16466. var diff = function (left, right) {
  16467. var size = left.length + right.length + 2;
  16468. var vDown = new Array(size);
  16469. var vUp = new Array(size);
  16470. var snake = function (start, end, diag) {
  16471. return {
  16472. start: start,
  16473. end: end,
  16474. diag: diag
  16475. };
  16476. };
  16477. var buildScript = function (start1, end1, start2, end2, script) {
  16478. var middle = getMiddleSnake(start1, end1, start2, end2);
  16479. if (middle === null || middle.start === end1 && middle.diag === end1 - end2 || middle.end === start1 && middle.diag === start1 - start2) {
  16480. var i = start1;
  16481. var j = start2;
  16482. while (i < end1 || j < end2) {
  16483. if (i < end1 && j < end2 && left[i] === right[j]) {
  16484. script.push([
  16485. KEEP,
  16486. left[i]
  16487. ]);
  16488. ++i;
  16489. ++j;
  16490. } else {
  16491. if (end1 - start1 > end2 - start2) {
  16492. script.push([
  16493. DELETE,
  16494. left[i]
  16495. ]);
  16496. ++i;
  16497. } else {
  16498. script.push([
  16499. INSERT,
  16500. right[j]
  16501. ]);
  16502. ++j;
  16503. }
  16504. }
  16505. }
  16506. } else {
  16507. buildScript(start1, middle.start, start2, middle.start - middle.diag, script);
  16508. for (var i2 = middle.start; i2 < middle.end; ++i2) {
  16509. script.push([
  16510. KEEP,
  16511. left[i2]
  16512. ]);
  16513. }
  16514. buildScript(middle.end, end1, middle.end - middle.diag, end2, script);
  16515. }
  16516. };
  16517. var buildSnake = function (start, diag, end1, end2) {
  16518. var end = start;
  16519. while (end - diag < end2 && end < end1 && left[end] === right[end - diag]) {
  16520. ++end;
  16521. }
  16522. return snake(start, end, diag);
  16523. };
  16524. var getMiddleSnake = function (start1, end1, start2, end2) {
  16525. var m = end1 - start1;
  16526. var n = end2 - start2;
  16527. if (m === 0 || n === 0) {
  16528. return null;
  16529. }
  16530. var delta = m - n;
  16531. var sum = n + m;
  16532. var offset = (sum % 2 === 0 ? sum : sum + 1) / 2;
  16533. vDown[1 + offset] = start1;
  16534. vUp[1 + offset] = end1 + 1;
  16535. var d, k, i, x, y;
  16536. for (d = 0; d <= offset; ++d) {
  16537. for (k = -d; k <= d; k += 2) {
  16538. i = k + offset;
  16539. if (k === -d || k !== d && vDown[i - 1] < vDown[i + 1]) {
  16540. vDown[i] = vDown[i + 1];
  16541. } else {
  16542. vDown[i] = vDown[i - 1] + 1;
  16543. }
  16544. x = vDown[i];
  16545. y = x - start1 + start2 - k;
  16546. while (x < end1 && y < end2 && left[x] === right[y]) {
  16547. vDown[i] = ++x;
  16548. ++y;
  16549. }
  16550. if (delta % 2 !== 0 && delta - d <= k && k <= delta + d) {
  16551. if (vUp[i - delta] <= vDown[i]) {
  16552. return buildSnake(vUp[i - delta], k + start1 - start2, end1, end2);
  16553. }
  16554. }
  16555. }
  16556. for (k = delta - d; k <= delta + d; k += 2) {
  16557. i = k + offset - delta;
  16558. if (k === delta - d || k !== delta + d && vUp[i + 1] <= vUp[i - 1]) {
  16559. vUp[i] = vUp[i + 1] - 1;
  16560. } else {
  16561. vUp[i] = vUp[i - 1];
  16562. }
  16563. x = vUp[i] - 1;
  16564. y = x - start1 + start2 - k;
  16565. while (x >= start1 && y >= start2 && left[x] === right[y]) {
  16566. vUp[i] = x--;
  16567. y--;
  16568. }
  16569. if (delta % 2 === 0 && -d <= k && k <= d) {
  16570. if (vUp[i] <= vDown[i + delta]) {
  16571. return buildSnake(vUp[i], k + start1 - start2, end1, end2);
  16572. }
  16573. }
  16574. }
  16575. }
  16576. };
  16577. var script = [];
  16578. buildScript(0, left.length, 0, right.length, script);
  16579. return script;
  16580. };
  16581. var getOuterHtml = function (elm) {
  16582. if (isElement$1(elm)) {
  16583. return elm.outerHTML;
  16584. } else if (isText$1(elm)) {
  16585. return Entities.encodeRaw(elm.data, false);
  16586. } else if (isComment$1(elm)) {
  16587. return '<!--' + elm.data + '-->';
  16588. }
  16589. return '';
  16590. };
  16591. var createFragment$1 = function (html) {
  16592. var node;
  16593. var container = document.createElement('div');
  16594. var frag = document.createDocumentFragment();
  16595. if (html) {
  16596. container.innerHTML = html;
  16597. }
  16598. while (node = container.firstChild) {
  16599. frag.appendChild(node);
  16600. }
  16601. return frag;
  16602. };
  16603. var insertAt = function (elm, html, index) {
  16604. var fragment = createFragment$1(html);
  16605. if (elm.hasChildNodes() && index < elm.childNodes.length) {
  16606. var target = elm.childNodes[index];
  16607. target.parentNode.insertBefore(fragment, target);
  16608. } else {
  16609. elm.appendChild(fragment);
  16610. }
  16611. };
  16612. var removeAt = function (elm, index) {
  16613. if (elm.hasChildNodes() && index < elm.childNodes.length) {
  16614. var target = elm.childNodes[index];
  16615. target.parentNode.removeChild(target);
  16616. }
  16617. };
  16618. var applyDiff = function (diff, elm) {
  16619. var index = 0;
  16620. each(diff, function (action) {
  16621. if (action[0] === KEEP) {
  16622. index++;
  16623. } else if (action[0] === INSERT) {
  16624. insertAt(elm, action[1], index);
  16625. index++;
  16626. } else if (action[0] === DELETE) {
  16627. removeAt(elm, index);
  16628. }
  16629. });
  16630. };
  16631. var read$2 = function (elm) {
  16632. return filter(map(from$1(elm.childNodes), getOuterHtml), function (item) {
  16633. return item.length > 0;
  16634. });
  16635. };
  16636. var write = function (fragments, elm) {
  16637. var currentFragments = map(from$1(elm.childNodes), getOuterHtml);
  16638. applyDiff(diff(currentFragments, fragments), elm);
  16639. return elm;
  16640. };
  16641. var undoLevelDocument = Cell(Optional.none());
  16642. var lazyTempDocument = function () {
  16643. return undoLevelDocument.get().getOrThunk(function () {
  16644. var doc = document.implementation.createHTMLDocument('undo');
  16645. undoLevelDocument.set(Optional.some(doc));
  16646. return doc;
  16647. });
  16648. };
  16649. var hasIframes = function (html) {
  16650. return html.indexOf('</iframe>') !== -1;
  16651. };
  16652. var createFragmentedLevel = function (fragments) {
  16653. return {
  16654. type: 'fragmented',
  16655. fragments: fragments,
  16656. content: '',
  16657. bookmark: null,
  16658. beforeBookmark: null
  16659. };
  16660. };
  16661. var createCompleteLevel = function (content) {
  16662. return {
  16663. type: 'complete',
  16664. fragments: null,
  16665. content: content,
  16666. bookmark: null,
  16667. beforeBookmark: null
  16668. };
  16669. };
  16670. var createFromEditor = function (editor) {
  16671. var fragments = read$2(editor.getBody());
  16672. var trimmedFragments = bind(fragments, function (html) {
  16673. var trimmed = trimInternal(editor.serializer, html);
  16674. return trimmed.length > 0 ? [trimmed] : [];
  16675. });
  16676. var content = trimmedFragments.join('');
  16677. return hasIframes(content) ? createFragmentedLevel(trimmedFragments) : createCompleteLevel(content);
  16678. };
  16679. var applyToEditor = function (editor, level, before) {
  16680. if (level.type === 'fragmented') {
  16681. write(level.fragments, editor.getBody());
  16682. } else {
  16683. editor.setContent(level.content, { format: 'raw' });
  16684. }
  16685. editor.selection.moveToBookmark(before ? level.beforeBookmark : level.bookmark);
  16686. };
  16687. var getLevelContent = function (level) {
  16688. return level.type === 'fragmented' ? level.fragments.join('') : level.content;
  16689. };
  16690. var getCleanLevelContent = function (level) {
  16691. var elm = SugarElement.fromTag('body', lazyTempDocument());
  16692. set$1(elm, getLevelContent(level));
  16693. each(descendants$1(elm, '*[data-mce-bogus]'), unwrap);
  16694. return get$6(elm);
  16695. };
  16696. var hasEqualContent = function (level1, level2) {
  16697. return getLevelContent(level1) === getLevelContent(level2);
  16698. };
  16699. var hasEqualCleanedContent = function (level1, level2) {
  16700. return getCleanLevelContent(level1) === getCleanLevelContent(level2);
  16701. };
  16702. var isEq$4 = function (level1, level2) {
  16703. if (!level1 || !level2) {
  16704. return false;
  16705. } else if (hasEqualContent(level1, level2)) {
  16706. return true;
  16707. } else {
  16708. return hasEqualCleanedContent(level1, level2);
  16709. }
  16710. };
  16711. var isUnlocked = function (locks) {
  16712. return locks.get() === 0;
  16713. };
  16714. var setTyping = function (undoManager, typing, locks) {
  16715. if (isUnlocked(locks)) {
  16716. undoManager.typing = typing;
  16717. }
  16718. };
  16719. var endTyping = function (undoManager, locks) {
  16720. if (undoManager.typing) {
  16721. setTyping(undoManager, false, locks);
  16722. undoManager.add();
  16723. }
  16724. };
  16725. var endTypingLevelIgnoreLocks = function (undoManager) {
  16726. if (undoManager.typing) {
  16727. undoManager.typing = false;
  16728. undoManager.add();
  16729. }
  16730. };
  16731. var beforeChange = function (editor, locks, beforeBookmark) {
  16732. if (isUnlocked(locks)) {
  16733. beforeBookmark.set(Optional.some(getUndoBookmark(editor.selection)));
  16734. }
  16735. };
  16736. var addUndoLevel = function (editor, undoManager, index, locks, beforeBookmark, level, event) {
  16737. var currentLevel = createFromEditor(editor);
  16738. level = level || {};
  16739. level = Tools.extend(level, currentLevel);
  16740. if (isUnlocked(locks) === false || editor.removed) {
  16741. return null;
  16742. }
  16743. var lastLevel = undoManager.data[index.get()];
  16744. if (editor.fire('BeforeAddUndo', {
  16745. level: level,
  16746. lastLevel: lastLevel,
  16747. originalEvent: event
  16748. }).isDefaultPrevented()) {
  16749. return null;
  16750. }
  16751. if (lastLevel && isEq$4(lastLevel, level)) {
  16752. return null;
  16753. }
  16754. if (undoManager.data[index.get()]) {
  16755. beforeBookmark.get().each(function (bm) {
  16756. undoManager.data[index.get()].beforeBookmark = bm;
  16757. });
  16758. }
  16759. var customUndoRedoLevels = getCustomUndoRedoLevels(editor);
  16760. if (customUndoRedoLevels) {
  16761. if (undoManager.data.length > customUndoRedoLevels) {
  16762. for (var i = 0; i < undoManager.data.length - 1; i++) {
  16763. undoManager.data[i] = undoManager.data[i + 1];
  16764. }
  16765. undoManager.data.length--;
  16766. index.set(undoManager.data.length);
  16767. }
  16768. }
  16769. level.bookmark = getUndoBookmark(editor.selection);
  16770. if (index.get() < undoManager.data.length - 1) {
  16771. undoManager.data.length = index.get() + 1;
  16772. }
  16773. undoManager.data.push(level);
  16774. index.set(undoManager.data.length - 1);
  16775. var args = {
  16776. level: level,
  16777. lastLevel: lastLevel,
  16778. originalEvent: event
  16779. };
  16780. if (index.get() > 0) {
  16781. editor.setDirty(true);
  16782. editor.fire('AddUndo', args);
  16783. editor.fire('change', args);
  16784. } else {
  16785. editor.fire('AddUndo', args);
  16786. }
  16787. return level;
  16788. };
  16789. var clear = function (editor, undoManager, index) {
  16790. undoManager.data = [];
  16791. index.set(0);
  16792. undoManager.typing = false;
  16793. editor.fire('ClearUndos');
  16794. };
  16795. var extra = function (editor, undoManager, index, callback1, callback2) {
  16796. if (undoManager.transact(callback1)) {
  16797. var bookmark = undoManager.data[index.get()].bookmark;
  16798. var lastLevel = undoManager.data[index.get() - 1];
  16799. applyToEditor(editor, lastLevel, true);
  16800. if (undoManager.transact(callback2)) {
  16801. undoManager.data[index.get() - 1].beforeBookmark = bookmark;
  16802. }
  16803. }
  16804. };
  16805. var redo = function (editor, index, data) {
  16806. var level;
  16807. if (index.get() < data.length - 1) {
  16808. index.set(index.get() + 1);
  16809. level = data[index.get()];
  16810. applyToEditor(editor, level, false);
  16811. editor.setDirty(true);
  16812. editor.fire('Redo', { level: level });
  16813. }
  16814. return level;
  16815. };
  16816. var undo = function (editor, undoManager, locks, index) {
  16817. var level;
  16818. if (undoManager.typing) {
  16819. undoManager.add();
  16820. undoManager.typing = false;
  16821. setTyping(undoManager, false, locks);
  16822. }
  16823. if (index.get() > 0) {
  16824. index.set(index.get() - 1);
  16825. level = undoManager.data[index.get()];
  16826. applyToEditor(editor, level, true);
  16827. editor.setDirty(true);
  16828. editor.fire('Undo', { level: level });
  16829. }
  16830. return level;
  16831. };
  16832. var reset = function (undoManager) {
  16833. undoManager.clear();
  16834. undoManager.add();
  16835. };
  16836. var hasUndo = function (editor, undoManager, index) {
  16837. return index.get() > 0 || undoManager.typing && undoManager.data[0] && !isEq$4(createFromEditor(editor), undoManager.data[0]);
  16838. };
  16839. var hasRedo = function (undoManager, index) {
  16840. return index.get() < undoManager.data.length - 1 && !undoManager.typing;
  16841. };
  16842. var transact = function (undoManager, locks, callback) {
  16843. endTyping(undoManager, locks);
  16844. undoManager.beforeChange();
  16845. undoManager.ignore(callback);
  16846. return undoManager.add();
  16847. };
  16848. var ignore = function (locks, callback) {
  16849. try {
  16850. locks.set(locks.get() + 1);
  16851. callback();
  16852. } finally {
  16853. locks.set(locks.get() - 1);
  16854. }
  16855. };
  16856. var isTreeNode$1 = function (content) {
  16857. return content instanceof AstNode;
  16858. };
  16859. var runSerializerFiltersOnFragment = function (editor, fragment) {
  16860. filter$3(editor.serializer.getNodeFilters(), editor.serializer.getAttributeFilters(), fragment);
  16861. };
  16862. var getInsertContext = function (editor) {
  16863. return Optional.from(editor.selection.getStart(true)).map(function (elm) {
  16864. return elm.nodeName.toLowerCase();
  16865. });
  16866. };
  16867. var createDummyUndoLevel = function () {
  16868. return {
  16869. type: 'complete',
  16870. fragments: [],
  16871. content: '',
  16872. bookmark: null,
  16873. beforeBookmark: null
  16874. };
  16875. };
  16876. var makePlainAdaptor = function (editor) {
  16877. return {
  16878. undoManager: {
  16879. beforeChange: function (locks, beforeBookmark) {
  16880. return beforeChange(editor, locks, beforeBookmark);
  16881. },
  16882. addUndoLevel: function (undoManager, index, locks, beforeBookmark, level, event) {
  16883. return addUndoLevel(editor, undoManager, index, locks, beforeBookmark, level, event);
  16884. },
  16885. undo: function (undoManager, locks, index) {
  16886. return undo(editor, undoManager, locks, index);
  16887. },
  16888. redo: function (index, data) {
  16889. return redo(editor, index, data);
  16890. },
  16891. clear: function (undoManager, index) {
  16892. return clear(editor, undoManager, index);
  16893. },
  16894. reset: function (undoManager) {
  16895. return reset(undoManager);
  16896. },
  16897. hasUndo: function (undoManager, index) {
  16898. return hasUndo(editor, undoManager, index);
  16899. },
  16900. hasRedo: function (undoManager, index) {
  16901. return hasRedo(undoManager, index);
  16902. },
  16903. transact: function (undoManager, locks, callback) {
  16904. return transact(undoManager, locks, callback);
  16905. },
  16906. ignore: function (locks, callback) {
  16907. return ignore(locks, callback);
  16908. },
  16909. extra: function (undoManager, index, callback1, callback2) {
  16910. return extra(editor, undoManager, index, callback1, callback2);
  16911. }
  16912. },
  16913. formatter: {
  16914. apply: function (name, vars, node) {
  16915. return applyFormat(editor, name, vars, node);
  16916. },
  16917. remove: function (name, vars, node, similar) {
  16918. return remove$6(editor, name, vars, node, similar);
  16919. },
  16920. toggle: function (name, vars, node) {
  16921. return toggle(editor, name, vars, node);
  16922. }
  16923. },
  16924. editor: {
  16925. getContent: function (args, format) {
  16926. return getContentInternal(editor, args, format);
  16927. },
  16928. setContent: function (content, args) {
  16929. return setContentInternal(editor, content, args);
  16930. },
  16931. insertContent: function (value, details) {
  16932. return insertHtmlAtCaret(editor, value, details);
  16933. }
  16934. },
  16935. selection: {
  16936. getContent: function (format, args) {
  16937. return getSelectedContentInternal(editor, format, args);
  16938. }
  16939. },
  16940. raw: {
  16941. getModel: function () {
  16942. return Optional.none();
  16943. }
  16944. }
  16945. };
  16946. };
  16947. var makeRtcAdaptor = function (tinymceEditor, rtcEditor) {
  16948. var defaultVars = function (vars) {
  16949. return isObject(vars) ? vars : {};
  16950. };
  16951. var unsupported = die('Unimplemented feature for rtc');
  16952. var ignore = noop;
  16953. return {
  16954. undoManager: {
  16955. beforeChange: ignore,
  16956. addUndoLevel: unsupported,
  16957. undo: function () {
  16958. rtcEditor.undo();
  16959. return createDummyUndoLevel();
  16960. },
  16961. redo: function () {
  16962. rtcEditor.redo();
  16963. return createDummyUndoLevel();
  16964. },
  16965. clear: unsupported,
  16966. reset: unsupported,
  16967. hasUndo: function () {
  16968. return rtcEditor.hasUndo();
  16969. },
  16970. hasRedo: function () {
  16971. return rtcEditor.hasRedo();
  16972. },
  16973. transact: function (_undoManager, _locks, fn) {
  16974. rtcEditor.transact(fn);
  16975. return createDummyUndoLevel();
  16976. },
  16977. ignore: unsupported,
  16978. extra: unsupported
  16979. },
  16980. formatter: {
  16981. apply: function (name, vars, _node) {
  16982. return rtcEditor.applyFormat(name, defaultVars(vars));
  16983. },
  16984. remove: function (name, vars, _node, _similar) {
  16985. return rtcEditor.removeFormat(name, defaultVars(vars));
  16986. },
  16987. toggle: function (name, vars, _node) {
  16988. return rtcEditor.toggleFormat(name, defaultVars(vars));
  16989. }
  16990. },
  16991. editor: {
  16992. getContent: function (args, format) {
  16993. if (format === 'html' || format === 'tree') {
  16994. var fragment = rtcEditor.getContent();
  16995. var serializer = HtmlSerializer({ inner: true });
  16996. runSerializerFiltersOnFragment(tinymceEditor, fragment);
  16997. return format === 'tree' ? fragment : serializer.serialize(fragment);
  16998. } else {
  16999. return makePlainAdaptor(tinymceEditor).editor.getContent(args, format);
  17000. }
  17001. },
  17002. setContent: function (content, _args) {
  17003. var fragment = isTreeNode$1(content) ? content : tinymceEditor.parser.parse(content, {
  17004. isRootContent: true,
  17005. insert: true
  17006. });
  17007. rtcEditor.setContent(fragment);
  17008. return content;
  17009. },
  17010. insertContent: function (value, _details) {
  17011. var contextArgs = getInsertContext(tinymceEditor).fold(function () {
  17012. return {};
  17013. }, function (context) {
  17014. return { context: context };
  17015. });
  17016. var fragment = isTreeNode$1(value) ? value : tinymceEditor.parser.parse(value, __assign(__assign({}, contextArgs), { insert: true }));
  17017. rtcEditor.insertContent(fragment);
  17018. }
  17019. },
  17020. selection: {
  17021. getContent: function (format, args) {
  17022. if (format === 'html' || format === 'tree') {
  17023. var fragment = rtcEditor.getSelectedContent();
  17024. var serializer = HtmlSerializer({});
  17025. runSerializerFiltersOnFragment(tinymceEditor, fragment);
  17026. return format === 'tree' ? fragment : serializer.serialize(fragment);
  17027. } else {
  17028. return makePlainAdaptor(tinymceEditor).selection.getContent(format, args);
  17029. }
  17030. }
  17031. },
  17032. raw: {
  17033. getModel: function () {
  17034. return Optional.some(rtcEditor.getRawModel());
  17035. }
  17036. }
  17037. };
  17038. };
  17039. var isRtc = function (editor) {
  17040. return has(editor.plugins, 'rtc');
  17041. };
  17042. var setup$4 = function (editor) {
  17043. var editorCast = editor;
  17044. return get(editor.plugins, 'rtc').fold(function () {
  17045. editorCast.rtcInstance = makePlainAdaptor(editor);
  17046. return Optional.none();
  17047. }, function (rtc) {
  17048. return Optional.some(rtc.setup().then(function (rtcEditor) {
  17049. editorCast.rtcInstance = makeRtcAdaptor(editor, rtcEditor);
  17050. return rtcEditor.isRemote;
  17051. }));
  17052. });
  17053. };
  17054. var getRtcInstanceWithFallback = function (editor) {
  17055. return editor.rtcInstance ? editor.rtcInstance : makePlainAdaptor(editor);
  17056. };
  17057. var getRtcInstanceWithError = function (editor) {
  17058. var rtcInstance = editor.rtcInstance;
  17059. if (!rtcInstance) {
  17060. throw new Error('Failed to get RTC instance not yet initialized.');
  17061. } else {
  17062. return rtcInstance;
  17063. }
  17064. };
  17065. var beforeChange$1 = function (editor, locks, beforeBookmark) {
  17066. getRtcInstanceWithError(editor).undoManager.beforeChange(locks, beforeBookmark);
  17067. };
  17068. var addUndoLevel$1 = function (editor, undoManager, index, locks, beforeBookmark, level, event) {
  17069. return getRtcInstanceWithError(editor).undoManager.addUndoLevel(undoManager, index, locks, beforeBookmark, level, event);
  17070. };
  17071. var undo$1 = function (editor, undoManager, locks, index) {
  17072. return getRtcInstanceWithError(editor).undoManager.undo(undoManager, locks, index);
  17073. };
  17074. var redo$1 = function (editor, index, data) {
  17075. return getRtcInstanceWithError(editor).undoManager.redo(index, data);
  17076. };
  17077. var clear$1 = function (editor, undoManager, index) {
  17078. getRtcInstanceWithError(editor).undoManager.clear(undoManager, index);
  17079. };
  17080. var reset$1 = function (editor, undoManager) {
  17081. getRtcInstanceWithError(editor).undoManager.reset(undoManager);
  17082. };
  17083. var hasUndo$1 = function (editor, undoManager, index) {
  17084. return getRtcInstanceWithError(editor).undoManager.hasUndo(undoManager, index);
  17085. };
  17086. var hasRedo$1 = function (editor, undoManager, index) {
  17087. return getRtcInstanceWithError(editor).undoManager.hasRedo(undoManager, index);
  17088. };
  17089. var transact$1 = function (editor, undoManager, locks, callback) {
  17090. return getRtcInstanceWithError(editor).undoManager.transact(undoManager, locks, callback);
  17091. };
  17092. var ignore$1 = function (editor, locks, callback) {
  17093. getRtcInstanceWithError(editor).undoManager.ignore(locks, callback);
  17094. };
  17095. var extra$1 = function (editor, undoManager, index, callback1, callback2) {
  17096. getRtcInstanceWithError(editor).undoManager.extra(undoManager, index, callback1, callback2);
  17097. };
  17098. var applyFormat$1 = function (editor, name, vars, node) {
  17099. getRtcInstanceWithError(editor).formatter.apply(name, vars, node);
  17100. };
  17101. var removeFormat$1 = function (editor, name, vars, node, similar) {
  17102. getRtcInstanceWithError(editor).formatter.remove(name, vars, node, similar);
  17103. };
  17104. var toggleFormat = function (editor, name, vars, node) {
  17105. getRtcInstanceWithError(editor).formatter.toggle(name, vars, node);
  17106. };
  17107. var getContent = function (editor, args, format) {
  17108. return getRtcInstanceWithFallback(editor).editor.getContent(args, format);
  17109. };
  17110. var setContent = function (editor, content, args) {
  17111. return getRtcInstanceWithFallback(editor).editor.setContent(content, args);
  17112. };
  17113. var insertContent = function (editor, value, details) {
  17114. return getRtcInstanceWithFallback(editor).editor.insertContent(value, details);
  17115. };
  17116. var getSelectedContent = function (editor, format, args) {
  17117. return getRtcInstanceWithError(editor).selection.getContent(format, args);
  17118. };
  17119. var getContent$1 = function (editor, args) {
  17120. if (args === void 0) {
  17121. args = {};
  17122. }
  17123. var format = args.format ? args.format : 'html';
  17124. return getSelectedContent(editor, format, args);
  17125. };
  17126. var removeEmpty = function (text) {
  17127. if (text.dom.length === 0) {
  17128. remove(text);
  17129. return Optional.none();
  17130. } else {
  17131. return Optional.some(text);
  17132. }
  17133. };
  17134. var walkPastBookmark = function (node, start) {
  17135. return node.filter(function (elm) {
  17136. return BookmarkManager$1.isBookmarkNode(elm.dom);
  17137. }).bind(start ? nextSibling : prevSibling);
  17138. };
  17139. var merge = function (outer, inner, rng, start) {
  17140. var outerElm = outer.dom;
  17141. var innerElm = inner.dom;
  17142. var oldLength = start ? outerElm.length : innerElm.length;
  17143. if (start) {
  17144. mergeTextNodes(outerElm, innerElm, false, !start);
  17145. rng.setStart(innerElm, oldLength);
  17146. } else {
  17147. mergeTextNodes(innerElm, outerElm, false, !start);
  17148. rng.setEnd(innerElm, oldLength);
  17149. }
  17150. };
  17151. var normalizeTextIfRequired = function (inner, start) {
  17152. parent(inner).each(function (root) {
  17153. var text = inner.dom;
  17154. if (start && needsToBeNbspLeft(root, CaretPosition$1(text, 0))) {
  17155. normalizeWhitespaceAfter(text, 0);
  17156. } else if (!start && needsToBeNbspRight(root, CaretPosition$1(text, text.length))) {
  17157. normalizeWhitespaceBefore(text, text.length);
  17158. }
  17159. });
  17160. };
  17161. var mergeAndNormalizeText = function (outerNode, innerNode, rng, start) {
  17162. outerNode.bind(function (outer) {
  17163. var normalizer = start ? normalizeWhitespaceBefore : normalizeWhitespaceAfter;
  17164. normalizer(outer.dom, start ? outer.dom.length : 0);
  17165. return innerNode.filter(isText).map(function (inner) {
  17166. return merge(outer, inner, rng, start);
  17167. });
  17168. }).orThunk(function () {
  17169. var innerTextNode = walkPastBookmark(innerNode, start).or(innerNode).filter(isText);
  17170. return innerTextNode.map(function (inner) {
  17171. return normalizeTextIfRequired(inner, start);
  17172. });
  17173. });
  17174. };
  17175. var rngSetContent = function (rng, fragment) {
  17176. var firstChild = Optional.from(fragment.firstChild).map(SugarElement.fromDom);
  17177. var lastChild = Optional.from(fragment.lastChild).map(SugarElement.fromDom);
  17178. rng.deleteContents();
  17179. rng.insertNode(fragment);
  17180. var prevText = firstChild.bind(prevSibling).filter(isText).bind(removeEmpty);
  17181. var nextText = lastChild.bind(nextSibling).filter(isText).bind(removeEmpty);
  17182. mergeAndNormalizeText(prevText, firstChild, rng, true);
  17183. mergeAndNormalizeText(nextText, lastChild, rng, false);
  17184. rng.collapse(false);
  17185. };
  17186. var setupArgs = function (args, content) {
  17187. return __assign(__assign({ format: 'html' }, args), {
  17188. set: true,
  17189. selection: true,
  17190. content: content
  17191. });
  17192. };
  17193. var cleanContent = function (editor, args) {
  17194. if (args.format !== 'raw') {
  17195. var rng = editor.selection.getRng();
  17196. var contextBlock = editor.dom.getParent(rng.commonAncestorContainer, editor.dom.isBlock);
  17197. var contextArgs = contextBlock ? { context: contextBlock.nodeName.toLowerCase() } : {};
  17198. var node = editor.parser.parse(args.content, __assign(__assign({
  17199. isRootContent: true,
  17200. forced_root_block: false
  17201. }, contextArgs), args));
  17202. return HtmlSerializer({ validate: editor.validate }, editor.schema).serialize(node);
  17203. } else {
  17204. return args.content;
  17205. }
  17206. };
  17207. var setContent$1 = function (editor, content, args) {
  17208. if (args === void 0) {
  17209. args = {};
  17210. }
  17211. var contentArgs = setupArgs(args, content);
  17212. if (!contentArgs.no_events) {
  17213. contentArgs = editor.fire('BeforeSetContent', contentArgs);
  17214. if (contentArgs.isDefaultPrevented()) {
  17215. editor.fire('SetContent', contentArgs);
  17216. return;
  17217. }
  17218. }
  17219. args.content = cleanContent(editor, contentArgs);
  17220. var rng = editor.selection.getRng();
  17221. rngSetContent(rng, rng.createContextualFragment(args.content));
  17222. editor.selection.setRng(rng);
  17223. scrollRangeIntoView(editor, rng);
  17224. if (!contentArgs.no_events) {
  17225. editor.fire('SetContent', contentArgs);
  17226. }
  17227. };
  17228. var deleteFromCallbackMap = function (callbackMap, selector, callback) {
  17229. if (callbackMap && callbackMap.hasOwnProperty(selector)) {
  17230. var newCallbacks = filter(callbackMap[selector], function (cb) {
  17231. return cb !== callback;
  17232. });
  17233. if (newCallbacks.length === 0) {
  17234. delete callbackMap[selector];
  17235. } else {
  17236. callbackMap[selector] = newCallbacks;
  17237. }
  17238. }
  17239. };
  17240. function SelectorChanged (dom, editor) {
  17241. var selectorChangedData;
  17242. var currentSelectors;
  17243. return {
  17244. selectorChangedWithUnbind: function (selector, callback) {
  17245. if (!selectorChangedData) {
  17246. selectorChangedData = {};
  17247. currentSelectors = {};
  17248. editor.on('NodeChange', function (e) {
  17249. var node = e.element, parents = dom.getParents(node, null, dom.getRoot()), matchedSelectors = {};
  17250. Tools.each(selectorChangedData, function (callbacks, selector) {
  17251. Tools.each(parents, function (node) {
  17252. if (dom.is(node, selector)) {
  17253. if (!currentSelectors[selector]) {
  17254. Tools.each(callbacks, function (callback) {
  17255. callback(true, {
  17256. node: node,
  17257. selector: selector,
  17258. parents: parents
  17259. });
  17260. });
  17261. currentSelectors[selector] = callbacks;
  17262. }
  17263. matchedSelectors[selector] = callbacks;
  17264. return false;
  17265. }
  17266. });
  17267. });
  17268. Tools.each(currentSelectors, function (callbacks, selector) {
  17269. if (!matchedSelectors[selector]) {
  17270. delete currentSelectors[selector];
  17271. Tools.each(callbacks, function (callback) {
  17272. callback(false, {
  17273. node: node,
  17274. selector: selector,
  17275. parents: parents
  17276. });
  17277. });
  17278. }
  17279. });
  17280. });
  17281. }
  17282. if (!selectorChangedData[selector]) {
  17283. selectorChangedData[selector] = [];
  17284. }
  17285. selectorChangedData[selector].push(callback);
  17286. return {
  17287. unbind: function () {
  17288. deleteFromCallbackMap(selectorChangedData, selector, callback);
  17289. deleteFromCallbackMap(currentSelectors, selector, callback);
  17290. }
  17291. };
  17292. }
  17293. };
  17294. }
  17295. var isNativeIeSelection = function (rng) {
  17296. return !!rng.select;
  17297. };
  17298. var isAttachedToDom = function (node) {
  17299. return !!(node && node.ownerDocument) && contains$2(SugarElement.fromDom(node.ownerDocument), SugarElement.fromDom(node));
  17300. };
  17301. var isValidRange = function (rng) {
  17302. if (!rng) {
  17303. return false;
  17304. } else if (isNativeIeSelection(rng)) {
  17305. return true;
  17306. } else {
  17307. return isAttachedToDom(rng.startContainer) && isAttachedToDom(rng.endContainer);
  17308. }
  17309. };
  17310. var EditorSelection = function (dom, win, serializer, editor) {
  17311. var selectedRange;
  17312. var explicitRange;
  17313. var selectorChangedWithUnbind = SelectorChanged(dom, editor).selectorChangedWithUnbind;
  17314. var setCursorLocation = function (node, offset) {
  17315. var rng = dom.createRng();
  17316. if (!node) {
  17317. moveEndPoint$1(dom, rng, editor.getBody(), true);
  17318. setRng(rng);
  17319. } else {
  17320. rng.setStart(node, offset);
  17321. rng.setEnd(node, offset);
  17322. setRng(rng);
  17323. collapse(false);
  17324. }
  17325. };
  17326. var getContent = function (args) {
  17327. return getContent$1(editor, args);
  17328. };
  17329. var setContent = function (content, args) {
  17330. return setContent$1(editor, content, args);
  17331. };
  17332. var getStart = function (real) {
  17333. return getStart$2(editor.getBody(), getRng$1(), real);
  17334. };
  17335. var getEnd$1 = function (real) {
  17336. return getEnd(editor.getBody(), getRng$1(), real);
  17337. };
  17338. var getBookmark = function (type, normalized) {
  17339. return bookmarkManager.getBookmark(type, normalized);
  17340. };
  17341. var moveToBookmark = function (bookmark) {
  17342. return bookmarkManager.moveToBookmark(bookmark);
  17343. };
  17344. var select = function (node, content) {
  17345. select$1(dom, node, content).each(setRng);
  17346. return node;
  17347. };
  17348. var isCollapsed = function () {
  17349. var rng = getRng$1(), sel = getSel();
  17350. if (!rng || rng.item) {
  17351. return false;
  17352. }
  17353. if (rng.compareEndPoints) {
  17354. return rng.compareEndPoints('StartToEnd', rng) === 0;
  17355. }
  17356. return !sel || rng.collapsed;
  17357. };
  17358. var collapse = function (toStart) {
  17359. var rng = getRng$1();
  17360. rng.collapse(!!toStart);
  17361. setRng(rng);
  17362. };
  17363. var getSel = function () {
  17364. return win.getSelection ? win.getSelection() : win.document.selection;
  17365. };
  17366. var getRng$1 = function () {
  17367. var selection, rng, elm;
  17368. var tryCompareBoundaryPoints = function (how, sourceRange, destinationRange) {
  17369. try {
  17370. return sourceRange.compareBoundaryPoints(how, destinationRange);
  17371. } catch (ex) {
  17372. return -1;
  17373. }
  17374. };
  17375. if (!win) {
  17376. return null;
  17377. }
  17378. var doc = win.document;
  17379. if (typeof doc === 'undefined' || doc === null) {
  17380. return null;
  17381. }
  17382. if (editor.bookmark !== undefined && hasFocus$1(editor) === false) {
  17383. var bookmark = getRng(editor);
  17384. if (bookmark.isSome()) {
  17385. return bookmark.map(function (r) {
  17386. return processRanges(editor, [r])[0];
  17387. }).getOr(doc.createRange());
  17388. }
  17389. }
  17390. try {
  17391. if ((selection = getSel()) && !isRestrictedNode(selection.anchorNode)) {
  17392. if (selection.rangeCount > 0) {
  17393. rng = selection.getRangeAt(0);
  17394. } else {
  17395. rng = selection.createRange ? selection.createRange() : doc.createRange();
  17396. }
  17397. rng = processRanges(editor, [rng])[0];
  17398. }
  17399. } catch (ex) {
  17400. }
  17401. if (!rng) {
  17402. rng = doc.createRange ? doc.createRange() : doc.body.createTextRange();
  17403. }
  17404. if (rng.setStart && rng.startContainer.nodeType === 9 && rng.collapsed) {
  17405. elm = dom.getRoot();
  17406. rng.setStart(elm, 0);
  17407. rng.setEnd(elm, 0);
  17408. }
  17409. if (selectedRange && explicitRange) {
  17410. if (tryCompareBoundaryPoints(rng.START_TO_START, rng, selectedRange) === 0 && tryCompareBoundaryPoints(rng.END_TO_END, rng, selectedRange) === 0) {
  17411. rng = explicitRange;
  17412. } else {
  17413. selectedRange = null;
  17414. explicitRange = null;
  17415. }
  17416. }
  17417. return rng;
  17418. };
  17419. var setRng = function (rng, forward) {
  17420. var node;
  17421. if (!isValidRange(rng)) {
  17422. return;
  17423. }
  17424. var ieRange = isNativeIeSelection(rng) ? rng : null;
  17425. if (ieRange) {
  17426. explicitRange = null;
  17427. try {
  17428. ieRange.select();
  17429. } catch (ex) {
  17430. }
  17431. return;
  17432. }
  17433. var sel = getSel();
  17434. var evt = editor.fire('SetSelectionRange', {
  17435. range: rng,
  17436. forward: forward
  17437. });
  17438. rng = evt.range;
  17439. if (sel) {
  17440. explicitRange = rng;
  17441. try {
  17442. sel.removeAllRanges();
  17443. sel.addRange(rng);
  17444. } catch (ex) {
  17445. }
  17446. if (forward === false && sel.extend) {
  17447. sel.collapse(rng.endContainer, rng.endOffset);
  17448. sel.extend(rng.startContainer, rng.startOffset);
  17449. }
  17450. selectedRange = sel.rangeCount > 0 ? sel.getRangeAt(0) : null;
  17451. }
  17452. if (!rng.collapsed && rng.startContainer === rng.endContainer && sel.setBaseAndExtent && !Env.ie) {
  17453. if (rng.endOffset - rng.startOffset < 2) {
  17454. if (rng.startContainer.hasChildNodes()) {
  17455. node = rng.startContainer.childNodes[rng.startOffset];
  17456. if (node && node.tagName === 'IMG') {
  17457. sel.setBaseAndExtent(rng.startContainer, rng.startOffset, rng.endContainer, rng.endOffset);
  17458. if (sel.anchorNode !== rng.startContainer || sel.focusNode !== rng.endContainer) {
  17459. sel.setBaseAndExtent(node, 0, node, 1);
  17460. }
  17461. }
  17462. }
  17463. }
  17464. }
  17465. editor.fire('AfterSetSelectionRange', {
  17466. range: rng,
  17467. forward: forward
  17468. });
  17469. };
  17470. var setNode = function (elm) {
  17471. setContent(dom.getOuterHTML(elm));
  17472. return elm;
  17473. };
  17474. var getNode = function () {
  17475. return getNode$1(editor.getBody(), getRng$1());
  17476. };
  17477. var getSelectedBlocks$1 = function (startElm, endElm) {
  17478. return getSelectedBlocks(dom, getRng$1(), startElm, endElm);
  17479. };
  17480. var isForward = function () {
  17481. var sel = getSel();
  17482. var anchorNode = sel === null || sel === void 0 ? void 0 : sel.anchorNode;
  17483. var focusNode = sel === null || sel === void 0 ? void 0 : sel.focusNode;
  17484. if (!sel || !anchorNode || !focusNode || isRestrictedNode(anchorNode) || isRestrictedNode(focusNode)) {
  17485. return true;
  17486. }
  17487. var anchorRange = dom.createRng();
  17488. anchorRange.setStart(anchorNode, sel.anchorOffset);
  17489. anchorRange.collapse(true);
  17490. var focusRange = dom.createRng();
  17491. focusRange.setStart(focusNode, sel.focusOffset);
  17492. focusRange.collapse(true);
  17493. return anchorRange.compareBoundaryPoints(anchorRange.START_TO_START, focusRange) <= 0;
  17494. };
  17495. var normalize$1 = function () {
  17496. var rng = getRng$1();
  17497. var sel = getSel();
  17498. if (!hasMultipleRanges(sel) && hasAnyRanges(editor)) {
  17499. var normRng = normalize(dom, rng);
  17500. normRng.each(function (normRng) {
  17501. setRng(normRng, isForward());
  17502. });
  17503. return normRng.getOr(rng);
  17504. }
  17505. return rng;
  17506. };
  17507. var selectorChanged = function (selector, callback) {
  17508. selectorChangedWithUnbind(selector, callback);
  17509. return exports;
  17510. };
  17511. var getScrollContainer = function () {
  17512. var scrollContainer;
  17513. var node = dom.getRoot();
  17514. while (node && node.nodeName !== 'BODY') {
  17515. if (node.scrollHeight > node.clientHeight) {
  17516. scrollContainer = node;
  17517. break;
  17518. }
  17519. node = node.parentNode;
  17520. }
  17521. return scrollContainer;
  17522. };
  17523. var scrollIntoView = function (elm, alignToTop) {
  17524. return scrollElementIntoView(editor, elm, alignToTop);
  17525. };
  17526. var placeCaretAt = function (clientX, clientY) {
  17527. return setRng(fromPoint$1(clientX, clientY, editor.getDoc()));
  17528. };
  17529. var getBoundingClientRect = function () {
  17530. var rng = getRng$1();
  17531. return rng.collapsed ? CaretPosition$1.fromRangeStart(rng).getClientRects()[0] : rng.getBoundingClientRect();
  17532. };
  17533. var destroy = function () {
  17534. win = selectedRange = explicitRange = null;
  17535. controlSelection.destroy();
  17536. };
  17537. var exports = {
  17538. bookmarkManager: null,
  17539. controlSelection: null,
  17540. dom: dom,
  17541. win: win,
  17542. serializer: serializer,
  17543. editor: editor,
  17544. collapse: collapse,
  17545. setCursorLocation: setCursorLocation,
  17546. getContent: getContent,
  17547. setContent: setContent,
  17548. getBookmark: getBookmark,
  17549. moveToBookmark: moveToBookmark,
  17550. select: select,
  17551. isCollapsed: isCollapsed,
  17552. isForward: isForward,
  17553. setNode: setNode,
  17554. getNode: getNode,
  17555. getSel: getSel,
  17556. setRng: setRng,
  17557. getRng: getRng$1,
  17558. getStart: getStart,
  17559. getEnd: getEnd$1,
  17560. getSelectedBlocks: getSelectedBlocks$1,
  17561. normalize: normalize$1,
  17562. selectorChanged: selectorChanged,
  17563. selectorChangedWithUnbind: selectorChangedWithUnbind,
  17564. getScrollContainer: getScrollContainer,
  17565. scrollIntoView: scrollIntoView,
  17566. placeCaretAt: placeCaretAt,
  17567. getBoundingClientRect: getBoundingClientRect,
  17568. destroy: destroy
  17569. };
  17570. var bookmarkManager = BookmarkManager$1(exports);
  17571. var controlSelection = ControlSelection(exports, editor);
  17572. exports.bookmarkManager = bookmarkManager;
  17573. exports.controlSelection = controlSelection;
  17574. return exports;
  17575. };
  17576. var removeAttrs = function (node, names) {
  17577. each(names, function (name) {
  17578. node.attr(name, null);
  17579. });
  17580. };
  17581. var addFontToSpansFilter = function (domParser, styles, fontSizes) {
  17582. domParser.addNodeFilter('font', function (nodes) {
  17583. each(nodes, function (node) {
  17584. var props = styles.parse(node.attr('style'));
  17585. var color = node.attr('color');
  17586. var face = node.attr('face');
  17587. var size = node.attr('size');
  17588. if (color) {
  17589. props.color = color;
  17590. }
  17591. if (face) {
  17592. props['font-family'] = face;
  17593. }
  17594. if (size) {
  17595. props['font-size'] = fontSizes[parseInt(node.attr('size'), 10) - 1];
  17596. }
  17597. node.name = 'span';
  17598. node.attr('style', styles.serialize(props));
  17599. removeAttrs(node, [
  17600. 'color',
  17601. 'face',
  17602. 'size'
  17603. ]);
  17604. });
  17605. });
  17606. };
  17607. var addStrikeToSpanFilter = function (domParser, styles) {
  17608. domParser.addNodeFilter('strike', function (nodes) {
  17609. each(nodes, function (node) {
  17610. var props = styles.parse(node.attr('style'));
  17611. props['text-decoration'] = 'line-through';
  17612. node.name = 'span';
  17613. node.attr('style', styles.serialize(props));
  17614. });
  17615. });
  17616. };
  17617. var addFilters = function (domParser, settings) {
  17618. var styles = Styles();
  17619. if (settings.convert_fonts_to_spans) {
  17620. addFontToSpansFilter(domParser, styles, Tools.explode(settings.font_size_legacy_values));
  17621. }
  17622. addStrikeToSpanFilter(domParser, styles);
  17623. };
  17624. var register$1 = function (domParser, settings) {
  17625. if (settings.inline_styles) {
  17626. addFilters(domParser, settings);
  17627. }
  17628. };
  17629. var blobUriToBlob = function (url) {
  17630. return new promiseObj(function (resolve, reject) {
  17631. var rejectWithError = function () {
  17632. reject('Cannot convert ' + url + ' to Blob. Resource might not exist or is inaccessible.');
  17633. };
  17634. try {
  17635. var xhr = new XMLHttpRequest();
  17636. xhr.open('GET', url, true);
  17637. xhr.responseType = 'blob';
  17638. xhr.onload = function () {
  17639. if (this.status === 200) {
  17640. resolve(this.response);
  17641. } else {
  17642. rejectWithError();
  17643. }
  17644. };
  17645. xhr.onerror = rejectWithError;
  17646. xhr.send();
  17647. } catch (ex) {
  17648. rejectWithError();
  17649. }
  17650. });
  17651. };
  17652. var parseDataUri$1 = function (uri) {
  17653. var type;
  17654. var uriParts = decodeURIComponent(uri).split(',');
  17655. var matches = /data:([^;]+)/.exec(uriParts[0]);
  17656. if (matches) {
  17657. type = matches[1];
  17658. }
  17659. return {
  17660. type: type,
  17661. data: uriParts[1]
  17662. };
  17663. };
  17664. var buildBlob = function (type, data) {
  17665. var str;
  17666. try {
  17667. str = atob(data);
  17668. } catch (e) {
  17669. return Optional.none();
  17670. }
  17671. var arr = new Uint8Array(str.length);
  17672. for (var i = 0; i < arr.length; i++) {
  17673. arr[i] = str.charCodeAt(i);
  17674. }
  17675. return Optional.some(new Blob([arr], { type: type }));
  17676. };
  17677. var dataUriToBlob = function (uri) {
  17678. return new promiseObj(function (resolve) {
  17679. var _a = parseDataUri$1(uri), type = _a.type, data = _a.data;
  17680. buildBlob(type, data).fold(function () {
  17681. return resolve(new Blob([]));
  17682. }, resolve);
  17683. });
  17684. };
  17685. var uriToBlob = function (url) {
  17686. if (url.indexOf('blob:') === 0) {
  17687. return blobUriToBlob(url);
  17688. }
  17689. if (url.indexOf('data:') === 0) {
  17690. return dataUriToBlob(url);
  17691. }
  17692. return null;
  17693. };
  17694. var blobToDataUri = function (blob) {
  17695. return new promiseObj(function (resolve) {
  17696. var reader = new FileReader();
  17697. reader.onloadend = function () {
  17698. resolve(reader.result);
  17699. };
  17700. reader.readAsDataURL(blob);
  17701. });
  17702. };
  17703. var count = 0;
  17704. var uniqueId = function (prefix) {
  17705. return (prefix || 'blobid') + count++;
  17706. };
  17707. var imageToBlobInfo = function (blobCache, img, resolve, reject) {
  17708. var base64, blobInfo;
  17709. if (img.src.indexOf('blob:') === 0) {
  17710. blobInfo = blobCache.getByUri(img.src);
  17711. if (blobInfo) {
  17712. resolve({
  17713. image: img,
  17714. blobInfo: blobInfo
  17715. });
  17716. } else {
  17717. uriToBlob(img.src).then(function (blob) {
  17718. blobToDataUri(blob).then(function (dataUri) {
  17719. base64 = parseDataUri$1(dataUri).data;
  17720. blobInfo = blobCache.create(uniqueId(), blob, base64);
  17721. blobCache.add(blobInfo);
  17722. resolve({
  17723. image: img,
  17724. blobInfo: blobInfo
  17725. });
  17726. });
  17727. }, function (err) {
  17728. reject(err);
  17729. });
  17730. }
  17731. return;
  17732. }
  17733. var _a = parseDataUri$1(img.src), data = _a.data, type = _a.type;
  17734. base64 = data;
  17735. blobInfo = blobCache.getByData(base64, type);
  17736. if (blobInfo) {
  17737. resolve({
  17738. image: img,
  17739. blobInfo: blobInfo
  17740. });
  17741. } else {
  17742. uriToBlob(img.src).then(function (blob) {
  17743. blobInfo = blobCache.create(uniqueId(), blob, base64);
  17744. blobCache.add(blobInfo);
  17745. resolve({
  17746. image: img,
  17747. blobInfo: blobInfo
  17748. });
  17749. }, function (err) {
  17750. reject(err);
  17751. });
  17752. }
  17753. };
  17754. var getAllImages = function (elm) {
  17755. return elm ? from$1(elm.getElementsByTagName('img')) : [];
  17756. };
  17757. function ImageScanner(uploadStatus, blobCache) {
  17758. var cachedPromises = {};
  17759. var findAll = function (elm, predicate) {
  17760. if (!predicate) {
  17761. predicate = always;
  17762. }
  17763. var images = filter(getAllImages(elm), function (img) {
  17764. var src = img.src;
  17765. if (!Env.fileApi) {
  17766. return false;
  17767. }
  17768. if (img.hasAttribute('data-mce-bogus')) {
  17769. return false;
  17770. }
  17771. if (img.hasAttribute('data-mce-placeholder')) {
  17772. return false;
  17773. }
  17774. if (!src || src === Env.transparentSrc) {
  17775. return false;
  17776. }
  17777. if (src.indexOf('blob:') === 0) {
  17778. return !uploadStatus.isUploaded(src) && predicate(img);
  17779. }
  17780. if (src.indexOf('data:') === 0) {
  17781. return predicate(img);
  17782. }
  17783. return false;
  17784. });
  17785. var promises = map(images, function (img) {
  17786. if (cachedPromises[img.src] !== undefined) {
  17787. return new promiseObj(function (resolve) {
  17788. cachedPromises[img.src].then(function (imageInfo) {
  17789. if (typeof imageInfo === 'string') {
  17790. return imageInfo;
  17791. }
  17792. resolve({
  17793. image: img,
  17794. blobInfo: imageInfo.blobInfo
  17795. });
  17796. });
  17797. });
  17798. }
  17799. var newPromise = new promiseObj(function (resolve, reject) {
  17800. imageToBlobInfo(blobCache, img, resolve, reject);
  17801. }).then(function (result) {
  17802. delete cachedPromises[result.image.src];
  17803. return result;
  17804. }).catch(function (error) {
  17805. delete cachedPromises[img.src];
  17806. return error;
  17807. });
  17808. cachedPromises[img.src] = newPromise;
  17809. return newPromise;
  17810. });
  17811. return promiseObj.all(promises);
  17812. };
  17813. return { findAll: findAll };
  17814. }
  17815. var paddEmptyNode = function (settings, args, blockElements, node) {
  17816. var brPreferred = settings.padd_empty_with_br || args.insert;
  17817. if (brPreferred && blockElements[node.name]) {
  17818. node.empty().append(new AstNode('br', 1)).shortEnded = true;
  17819. } else {
  17820. node.empty().append(new AstNode('#text', 3)).value = nbsp;
  17821. }
  17822. };
  17823. var isPaddedWithNbsp = function (node) {
  17824. return hasOnlyChild(node, '#text') && node.firstChild.value === nbsp;
  17825. };
  17826. var hasOnlyChild = function (node, name) {
  17827. return node && node.firstChild && node.firstChild === node.lastChild && node.firstChild.name === name;
  17828. };
  17829. var isPadded = function (schema, node) {
  17830. var rule = schema.getElementRule(node.name);
  17831. return rule && rule.paddEmpty;
  17832. };
  17833. var isEmpty$2 = function (schema, nonEmptyElements, whitespaceElements, node) {
  17834. return node.isEmpty(nonEmptyElements, whitespaceElements, function (node) {
  17835. return isPadded(schema, node);
  17836. });
  17837. };
  17838. var isLineBreakNode = function (node, blockElements) {
  17839. return node && (blockElements[node.name] || node.name === 'br');
  17840. };
  17841. var isBogusImage = function (img) {
  17842. return img.attr('data-mce-bogus');
  17843. };
  17844. var isInternalImageSource = function (img) {
  17845. return img.attr('src') === Env.transparentSrc || img.attr('data-mce-placeholder');
  17846. };
  17847. var isValidDataImg = function (img, settings) {
  17848. if (settings.images_dataimg_filter) {
  17849. var imgElem_1 = new Image();
  17850. imgElem_1.src = img.attr('src');
  17851. each$1(img.attributes.map, function (value, key) {
  17852. imgElem_1.setAttribute(key, value);
  17853. });
  17854. return settings.images_dataimg_filter(imgElem_1);
  17855. } else {
  17856. return true;
  17857. }
  17858. };
  17859. var registerBase64ImageFilter = function (parser, settings) {
  17860. var blobCache = settings.blob_cache;
  17861. var processImage = function (img) {
  17862. var inputSrc = img.attr('src');
  17863. if (isInternalImageSource(img) || isBogusImage(img)) {
  17864. return;
  17865. }
  17866. parseDataUri(inputSrc).filter(function () {
  17867. return isValidDataImg(img, settings);
  17868. }).bind(function (_a) {
  17869. var type = _a.type, data = _a.data;
  17870. return Optional.from(blobCache.getByData(data, type)).orThunk(function () {
  17871. return buildBlob(type, data).map(function (blob) {
  17872. var blobInfo = blobCache.create(uniqueId(), blob, data);
  17873. blobCache.add(blobInfo);
  17874. return blobInfo;
  17875. });
  17876. });
  17877. }).each(function (blobInfo) {
  17878. img.attr('src', blobInfo.blobUri());
  17879. });
  17880. };
  17881. if (blobCache) {
  17882. parser.addAttributeFilter('src', function (nodes) {
  17883. return each(nodes, processImage);
  17884. });
  17885. }
  17886. };
  17887. var register$2 = function (parser, settings) {
  17888. var schema = parser.schema;
  17889. if (settings.remove_trailing_brs) {
  17890. parser.addNodeFilter('br', function (nodes, _, args) {
  17891. var i;
  17892. var l = nodes.length;
  17893. var node;
  17894. var blockElements = Tools.extend({}, schema.getBlockElements());
  17895. var nonEmptyElements = schema.getNonEmptyElements();
  17896. var parent, lastParent, prev, prevName;
  17897. var whiteSpaceElements = schema.getWhiteSpaceElements();
  17898. var elementRule, textNode;
  17899. blockElements.body = 1;
  17900. for (i = 0; i < l; i++) {
  17901. node = nodes[i];
  17902. parent = node.parent;
  17903. if (blockElements[node.parent.name] && node === parent.lastChild) {
  17904. prev = node.prev;
  17905. while (prev) {
  17906. prevName = prev.name;
  17907. if (prevName !== 'span' || prev.attr('data-mce-type') !== 'bookmark') {
  17908. if (prevName === 'br') {
  17909. node = null;
  17910. }
  17911. break;
  17912. }
  17913. prev = prev.prev;
  17914. }
  17915. if (node) {
  17916. node.remove();
  17917. if (isEmpty$2(schema, nonEmptyElements, whiteSpaceElements, parent)) {
  17918. elementRule = schema.getElementRule(parent.name);
  17919. if (elementRule) {
  17920. if (elementRule.removeEmpty) {
  17921. parent.remove();
  17922. } else if (elementRule.paddEmpty) {
  17923. paddEmptyNode(settings, args, blockElements, parent);
  17924. }
  17925. }
  17926. }
  17927. }
  17928. } else {
  17929. lastParent = node;
  17930. while (parent && parent.firstChild === lastParent && parent.lastChild === lastParent) {
  17931. lastParent = parent;
  17932. if (blockElements[parent.name]) {
  17933. break;
  17934. }
  17935. parent = parent.parent;
  17936. }
  17937. if (lastParent === parent && settings.padd_empty_with_br !== true) {
  17938. textNode = new AstNode('#text', 3);
  17939. textNode.value = nbsp;
  17940. node.replace(textNode);
  17941. }
  17942. }
  17943. }
  17944. });
  17945. }
  17946. parser.addAttributeFilter('href', function (nodes) {
  17947. var i = nodes.length;
  17948. var appendRel = function (rel) {
  17949. var parts = rel.split(' ').filter(function (p) {
  17950. return p.length > 0;
  17951. });
  17952. return parts.concat(['noopener']).sort().join(' ');
  17953. };
  17954. var addNoOpener = function (rel) {
  17955. var newRel = rel ? Tools.trim(rel) : '';
  17956. if (!/\b(noopener)\b/g.test(newRel)) {
  17957. return appendRel(newRel);
  17958. } else {
  17959. return newRel;
  17960. }
  17961. };
  17962. if (!settings.allow_unsafe_link_target) {
  17963. while (i--) {
  17964. var node = nodes[i];
  17965. if (node.name === 'a' && node.attr('target') === '_blank') {
  17966. node.attr('rel', addNoOpener(node.attr('rel')));
  17967. }
  17968. }
  17969. }
  17970. });
  17971. if (!settings.allow_html_in_named_anchor) {
  17972. parser.addAttributeFilter('id,name', function (nodes) {
  17973. var i = nodes.length, sibling, prevSibling, parent, node;
  17974. while (i--) {
  17975. node = nodes[i];
  17976. if (node.name === 'a' && node.firstChild && !node.attr('href')) {
  17977. parent = node.parent;
  17978. sibling = node.lastChild;
  17979. do {
  17980. prevSibling = sibling.prev;
  17981. parent.insert(sibling, node);
  17982. sibling = prevSibling;
  17983. } while (sibling);
  17984. }
  17985. }
  17986. });
  17987. }
  17988. if (settings.fix_list_elements) {
  17989. parser.addNodeFilter('ul,ol', function (nodes) {
  17990. var i = nodes.length, node, parentNode;
  17991. while (i--) {
  17992. node = nodes[i];
  17993. parentNode = node.parent;
  17994. if (parentNode.name === 'ul' || parentNode.name === 'ol') {
  17995. if (node.prev && node.prev.name === 'li') {
  17996. node.prev.append(node);
  17997. } else {
  17998. var li = new AstNode('li', 1);
  17999. li.attr('style', 'list-style-type: none');
  18000. node.wrap(li);
  18001. }
  18002. }
  18003. }
  18004. });
  18005. }
  18006. if (settings.validate && schema.getValidClasses()) {
  18007. parser.addAttributeFilter('class', function (nodes) {
  18008. var i = nodes.length, node, classList, ci, className, classValue;
  18009. var validClasses = schema.getValidClasses();
  18010. var validClassesMap, valid;
  18011. while (i--) {
  18012. node = nodes[i];
  18013. classList = node.attr('class').split(' ');
  18014. classValue = '';
  18015. for (ci = 0; ci < classList.length; ci++) {
  18016. className = classList[ci];
  18017. valid = false;
  18018. validClassesMap = validClasses['*'];
  18019. if (validClassesMap && validClassesMap[className]) {
  18020. valid = true;
  18021. }
  18022. validClassesMap = validClasses[node.name];
  18023. if (!valid && validClassesMap && validClassesMap[className]) {
  18024. valid = true;
  18025. }
  18026. if (valid) {
  18027. if (classValue) {
  18028. classValue += ' ';
  18029. }
  18030. classValue += className;
  18031. }
  18032. }
  18033. if (!classValue.length) {
  18034. classValue = null;
  18035. }
  18036. node.attr('class', classValue);
  18037. }
  18038. });
  18039. }
  18040. registerBase64ImageFilter(parser, settings);
  18041. };
  18042. var makeMap$4 = Tools.makeMap, each$d = Tools.each, explode$2 = Tools.explode, extend$2 = Tools.extend;
  18043. var DomParser = function (settings, schema) {
  18044. if (schema === void 0) {
  18045. schema = Schema();
  18046. }
  18047. var nodeFilters = {};
  18048. var attributeFilters = [];
  18049. var matchedNodes = {};
  18050. var matchedAttributes = {};
  18051. settings = settings || {};
  18052. settings.validate = 'validate' in settings ? settings.validate : true;
  18053. settings.root_name = settings.root_name || 'body';
  18054. var fixInvalidChildren = function (nodes) {
  18055. var ni, node, parent, parents, newParent, currentNode, tempNode, childNode, i;
  18056. var sibling, nextNode;
  18057. var nonSplitableElements = makeMap$4('tr,td,th,tbody,thead,tfoot,table');
  18058. var nonEmptyElements = schema.getNonEmptyElements();
  18059. var whitespaceElements = schema.getWhiteSpaceElements();
  18060. var textBlockElements = schema.getTextBlockElements();
  18061. var specialElements = schema.getSpecialElements();
  18062. for (ni = 0; ni < nodes.length; ni++) {
  18063. node = nodes[ni];
  18064. if (!node.parent || node.fixed) {
  18065. continue;
  18066. }
  18067. if (textBlockElements[node.name] && node.parent.name === 'li') {
  18068. sibling = node.next;
  18069. while (sibling) {
  18070. if (textBlockElements[sibling.name]) {
  18071. sibling.name = 'li';
  18072. sibling.fixed = true;
  18073. node.parent.insert(sibling, node.parent);
  18074. } else {
  18075. break;
  18076. }
  18077. sibling = sibling.next;
  18078. }
  18079. node.unwrap(node);
  18080. continue;
  18081. }
  18082. parents = [node];
  18083. for (parent = node.parent; parent && !schema.isValidChild(parent.name, node.name) && !nonSplitableElements[parent.name]; parent = parent.parent) {
  18084. parents.push(parent);
  18085. }
  18086. if (parent && parents.length > 1) {
  18087. parents.reverse();
  18088. newParent = currentNode = filterNode(parents[0].clone());
  18089. for (i = 0; i < parents.length - 1; i++) {
  18090. if (schema.isValidChild(currentNode.name, parents[i].name)) {
  18091. tempNode = filterNode(parents[i].clone());
  18092. currentNode.append(tempNode);
  18093. } else {
  18094. tempNode = currentNode;
  18095. }
  18096. for (childNode = parents[i].firstChild; childNode && childNode !== parents[i + 1];) {
  18097. nextNode = childNode.next;
  18098. tempNode.append(childNode);
  18099. childNode = nextNode;
  18100. }
  18101. currentNode = tempNode;
  18102. }
  18103. if (!isEmpty$2(schema, nonEmptyElements, whitespaceElements, newParent)) {
  18104. parent.insert(newParent, parents[0], true);
  18105. parent.insert(node, newParent);
  18106. } else {
  18107. parent.insert(node, parents[0], true);
  18108. }
  18109. parent = parents[0];
  18110. if (isEmpty$2(schema, nonEmptyElements, whitespaceElements, parent) || hasOnlyChild(parent, 'br')) {
  18111. parent.empty().remove();
  18112. }
  18113. } else if (node.parent) {
  18114. if (node.name === 'li') {
  18115. sibling = node.prev;
  18116. if (sibling && (sibling.name === 'ul' || sibling.name === 'ol')) {
  18117. sibling.append(node);
  18118. continue;
  18119. }
  18120. sibling = node.next;
  18121. if (sibling && (sibling.name === 'ul' || sibling.name === 'ol')) {
  18122. sibling.insert(node, sibling.firstChild, true);
  18123. continue;
  18124. }
  18125. node.wrap(filterNode(new AstNode('ul', 1)));
  18126. continue;
  18127. }
  18128. if (schema.isValidChild(node.parent.name, 'div') && schema.isValidChild('div', node.name)) {
  18129. node.wrap(filterNode(new AstNode('div', 1)));
  18130. } else {
  18131. if (specialElements[node.name]) {
  18132. node.empty().remove();
  18133. } else {
  18134. node.unwrap();
  18135. }
  18136. }
  18137. }
  18138. }
  18139. };
  18140. var filterNode = function (node) {
  18141. var i, name, list;
  18142. name = node.name;
  18143. if (name in nodeFilters) {
  18144. list = matchedNodes[name];
  18145. if (list) {
  18146. list.push(node);
  18147. } else {
  18148. matchedNodes[name] = [node];
  18149. }
  18150. }
  18151. i = attributeFilters.length;
  18152. while (i--) {
  18153. name = attributeFilters[i].name;
  18154. if (name in node.attributes.map) {
  18155. list = matchedAttributes[name];
  18156. if (list) {
  18157. list.push(node);
  18158. } else {
  18159. matchedAttributes[name] = [node];
  18160. }
  18161. }
  18162. }
  18163. return node;
  18164. };
  18165. var addNodeFilter = function (name, callback) {
  18166. each$d(explode$2(name), function (name) {
  18167. var list = nodeFilters[name];
  18168. if (!list) {
  18169. nodeFilters[name] = list = [];
  18170. }
  18171. list.push(callback);
  18172. });
  18173. };
  18174. var getNodeFilters = function () {
  18175. var out = [];
  18176. for (var name_1 in nodeFilters) {
  18177. if (nodeFilters.hasOwnProperty(name_1)) {
  18178. out.push({
  18179. name: name_1,
  18180. callbacks: nodeFilters[name_1]
  18181. });
  18182. }
  18183. }
  18184. return out;
  18185. };
  18186. var addAttributeFilter = function (name, callback) {
  18187. each$d(explode$2(name), function (name) {
  18188. var i;
  18189. for (i = 0; i < attributeFilters.length; i++) {
  18190. if (attributeFilters[i].name === name) {
  18191. attributeFilters[i].callbacks.push(callback);
  18192. return;
  18193. }
  18194. }
  18195. attributeFilters.push({
  18196. name: name,
  18197. callbacks: [callback]
  18198. });
  18199. });
  18200. };
  18201. var getAttributeFilters = function () {
  18202. return [].concat(attributeFilters);
  18203. };
  18204. var parse = function (html, args) {
  18205. var nodes, i, l, fi, fl, list, name;
  18206. var invalidChildren = [];
  18207. var isInWhiteSpacePreservedElement;
  18208. var node;
  18209. var getRootBlockName = function (name) {
  18210. if (name === false) {
  18211. return '';
  18212. } else if (name === true) {
  18213. return 'p';
  18214. } else {
  18215. return name;
  18216. }
  18217. };
  18218. args = args || {};
  18219. matchedNodes = {};
  18220. matchedAttributes = {};
  18221. var blockElements = extend$2(makeMap$4('script,style,head,html,body,title,meta,param'), schema.getBlockElements());
  18222. var nonEmptyElements = schema.getNonEmptyElements();
  18223. var children = schema.children;
  18224. var validate = settings.validate;
  18225. var forcedRootBlockName = 'forced_root_block' in args ? args.forced_root_block : settings.forced_root_block;
  18226. var rootBlockName = getRootBlockName(forcedRootBlockName);
  18227. var whiteSpaceElements = schema.getWhiteSpaceElements();
  18228. var startWhiteSpaceRegExp = /^[ \t\r\n]+/;
  18229. var endWhiteSpaceRegExp = /[ \t\r\n]+$/;
  18230. var allWhiteSpaceRegExp = /[ \t\r\n]+/g;
  18231. var isAllWhiteSpaceRegExp = /^[ \t\r\n]+$/;
  18232. isInWhiteSpacePreservedElement = whiteSpaceElements.hasOwnProperty(args.context) || whiteSpaceElements.hasOwnProperty(settings.root_name);
  18233. var addRootBlocks = function () {
  18234. var node = rootNode.firstChild, next, rootBlockNode;
  18235. var trim = function (rootBlockNode) {
  18236. if (rootBlockNode) {
  18237. node = rootBlockNode.firstChild;
  18238. if (node && node.type === 3) {
  18239. node.value = node.value.replace(startWhiteSpaceRegExp, '');
  18240. }
  18241. node = rootBlockNode.lastChild;
  18242. if (node && node.type === 3) {
  18243. node.value = node.value.replace(endWhiteSpaceRegExp, '');
  18244. }
  18245. }
  18246. };
  18247. if (!schema.isValidChild(rootNode.name, rootBlockName.toLowerCase())) {
  18248. return;
  18249. }
  18250. while (node) {
  18251. next = node.next;
  18252. if (node.type === 3 || node.type === 1 && node.name !== 'p' && !blockElements[node.name] && !node.attr('data-mce-type')) {
  18253. if (!rootBlockNode) {
  18254. rootBlockNode = createNode(rootBlockName, 1);
  18255. rootBlockNode.attr(settings.forced_root_block_attrs);
  18256. rootNode.insert(rootBlockNode, node);
  18257. rootBlockNode.append(node);
  18258. } else {
  18259. rootBlockNode.append(node);
  18260. }
  18261. } else {
  18262. trim(rootBlockNode);
  18263. rootBlockNode = null;
  18264. }
  18265. node = next;
  18266. }
  18267. trim(rootBlockNode);
  18268. };
  18269. var createNode = function (name, type) {
  18270. var node = new AstNode(name, type);
  18271. var list;
  18272. if (name in nodeFilters) {
  18273. list = matchedNodes[name];
  18274. if (list) {
  18275. list.push(node);
  18276. } else {
  18277. matchedNodes[name] = [node];
  18278. }
  18279. }
  18280. return node;
  18281. };
  18282. var removeWhitespaceBefore = function (node) {
  18283. var textNode, textNodeNext, textVal, sibling;
  18284. var blockElements = schema.getBlockElements();
  18285. for (textNode = node.prev; textNode && textNode.type === 3;) {
  18286. textVal = textNode.value.replace(endWhiteSpaceRegExp, '');
  18287. if (textVal.length > 0) {
  18288. textNode.value = textVal;
  18289. return;
  18290. }
  18291. textNodeNext = textNode.next;
  18292. if (textNodeNext) {
  18293. if (textNodeNext.type === 3 && textNodeNext.value.length) {
  18294. textNode = textNode.prev;
  18295. continue;
  18296. }
  18297. if (!blockElements[textNodeNext.name] && textNodeNext.name !== 'script' && textNodeNext.name !== 'style') {
  18298. textNode = textNode.prev;
  18299. continue;
  18300. }
  18301. }
  18302. sibling = textNode.prev;
  18303. textNode.remove();
  18304. textNode = sibling;
  18305. }
  18306. };
  18307. var cloneAndExcludeBlocks = function (input) {
  18308. var name;
  18309. var output = {};
  18310. for (name in input) {
  18311. if (name !== 'li' && name !== 'p') {
  18312. output[name] = input[name];
  18313. }
  18314. }
  18315. return output;
  18316. };
  18317. var parser = SaxParser$1({
  18318. validate: validate,
  18319. allow_html_data_urls: settings.allow_html_data_urls,
  18320. allow_script_urls: settings.allow_script_urls,
  18321. allow_conditional_comments: settings.allow_conditional_comments,
  18322. preserve_cdata: settings.preserve_cdata,
  18323. self_closing_elements: cloneAndExcludeBlocks(schema.getSelfClosingElements()),
  18324. cdata: function (text) {
  18325. node.append(createNode('#cdata', 4)).value = text;
  18326. },
  18327. text: function (text, raw) {
  18328. var textNode;
  18329. if (!isInWhiteSpacePreservedElement) {
  18330. text = text.replace(allWhiteSpaceRegExp, ' ');
  18331. if (isLineBreakNode(node.lastChild, blockElements)) {
  18332. text = text.replace(startWhiteSpaceRegExp, '');
  18333. }
  18334. }
  18335. if (text.length !== 0) {
  18336. textNode = createNode('#text', 3);
  18337. textNode.raw = !!raw;
  18338. node.append(textNode).value = text;
  18339. }
  18340. },
  18341. comment: function (text) {
  18342. node.append(createNode('#comment', 8)).value = text;
  18343. },
  18344. pi: function (name, text) {
  18345. node.append(createNode(name, 7)).value = text;
  18346. removeWhitespaceBefore(node);
  18347. },
  18348. doctype: function (text) {
  18349. var newNode = node.append(createNode('#doctype', 10));
  18350. newNode.value = text;
  18351. removeWhitespaceBefore(node);
  18352. },
  18353. start: function (name, attrs, empty) {
  18354. var newNode, attrFiltersLen, attrName, parent;
  18355. var elementRule = validate ? schema.getElementRule(name) : {};
  18356. if (elementRule) {
  18357. newNode = createNode(elementRule.outputName || name, 1);
  18358. newNode.attributes = attrs;
  18359. newNode.shortEnded = empty;
  18360. node.append(newNode);
  18361. parent = children[node.name];
  18362. if (parent && children[newNode.name] && !parent[newNode.name]) {
  18363. invalidChildren.push(newNode);
  18364. }
  18365. attrFiltersLen = attributeFilters.length;
  18366. while (attrFiltersLen--) {
  18367. attrName = attributeFilters[attrFiltersLen].name;
  18368. if (attrName in attrs.map) {
  18369. list = matchedAttributes[attrName];
  18370. if (list) {
  18371. list.push(newNode);
  18372. } else {
  18373. matchedAttributes[attrName] = [newNode];
  18374. }
  18375. }
  18376. }
  18377. if (blockElements[name]) {
  18378. removeWhitespaceBefore(newNode);
  18379. }
  18380. if (!empty) {
  18381. node = newNode;
  18382. }
  18383. if (!isInWhiteSpacePreservedElement && whiteSpaceElements[name]) {
  18384. isInWhiteSpacePreservedElement = true;
  18385. }
  18386. }
  18387. },
  18388. end: function (name) {
  18389. var textNode, text, sibling, tempNode;
  18390. var elementRule = validate ? schema.getElementRule(name) : {};
  18391. if (elementRule) {
  18392. if (blockElements[name]) {
  18393. if (!isInWhiteSpacePreservedElement) {
  18394. textNode = node.firstChild;
  18395. if (textNode && textNode.type === 3) {
  18396. text = textNode.value.replace(startWhiteSpaceRegExp, '');
  18397. if (text.length > 0) {
  18398. textNode.value = text;
  18399. textNode = textNode.next;
  18400. } else {
  18401. sibling = textNode.next;
  18402. textNode.remove();
  18403. textNode = sibling;
  18404. while (textNode && textNode.type === 3) {
  18405. text = textNode.value;
  18406. sibling = textNode.next;
  18407. if (text.length === 0 || isAllWhiteSpaceRegExp.test(text)) {
  18408. textNode.remove();
  18409. textNode = sibling;
  18410. }
  18411. textNode = sibling;
  18412. }
  18413. }
  18414. }
  18415. textNode = node.lastChild;
  18416. if (textNode && textNode.type === 3) {
  18417. text = textNode.value.replace(endWhiteSpaceRegExp, '');
  18418. if (text.length > 0) {
  18419. textNode.value = text;
  18420. textNode = textNode.prev;
  18421. } else {
  18422. sibling = textNode.prev;
  18423. textNode.remove();
  18424. textNode = sibling;
  18425. while (textNode && textNode.type === 3) {
  18426. text = textNode.value;
  18427. sibling = textNode.prev;
  18428. if (text.length === 0 || isAllWhiteSpaceRegExp.test(text)) {
  18429. textNode.remove();
  18430. textNode = sibling;
  18431. }
  18432. textNode = sibling;
  18433. }
  18434. }
  18435. }
  18436. }
  18437. }
  18438. if (isInWhiteSpacePreservedElement && whiteSpaceElements[name]) {
  18439. isInWhiteSpacePreservedElement = false;
  18440. }
  18441. if (elementRule.removeEmpty && isEmpty$2(schema, nonEmptyElements, whiteSpaceElements, node)) {
  18442. tempNode = node.parent;
  18443. if (blockElements[node.name]) {
  18444. node.empty().remove();
  18445. } else {
  18446. node.unwrap();
  18447. }
  18448. node = tempNode;
  18449. return;
  18450. }
  18451. if (elementRule.paddEmpty && (isPaddedWithNbsp(node) || isEmpty$2(schema, nonEmptyElements, whiteSpaceElements, node))) {
  18452. paddEmptyNode(settings, args, blockElements, node);
  18453. }
  18454. node = node.parent;
  18455. }
  18456. }
  18457. }, schema);
  18458. var rootNode = node = new AstNode(args.context || settings.root_name, 11);
  18459. parser.parse(html, args.format);
  18460. if (validate && invalidChildren.length) {
  18461. if (!args.context) {
  18462. fixInvalidChildren(invalidChildren);
  18463. } else {
  18464. args.invalid = true;
  18465. }
  18466. }
  18467. if (rootBlockName && (rootNode.name === 'body' || args.isRootContent)) {
  18468. addRootBlocks();
  18469. }
  18470. if (!args.invalid) {
  18471. for (name in matchedNodes) {
  18472. if (!matchedNodes.hasOwnProperty(name)) {
  18473. continue;
  18474. }
  18475. list = nodeFilters[name];
  18476. nodes = matchedNodes[name];
  18477. fi = nodes.length;
  18478. while (fi--) {
  18479. if (!nodes[fi].parent) {
  18480. nodes.splice(fi, 1);
  18481. }
  18482. }
  18483. for (i = 0, l = list.length; i < l; i++) {
  18484. list[i](nodes, name, args);
  18485. }
  18486. }
  18487. for (i = 0, l = attributeFilters.length; i < l; i++) {
  18488. list = attributeFilters[i];
  18489. if (list.name in matchedAttributes) {
  18490. nodes = matchedAttributes[list.name];
  18491. fi = nodes.length;
  18492. while (fi--) {
  18493. if (!nodes[fi].parent) {
  18494. nodes.splice(fi, 1);
  18495. }
  18496. }
  18497. for (fi = 0, fl = list.callbacks.length; fi < fl; fi++) {
  18498. list.callbacks[fi](nodes, list.name, args);
  18499. }
  18500. }
  18501. }
  18502. }
  18503. return rootNode;
  18504. };
  18505. var exports = {
  18506. schema: schema,
  18507. addAttributeFilter: addAttributeFilter,
  18508. getAttributeFilters: getAttributeFilters,
  18509. addNodeFilter: addNodeFilter,
  18510. getNodeFilters: getNodeFilters,
  18511. filterNode: filterNode,
  18512. parse: parse
  18513. };
  18514. register$2(exports, settings);
  18515. register$1(exports, settings);
  18516. return exports;
  18517. };
  18518. var register$3 = function (htmlParser, settings, dom) {
  18519. htmlParser.addAttributeFilter('data-mce-tabindex', function (nodes, name) {
  18520. var i = nodes.length, node;
  18521. while (i--) {
  18522. node = nodes[i];
  18523. node.attr('tabindex', node.attr('data-mce-tabindex'));
  18524. node.attr(name, null);
  18525. }
  18526. });
  18527. htmlParser.addAttributeFilter('src,href,style', function (nodes, name) {
  18528. var i = nodes.length, node, value;
  18529. var internalName = 'data-mce-' + name;
  18530. var urlConverter = settings.url_converter;
  18531. var urlConverterScope = settings.url_converter_scope;
  18532. while (i--) {
  18533. node = nodes[i];
  18534. value = node.attr(internalName);
  18535. if (value !== undefined) {
  18536. node.attr(name, value.length > 0 ? value : null);
  18537. node.attr(internalName, null);
  18538. } else {
  18539. value = node.attr(name);
  18540. if (name === 'style') {
  18541. value = dom.serializeStyle(dom.parseStyle(value), node.name);
  18542. } else if (urlConverter) {
  18543. value = urlConverter.call(urlConverterScope, value, name, node.name);
  18544. }
  18545. node.attr(name, value.length > 0 ? value : null);
  18546. }
  18547. }
  18548. });
  18549. htmlParser.addAttributeFilter('class', function (nodes) {
  18550. var i = nodes.length, node, value;
  18551. while (i--) {
  18552. node = nodes[i];
  18553. value = node.attr('class');
  18554. if (value) {
  18555. value = node.attr('class').replace(/(?:^|\s)mce-item-\w+(?!\S)/g, '');
  18556. node.attr('class', value.length > 0 ? value : null);
  18557. }
  18558. }
  18559. });
  18560. htmlParser.addAttributeFilter('data-mce-type', function (nodes, name, args) {
  18561. var i = nodes.length, node;
  18562. while (i--) {
  18563. node = nodes[i];
  18564. if (node.attr('data-mce-type') === 'bookmark' && !args.cleanup) {
  18565. var hasChildren = Optional.from(node.firstChild).exists(function (firstChild) {
  18566. return !isZwsp$1(firstChild.value);
  18567. });
  18568. if (hasChildren) {
  18569. node.unwrap();
  18570. } else {
  18571. node.remove();
  18572. }
  18573. }
  18574. }
  18575. });
  18576. htmlParser.addNodeFilter('noscript', function (nodes) {
  18577. var i = nodes.length, node;
  18578. while (i--) {
  18579. node = nodes[i].firstChild;
  18580. if (node) {
  18581. node.value = Entities.decode(node.value);
  18582. }
  18583. }
  18584. });
  18585. htmlParser.addNodeFilter('script,style', function (nodes, name) {
  18586. var i = nodes.length, node, value, type;
  18587. var trim = function (value) {
  18588. return value.replace(/(<!--\[CDATA\[|\]\]-->)/g, '\n').replace(/^[\r\n]*|[\r\n]*$/g, '').replace(/^\s*((<!--)?(\s*\/\/)?\s*<!\[CDATA\[|(<!--\s*)?\/\*\s*<!\[CDATA\[\s*\*\/|(\/\/)?\s*<!--|\/\*\s*<!--\s*\*\/)\s*[\r\n]*/gi, '').replace(/\s*(\/\*\s*\]\]>\s*\*\/(-->)?|\s*\/\/\s*\]\]>(-->)?|\/\/\s*(-->)?|\]\]>|\/\*\s*-->\s*\*\/|\s*-->\s*)\s*$/g, '');
  18589. };
  18590. while (i--) {
  18591. node = nodes[i];
  18592. value = node.firstChild ? node.firstChild.value : '';
  18593. if (name === 'script') {
  18594. type = node.attr('type');
  18595. if (type) {
  18596. node.attr('type', type === 'mce-no/type' ? null : type.replace(/^mce\-/, ''));
  18597. }
  18598. if (settings.element_format === 'xhtml' && value.length > 0) {
  18599. node.firstChild.value = '// <![CDATA[\n' + trim(value) + '\n// ]]>';
  18600. }
  18601. } else {
  18602. if (settings.element_format === 'xhtml' && value.length > 0) {
  18603. node.firstChild.value = '<!--\n' + trim(value) + '\n-->';
  18604. }
  18605. }
  18606. }
  18607. });
  18608. htmlParser.addNodeFilter('#comment', function (nodes) {
  18609. var i = nodes.length, node;
  18610. while (i--) {
  18611. node = nodes[i];
  18612. if (settings.preserve_cdata && node.value.indexOf('[CDATA[') === 0) {
  18613. node.name = '#cdata';
  18614. node.type = 4;
  18615. node.value = dom.decode(node.value.replace(/^\[CDATA\[|\]\]$/g, ''));
  18616. } else if (node.value.indexOf('mce:protected ') === 0) {
  18617. node.name = '#text';
  18618. node.type = 3;
  18619. node.raw = true;
  18620. node.value = unescape(node.value).substr(14);
  18621. }
  18622. }
  18623. });
  18624. htmlParser.addNodeFilter('xml:namespace,input', function (nodes, name) {
  18625. var i = nodes.length, node;
  18626. while (i--) {
  18627. node = nodes[i];
  18628. if (node.type === 7) {
  18629. node.remove();
  18630. } else if (node.type === 1) {
  18631. if (name === 'input' && !node.attr('type')) {
  18632. node.attr('type', 'text');
  18633. }
  18634. }
  18635. }
  18636. });
  18637. htmlParser.addAttributeFilter('data-mce-type', function (nodes) {
  18638. each(nodes, function (node) {
  18639. if (node.attr('data-mce-type') === 'format-caret') {
  18640. if (node.isEmpty(htmlParser.schema.getNonEmptyElements())) {
  18641. node.remove();
  18642. } else {
  18643. node.unwrap();
  18644. }
  18645. }
  18646. });
  18647. });
  18648. htmlParser.addAttributeFilter('data-mce-src,data-mce-href,data-mce-style,' + 'data-mce-selected,data-mce-expando,' + 'data-mce-type,data-mce-resize,data-mce-placeholder', function (nodes, name) {
  18649. var i = nodes.length;
  18650. while (i--) {
  18651. nodes[i].attr(name, null);
  18652. }
  18653. });
  18654. };
  18655. var trimTrailingBr = function (rootNode) {
  18656. var isBr = function (node) {
  18657. return node && node.name === 'br';
  18658. };
  18659. var brNode1 = rootNode.lastChild;
  18660. if (isBr(brNode1)) {
  18661. var brNode2 = brNode1.prev;
  18662. if (isBr(brNode2)) {
  18663. brNode1.remove();
  18664. brNode2.remove();
  18665. }
  18666. }
  18667. };
  18668. var preProcess = function (editor, node, args) {
  18669. var doc, oldDoc;
  18670. var dom = editor.dom;
  18671. node = node.cloneNode(true);
  18672. var impl = document.implementation;
  18673. if (impl.createHTMLDocument) {
  18674. doc = impl.createHTMLDocument('');
  18675. Tools.each(node.nodeName === 'BODY' ? node.childNodes : [node], function (node) {
  18676. doc.body.appendChild(doc.importNode(node, true));
  18677. });
  18678. if (node.nodeName !== 'BODY') {
  18679. node = doc.body.firstChild;
  18680. } else {
  18681. node = doc.body;
  18682. }
  18683. oldDoc = dom.doc;
  18684. dom.doc = doc;
  18685. }
  18686. firePreProcess(editor, __assign(__assign({}, args), { node: node }));
  18687. if (oldDoc) {
  18688. dom.doc = oldDoc;
  18689. }
  18690. return node;
  18691. };
  18692. var shouldFireEvent = function (editor, args) {
  18693. return editor && editor.hasEventListeners('PreProcess') && !args.no_events;
  18694. };
  18695. var process = function (editor, node, args) {
  18696. return shouldFireEvent(editor, args) ? preProcess(editor, node, args) : node;
  18697. };
  18698. var addTempAttr = function (htmlParser, tempAttrs, name) {
  18699. if (Tools.inArray(tempAttrs, name) === -1) {
  18700. htmlParser.addAttributeFilter(name, function (nodes, name) {
  18701. var i = nodes.length;
  18702. while (i--) {
  18703. nodes[i].attr(name, null);
  18704. }
  18705. });
  18706. tempAttrs.push(name);
  18707. }
  18708. };
  18709. var postProcess$1 = function (editor, args, content) {
  18710. if (!args.no_events && editor) {
  18711. var outArgs = firePostProcess(editor, __assign(__assign({}, args), { content: content }));
  18712. return outArgs.content;
  18713. } else {
  18714. return content;
  18715. }
  18716. };
  18717. var getHtmlFromNode = function (dom, node, args) {
  18718. var html = trim$2(args.getInner ? node.innerHTML : dom.getOuterHTML(node));
  18719. return args.selection || isWsPreserveElement(SugarElement.fromDom(node)) ? html : Tools.trim(html);
  18720. };
  18721. var parseHtml = function (htmlParser, html, args) {
  18722. var parserArgs = args.selection ? __assign({ forced_root_block: false }, args) : args;
  18723. var rootNode = htmlParser.parse(html, parserArgs);
  18724. trimTrailingBr(rootNode);
  18725. return rootNode;
  18726. };
  18727. var serializeNode = function (settings, schema, node) {
  18728. var htmlSerializer = HtmlSerializer(settings, schema);
  18729. return htmlSerializer.serialize(node);
  18730. };
  18731. var toHtml = function (editor, settings, schema, rootNode, args) {
  18732. var content = serializeNode(settings, schema, rootNode);
  18733. return postProcess$1(editor, args, content);
  18734. };
  18735. var DomSerializerImpl = function (settings, editor) {
  18736. var tempAttrs = ['data-mce-selected'];
  18737. var dom = editor && editor.dom ? editor.dom : DOMUtils$1.DOM;
  18738. var schema = editor && editor.schema ? editor.schema : Schema(settings);
  18739. settings.entity_encoding = settings.entity_encoding || 'named';
  18740. settings.remove_trailing_brs = 'remove_trailing_brs' in settings ? settings.remove_trailing_brs : true;
  18741. var htmlParser = DomParser(settings, schema);
  18742. register$3(htmlParser, settings, dom);
  18743. var serialize = function (node, parserArgs) {
  18744. if (parserArgs === void 0) {
  18745. parserArgs = {};
  18746. }
  18747. var args = __assign({ format: 'html' }, parserArgs);
  18748. var targetNode = process(editor, node, args);
  18749. var html = getHtmlFromNode(dom, targetNode, args);
  18750. var rootNode = parseHtml(htmlParser, html, args);
  18751. return args.format === 'tree' ? rootNode : toHtml(editor, settings, schema, rootNode, args);
  18752. };
  18753. return {
  18754. schema: schema,
  18755. addNodeFilter: htmlParser.addNodeFilter,
  18756. addAttributeFilter: htmlParser.addAttributeFilter,
  18757. serialize: serialize,
  18758. addRules: function (rules) {
  18759. schema.addValidElements(rules);
  18760. },
  18761. setRules: function (rules) {
  18762. schema.setValidElements(rules);
  18763. },
  18764. addTempAttr: curry(addTempAttr, htmlParser, tempAttrs),
  18765. getTempAttrs: function () {
  18766. return tempAttrs;
  18767. },
  18768. getNodeFilters: htmlParser.getNodeFilters,
  18769. getAttributeFilters: htmlParser.getAttributeFilters
  18770. };
  18771. };
  18772. var DomSerializer = function (settings, editor) {
  18773. var domSerializer = DomSerializerImpl(settings, editor);
  18774. return {
  18775. schema: domSerializer.schema,
  18776. addNodeFilter: domSerializer.addNodeFilter,
  18777. addAttributeFilter: domSerializer.addAttributeFilter,
  18778. serialize: domSerializer.serialize,
  18779. addRules: domSerializer.addRules,
  18780. setRules: domSerializer.setRules,
  18781. addTempAttr: domSerializer.addTempAttr,
  18782. getTempAttrs: domSerializer.getTempAttrs,
  18783. getNodeFilters: domSerializer.getNodeFilters,
  18784. getAttributeFilters: domSerializer.getAttributeFilters
  18785. };
  18786. };
  18787. var defaultFormat$1 = 'html';
  18788. var getContent$2 = function (editor, args) {
  18789. if (args === void 0) {
  18790. args = {};
  18791. }
  18792. var format = args.format ? args.format : defaultFormat$1;
  18793. return getContent(editor, args, format);
  18794. };
  18795. var setContent$2 = function (editor, content, args) {
  18796. if (args === void 0) {
  18797. args = {};
  18798. }
  18799. return setContent(editor, content, args);
  18800. };
  18801. var DOM$3 = DOMUtils$1.DOM;
  18802. var restoreOriginalStyles = function (editor) {
  18803. DOM$3.setStyle(editor.id, 'display', editor.orgDisplay);
  18804. };
  18805. var safeDestroy = function (x) {
  18806. return Optional.from(x).each(function (x) {
  18807. return x.destroy();
  18808. });
  18809. };
  18810. var clearDomReferences = function (editor) {
  18811. editor.contentAreaContainer = editor.formElement = editor.container = editor.editorContainer = null;
  18812. editor.bodyElement = editor.contentDocument = editor.contentWindow = null;
  18813. editor.iframeElement = editor.targetElm = null;
  18814. if (editor.selection) {
  18815. editor.selection = editor.selection.win = editor.selection.dom = editor.selection.dom.doc = null;
  18816. }
  18817. };
  18818. var restoreForm = function (editor) {
  18819. var form = editor.formElement;
  18820. if (form) {
  18821. if (form._mceOldSubmit) {
  18822. form.submit = form._mceOldSubmit;
  18823. form._mceOldSubmit = null;
  18824. }
  18825. DOM$3.unbind(form, 'submit reset', editor.formEventDelegate);
  18826. }
  18827. };
  18828. var remove$7 = function (editor) {
  18829. if (!editor.removed) {
  18830. var _selectionOverrides = editor._selectionOverrides, editorUpload = editor.editorUpload;
  18831. var body = editor.getBody();
  18832. var element = editor.getElement();
  18833. if (body) {
  18834. editor.save({ is_removing: true });
  18835. }
  18836. editor.removed = true;
  18837. editor.unbindAllNativeEvents();
  18838. if (editor.hasHiddenInput && element) {
  18839. DOM$3.remove(element.nextSibling);
  18840. }
  18841. fireRemove(editor);
  18842. editor.editorManager.remove(editor);
  18843. if (!editor.inline && body) {
  18844. restoreOriginalStyles(editor);
  18845. }
  18846. fireDetach(editor);
  18847. DOM$3.remove(editor.getContainer());
  18848. safeDestroy(_selectionOverrides);
  18849. safeDestroy(editorUpload);
  18850. editor.destroy();
  18851. }
  18852. };
  18853. var destroy = function (editor, automatic) {
  18854. var selection = editor.selection, dom = editor.dom;
  18855. if (editor.destroyed) {
  18856. return;
  18857. }
  18858. if (!automatic && !editor.removed) {
  18859. editor.remove();
  18860. return;
  18861. }
  18862. if (!automatic) {
  18863. editor.editorManager.off('beforeunload', editor._beforeUnload);
  18864. if (editor.theme && editor.theme.destroy) {
  18865. editor.theme.destroy();
  18866. }
  18867. safeDestroy(selection);
  18868. safeDestroy(dom);
  18869. }
  18870. restoreForm(editor);
  18871. clearDomReferences(editor);
  18872. editor.destroyed = true;
  18873. };
  18874. var hasOwnProperty$2 = Object.prototype.hasOwnProperty;
  18875. var deep$1 = function (old, nu) {
  18876. var bothObjects = isObject(old) && isObject(nu);
  18877. return bothObjects ? deepMerge(old, nu) : nu;
  18878. };
  18879. var baseMerge = function (merger) {
  18880. return function () {
  18881. var objects = new Array(arguments.length);
  18882. for (var i = 0; i < objects.length; i++) {
  18883. objects[i] = arguments[i];
  18884. }
  18885. if (objects.length === 0) {
  18886. throw new Error('Can\'t merge zero objects');
  18887. }
  18888. var ret = {};
  18889. for (var j = 0; j < objects.length; j++) {
  18890. var curObject = objects[j];
  18891. for (var key in curObject) {
  18892. if (hasOwnProperty$2.call(curObject, key)) {
  18893. ret[key] = merger(ret[key], curObject[key]);
  18894. }
  18895. }
  18896. }
  18897. return ret;
  18898. };
  18899. };
  18900. var deepMerge = baseMerge(deep$1);
  18901. var sectionResult = function (sections, settings) {
  18902. return {
  18903. sections: constant(sections),
  18904. settings: constant(settings)
  18905. };
  18906. };
  18907. var deviceDetection = detect$3().deviceType;
  18908. var isTouch = deviceDetection.isTouch();
  18909. var isPhone = deviceDetection.isPhone();
  18910. var isTablet = deviceDetection.isTablet();
  18911. var legacyMobilePlugins = [
  18912. 'lists',
  18913. 'autolink',
  18914. 'autosave'
  18915. ];
  18916. var defaultTouchSettings = {
  18917. table_grid: false,
  18918. object_resizing: false,
  18919. resize: false
  18920. };
  18921. var normalizePlugins = function (plugins) {
  18922. var pluginNames = isArray(plugins) ? plugins.join(' ') : plugins;
  18923. var trimmedPlugins = map(isString(pluginNames) ? pluginNames.split(' ') : [], trim);
  18924. return filter(trimmedPlugins, function (item) {
  18925. return item.length > 0;
  18926. });
  18927. };
  18928. var filterLegacyMobilePlugins = function (plugins) {
  18929. return filter(plugins, curry(contains, legacyMobilePlugins));
  18930. };
  18931. var extractSections = function (keys, settings) {
  18932. var result = bifilter(settings, function (value, key) {
  18933. return contains(keys, key);
  18934. });
  18935. return sectionResult(result.t, result.f);
  18936. };
  18937. var getSection = function (sectionResult, name, defaults) {
  18938. if (defaults === void 0) {
  18939. defaults = {};
  18940. }
  18941. var sections = sectionResult.sections();
  18942. var sectionSettings = sections.hasOwnProperty(name) ? sections[name] : {};
  18943. return Tools.extend({}, defaults, sectionSettings);
  18944. };
  18945. var hasSection = function (sectionResult, name) {
  18946. return sectionResult.sections().hasOwnProperty(name);
  18947. };
  18948. var isSectionTheme = function (sectionResult, name, theme) {
  18949. var section = sectionResult.sections();
  18950. return hasSection(sectionResult, name) && section[name].theme === theme;
  18951. };
  18952. var getSectionConfig = function (sectionResult, name) {
  18953. return hasSection(sectionResult, name) ? sectionResult.sections()[name] : {};
  18954. };
  18955. var getToolbarMode = function (settings, defaultVal) {
  18956. return get(settings, 'toolbar_mode').orThunk(function () {
  18957. return get(settings, 'toolbar_drawer').map(function (val) {
  18958. return val === false ? 'wrap' : val;
  18959. });
  18960. }).getOr(defaultVal);
  18961. };
  18962. var getDefaultSettings = function (settings, id, documentBaseUrl, isTouch, editor) {
  18963. var baseDefaults = {
  18964. id: id,
  18965. theme: 'silver',
  18966. toolbar_mode: getToolbarMode(settings, 'floating'),
  18967. plugins: '',
  18968. document_base_url: documentBaseUrl,
  18969. add_form_submit_trigger: true,
  18970. submit_patch: true,
  18971. add_unload_trigger: true,
  18972. convert_urls: true,
  18973. relative_urls: true,
  18974. remove_script_host: true,
  18975. object_resizing: true,
  18976. doctype: '<!DOCTYPE html>',
  18977. visual: true,
  18978. font_size_legacy_values: 'xx-small,small,medium,large,x-large,xx-large,300%',
  18979. forced_root_block: 'p',
  18980. hidden_input: true,
  18981. inline_styles: true,
  18982. convert_fonts_to_spans: true,
  18983. indent: true,
  18984. indent_before: 'p,h1,h2,h3,h4,h5,h6,blockquote,div,title,style,pre,script,td,th,ul,ol,li,dl,dt,dd,area,table,thead,' + 'tfoot,tbody,tr,section,summary,article,hgroup,aside,figure,figcaption,option,optgroup,datalist',
  18985. indent_after: 'p,h1,h2,h3,h4,h5,h6,blockquote,div,title,style,pre,script,td,th,ul,ol,li,dl,dt,dd,area,table,thead,' + 'tfoot,tbody,tr,section,summary,article,hgroup,aside,figure,figcaption,option,optgroup,datalist',
  18986. entity_encoding: 'named',
  18987. url_converter: editor.convertURL,
  18988. url_converter_scope: editor
  18989. };
  18990. return __assign(__assign({}, baseDefaults), isTouch ? defaultTouchSettings : {});
  18991. };
  18992. var getDefaultMobileSettings = function (mobileSettings, isPhone) {
  18993. var defaultMobileSettings = {
  18994. resize: false,
  18995. toolbar_mode: getToolbarMode(mobileSettings, 'scrolling'),
  18996. toolbar_sticky: false
  18997. };
  18998. var defaultPhoneSettings = { menubar: false };
  18999. return __assign(__assign(__assign({}, defaultTouchSettings), defaultMobileSettings), isPhone ? defaultPhoneSettings : {});
  19000. };
  19001. var getExternalPlugins$1 = function (overrideSettings, settings) {
  19002. var userDefinedExternalPlugins = settings.external_plugins ? settings.external_plugins : {};
  19003. if (overrideSettings && overrideSettings.external_plugins) {
  19004. return Tools.extend({}, overrideSettings.external_plugins, userDefinedExternalPlugins);
  19005. } else {
  19006. return userDefinedExternalPlugins;
  19007. }
  19008. };
  19009. var combinePlugins = function (forcedPlugins, plugins) {
  19010. return [].concat(normalizePlugins(forcedPlugins)).concat(normalizePlugins(plugins));
  19011. };
  19012. var processPlugins = function (isMobileDevice, sectionResult, defaultOverrideSettings, settings) {
  19013. var forcedPlugins = normalizePlugins(defaultOverrideSettings.forced_plugins);
  19014. var desktopPlugins = normalizePlugins(settings.plugins);
  19015. var mobileConfig = getSectionConfig(sectionResult, 'mobile');
  19016. var mobilePlugins = mobileConfig.plugins ? normalizePlugins(mobileConfig.plugins) : desktopPlugins;
  19017. var platformPlugins = isMobileDevice && isSectionTheme(sectionResult, 'mobile', 'mobile') ? filterLegacyMobilePlugins(mobilePlugins) : isMobileDevice && hasSection(sectionResult, 'mobile') ? mobilePlugins : desktopPlugins;
  19018. var combinedPlugins = combinePlugins(forcedPlugins, platformPlugins);
  19019. return Tools.extend(settings, { plugins: combinedPlugins.join(' ') });
  19020. };
  19021. var isOnMobile = function (isMobileDevice, sectionResult) {
  19022. return isMobileDevice && hasSection(sectionResult, 'mobile');
  19023. };
  19024. var combineSettings = function (isMobileDevice, isPhone, defaultSettings, defaultOverrideSettings, settings) {
  19025. var defaultDeviceSettings = isMobileDevice ? { mobile: getDefaultMobileSettings(settings.mobile || {}, isPhone) } : {};
  19026. var sectionResult = extractSections(['mobile'], deepMerge(defaultDeviceSettings, settings));
  19027. var extendedSettings = Tools.extend(defaultSettings, defaultOverrideSettings, sectionResult.settings(), isOnMobile(isMobileDevice, sectionResult) ? getSection(sectionResult, 'mobile') : {}, {
  19028. validate: true,
  19029. external_plugins: getExternalPlugins$1(defaultOverrideSettings, sectionResult.settings())
  19030. });
  19031. return processPlugins(isMobileDevice, sectionResult, defaultOverrideSettings, extendedSettings);
  19032. };
  19033. var getEditorSettings = function (editor, id, documentBaseUrl, defaultOverrideSettings, settings) {
  19034. var defaultSettings = getDefaultSettings(settings, id, documentBaseUrl, isTouch, editor);
  19035. return combineSettings(isPhone || isTablet, isPhone, defaultSettings, defaultOverrideSettings, settings);
  19036. };
  19037. var getFiltered = function (predicate, editor, name) {
  19038. return Optional.from(editor.settings[name]).filter(predicate);
  19039. };
  19040. var getParamObject = function (value) {
  19041. var output = {};
  19042. if (typeof value === 'string') {
  19043. each(value.indexOf('=') > 0 ? value.split(/[;,](?![^=;,]*(?:[;,]|$))/) : value.split(','), function (val) {
  19044. var arr = val.split('=');
  19045. if (arr.length > 1) {
  19046. output[Tools.trim(arr[0])] = Tools.trim(arr[1]);
  19047. } else {
  19048. output[Tools.trim(arr[0])] = Tools.trim(arr[0]);
  19049. }
  19050. });
  19051. } else {
  19052. output = value;
  19053. }
  19054. return output;
  19055. };
  19056. var isArrayOf = function (p) {
  19057. return function (a) {
  19058. return isArray(a) && forall(a, p);
  19059. };
  19060. };
  19061. var getParam = function (editor, name, defaultVal, type) {
  19062. var value = name in editor.settings ? editor.settings[name] : defaultVal;
  19063. if (type === 'hash') {
  19064. return getParamObject(value);
  19065. } else if (type === 'string') {
  19066. return getFiltered(isString, editor, name).getOr(defaultVal);
  19067. } else if (type === 'number') {
  19068. return getFiltered(isNumber, editor, name).getOr(defaultVal);
  19069. } else if (type === 'boolean') {
  19070. return getFiltered(isBoolean, editor, name).getOr(defaultVal);
  19071. } else if (type === 'object') {
  19072. return getFiltered(isObject, editor, name).getOr(defaultVal);
  19073. } else if (type === 'array') {
  19074. return getFiltered(isArray, editor, name).getOr(defaultVal);
  19075. } else if (type === 'string[]') {
  19076. return getFiltered(isArrayOf(isString), editor, name).getOr(defaultVal);
  19077. } else if (type === 'function') {
  19078. return getFiltered(isFunction, editor, name).getOr(defaultVal);
  19079. } else {
  19080. return value;
  19081. }
  19082. };
  19083. var CreateIconManager = function () {
  19084. var lookup = {};
  19085. var add = function (id, iconPack) {
  19086. lookup[id] = iconPack;
  19087. };
  19088. var get = function (id) {
  19089. if (lookup[id]) {
  19090. return lookup[id];
  19091. }
  19092. return { icons: {} };
  19093. };
  19094. var has$1 = function (id) {
  19095. return has(lookup, id);
  19096. };
  19097. return {
  19098. add: add,
  19099. get: get,
  19100. has: has$1
  19101. };
  19102. };
  19103. var IconManager = CreateIconManager();
  19104. var getProp = function (propName, elm) {
  19105. var rawElm = elm.dom;
  19106. return rawElm[propName];
  19107. };
  19108. var getComputedSizeProp = function (propName, elm) {
  19109. return parseInt(get$4(elm, propName), 10);
  19110. };
  19111. var getClientWidth = curry(getProp, 'clientWidth');
  19112. var getClientHeight = curry(getProp, 'clientHeight');
  19113. var getMarginTop = curry(getComputedSizeProp, 'margin-top');
  19114. var getMarginLeft = curry(getComputedSizeProp, 'margin-left');
  19115. var getBoundingClientRect$1 = function (elm) {
  19116. return elm.dom.getBoundingClientRect();
  19117. };
  19118. var isInsideElementContentArea = function (bodyElm, clientX, clientY) {
  19119. var clientWidth = getClientWidth(bodyElm);
  19120. var clientHeight = getClientHeight(bodyElm);
  19121. return clientX >= 0 && clientY >= 0 && clientX <= clientWidth && clientY <= clientHeight;
  19122. };
  19123. var transpose = function (inline, elm, clientX, clientY) {
  19124. var clientRect = getBoundingClientRect$1(elm);
  19125. var deltaX = inline ? clientRect.left + elm.dom.clientLeft + getMarginLeft(elm) : 0;
  19126. var deltaY = inline ? clientRect.top + elm.dom.clientTop + getMarginTop(elm) : 0;
  19127. var x = clientX - deltaX;
  19128. var y = clientY - deltaY;
  19129. return {
  19130. x: x,
  19131. y: y
  19132. };
  19133. };
  19134. var isXYInContentArea = function (editor, clientX, clientY) {
  19135. var bodyElm = SugarElement.fromDom(editor.getBody());
  19136. var targetElm = editor.inline ? bodyElm : documentElement(bodyElm);
  19137. var transposedPoint = transpose(editor.inline, targetElm, clientX, clientY);
  19138. return isInsideElementContentArea(targetElm, transposedPoint.x, transposedPoint.y);
  19139. };
  19140. var fromDomSafe = function (node) {
  19141. return Optional.from(node).map(SugarElement.fromDom);
  19142. };
  19143. var isEditorAttachedToDom = function (editor) {
  19144. var rawContainer = editor.inline ? editor.getBody() : editor.getContentAreaContainer();
  19145. return fromDomSafe(rawContainer).map(inBody).getOr(false);
  19146. };
  19147. function NotificationManagerImpl() {
  19148. var unimplemented = function () {
  19149. throw new Error('Theme did not provide a NotificationManager implementation.');
  19150. };
  19151. return {
  19152. open: unimplemented,
  19153. close: unimplemented,
  19154. reposition: unimplemented,
  19155. getArgs: unimplemented
  19156. };
  19157. }
  19158. function NotificationManager(editor) {
  19159. var notifications = [];
  19160. var getImplementation = function () {
  19161. var theme = editor.theme;
  19162. return theme && theme.getNotificationManagerImpl ? theme.getNotificationManagerImpl() : NotificationManagerImpl();
  19163. };
  19164. var getTopNotification = function () {
  19165. return Optional.from(notifications[0]);
  19166. };
  19167. var isEqual = function (a, b) {
  19168. return a.type === b.type && a.text === b.text && !a.progressBar && !a.timeout && !b.progressBar && !b.timeout;
  19169. };
  19170. var reposition = function () {
  19171. if (notifications.length > 0) {
  19172. getImplementation().reposition(notifications);
  19173. }
  19174. };
  19175. var addNotification = function (notification) {
  19176. notifications.push(notification);
  19177. };
  19178. var closeNotification = function (notification) {
  19179. findIndex(notifications, function (otherNotification) {
  19180. return otherNotification === notification;
  19181. }).each(function (index) {
  19182. notifications.splice(index, 1);
  19183. });
  19184. };
  19185. var open = function (spec) {
  19186. if (editor.removed || !isEditorAttachedToDom(editor)) {
  19187. return;
  19188. }
  19189. return find(notifications, function (notification) {
  19190. return isEqual(getImplementation().getArgs(notification), spec);
  19191. }).getOrThunk(function () {
  19192. editor.editorManager.setActive(editor);
  19193. var notification = getImplementation().open(spec, function () {
  19194. closeNotification(notification);
  19195. reposition();
  19196. getTopNotification().fold(function () {
  19197. return editor.focus();
  19198. }, function (top) {
  19199. return focus(SugarElement.fromDom(top.getEl()));
  19200. });
  19201. });
  19202. addNotification(notification);
  19203. reposition();
  19204. return notification;
  19205. });
  19206. };
  19207. var close = function () {
  19208. getTopNotification().each(function (notification) {
  19209. getImplementation().close(notification);
  19210. closeNotification(notification);
  19211. reposition();
  19212. });
  19213. };
  19214. var getNotifications = function () {
  19215. return notifications;
  19216. };
  19217. var registerEvents = function (editor) {
  19218. editor.on('SkinLoaded', function () {
  19219. var serviceMessage = getServiceMessage(editor);
  19220. if (serviceMessage) {
  19221. open({
  19222. text: serviceMessage,
  19223. type: 'warning',
  19224. timeout: 0
  19225. });
  19226. }
  19227. });
  19228. editor.on('ResizeEditor ResizeWindow NodeChange', function () {
  19229. Delay.requestAnimationFrame(reposition);
  19230. });
  19231. editor.on('remove', function () {
  19232. each(notifications.slice(), function (notification) {
  19233. getImplementation().close(notification);
  19234. });
  19235. });
  19236. };
  19237. registerEvents(editor);
  19238. return {
  19239. open: open,
  19240. close: close,
  19241. getNotifications: getNotifications
  19242. };
  19243. }
  19244. var PluginManager = AddOnManager$1.PluginManager;
  19245. var ThemeManager = AddOnManager$1.ThemeManager;
  19246. function WindowManagerImpl () {
  19247. var unimplemented = function () {
  19248. throw new Error('Theme did not provide a WindowManager implementation.');
  19249. };
  19250. return {
  19251. open: unimplemented,
  19252. openUrl: unimplemented,
  19253. alert: unimplemented,
  19254. confirm: unimplemented,
  19255. close: unimplemented,
  19256. getParams: unimplemented,
  19257. setParams: unimplemented
  19258. };
  19259. }
  19260. var WindowManager = function (editor) {
  19261. var dialogs = [];
  19262. var getImplementation = function () {
  19263. var theme = editor.theme;
  19264. return theme && theme.getWindowManagerImpl ? theme.getWindowManagerImpl() : WindowManagerImpl();
  19265. };
  19266. var funcBind = function (scope, f) {
  19267. return function () {
  19268. return f ? f.apply(scope, arguments) : undefined;
  19269. };
  19270. };
  19271. var fireOpenEvent = function (dialog) {
  19272. editor.fire('OpenWindow', { dialog: dialog });
  19273. };
  19274. var fireCloseEvent = function (dialog) {
  19275. editor.fire('CloseWindow', { dialog: dialog });
  19276. };
  19277. var addDialog = function (dialog) {
  19278. dialogs.push(dialog);
  19279. fireOpenEvent(dialog);
  19280. };
  19281. var closeDialog = function (dialog) {
  19282. fireCloseEvent(dialog);
  19283. dialogs = filter(dialogs, function (otherDialog) {
  19284. return otherDialog !== dialog;
  19285. });
  19286. if (dialogs.length === 0) {
  19287. editor.focus();
  19288. }
  19289. };
  19290. var getTopDialog = function () {
  19291. return Optional.from(dialogs[dialogs.length - 1]);
  19292. };
  19293. var storeSelectionAndOpenDialog = function (openDialog) {
  19294. editor.editorManager.setActive(editor);
  19295. store(editor);
  19296. var dialog = openDialog();
  19297. addDialog(dialog);
  19298. return dialog;
  19299. };
  19300. var open = function (args, params) {
  19301. return storeSelectionAndOpenDialog(function () {
  19302. return getImplementation().open(args, params, closeDialog);
  19303. });
  19304. };
  19305. var openUrl = function (args) {
  19306. return storeSelectionAndOpenDialog(function () {
  19307. return getImplementation().openUrl(args, closeDialog);
  19308. });
  19309. };
  19310. var alert = function (message, callback, scope) {
  19311. getImplementation().alert(message, funcBind(scope ? scope : this, callback));
  19312. };
  19313. var confirm = function (message, callback, scope) {
  19314. getImplementation().confirm(message, funcBind(scope ? scope : this, callback));
  19315. };
  19316. var close = function () {
  19317. getTopDialog().each(function (dialog) {
  19318. getImplementation().close(dialog);
  19319. closeDialog(dialog);
  19320. });
  19321. };
  19322. editor.on('remove', function () {
  19323. each(dialogs, function (dialog) {
  19324. getImplementation().close(dialog);
  19325. });
  19326. });
  19327. return {
  19328. open: open,
  19329. openUrl: openUrl,
  19330. alert: alert,
  19331. confirm: confirm,
  19332. close: close
  19333. };
  19334. };
  19335. var displayNotification = function (editor, message) {
  19336. editor.notificationManager.open({
  19337. type: 'error',
  19338. text: message
  19339. });
  19340. };
  19341. var displayError = function (editor, message) {
  19342. if (editor._skinLoaded) {
  19343. displayNotification(editor, message);
  19344. } else {
  19345. editor.on('SkinLoaded', function () {
  19346. displayNotification(editor, message);
  19347. });
  19348. }
  19349. };
  19350. var uploadError = function (editor, message) {
  19351. displayError(editor, I18n.translate([
  19352. 'Failed to upload image: {0}',
  19353. message
  19354. ]));
  19355. };
  19356. var logError = function (editor, errorType, msg) {
  19357. fireError(editor, errorType, { message: msg });
  19358. console.error(msg);
  19359. };
  19360. var createLoadError = function (type, url, name) {
  19361. return name ? 'Failed to load ' + type + ': ' + name + ' from url ' + url : 'Failed to load ' + type + ' url: ' + url;
  19362. };
  19363. var pluginLoadError = function (editor, url, name) {
  19364. logError(editor, 'PluginLoadError', createLoadError('plugin', url, name));
  19365. };
  19366. var iconsLoadError = function (editor, url, name) {
  19367. logError(editor, 'IconsLoadError', createLoadError('icons', url, name));
  19368. };
  19369. var languageLoadError = function (editor, url, name) {
  19370. logError(editor, 'LanguageLoadError', createLoadError('language', url, name));
  19371. };
  19372. var pluginInitError = function (editor, name, err) {
  19373. var message = I18n.translate([
  19374. 'Failed to initialize plugin: {0}',
  19375. name
  19376. ]);
  19377. initError(message, err);
  19378. displayError(editor, message);
  19379. };
  19380. var initError = function (message) {
  19381. var x = [];
  19382. for (var _i = 1; _i < arguments.length; _i++) {
  19383. x[_i - 1] = arguments[_i];
  19384. }
  19385. var console = window.console;
  19386. if (console) {
  19387. if (console.error) {
  19388. console.error.apply(console, __spreadArrays([message], x));
  19389. } else {
  19390. console.log.apply(console, __spreadArrays([message], x));
  19391. }
  19392. }
  19393. };
  19394. var isContentCssSkinName = function (url) {
  19395. return /^[a-z0-9\-]+$/i.test(url);
  19396. };
  19397. var getContentCssUrls = function (editor) {
  19398. var contentCss = getContentCss(editor);
  19399. var skinUrl = editor.editorManager.baseURL + '/skins/content';
  19400. var suffix = editor.editorManager.suffix;
  19401. var contentCssFile = 'content' + suffix + '.css';
  19402. var inline = editor.inline === true;
  19403. return map(contentCss, function (url) {
  19404. if (isContentCssSkinName(url) && !inline) {
  19405. return skinUrl + '/' + url + '/' + contentCssFile;
  19406. } else {
  19407. return editor.documentBaseURI.toAbsolute(url);
  19408. }
  19409. });
  19410. };
  19411. var appendContentCssFromSettings = function (editor) {
  19412. editor.contentCSS = editor.contentCSS.concat(getContentCssUrls(editor));
  19413. };
  19414. function Uploader(uploadStatus, settings) {
  19415. var pendingPromises = {};
  19416. var pathJoin = function (path1, path2) {
  19417. if (path1) {
  19418. return path1.replace(/\/$/, '') + '/' + path2.replace(/^\//, '');
  19419. }
  19420. return path2;
  19421. };
  19422. var defaultHandler = function (blobInfo, success, failure, progress) {
  19423. var xhr = new XMLHttpRequest();
  19424. xhr.open('POST', settings.url);
  19425. xhr.withCredentials = settings.credentials;
  19426. xhr.upload.onprogress = function (e) {
  19427. progress(e.loaded / e.total * 100);
  19428. };
  19429. xhr.onerror = function () {
  19430. failure('Image upload failed due to a XHR Transport error. Code: ' + xhr.status);
  19431. };
  19432. xhr.onload = function () {
  19433. if (xhr.status < 200 || xhr.status >= 300) {
  19434. failure('HTTP Error: ' + xhr.status);
  19435. return;
  19436. }
  19437. var json = JSON.parse(xhr.responseText);
  19438. if (!json || typeof json.location !== 'string') {
  19439. failure('Invalid JSON: ' + xhr.responseText);
  19440. return;
  19441. }
  19442. success(pathJoin(settings.basePath, json.location));
  19443. };
  19444. var formData = new FormData();
  19445. formData.append('file', blobInfo.blob(), blobInfo.filename());
  19446. xhr.send(formData);
  19447. };
  19448. var noUpload = function () {
  19449. return new promiseObj(function (resolve) {
  19450. resolve([]);
  19451. });
  19452. };
  19453. var handlerSuccess = function (blobInfo, url) {
  19454. return {
  19455. url: url,
  19456. blobInfo: blobInfo,
  19457. status: true
  19458. };
  19459. };
  19460. var handlerFailure = function (blobInfo, message, options) {
  19461. return {
  19462. url: '',
  19463. blobInfo: blobInfo,
  19464. status: false,
  19465. error: {
  19466. message: message,
  19467. options: options
  19468. }
  19469. };
  19470. };
  19471. var resolvePending = function (blobUri, result) {
  19472. Tools.each(pendingPromises[blobUri], function (resolve) {
  19473. resolve(result);
  19474. });
  19475. delete pendingPromises[blobUri];
  19476. };
  19477. var uploadBlobInfo = function (blobInfo, handler, openNotification) {
  19478. uploadStatus.markPending(blobInfo.blobUri());
  19479. return new promiseObj(function (resolve) {
  19480. var notification, progress;
  19481. var noop = function () {
  19482. };
  19483. try {
  19484. var closeNotification_1 = function () {
  19485. if (notification) {
  19486. notification.close();
  19487. progress = noop;
  19488. }
  19489. };
  19490. var success = function (url) {
  19491. closeNotification_1();
  19492. uploadStatus.markUploaded(blobInfo.blobUri(), url);
  19493. resolvePending(blobInfo.blobUri(), handlerSuccess(blobInfo, url));
  19494. resolve(handlerSuccess(blobInfo, url));
  19495. };
  19496. var failure = function (error, options) {
  19497. var failureOptions = options ? options : {};
  19498. closeNotification_1();
  19499. uploadStatus.removeFailed(blobInfo.blobUri());
  19500. resolvePending(blobInfo.blobUri(), handlerFailure(blobInfo, error, failureOptions));
  19501. resolve(handlerFailure(blobInfo, error, failureOptions));
  19502. };
  19503. progress = function (percent) {
  19504. if (percent < 0 || percent > 100) {
  19505. return;
  19506. }
  19507. if (!notification) {
  19508. notification = openNotification();
  19509. }
  19510. notification.progressBar.value(percent);
  19511. };
  19512. handler(blobInfo, success, failure, progress);
  19513. } catch (ex) {
  19514. resolve(handlerFailure(blobInfo, ex.message, {}));
  19515. }
  19516. });
  19517. };
  19518. var isDefaultHandler = function (handler) {
  19519. return handler === defaultHandler;
  19520. };
  19521. var pendingUploadBlobInfo = function (blobInfo) {
  19522. var blobUri = blobInfo.blobUri();
  19523. return new promiseObj(function (resolve) {
  19524. pendingPromises[blobUri] = pendingPromises[blobUri] || [];
  19525. pendingPromises[blobUri].push(resolve);
  19526. });
  19527. };
  19528. var uploadBlobs = function (blobInfos, openNotification) {
  19529. blobInfos = Tools.grep(blobInfos, function (blobInfo) {
  19530. return !uploadStatus.isUploaded(blobInfo.blobUri());
  19531. });
  19532. return promiseObj.all(Tools.map(blobInfos, function (blobInfo) {
  19533. return uploadStatus.isPending(blobInfo.blobUri()) ? pendingUploadBlobInfo(blobInfo) : uploadBlobInfo(blobInfo, settings.handler, openNotification);
  19534. }));
  19535. };
  19536. var upload = function (blobInfos, openNotification) {
  19537. return !settings.url && isDefaultHandler(settings.handler) ? noUpload() : uploadBlobs(blobInfos, openNotification);
  19538. };
  19539. if (isFunction(settings.handler) === false) {
  19540. settings.handler = defaultHandler;
  19541. }
  19542. return { upload: upload };
  19543. }
  19544. function UploadStatus () {
  19545. var PENDING = 1, UPLOADED = 2;
  19546. var blobUriStatuses = {};
  19547. var createStatus = function (status, resultUri) {
  19548. return {
  19549. status: status,
  19550. resultUri: resultUri
  19551. };
  19552. };
  19553. var hasBlobUri = function (blobUri) {
  19554. return blobUri in blobUriStatuses;
  19555. };
  19556. var getResultUri = function (blobUri) {
  19557. var result = blobUriStatuses[blobUri];
  19558. return result ? result.resultUri : null;
  19559. };
  19560. var isPending = function (blobUri) {
  19561. return hasBlobUri(blobUri) ? blobUriStatuses[blobUri].status === PENDING : false;
  19562. };
  19563. var isUploaded = function (blobUri) {
  19564. return hasBlobUri(blobUri) ? blobUriStatuses[blobUri].status === UPLOADED : false;
  19565. };
  19566. var markPending = function (blobUri) {
  19567. blobUriStatuses[blobUri] = createStatus(PENDING, null);
  19568. };
  19569. var markUploaded = function (blobUri, resultUri) {
  19570. blobUriStatuses[blobUri] = createStatus(UPLOADED, resultUri);
  19571. };
  19572. var removeFailed = function (blobUri) {
  19573. delete blobUriStatuses[blobUri];
  19574. };
  19575. var destroy = function () {
  19576. blobUriStatuses = {};
  19577. };
  19578. return {
  19579. hasBlobUri: hasBlobUri,
  19580. getResultUri: getResultUri,
  19581. isPending: isPending,
  19582. isUploaded: isUploaded,
  19583. markPending: markPending,
  19584. markUploaded: markUploaded,
  19585. removeFailed: removeFailed,
  19586. destroy: destroy
  19587. };
  19588. }
  19589. var count$1 = 0;
  19590. var seed = function () {
  19591. var rnd = function () {
  19592. return Math.round(Math.random() * 4294967295).toString(36);
  19593. };
  19594. var now = new Date().getTime();
  19595. return 's' + now.toString(36) + rnd() + rnd() + rnd();
  19596. };
  19597. var uuid = function (prefix) {
  19598. return prefix + count$1++ + seed();
  19599. };
  19600. var BlobCache = function () {
  19601. var cache = [];
  19602. var mimeToExt = function (mime) {
  19603. var mimes = {
  19604. 'image/jpeg': 'jpg',
  19605. 'image/jpg': 'jpg',
  19606. 'image/gif': 'gif',
  19607. 'image/png': 'png'
  19608. };
  19609. return mimes[mime.toLowerCase()] || 'dat';
  19610. };
  19611. var create = function (o, blob, base64, filename) {
  19612. if (isString(o)) {
  19613. var id = o;
  19614. return toBlobInfo({
  19615. id: id,
  19616. name: filename,
  19617. blob: blob,
  19618. base64: base64
  19619. });
  19620. } else if (isObject(o)) {
  19621. return toBlobInfo(o);
  19622. } else {
  19623. throw new Error('Unknown input type');
  19624. }
  19625. };
  19626. var toBlobInfo = function (o) {
  19627. if (!o.blob || !o.base64) {
  19628. throw new Error('blob and base64 representations of the image are required for BlobInfo to be created');
  19629. }
  19630. var id = o.id || uuid('blobid');
  19631. var name = o.name || id;
  19632. return {
  19633. id: constant(id),
  19634. name: constant(name),
  19635. filename: constant(name + '.' + mimeToExt(o.blob.type)),
  19636. blob: constant(o.blob),
  19637. base64: constant(o.base64),
  19638. blobUri: constant(o.blobUri || URL.createObjectURL(o.blob)),
  19639. uri: constant(o.uri)
  19640. };
  19641. };
  19642. var add = function (blobInfo) {
  19643. if (!get(blobInfo.id())) {
  19644. cache.push(blobInfo);
  19645. }
  19646. };
  19647. var findFirst = function (predicate) {
  19648. return find(cache, predicate).getOrUndefined();
  19649. };
  19650. var get = function (id) {
  19651. return findFirst(function (cachedBlobInfo) {
  19652. return cachedBlobInfo.id() === id;
  19653. });
  19654. };
  19655. var getByUri = function (blobUri) {
  19656. return findFirst(function (blobInfo) {
  19657. return blobInfo.blobUri() === blobUri;
  19658. });
  19659. };
  19660. var getByData = function (base64, type) {
  19661. return findFirst(function (blobInfo) {
  19662. return blobInfo.base64() === base64 && blobInfo.blob().type === type;
  19663. });
  19664. };
  19665. var removeByUri = function (blobUri) {
  19666. cache = filter(cache, function (blobInfo) {
  19667. if (blobInfo.blobUri() === blobUri) {
  19668. URL.revokeObjectURL(blobInfo.blobUri());
  19669. return false;
  19670. }
  19671. return true;
  19672. });
  19673. };
  19674. var destroy = function () {
  19675. each(cache, function (cachedBlobInfo) {
  19676. URL.revokeObjectURL(cachedBlobInfo.blobUri());
  19677. });
  19678. cache = [];
  19679. };
  19680. return {
  19681. create: create,
  19682. add: add,
  19683. get: get,
  19684. getByUri: getByUri,
  19685. getByData: getByData,
  19686. findFirst: findFirst,
  19687. removeByUri: removeByUri,
  19688. destroy: destroy
  19689. };
  19690. };
  19691. var EditorUpload = function (editor) {
  19692. var blobCache = BlobCache();
  19693. var uploader, imageScanner;
  19694. var uploadStatus = UploadStatus();
  19695. var urlFilters = [];
  19696. var aliveGuard = function (callback) {
  19697. return function (result) {
  19698. if (editor.selection) {
  19699. return callback(result);
  19700. }
  19701. return [];
  19702. };
  19703. };
  19704. var cacheInvalidator = function (url) {
  19705. return url + (url.indexOf('?') === -1 ? '?' : '&') + new Date().getTime();
  19706. };
  19707. var replaceString = function (content, search, replace) {
  19708. var index = 0;
  19709. do {
  19710. index = content.indexOf(search, index);
  19711. if (index !== -1) {
  19712. content = content.substring(0, index) + replace + content.substr(index + search.length);
  19713. index += replace.length - search.length + 1;
  19714. }
  19715. } while (index !== -1);
  19716. return content;
  19717. };
  19718. var replaceImageUrl = function (content, targetUrl, replacementUrl) {
  19719. var replacementString = 'src="' + replacementUrl + '"' + (replacementUrl === Env.transparentSrc ? ' data-mce-placeholder="1"' : '');
  19720. content = replaceString(content, 'src="' + targetUrl + '"', replacementString);
  19721. content = replaceString(content, 'data-mce-src="' + targetUrl + '"', 'data-mce-src="' + replacementUrl + '"');
  19722. return content;
  19723. };
  19724. var replaceUrlInUndoStack = function (targetUrl, replacementUrl) {
  19725. each(editor.undoManager.data, function (level) {
  19726. if (level.type === 'fragmented') {
  19727. level.fragments = map(level.fragments, function (fragment) {
  19728. return replaceImageUrl(fragment, targetUrl, replacementUrl);
  19729. });
  19730. } else {
  19731. level.content = replaceImageUrl(level.content, targetUrl, replacementUrl);
  19732. }
  19733. });
  19734. };
  19735. var openNotification = function () {
  19736. return editor.notificationManager.open({
  19737. text: editor.translate('Image uploading...'),
  19738. type: 'info',
  19739. timeout: -1,
  19740. progressBar: true
  19741. });
  19742. };
  19743. var replaceImageUriInView = function (image, resultUri) {
  19744. var src = editor.convertURL(resultUri, 'src');
  19745. replaceUrlInUndoStack(image.src, resultUri);
  19746. editor.$(image).attr({
  19747. 'src': shouldReuseFileName(editor) ? cacheInvalidator(resultUri) : resultUri,
  19748. 'data-mce-src': src
  19749. });
  19750. };
  19751. var uploadImages = function (callback) {
  19752. if (!uploader) {
  19753. uploader = Uploader(uploadStatus, {
  19754. url: getImageUploadUrl(editor),
  19755. basePath: getImageUploadBasePath(editor),
  19756. credentials: getImagesUploadCredentials(editor),
  19757. handler: getImagesUploadHandler(editor)
  19758. });
  19759. }
  19760. return scanForImages().then(aliveGuard(function (imageInfos) {
  19761. var blobInfos = map(imageInfos, function (imageInfo) {
  19762. return imageInfo.blobInfo;
  19763. });
  19764. return uploader.upload(blobInfos, openNotification).then(aliveGuard(function (result) {
  19765. var imagesToRemove = [];
  19766. var filteredResult = map(result, function (uploadInfo, index) {
  19767. var blobInfo = imageInfos[index].blobInfo;
  19768. var image = imageInfos[index].image;
  19769. if (uploadInfo.status && shouldReplaceBlobUris(editor)) {
  19770. blobCache.removeByUri(image.src);
  19771. replaceImageUriInView(image, uploadInfo.url);
  19772. } else if (uploadInfo.error) {
  19773. if (uploadInfo.error.options.remove) {
  19774. replaceUrlInUndoStack(image.getAttribute('src'), Env.transparentSrc);
  19775. imagesToRemove.push(image);
  19776. }
  19777. uploadError(editor, uploadInfo.error.message);
  19778. }
  19779. return {
  19780. element: image,
  19781. status: uploadInfo.status,
  19782. uploadUri: uploadInfo.url,
  19783. blobInfo: blobInfo
  19784. };
  19785. });
  19786. if (imagesToRemove.length > 0) {
  19787. if (isRtc(editor)) {
  19788. console.error('Removing images on failed uploads is currently unsupported for RTC');
  19789. } else {
  19790. editor.undoManager.transact(function () {
  19791. each(imagesToRemove, function (element) {
  19792. editor.dom.remove(element);
  19793. blobCache.removeByUri(element.src);
  19794. });
  19795. });
  19796. }
  19797. }
  19798. if (callback) {
  19799. callback(filteredResult);
  19800. }
  19801. return filteredResult;
  19802. }));
  19803. }));
  19804. };
  19805. var uploadImagesAuto = function (callback) {
  19806. if (isAutomaticUploadsEnabled(editor)) {
  19807. return uploadImages(callback);
  19808. }
  19809. };
  19810. var isValidDataUriImage = function (imgElm) {
  19811. if (forall(urlFilters, function (filter) {
  19812. return filter(imgElm);
  19813. }) === false) {
  19814. return false;
  19815. }
  19816. if (imgElm.getAttribute('src').indexOf('data:') === 0) {
  19817. var dataImgFilter = getImagesDataImgFilter(editor);
  19818. return dataImgFilter(imgElm);
  19819. }
  19820. return true;
  19821. };
  19822. var addFilter = function (filter) {
  19823. urlFilters.push(filter);
  19824. };
  19825. var scanForImages = function () {
  19826. if (!imageScanner) {
  19827. imageScanner = ImageScanner(uploadStatus, blobCache);
  19828. }
  19829. return imageScanner.findAll(editor.getBody(), isValidDataUriImage).then(aliveGuard(function (result) {
  19830. result = filter(result, function (resultItem) {
  19831. if (typeof resultItem === 'string') {
  19832. displayError(editor, resultItem);
  19833. return false;
  19834. }
  19835. return true;
  19836. });
  19837. each(result, function (resultItem) {
  19838. replaceUrlInUndoStack(resultItem.image.src, resultItem.blobInfo.blobUri());
  19839. resultItem.image.src = resultItem.blobInfo.blobUri();
  19840. resultItem.image.removeAttribute('data-mce-src');
  19841. });
  19842. return result;
  19843. }));
  19844. };
  19845. var destroy = function () {
  19846. blobCache.destroy();
  19847. uploadStatus.destroy();
  19848. imageScanner = uploader = null;
  19849. };
  19850. var replaceBlobUris = function (content) {
  19851. return content.replace(/src="(blob:[^"]+)"/g, function (match, blobUri) {
  19852. var resultUri = uploadStatus.getResultUri(blobUri);
  19853. if (resultUri) {
  19854. return 'src="' + resultUri + '"';
  19855. }
  19856. var blobInfo = blobCache.getByUri(blobUri);
  19857. if (!blobInfo) {
  19858. blobInfo = foldl(editor.editorManager.get(), function (result, editor) {
  19859. return result || editor.editorUpload && editor.editorUpload.blobCache.getByUri(blobUri);
  19860. }, null);
  19861. }
  19862. if (blobInfo) {
  19863. var blob = blobInfo.blob();
  19864. return 'src="data:' + blob.type + ';base64,' + blobInfo.base64() + '"';
  19865. }
  19866. return match;
  19867. });
  19868. };
  19869. editor.on('SetContent', function () {
  19870. if (isAutomaticUploadsEnabled(editor)) {
  19871. uploadImagesAuto();
  19872. } else {
  19873. scanForImages();
  19874. }
  19875. });
  19876. editor.on('RawSaveContent', function (e) {
  19877. e.content = replaceBlobUris(e.content);
  19878. });
  19879. editor.on('GetContent', function (e) {
  19880. if (e.source_view || e.format === 'raw') {
  19881. return;
  19882. }
  19883. e.content = replaceBlobUris(e.content);
  19884. });
  19885. editor.on('PostRender', function () {
  19886. editor.parser.addNodeFilter('img', function (images) {
  19887. each(images, function (img) {
  19888. var src = img.attr('src');
  19889. if (blobCache.getByUri(src)) {
  19890. return;
  19891. }
  19892. var resultUri = uploadStatus.getResultUri(src);
  19893. if (resultUri) {
  19894. img.attr('src', resultUri);
  19895. }
  19896. });
  19897. });
  19898. });
  19899. return {
  19900. blobCache: blobCache,
  19901. addFilter: addFilter,
  19902. uploadImages: uploadImages,
  19903. uploadImagesAuto: uploadImagesAuto,
  19904. scanForImages: scanForImages,
  19905. destroy: destroy
  19906. };
  19907. };
  19908. var setup$5 = function (registeredFormatListeners, editor) {
  19909. var currentFormats = Cell({});
  19910. registeredFormatListeners.set({});
  19911. editor.on('NodeChange', function (e) {
  19912. updateAndFireChangeCallbacks(editor, e.element, currentFormats, registeredFormatListeners.get());
  19913. });
  19914. };
  19915. var updateAndFireChangeCallbacks = function (editor, elm, currentFormats, formatChangeData) {
  19916. var formatsList = keys(currentFormats.get());
  19917. var newFormats = {};
  19918. var matchedFormats = {};
  19919. var parents = filter(getParents$1(editor.dom, elm), function (node) {
  19920. return node.nodeType === 1 && !node.getAttribute('data-mce-bogus');
  19921. });
  19922. each$1(formatChangeData, function (data, format) {
  19923. Tools.each(parents, function (node) {
  19924. if (editor.formatter.matchNode(node, format, {}, data.similar)) {
  19925. if (formatsList.indexOf(format) === -1) {
  19926. each(data.callbacks, function (callback) {
  19927. callback(true, {
  19928. node: node,
  19929. format: format,
  19930. parents: parents
  19931. });
  19932. });
  19933. newFormats[format] = data.callbacks;
  19934. }
  19935. matchedFormats[format] = data.callbacks;
  19936. return false;
  19937. }
  19938. if (matchesUnInheritedFormatSelector(editor, node, format)) {
  19939. return false;
  19940. }
  19941. });
  19942. });
  19943. var remainingFormats = filterRemainingFormats(currentFormats.get(), matchedFormats, elm, parents);
  19944. currentFormats.set(__assign(__assign({}, newFormats), remainingFormats));
  19945. };
  19946. var filterRemainingFormats = function (currentFormats, matchedFormats, elm, parents) {
  19947. return bifilter(currentFormats, function (callbacks, format) {
  19948. if (!has(matchedFormats, format)) {
  19949. each(callbacks, function (callback) {
  19950. callback(false, {
  19951. node: elm,
  19952. format: format,
  19953. parents: parents
  19954. });
  19955. });
  19956. return false;
  19957. } else {
  19958. return true;
  19959. }
  19960. }).t;
  19961. };
  19962. var addListeners = function (registeredFormatListeners, formats, callback, similar) {
  19963. var formatChangeItems = registeredFormatListeners.get();
  19964. each(formats.split(','), function (format) {
  19965. if (!formatChangeItems[format]) {
  19966. formatChangeItems[format] = {
  19967. similar: similar,
  19968. callbacks: []
  19969. };
  19970. }
  19971. formatChangeItems[format].callbacks.push(callback);
  19972. });
  19973. registeredFormatListeners.set(formatChangeItems);
  19974. };
  19975. var removeListeners = function (registeredFormatListeners, formats, callback) {
  19976. var formatChangeItems = registeredFormatListeners.get();
  19977. each(formats.split(','), function (format) {
  19978. formatChangeItems[format].callbacks = filter(formatChangeItems[format].callbacks, function (c) {
  19979. return c !== callback;
  19980. });
  19981. if (formatChangeItems[format].callbacks.length === 0) {
  19982. delete formatChangeItems[format];
  19983. }
  19984. });
  19985. registeredFormatListeners.set(formatChangeItems);
  19986. };
  19987. var formatChanged = function (editor, registeredFormatListeners, formats, callback, similar) {
  19988. if (registeredFormatListeners.get() === null) {
  19989. setup$5(registeredFormatListeners, editor);
  19990. }
  19991. addListeners(registeredFormatListeners, formats, callback, similar);
  19992. return {
  19993. unbind: function () {
  19994. return removeListeners(registeredFormatListeners, formats, callback);
  19995. }
  19996. };
  19997. };
  19998. var get$9 = function (dom) {
  19999. var formats = {
  20000. valigntop: [{
  20001. selector: 'td,th',
  20002. styles: { verticalAlign: 'top' }
  20003. }],
  20004. valignmiddle: [{
  20005. selector: 'td,th',
  20006. styles: { verticalAlign: 'middle' }
  20007. }],
  20008. valignbottom: [{
  20009. selector: 'td,th',
  20010. styles: { verticalAlign: 'bottom' }
  20011. }],
  20012. alignleft: [
  20013. {
  20014. selector: 'figure.image',
  20015. collapsed: false,
  20016. classes: 'align-left',
  20017. ceFalseOverride: true,
  20018. preview: 'font-family font-size'
  20019. },
  20020. {
  20021. selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li',
  20022. styles: { textAlign: 'left' },
  20023. inherit: false,
  20024. preview: false,
  20025. defaultBlock: 'div'
  20026. },
  20027. {
  20028. selector: 'img,table',
  20029. collapsed: false,
  20030. styles: { float: 'left' },
  20031. preview: 'font-family font-size'
  20032. }
  20033. ],
  20034. aligncenter: [
  20035. {
  20036. selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li',
  20037. styles: { textAlign: 'center' },
  20038. inherit: false,
  20039. preview: 'font-family font-size',
  20040. defaultBlock: 'div'
  20041. },
  20042. {
  20043. selector: 'figure.image',
  20044. collapsed: false,
  20045. classes: 'align-center',
  20046. ceFalseOverride: true,
  20047. preview: 'font-family font-size'
  20048. },
  20049. {
  20050. selector: 'img',
  20051. collapsed: false,
  20052. styles: {
  20053. display: 'block',
  20054. marginLeft: 'auto',
  20055. marginRight: 'auto'
  20056. },
  20057. preview: false
  20058. },
  20059. {
  20060. selector: 'table',
  20061. collapsed: false,
  20062. styles: {
  20063. marginLeft: 'auto',
  20064. marginRight: 'auto'
  20065. },
  20066. preview: 'font-family font-size'
  20067. }
  20068. ],
  20069. alignright: [
  20070. {
  20071. selector: 'figure.image',
  20072. collapsed: false,
  20073. classes: 'align-right',
  20074. ceFalseOverride: true,
  20075. preview: 'font-family font-size'
  20076. },
  20077. {
  20078. selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li',
  20079. styles: { textAlign: 'right' },
  20080. inherit: false,
  20081. preview: 'font-family font-size',
  20082. defaultBlock: 'div'
  20083. },
  20084. {
  20085. selector: 'img,table',
  20086. collapsed: false,
  20087. styles: { float: 'right' },
  20088. preview: 'font-family font-size'
  20089. }
  20090. ],
  20091. alignjustify: [{
  20092. selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li',
  20093. styles: { textAlign: 'justify' },
  20094. inherit: false,
  20095. defaultBlock: 'div',
  20096. preview: 'font-family font-size'
  20097. }],
  20098. bold: [
  20099. {
  20100. inline: 'strong',
  20101. remove: 'all',
  20102. preserve_attributes: [
  20103. 'class',
  20104. 'style'
  20105. ]
  20106. },
  20107. {
  20108. inline: 'span',
  20109. styles: { fontWeight: 'bold' }
  20110. },
  20111. {
  20112. inline: 'b',
  20113. remove: 'all',
  20114. preserve_attributes: [
  20115. 'class',
  20116. 'style'
  20117. ]
  20118. }
  20119. ],
  20120. italic: [
  20121. {
  20122. inline: 'em',
  20123. remove: 'all',
  20124. preserve_attributes: [
  20125. 'class',
  20126. 'style'
  20127. ]
  20128. },
  20129. {
  20130. inline: 'span',
  20131. styles: { fontStyle: 'italic' }
  20132. },
  20133. {
  20134. inline: 'i',
  20135. remove: 'all',
  20136. preserve_attributes: [
  20137. 'class',
  20138. 'style'
  20139. ]
  20140. }
  20141. ],
  20142. underline: [
  20143. {
  20144. inline: 'span',
  20145. styles: { textDecoration: 'underline' },
  20146. exact: true
  20147. },
  20148. {
  20149. inline: 'u',
  20150. remove: 'all',
  20151. preserve_attributes: [
  20152. 'class',
  20153. 'style'
  20154. ]
  20155. }
  20156. ],
  20157. strikethrough: [
  20158. {
  20159. inline: 'span',
  20160. styles: { textDecoration: 'line-through' },
  20161. exact: true
  20162. },
  20163. {
  20164. inline: 'strike',
  20165. remove: 'all',
  20166. preserve_attributes: [
  20167. 'class',
  20168. 'style'
  20169. ]
  20170. }
  20171. ],
  20172. forecolor: {
  20173. inline: 'span',
  20174. styles: { color: '%value' },
  20175. links: true,
  20176. remove_similar: true,
  20177. clear_child_styles: true
  20178. },
  20179. hilitecolor: {
  20180. inline: 'span',
  20181. styles: { backgroundColor: '%value' },
  20182. links: true,
  20183. remove_similar: true,
  20184. clear_child_styles: true
  20185. },
  20186. fontname: {
  20187. inline: 'span',
  20188. toggle: false,
  20189. styles: { fontFamily: '%value' },
  20190. clear_child_styles: true
  20191. },
  20192. fontsize: {
  20193. inline: 'span',
  20194. toggle: false,
  20195. styles: { fontSize: '%value' },
  20196. clear_child_styles: true
  20197. },
  20198. lineheight: {
  20199. selector: 'h1,h2,h3,h4,h5,h6,p,li,td,th,div',
  20200. defaultBlock: 'p',
  20201. styles: { lineHeight: '%value' }
  20202. },
  20203. fontsize_class: {
  20204. inline: 'span',
  20205. attributes: { class: '%value' }
  20206. },
  20207. blockquote: {
  20208. block: 'blockquote',
  20209. wrapper: true,
  20210. remove: 'all'
  20211. },
  20212. subscript: { inline: 'sub' },
  20213. superscript: { inline: 'sup' },
  20214. code: { inline: 'code' },
  20215. link: {
  20216. inline: 'a',
  20217. selector: 'a',
  20218. remove: 'all',
  20219. split: true,
  20220. deep: true,
  20221. onmatch: function (node, _fmt, _itemName) {
  20222. return isElement$1(node) && node.hasAttribute('href');
  20223. },
  20224. onformat: function (elm, _fmt, vars) {
  20225. Tools.each(vars, function (value, key) {
  20226. dom.setAttrib(elm, key, value);
  20227. });
  20228. }
  20229. },
  20230. removeformat: [
  20231. {
  20232. selector: 'b,strong,em,i,font,u,strike,sub,sup,dfn,code,samp,kbd,var,cite,mark,q,del,ins',
  20233. remove: 'all',
  20234. split: true,
  20235. expand: false,
  20236. block_expand: true,
  20237. deep: true
  20238. },
  20239. {
  20240. selector: 'span',
  20241. attributes: [
  20242. 'style',
  20243. 'class'
  20244. ],
  20245. remove: 'empty',
  20246. split: true,
  20247. expand: false,
  20248. deep: true
  20249. },
  20250. {
  20251. selector: '*',
  20252. attributes: [
  20253. 'style',
  20254. 'class'
  20255. ],
  20256. split: false,
  20257. expand: false,
  20258. deep: true
  20259. }
  20260. ]
  20261. };
  20262. Tools.each('p h1 h2 h3 h4 h5 h6 div address pre div dt dd samp'.split(/\s/), function (name) {
  20263. formats[name] = {
  20264. block: name,
  20265. remove: 'all'
  20266. };
  20267. });
  20268. return formats;
  20269. };
  20270. function FormatRegistry(editor) {
  20271. var formats = {};
  20272. var get = function (name) {
  20273. return name ? formats[name] : formats;
  20274. };
  20275. var has$1 = function (name) {
  20276. return has(formats, name);
  20277. };
  20278. var register = function (name, format) {
  20279. if (name) {
  20280. if (typeof name !== 'string') {
  20281. Tools.each(name, function (format, name) {
  20282. register(name, format);
  20283. });
  20284. } else {
  20285. if (!isArray(format)) {
  20286. format = [format];
  20287. }
  20288. Tools.each(format, function (format) {
  20289. if (typeof format.deep === 'undefined') {
  20290. format.deep = !format.selector;
  20291. }
  20292. if (typeof format.split === 'undefined') {
  20293. format.split = !format.selector || format.inline;
  20294. }
  20295. if (typeof format.remove === 'undefined' && format.selector && !format.inline) {
  20296. format.remove = 'none';
  20297. }
  20298. if (format.selector && format.inline) {
  20299. format.mixed = true;
  20300. format.block_expand = true;
  20301. }
  20302. if (typeof format.classes === 'string') {
  20303. format.classes = format.classes.split(/\s+/);
  20304. }
  20305. });
  20306. formats[name] = format;
  20307. }
  20308. }
  20309. };
  20310. var unregister = function (name) {
  20311. if (name && formats[name]) {
  20312. delete formats[name];
  20313. }
  20314. return formats;
  20315. };
  20316. register(get$9(editor.dom));
  20317. register(getFormats(editor));
  20318. return {
  20319. get: get,
  20320. has: has$1,
  20321. register: register,
  20322. unregister: unregister
  20323. };
  20324. }
  20325. var each$e = Tools.each;
  20326. var dom = DOMUtils$1.DOM;
  20327. var parsedSelectorToHtml = function (ancestry, editor) {
  20328. var elm, item, fragment;
  20329. var schema = editor && editor.schema || Schema({});
  20330. var decorate = function (elm, item) {
  20331. if (item.classes.length) {
  20332. dom.addClass(elm, item.classes.join(' '));
  20333. }
  20334. dom.setAttribs(elm, item.attrs);
  20335. };
  20336. var createElement = function (sItem) {
  20337. item = typeof sItem === 'string' ? {
  20338. name: sItem,
  20339. classes: [],
  20340. attrs: {}
  20341. } : sItem;
  20342. var elm = dom.create(item.name);
  20343. decorate(elm, item);
  20344. return elm;
  20345. };
  20346. var getRequiredParent = function (elm, candidate) {
  20347. var name = typeof elm !== 'string' ? elm.nodeName.toLowerCase() : elm;
  20348. var elmRule = schema.getElementRule(name);
  20349. var parentsRequired = elmRule && elmRule.parentsRequired;
  20350. if (parentsRequired && parentsRequired.length) {
  20351. return candidate && Tools.inArray(parentsRequired, candidate) !== -1 ? candidate : parentsRequired[0];
  20352. } else {
  20353. return false;
  20354. }
  20355. };
  20356. var wrapInHtml = function (elm, ancestry, siblings) {
  20357. var parent, parentCandidate;
  20358. var ancestor = ancestry.length > 0 && ancestry[0];
  20359. var ancestorName = ancestor && ancestor.name;
  20360. var parentRequired = getRequiredParent(elm, ancestorName);
  20361. if (parentRequired) {
  20362. if (ancestorName === parentRequired) {
  20363. parentCandidate = ancestry[0];
  20364. ancestry = ancestry.slice(1);
  20365. } else {
  20366. parentCandidate = parentRequired;
  20367. }
  20368. } else if (ancestor) {
  20369. parentCandidate = ancestry[0];
  20370. ancestry = ancestry.slice(1);
  20371. } else if (!siblings) {
  20372. return elm;
  20373. }
  20374. if (parentCandidate) {
  20375. parent = createElement(parentCandidate);
  20376. parent.appendChild(elm);
  20377. }
  20378. if (siblings) {
  20379. if (!parent) {
  20380. parent = dom.create('div');
  20381. parent.appendChild(elm);
  20382. }
  20383. Tools.each(siblings, function (sibling) {
  20384. var siblingElm = createElement(sibling);
  20385. parent.insertBefore(siblingElm, elm);
  20386. });
  20387. }
  20388. return wrapInHtml(parent, ancestry, parentCandidate && parentCandidate.siblings);
  20389. };
  20390. if (ancestry && ancestry.length) {
  20391. item = ancestry[0];
  20392. elm = createElement(item);
  20393. fragment = dom.create('div');
  20394. fragment.appendChild(wrapInHtml(elm, ancestry.slice(1), item.siblings));
  20395. return fragment;
  20396. } else {
  20397. return '';
  20398. }
  20399. };
  20400. var parseSelectorItem = function (item) {
  20401. var tagName;
  20402. var obj = {
  20403. classes: [],
  20404. attrs: {}
  20405. };
  20406. item = obj.selector = Tools.trim(item);
  20407. if (item !== '*') {
  20408. tagName = item.replace(/(?:([#\.]|::?)([\w\-]+)|(\[)([^\]]+)\]?)/g, function ($0, $1, $2, $3, $4) {
  20409. switch ($1) {
  20410. case '#':
  20411. obj.attrs.id = $2;
  20412. break;
  20413. case '.':
  20414. obj.classes.push($2);
  20415. break;
  20416. case ':':
  20417. if (Tools.inArray('checked disabled enabled read-only required'.split(' '), $2) !== -1) {
  20418. obj.attrs[$2] = $2;
  20419. }
  20420. break;
  20421. }
  20422. if ($3 === '[') {
  20423. var m = $4.match(/([\w\-]+)(?:\=\"([^\"]+))?/);
  20424. if (m) {
  20425. obj.attrs[m[1]] = m[2];
  20426. }
  20427. }
  20428. return '';
  20429. });
  20430. }
  20431. obj.name = tagName || 'div';
  20432. return obj;
  20433. };
  20434. var parseSelector = function (selector) {
  20435. if (!selector || typeof selector !== 'string') {
  20436. return [];
  20437. }
  20438. selector = selector.split(/\s*,\s*/)[0];
  20439. selector = selector.replace(/\s*(~\+|~|\+|>)\s*/g, '$1');
  20440. return Tools.map(selector.split(/(?:>|\s+(?![^\[\]]+\]))/), function (item) {
  20441. var siblings = Tools.map(item.split(/(?:~\+|~|\+)/), parseSelectorItem);
  20442. var obj = siblings.pop();
  20443. if (siblings.length) {
  20444. obj.siblings = siblings;
  20445. }
  20446. return obj;
  20447. }).reverse();
  20448. };
  20449. var getCssText = function (editor, format) {
  20450. var name, previewFrag;
  20451. var previewCss = '', parentFontSize;
  20452. var previewStyles = getPreviewStyles(editor);
  20453. if (previewStyles === '') {
  20454. return '';
  20455. }
  20456. var removeVars = function (val) {
  20457. return val.replace(/%(\w+)/g, '');
  20458. };
  20459. if (typeof format === 'string') {
  20460. format = editor.formatter.get(format);
  20461. if (!format) {
  20462. return;
  20463. }
  20464. format = format[0];
  20465. }
  20466. if ('preview' in format) {
  20467. var previewOpt = get(format, 'preview');
  20468. if (previewOpt.is(false)) {
  20469. return '';
  20470. } else {
  20471. previewStyles = previewOpt.getOr(previewStyles);
  20472. }
  20473. }
  20474. name = format.block || format.inline || 'span';
  20475. var items = parseSelector(format.selector);
  20476. if (items.length) {
  20477. if (!items[0].name) {
  20478. items[0].name = name;
  20479. }
  20480. name = format.selector;
  20481. previewFrag = parsedSelectorToHtml(items, editor);
  20482. } else {
  20483. previewFrag = parsedSelectorToHtml([name], editor);
  20484. }
  20485. var previewElm = dom.select(name, previewFrag)[0] || previewFrag.firstChild;
  20486. each$e(format.styles, function (value, name) {
  20487. var newValue = removeVars(value);
  20488. if (newValue) {
  20489. dom.setStyle(previewElm, name, newValue);
  20490. }
  20491. });
  20492. each$e(format.attributes, function (value, name) {
  20493. var newValue = removeVars(value);
  20494. if (newValue) {
  20495. dom.setAttrib(previewElm, name, newValue);
  20496. }
  20497. });
  20498. each$e(format.classes, function (value) {
  20499. var newValue = removeVars(value);
  20500. if (!dom.hasClass(previewElm, newValue)) {
  20501. dom.addClass(previewElm, newValue);
  20502. }
  20503. });
  20504. editor.fire('PreviewFormats');
  20505. dom.setStyles(previewFrag, {
  20506. position: 'absolute',
  20507. left: -65535
  20508. });
  20509. editor.getBody().appendChild(previewFrag);
  20510. parentFontSize = dom.getStyle(editor.getBody(), 'fontSize', true);
  20511. parentFontSize = /px$/.test(parentFontSize) ? parseInt(parentFontSize, 10) : 0;
  20512. each$e(previewStyles.split(' '), function (name) {
  20513. var value = dom.getStyle(previewElm, name, true);
  20514. if (name === 'background-color' && /transparent|rgba\s*\([^)]+,\s*0\)/.test(value)) {
  20515. value = dom.getStyle(editor.getBody(), name, true);
  20516. if (dom.toHex(value).toLowerCase() === '#ffffff') {
  20517. return;
  20518. }
  20519. }
  20520. if (name === 'color') {
  20521. if (dom.toHex(value).toLowerCase() === '#000000') {
  20522. return;
  20523. }
  20524. }
  20525. if (name === 'font-size') {
  20526. if (/em|%$/.test(value)) {
  20527. if (parentFontSize === 0) {
  20528. return;
  20529. }
  20530. var numValue = parseFloat(value) / (/%$/.test(value) ? 100 : 1);
  20531. value = numValue * parentFontSize + 'px';
  20532. }
  20533. }
  20534. if (name === 'border' && value) {
  20535. previewCss += 'padding:0 2px;';
  20536. }
  20537. previewCss += name + ':' + value + ';';
  20538. });
  20539. editor.fire('AfterPreviewFormats');
  20540. dom.remove(previewFrag);
  20541. return previewCss;
  20542. };
  20543. var setup$6 = function (editor) {
  20544. editor.addShortcut('meta+b', '', 'Bold');
  20545. editor.addShortcut('meta+i', '', 'Italic');
  20546. editor.addShortcut('meta+u', '', 'Underline');
  20547. for (var i = 1; i <= 6; i++) {
  20548. editor.addShortcut('access+' + i, '', [
  20549. 'FormatBlock',
  20550. false,
  20551. 'h' + i
  20552. ]);
  20553. }
  20554. editor.addShortcut('access+7', '', [
  20555. 'FormatBlock',
  20556. false,
  20557. 'p'
  20558. ]);
  20559. editor.addShortcut('access+8', '', [
  20560. 'FormatBlock',
  20561. false,
  20562. 'div'
  20563. ]);
  20564. editor.addShortcut('access+9', '', [
  20565. 'FormatBlock',
  20566. false,
  20567. 'address'
  20568. ]);
  20569. };
  20570. var Formatter = function (editor) {
  20571. var formats = FormatRegistry(editor);
  20572. var formatChangeState = Cell(null);
  20573. setup$6(editor);
  20574. setup$3(editor);
  20575. return {
  20576. get: formats.get,
  20577. has: formats.has,
  20578. register: formats.register,
  20579. unregister: formats.unregister,
  20580. apply: function (name, vars, node) {
  20581. applyFormat$1(editor, name, vars, node);
  20582. },
  20583. remove: function (name, vars, node, similar) {
  20584. removeFormat$1(editor, name, vars, node, similar);
  20585. },
  20586. toggle: function (name, vars, node) {
  20587. toggleFormat(editor, name, vars, node);
  20588. },
  20589. match: curry(match, editor),
  20590. matchAll: curry(matchAll, editor),
  20591. matchNode: curry(matchNode, editor),
  20592. canApply: curry(canApply, editor),
  20593. formatChanged: curry(formatChanged, editor, formatChangeState),
  20594. getCssText: curry(getCssText, editor)
  20595. };
  20596. };
  20597. var registerEvents$1 = function (editor, undoManager, locks) {
  20598. var isFirstTypedCharacter = Cell(false);
  20599. var addNonTypingUndoLevel = function (e) {
  20600. setTyping(undoManager, false, locks);
  20601. undoManager.add({}, e);
  20602. };
  20603. editor.on('init', function () {
  20604. undoManager.add();
  20605. });
  20606. editor.on('BeforeExecCommand', function (e) {
  20607. var cmd = e.command.toLowerCase();
  20608. if (cmd !== 'undo' && cmd !== 'redo' && cmd !== 'mcerepaint') {
  20609. endTyping(undoManager, locks);
  20610. undoManager.beforeChange();
  20611. }
  20612. });
  20613. editor.on('ExecCommand', function (e) {
  20614. var cmd = e.command.toLowerCase();
  20615. if (cmd !== 'undo' && cmd !== 'redo' && cmd !== 'mcerepaint') {
  20616. addNonTypingUndoLevel(e);
  20617. }
  20618. });
  20619. editor.on('ObjectResizeStart cut', function () {
  20620. undoManager.beforeChange();
  20621. });
  20622. editor.on('SaveContent ObjectResized blur', addNonTypingUndoLevel);
  20623. editor.on('dragend', addNonTypingUndoLevel);
  20624. editor.on('keyup', function (e) {
  20625. var keyCode = e.keyCode;
  20626. if (e.isDefaultPrevented()) {
  20627. return;
  20628. }
  20629. if (keyCode >= 33 && keyCode <= 36 || keyCode >= 37 && keyCode <= 40 || keyCode === 45 || e.ctrlKey) {
  20630. addNonTypingUndoLevel();
  20631. editor.nodeChanged();
  20632. }
  20633. if (keyCode === 46 || keyCode === 8) {
  20634. editor.nodeChanged();
  20635. }
  20636. if (isFirstTypedCharacter.get() && undoManager.typing && isEq$4(createFromEditor(editor), undoManager.data[0]) === false) {
  20637. if (editor.isDirty() === false) {
  20638. editor.setDirty(true);
  20639. editor.fire('change', {
  20640. level: undoManager.data[0],
  20641. lastLevel: null
  20642. });
  20643. }
  20644. editor.fire('TypingUndo');
  20645. isFirstTypedCharacter.set(false);
  20646. editor.nodeChanged();
  20647. }
  20648. });
  20649. editor.on('keydown', function (e) {
  20650. var keyCode = e.keyCode;
  20651. if (e.isDefaultPrevented()) {
  20652. return;
  20653. }
  20654. if (keyCode >= 33 && keyCode <= 36 || keyCode >= 37 && keyCode <= 40 || keyCode === 45) {
  20655. if (undoManager.typing) {
  20656. addNonTypingUndoLevel(e);
  20657. }
  20658. return;
  20659. }
  20660. var modKey = e.ctrlKey && !e.altKey || e.metaKey;
  20661. if ((keyCode < 16 || keyCode > 20) && keyCode !== 224 && keyCode !== 91 && !undoManager.typing && !modKey) {
  20662. undoManager.beforeChange();
  20663. setTyping(undoManager, true, locks);
  20664. undoManager.add({}, e);
  20665. isFirstTypedCharacter.set(true);
  20666. }
  20667. });
  20668. editor.on('mousedown', function (e) {
  20669. if (undoManager.typing) {
  20670. addNonTypingUndoLevel(e);
  20671. }
  20672. });
  20673. var isInsertReplacementText = function (event) {
  20674. return event.inputType === 'insertReplacementText';
  20675. };
  20676. var isInsertTextDataNull = function (event) {
  20677. return event.inputType === 'insertText' && event.data === null;
  20678. };
  20679. var isInsertFromPasteOrDrop = function (event) {
  20680. return event.inputType === 'insertFromPaste' || event.inputType === 'insertFromDrop';
  20681. };
  20682. editor.on('input', function (e) {
  20683. if (e.inputType && (isInsertReplacementText(e) || isInsertTextDataNull(e) || isInsertFromPasteOrDrop(e))) {
  20684. addNonTypingUndoLevel(e);
  20685. }
  20686. });
  20687. editor.on('AddUndo Undo Redo ClearUndos', function (e) {
  20688. if (!e.isDefaultPrevented()) {
  20689. editor.nodeChanged();
  20690. }
  20691. });
  20692. };
  20693. var addKeyboardShortcuts = function (editor) {
  20694. editor.addShortcut('meta+z', '', 'Undo');
  20695. editor.addShortcut('meta+y,meta+shift+z', '', 'Redo');
  20696. };
  20697. var UndoManager = function (editor) {
  20698. var beforeBookmark = Cell(Optional.none());
  20699. var locks = Cell(0);
  20700. var index = Cell(0);
  20701. var undoManager = {
  20702. data: [],
  20703. typing: false,
  20704. beforeChange: function () {
  20705. beforeChange$1(editor, locks, beforeBookmark);
  20706. },
  20707. add: function (level, event) {
  20708. return addUndoLevel$1(editor, undoManager, index, locks, beforeBookmark, level, event);
  20709. },
  20710. undo: function () {
  20711. return undo$1(editor, undoManager, locks, index);
  20712. },
  20713. redo: function () {
  20714. return redo$1(editor, index, undoManager.data);
  20715. },
  20716. clear: function () {
  20717. clear$1(editor, undoManager, index);
  20718. },
  20719. reset: function () {
  20720. reset$1(editor, undoManager);
  20721. },
  20722. hasUndo: function () {
  20723. return hasUndo$1(editor, undoManager, index);
  20724. },
  20725. hasRedo: function () {
  20726. return hasRedo$1(editor, undoManager, index);
  20727. },
  20728. transact: function (callback) {
  20729. return transact$1(editor, undoManager, locks, callback);
  20730. },
  20731. ignore: function (callback) {
  20732. ignore$1(editor, locks, callback);
  20733. },
  20734. extra: function (callback1, callback2) {
  20735. extra$1(editor, undoManager, index, callback1, callback2);
  20736. }
  20737. };
  20738. if (!isRtc(editor)) {
  20739. registerEvents$1(editor, undoManager, locks);
  20740. }
  20741. addKeyboardShortcuts(editor);
  20742. return undoManager;
  20743. };
  20744. var nonTypingKeycodes = [
  20745. 9,
  20746. 27,
  20747. VK.HOME,
  20748. VK.END,
  20749. 19,
  20750. 20,
  20751. 44,
  20752. 144,
  20753. 145,
  20754. 33,
  20755. 34,
  20756. 45,
  20757. 16,
  20758. 17,
  20759. 18,
  20760. 91,
  20761. 92,
  20762. 93,
  20763. VK.DOWN,
  20764. VK.UP,
  20765. VK.LEFT,
  20766. VK.RIGHT
  20767. ].concat(Env.browser.isFirefox() ? [224] : []);
  20768. var placeholderAttr = 'data-mce-placeholder';
  20769. var isKeyboardEvent = function (e) {
  20770. return e.type === 'keydown' || e.type === 'keyup';
  20771. };
  20772. var isDeleteEvent = function (e) {
  20773. var keyCode = e.keyCode;
  20774. return keyCode === VK.BACKSPACE || keyCode === VK.DELETE;
  20775. };
  20776. var isNonTypingKeyboardEvent = function (e) {
  20777. if (isKeyboardEvent(e)) {
  20778. var keyCode = e.keyCode;
  20779. return !isDeleteEvent(e) && (VK.metaKeyPressed(e) || e.altKey || keyCode >= 112 && keyCode <= 123 || contains(nonTypingKeycodes, keyCode));
  20780. } else {
  20781. return false;
  20782. }
  20783. };
  20784. var isTypingKeyboardEvent = function (e) {
  20785. return isKeyboardEvent(e) && !(isDeleteEvent(e) || e.type === 'keyup' && e.keyCode === 229);
  20786. };
  20787. var isVisuallyEmpty = function (dom, rootElm, forcedRootBlock) {
  20788. if (isEmpty(SugarElement.fromDom(rootElm), false)) {
  20789. var isForcedRootBlockFalse = forcedRootBlock === '';
  20790. var firstElement = rootElm.firstElementChild;
  20791. if (!firstElement) {
  20792. return true;
  20793. } else if (dom.getStyle(rootElm.firstElementChild, 'padding-left') || dom.getStyle(rootElm.firstElementChild, 'padding-right')) {
  20794. return false;
  20795. } else {
  20796. return isForcedRootBlockFalse ? !dom.isBlock(firstElement) : forcedRootBlock === firstElement.nodeName.toLowerCase();
  20797. }
  20798. } else {
  20799. return false;
  20800. }
  20801. };
  20802. var setup$7 = function (editor) {
  20803. var dom = editor.dom;
  20804. var rootBlock = getForcedRootBlock(editor);
  20805. var placeholder = getPlaceholder(editor);
  20806. var updatePlaceholder = function (e, initial) {
  20807. if (isNonTypingKeyboardEvent(e)) {
  20808. return;
  20809. }
  20810. var body = editor.getBody();
  20811. var showPlaceholder = isTypingKeyboardEvent(e) ? false : isVisuallyEmpty(dom, body, rootBlock);
  20812. var isPlaceholderShown = dom.getAttrib(body, placeholderAttr) !== '';
  20813. if (isPlaceholderShown !== showPlaceholder || initial) {
  20814. dom.setAttrib(body, placeholderAttr, showPlaceholder ? placeholder : null);
  20815. dom.setAttrib(body, 'aria-placeholder', showPlaceholder ? placeholder : null);
  20816. firePlaceholderToggle(editor, showPlaceholder);
  20817. editor.on(showPlaceholder ? 'keydown' : 'keyup', updatePlaceholder);
  20818. editor.off(showPlaceholder ? 'keyup' : 'keydown', updatePlaceholder);
  20819. }
  20820. };
  20821. if (placeholder) {
  20822. editor.on('init', function (e) {
  20823. updatePlaceholder(e, true);
  20824. editor.on('change SetContent ExecCommand', updatePlaceholder);
  20825. editor.on('paste', function (e) {
  20826. return Delay.setEditorTimeout(editor, function () {
  20827. return updatePlaceholder(e);
  20828. });
  20829. });
  20830. });
  20831. }
  20832. };
  20833. var strongRtl = /[\u0591-\u07FF\uFB1D-\uFDFF\uFE70-\uFEFC]/;
  20834. var hasStrongRtl = function (text) {
  20835. return strongRtl.test(text);
  20836. };
  20837. var isInlineTarget = function (editor, elm) {
  20838. return is$1(SugarElement.fromDom(elm), getInlineBoundarySelector(editor));
  20839. };
  20840. var isRtl$1 = function (element) {
  20841. return DOMUtils$1.DOM.getStyle(element, 'direction', true) === 'rtl' || hasStrongRtl(element.textContent);
  20842. };
  20843. var findInlineParents = function (isInlineTarget, rootNode, pos) {
  20844. return filter(DOMUtils$1.DOM.getParents(pos.container(), '*', rootNode), isInlineTarget);
  20845. };
  20846. var findRootInline = function (isInlineTarget, rootNode, pos) {
  20847. var parents = findInlineParents(isInlineTarget, rootNode, pos);
  20848. return Optional.from(parents[parents.length - 1]);
  20849. };
  20850. var hasSameParentBlock = function (rootNode, node1, node2) {
  20851. var block1 = getParentBlock(node1, rootNode);
  20852. var block2 = getParentBlock(node2, rootNode);
  20853. return block1 && block1 === block2;
  20854. };
  20855. var isAtZwsp = function (pos) {
  20856. return isBeforeInline(pos) || isAfterInline(pos);
  20857. };
  20858. var normalizePosition = function (forward, pos) {
  20859. if (!pos) {
  20860. return pos;
  20861. }
  20862. var container = pos.container(), offset = pos.offset();
  20863. if (forward) {
  20864. if (isCaretContainerInline(container)) {
  20865. if (isText$1(container.nextSibling)) {
  20866. return CaretPosition$1(container.nextSibling, 0);
  20867. } else {
  20868. return CaretPosition$1.after(container);
  20869. }
  20870. } else {
  20871. return isBeforeInline(pos) ? CaretPosition$1(container, offset + 1) : pos;
  20872. }
  20873. } else {
  20874. if (isCaretContainerInline(container)) {
  20875. if (isText$1(container.previousSibling)) {
  20876. return CaretPosition$1(container.previousSibling, container.previousSibling.data.length);
  20877. } else {
  20878. return CaretPosition$1.before(container);
  20879. }
  20880. } else {
  20881. return isAfterInline(pos) ? CaretPosition$1(container, offset - 1) : pos;
  20882. }
  20883. }
  20884. };
  20885. var normalizeForwards = curry(normalizePosition, true);
  20886. var normalizeBackwards = curry(normalizePosition, false);
  20887. var isBeforeRoot = function (rootNode) {
  20888. return function (elm) {
  20889. return eq$2(rootNode, SugarElement.fromDom(elm.dom.parentNode));
  20890. };
  20891. };
  20892. var getParentBlock$1 = function (rootNode, elm) {
  20893. return contains$2(rootNode, elm) ? closest(elm, function (element) {
  20894. return isTextBlock(element) || isListItem(element);
  20895. }, isBeforeRoot(rootNode)) : Optional.none();
  20896. };
  20897. var placeCaretInEmptyBody = function (editor) {
  20898. var body = editor.getBody();
  20899. var node = body.firstChild && editor.dom.isBlock(body.firstChild) ? body.firstChild : body;
  20900. editor.selection.setCursorLocation(node, 0);
  20901. };
  20902. var paddEmptyBody = function (editor) {
  20903. if (editor.dom.isEmpty(editor.getBody())) {
  20904. editor.setContent('');
  20905. placeCaretInEmptyBody(editor);
  20906. }
  20907. };
  20908. var willDeleteLastPositionInElement = function (forward, fromPos, elm) {
  20909. return lift2(firstPositionIn(elm), lastPositionIn(elm), function (firstPos, lastPos) {
  20910. var normalizedFirstPos = normalizePosition(true, firstPos);
  20911. var normalizedLastPos = normalizePosition(false, lastPos);
  20912. var normalizedFromPos = normalizePosition(false, fromPos);
  20913. if (forward) {
  20914. return nextPosition(elm, normalizedFromPos).exists(function (nextPos) {
  20915. return nextPos.isEqual(normalizedLastPos) && fromPos.isEqual(normalizedFirstPos);
  20916. });
  20917. } else {
  20918. return prevPosition(elm, normalizedFromPos).exists(function (prevPos) {
  20919. return prevPos.isEqual(normalizedFirstPos) && fromPos.isEqual(normalizedLastPos);
  20920. });
  20921. }
  20922. }).getOr(true);
  20923. };
  20924. var blockPosition = function (block, position) {
  20925. return {
  20926. block: block,
  20927. position: position
  20928. };
  20929. };
  20930. var blockBoundary = function (from, to) {
  20931. return {
  20932. from: from,
  20933. to: to
  20934. };
  20935. };
  20936. var getBlockPosition = function (rootNode, pos) {
  20937. var rootElm = SugarElement.fromDom(rootNode);
  20938. var containerElm = SugarElement.fromDom(pos.container());
  20939. return getParentBlock$1(rootElm, containerElm).map(function (block) {
  20940. return blockPosition(block, pos);
  20941. });
  20942. };
  20943. var isDifferentBlocks = function (blockBoundary) {
  20944. return eq$2(blockBoundary.from.block, blockBoundary.to.block) === false;
  20945. };
  20946. var hasSameParent = function (blockBoundary) {
  20947. return parent(blockBoundary.from.block).bind(function (parent1) {
  20948. return parent(blockBoundary.to.block).filter(function (parent2) {
  20949. return eq$2(parent1, parent2);
  20950. });
  20951. }).isSome();
  20952. };
  20953. var isEditable = function (blockBoundary) {
  20954. return isContentEditableFalse(blockBoundary.from.block.dom) === false && isContentEditableFalse(blockBoundary.to.block.dom) === false;
  20955. };
  20956. var skipLastBr = function (rootNode, forward, blockPosition) {
  20957. if (isBr(blockPosition.position.getNode()) && isEmpty(blockPosition.block) === false) {
  20958. return positionIn(false, blockPosition.block.dom).bind(function (lastPositionInBlock) {
  20959. if (lastPositionInBlock.isEqual(blockPosition.position)) {
  20960. return fromPosition(forward, rootNode, lastPositionInBlock).bind(function (to) {
  20961. return getBlockPosition(rootNode, to);
  20962. });
  20963. } else {
  20964. return Optional.some(blockPosition);
  20965. }
  20966. }).getOr(blockPosition);
  20967. } else {
  20968. return blockPosition;
  20969. }
  20970. };
  20971. var readFromRange = function (rootNode, forward, rng) {
  20972. var fromBlockPos = getBlockPosition(rootNode, CaretPosition$1.fromRangeStart(rng));
  20973. var toBlockPos = fromBlockPos.bind(function (blockPos) {
  20974. return fromPosition(forward, rootNode, blockPos.position).bind(function (to) {
  20975. return getBlockPosition(rootNode, to).map(function (blockPos) {
  20976. return skipLastBr(rootNode, forward, blockPos);
  20977. });
  20978. });
  20979. });
  20980. return lift2(fromBlockPos, toBlockPos, blockBoundary).filter(function (blockBoundary) {
  20981. return isDifferentBlocks(blockBoundary) && hasSameParent(blockBoundary) && isEditable(blockBoundary);
  20982. });
  20983. };
  20984. var read$3 = function (rootNode, forward, rng) {
  20985. return rng.collapsed ? readFromRange(rootNode, forward, rng) : Optional.none();
  20986. };
  20987. var getChildrenUntilBlockBoundary = function (block) {
  20988. var children$1 = children(block);
  20989. return findIndex(children$1, isBlock).fold(function () {
  20990. return children$1;
  20991. }, function (index) {
  20992. return children$1.slice(0, index);
  20993. });
  20994. };
  20995. var extractChildren = function (block) {
  20996. var children = getChildrenUntilBlockBoundary(block);
  20997. each(children, remove);
  20998. return children;
  20999. };
  21000. var removeEmptyRoot = function (rootNode, block) {
  21001. var parents = parentsAndSelf(block, rootNode);
  21002. return find(parents.reverse(), function (element) {
  21003. return isEmpty(element);
  21004. }).each(remove);
  21005. };
  21006. var isEmptyBefore = function (el) {
  21007. return filter(prevSiblings(el), function (el) {
  21008. return !isEmpty(el);
  21009. }).length === 0;
  21010. };
  21011. var nestedBlockMerge = function (rootNode, fromBlock, toBlock, insertionPoint) {
  21012. if (isEmpty(toBlock)) {
  21013. fillWithPaddingBr(toBlock);
  21014. return firstPositionIn(toBlock.dom);
  21015. }
  21016. if (isEmptyBefore(insertionPoint) && isEmpty(fromBlock)) {
  21017. before(insertionPoint, SugarElement.fromTag('br'));
  21018. }
  21019. var position = prevPosition(toBlock.dom, CaretPosition$1.before(insertionPoint.dom));
  21020. each(extractChildren(fromBlock), function (child) {
  21021. before(insertionPoint, child);
  21022. });
  21023. removeEmptyRoot(rootNode, fromBlock);
  21024. return position;
  21025. };
  21026. var sidelongBlockMerge = function (rootNode, fromBlock, toBlock) {
  21027. if (isEmpty(toBlock)) {
  21028. remove(toBlock);
  21029. if (isEmpty(fromBlock)) {
  21030. fillWithPaddingBr(fromBlock);
  21031. }
  21032. return firstPositionIn(fromBlock.dom);
  21033. }
  21034. var position = lastPositionIn(toBlock.dom);
  21035. each(extractChildren(fromBlock), function (child) {
  21036. append(toBlock, child);
  21037. });
  21038. removeEmptyRoot(rootNode, fromBlock);
  21039. return position;
  21040. };
  21041. var findInsertionPoint = function (toBlock, block) {
  21042. var parentsAndSelf$1 = parentsAndSelf(block, toBlock);
  21043. return Optional.from(parentsAndSelf$1[parentsAndSelf$1.length - 1]);
  21044. };
  21045. var getInsertionPoint = function (fromBlock, toBlock) {
  21046. return contains$2(toBlock, fromBlock) ? findInsertionPoint(toBlock, fromBlock) : Optional.none();
  21047. };
  21048. var trimBr = function (first, block) {
  21049. positionIn(first, block.dom).map(function (position) {
  21050. return position.getNode();
  21051. }).map(SugarElement.fromDom).filter(isBr$1).each(remove);
  21052. };
  21053. var mergeBlockInto = function (rootNode, fromBlock, toBlock) {
  21054. trimBr(true, fromBlock);
  21055. trimBr(false, toBlock);
  21056. return getInsertionPoint(fromBlock, toBlock).fold(curry(sidelongBlockMerge, rootNode, fromBlock, toBlock), curry(nestedBlockMerge, rootNode, fromBlock, toBlock));
  21057. };
  21058. var mergeBlocks = function (rootNode, forward, block1, block2) {
  21059. return forward ? mergeBlockInto(rootNode, block2, block1) : mergeBlockInto(rootNode, block1, block2);
  21060. };
  21061. var backspaceDelete$1 = function (editor, forward) {
  21062. var rootNode = SugarElement.fromDom(editor.getBody());
  21063. var position = read$3(rootNode.dom, forward, editor.selection.getRng()).bind(function (blockBoundary) {
  21064. return mergeBlocks(rootNode, forward, blockBoundary.from.block, blockBoundary.to.block);
  21065. });
  21066. position.each(function (pos) {
  21067. editor.selection.setRng(pos.toRange());
  21068. });
  21069. return position.isSome();
  21070. };
  21071. var deleteRangeMergeBlocks = function (rootNode, selection) {
  21072. var rng = selection.getRng();
  21073. return lift2(getParentBlock$1(rootNode, SugarElement.fromDom(rng.startContainer)), getParentBlock$1(rootNode, SugarElement.fromDom(rng.endContainer)), function (block1, block2) {
  21074. if (eq$2(block1, block2) === false) {
  21075. rng.deleteContents();
  21076. mergeBlocks(rootNode, true, block1, block2).each(function (pos) {
  21077. selection.setRng(pos.toRange());
  21078. });
  21079. return true;
  21080. } else {
  21081. return false;
  21082. }
  21083. }).getOr(false);
  21084. };
  21085. var isRawNodeInTable = function (root, rawNode) {
  21086. var node = SugarElement.fromDom(rawNode);
  21087. var isRoot = curry(eq$2, root);
  21088. return ancestor(node, isTableCell$1, isRoot).isSome();
  21089. };
  21090. var isSelectionInTable = function (root, rng) {
  21091. return isRawNodeInTable(root, rng.startContainer) || isRawNodeInTable(root, rng.endContainer);
  21092. };
  21093. var isEverythingSelected = function (root, rng) {
  21094. var noPrevious = prevPosition(root.dom, CaretPosition$1.fromRangeStart(rng)).isNone();
  21095. var noNext = nextPosition(root.dom, CaretPosition$1.fromRangeEnd(rng)).isNone();
  21096. return !isSelectionInTable(root, rng) && noPrevious && noNext;
  21097. };
  21098. var emptyEditor = function (editor) {
  21099. editor.setContent('');
  21100. editor.selection.setCursorLocation();
  21101. return true;
  21102. };
  21103. var deleteRange$1 = function (editor) {
  21104. var rootNode = SugarElement.fromDom(editor.getBody());
  21105. var rng = editor.selection.getRng();
  21106. return isEverythingSelected(rootNode, rng) ? emptyEditor(editor) : deleteRangeMergeBlocks(rootNode, editor.selection);
  21107. };
  21108. var backspaceDelete$2 = function (editor, _forward) {
  21109. return editor.selection.isCollapsed() ? false : deleteRange$1(editor);
  21110. };
  21111. var isContentEditableTrue$2 = isContentEditableTrue;
  21112. var isContentEditableFalse$7 = isContentEditableFalse;
  21113. var showCaret = function (direction, editor, node, before, scrollIntoView) {
  21114. return Optional.from(editor._selectionOverrides.showCaret(direction, node, before, scrollIntoView));
  21115. };
  21116. var getNodeRange = function (node) {
  21117. var rng = node.ownerDocument.createRange();
  21118. rng.selectNode(node);
  21119. return rng;
  21120. };
  21121. var selectNode = function (editor, node) {
  21122. var e = editor.fire('BeforeObjectSelected', { target: node });
  21123. if (e.isDefaultPrevented()) {
  21124. return Optional.none();
  21125. }
  21126. return Optional.some(getNodeRange(node));
  21127. };
  21128. var renderCaretAtRange = function (editor, range, scrollIntoView) {
  21129. var normalizedRange = normalizeRange(1, editor.getBody(), range);
  21130. var caretPosition = CaretPosition$1.fromRangeStart(normalizedRange);
  21131. var caretPositionNode = caretPosition.getNode();
  21132. if (isInlineFakeCaretTarget(caretPositionNode)) {
  21133. return showCaret(1, editor, caretPositionNode, !caretPosition.isAtEnd(), false);
  21134. }
  21135. var caretPositionBeforeNode = caretPosition.getNode(true);
  21136. if (isInlineFakeCaretTarget(caretPositionBeforeNode)) {
  21137. return showCaret(1, editor, caretPositionBeforeNode, false, false);
  21138. }
  21139. var ceRoot = editor.dom.getParent(caretPosition.getNode(), function (node) {
  21140. return isContentEditableFalse$7(node) || isContentEditableTrue$2(node);
  21141. });
  21142. if (isInlineFakeCaretTarget(ceRoot)) {
  21143. return showCaret(1, editor, ceRoot, false, scrollIntoView);
  21144. }
  21145. return Optional.none();
  21146. };
  21147. var renderRangeCaret = function (editor, range, scrollIntoView) {
  21148. return range.collapsed ? renderCaretAtRange(editor, range, scrollIntoView).getOr(range) : range;
  21149. };
  21150. var isBeforeBoundary = function (pos) {
  21151. return isBeforeContentEditableFalse(pos) || isBeforeMedia(pos);
  21152. };
  21153. var isAfterBoundary = function (pos) {
  21154. return isAfterContentEditableFalse(pos) || isAfterMedia(pos);
  21155. };
  21156. var trimEmptyTextNode$1 = function (dom, node) {
  21157. if (isText$1(node) && node.data.length === 0) {
  21158. dom.remove(node);
  21159. }
  21160. };
  21161. var deleteContentAndShowCaret = function (editor, range, node, direction, forward, peekCaretPosition) {
  21162. showCaret(direction, editor, peekCaretPosition.getNode(!forward), forward, true).each(function (caretRange) {
  21163. if (range.collapsed) {
  21164. var deleteRange = range.cloneRange();
  21165. if (forward) {
  21166. deleteRange.setEnd(caretRange.startContainer, caretRange.startOffset);
  21167. } else {
  21168. deleteRange.setStart(caretRange.endContainer, caretRange.endOffset);
  21169. }
  21170. deleteRange.deleteContents();
  21171. } else {
  21172. range.deleteContents();
  21173. }
  21174. editor.selection.setRng(caretRange);
  21175. });
  21176. trimEmptyTextNode$1(editor.dom, node);
  21177. return true;
  21178. };
  21179. var deleteBoundaryText = function (editor, forward) {
  21180. var range = editor.selection.getRng();
  21181. if (!isText$1(range.commonAncestorContainer)) {
  21182. return false;
  21183. }
  21184. var direction = forward ? HDirection.Forwards : HDirection.Backwards;
  21185. var caretWalker = CaretWalker(editor.getBody());
  21186. var getNextPosFn = curry(getVisualCaretPosition, forward ? caretWalker.next : caretWalker.prev);
  21187. var isBeforeFn = forward ? isBeforeBoundary : isAfterBoundary;
  21188. var caretPosition = getNormalizedRangeEndPoint(direction, editor.getBody(), range);
  21189. var nextCaretPosition = normalizePosition(forward, getNextPosFn(caretPosition));
  21190. if (!nextCaretPosition || !isMoveInsideSameBlock(caretPosition, nextCaretPosition)) {
  21191. return false;
  21192. } else if (isBeforeFn(nextCaretPosition)) {
  21193. return deleteContentAndShowCaret(editor, range, caretPosition.getNode(), direction, forward, nextCaretPosition);
  21194. }
  21195. var peekCaretPosition = getNextPosFn(nextCaretPosition);
  21196. if (peekCaretPosition && isBeforeFn(peekCaretPosition)) {
  21197. if (isMoveInsideSameBlock(nextCaretPosition, peekCaretPosition)) {
  21198. return deleteContentAndShowCaret(editor, range, caretPosition.getNode(), direction, forward, peekCaretPosition);
  21199. }
  21200. }
  21201. return false;
  21202. };
  21203. var backspaceDelete$3 = function (editor, forward) {
  21204. return deleteBoundaryText(editor, forward);
  21205. };
  21206. var isCompoundElement = function (node) {
  21207. return isTableCell$1(SugarElement.fromDom(node)) || isListItem(SugarElement.fromDom(node));
  21208. };
  21209. var DeleteAction = Adt.generate([
  21210. { remove: ['element'] },
  21211. { moveToElement: ['element'] },
  21212. { moveToPosition: ['position'] }
  21213. ]);
  21214. var isAtContentEditableBlockCaret = function (forward, from) {
  21215. var elm = from.getNode(forward === false);
  21216. var caretLocation = forward ? 'after' : 'before';
  21217. return isElement$1(elm) && elm.getAttribute('data-mce-caret') === caretLocation;
  21218. };
  21219. var isDeleteFromCefDifferentBlocks = function (root, forward, from, to) {
  21220. var inSameBlock = function (elm) {
  21221. return isInline(SugarElement.fromDom(elm)) && !isInSameBlock(from, to, root);
  21222. };
  21223. return getRelativeCefElm(!forward, from).fold(function () {
  21224. return getRelativeCefElm(forward, to).fold(never, inSameBlock);
  21225. }, inSameBlock);
  21226. };
  21227. var deleteEmptyBlockOrMoveToCef = function (root, forward, from, to) {
  21228. var toCefElm = to.getNode(forward === false);
  21229. return getParentBlock$1(SugarElement.fromDom(root), SugarElement.fromDom(from.getNode())).map(function (blockElm) {
  21230. return isEmpty(blockElm) ? DeleteAction.remove(blockElm.dom) : DeleteAction.moveToElement(toCefElm);
  21231. }).orThunk(function () {
  21232. return Optional.some(DeleteAction.moveToElement(toCefElm));
  21233. });
  21234. };
  21235. var findCefPosition = function (root, forward, from) {
  21236. return fromPosition(forward, root, from).bind(function (to) {
  21237. if (isCompoundElement(to.getNode())) {
  21238. return Optional.none();
  21239. } else if (isDeleteFromCefDifferentBlocks(root, forward, from, to)) {
  21240. return Optional.none();
  21241. } else if (forward && isContentEditableFalse(to.getNode())) {
  21242. return deleteEmptyBlockOrMoveToCef(root, forward, from, to);
  21243. } else if (forward === false && isContentEditableFalse(to.getNode(true))) {
  21244. return deleteEmptyBlockOrMoveToCef(root, forward, from, to);
  21245. } else if (forward && isAfterContentEditableFalse(from)) {
  21246. return Optional.some(DeleteAction.moveToPosition(to));
  21247. } else if (forward === false && isBeforeContentEditableFalse(from)) {
  21248. return Optional.some(DeleteAction.moveToPosition(to));
  21249. } else {
  21250. return Optional.none();
  21251. }
  21252. });
  21253. };
  21254. var getContentEditableBlockAction = function (forward, elm) {
  21255. if (forward && isContentEditableFalse(elm.nextSibling)) {
  21256. return Optional.some(DeleteAction.moveToElement(elm.nextSibling));
  21257. } else if (forward === false && isContentEditableFalse(elm.previousSibling)) {
  21258. return Optional.some(DeleteAction.moveToElement(elm.previousSibling));
  21259. } else {
  21260. return Optional.none();
  21261. }
  21262. };
  21263. var skipMoveToActionFromInlineCefToContent = function (root, from, deleteAction) {
  21264. return deleteAction.fold(function (elm) {
  21265. return Optional.some(DeleteAction.remove(elm));
  21266. }, function (elm) {
  21267. return Optional.some(DeleteAction.moveToElement(elm));
  21268. }, function (to) {
  21269. if (isInSameBlock(from, to, root)) {
  21270. return Optional.none();
  21271. } else {
  21272. return Optional.some(DeleteAction.moveToPosition(to));
  21273. }
  21274. });
  21275. };
  21276. var getContentEditableAction = function (root, forward, from) {
  21277. if (isAtContentEditableBlockCaret(forward, from)) {
  21278. return getContentEditableBlockAction(forward, from.getNode(forward === false)).fold(function () {
  21279. return findCefPosition(root, forward, from);
  21280. }, Optional.some);
  21281. } else {
  21282. return findCefPosition(root, forward, from).bind(function (deleteAction) {
  21283. return skipMoveToActionFromInlineCefToContent(root, from, deleteAction);
  21284. });
  21285. }
  21286. };
  21287. var read$4 = function (root, forward, rng) {
  21288. var normalizedRange = normalizeRange(forward ? 1 : -1, root, rng);
  21289. var from = CaretPosition$1.fromRangeStart(normalizedRange);
  21290. var rootElement = SugarElement.fromDom(root);
  21291. if (forward === false && isAfterContentEditableFalse(from)) {
  21292. return Optional.some(DeleteAction.remove(from.getNode(true)));
  21293. } else if (forward && isBeforeContentEditableFalse(from)) {
  21294. return Optional.some(DeleteAction.remove(from.getNode()));
  21295. } else if (forward === false && isBeforeContentEditableFalse(from) && isAfterBr(rootElement, from)) {
  21296. return findPreviousBr(rootElement, from).map(function (br) {
  21297. return DeleteAction.remove(br.getNode());
  21298. });
  21299. } else if (forward && isAfterContentEditableFalse(from) && isBeforeBr(rootElement, from)) {
  21300. return findNextBr(rootElement, from).map(function (br) {
  21301. return DeleteAction.remove(br.getNode());
  21302. });
  21303. } else {
  21304. return getContentEditableAction(root, forward, from);
  21305. }
  21306. };
  21307. var deleteElement$1 = function (editor, forward) {
  21308. return function (element) {
  21309. editor._selectionOverrides.hideFakeCaret();
  21310. deleteElement(editor, forward, SugarElement.fromDom(element));
  21311. return true;
  21312. };
  21313. };
  21314. var moveToElement = function (editor, forward) {
  21315. return function (element) {
  21316. var pos = forward ? CaretPosition$1.before(element) : CaretPosition$1.after(element);
  21317. editor.selection.setRng(pos.toRange());
  21318. return true;
  21319. };
  21320. };
  21321. var moveToPosition = function (editor) {
  21322. return function (pos) {
  21323. editor.selection.setRng(pos.toRange());
  21324. return true;
  21325. };
  21326. };
  21327. var getAncestorCe = function (editor, node) {
  21328. return Optional.from(getContentEditableRoot(editor.getBody(), node));
  21329. };
  21330. var backspaceDeleteCaret = function (editor, forward) {
  21331. var selectedNode = editor.selection.getNode();
  21332. return getAncestorCe(editor, selectedNode).filter(isContentEditableFalse).fold(function () {
  21333. return read$4(editor.getBody(), forward, editor.selection.getRng()).exists(function (deleteAction) {
  21334. return deleteAction.fold(deleteElement$1(editor, forward), moveToElement(editor, forward), moveToPosition(editor));
  21335. });
  21336. }, always);
  21337. };
  21338. var deleteOffscreenSelection = function (rootElement) {
  21339. each(descendants$1(rootElement, '.mce-offscreen-selection'), remove);
  21340. };
  21341. var backspaceDeleteRange = function (editor, forward) {
  21342. var selectedNode = editor.selection.getNode();
  21343. if (isContentEditableFalse(selectedNode)) {
  21344. var hasCefAncestor = getAncestorCe(editor, selectedNode.parentNode).filter(isContentEditableFalse);
  21345. return hasCefAncestor.fold(function () {
  21346. deleteOffscreenSelection(SugarElement.fromDom(editor.getBody()));
  21347. deleteElement(editor, forward, SugarElement.fromDom(editor.selection.getNode()));
  21348. paddEmptyBody(editor);
  21349. return true;
  21350. }, function () {
  21351. return true;
  21352. });
  21353. }
  21354. return false;
  21355. };
  21356. var paddEmptyElement = function (editor) {
  21357. var dom = editor.dom, selection = editor.selection;
  21358. var ceRoot = getContentEditableRoot(editor.getBody(), selection.getNode());
  21359. if (isContentEditableTrue(ceRoot) && dom.isBlock(ceRoot) && dom.isEmpty(ceRoot)) {
  21360. var br = dom.create('br', { 'data-mce-bogus': '1' });
  21361. dom.setHTML(ceRoot, '');
  21362. ceRoot.appendChild(br);
  21363. selection.setRng(CaretPosition$1.before(br).toRange());
  21364. }
  21365. return true;
  21366. };
  21367. var backspaceDelete$4 = function (editor, forward) {
  21368. if (editor.selection.isCollapsed()) {
  21369. return backspaceDeleteCaret(editor, forward);
  21370. } else {
  21371. return backspaceDeleteRange(editor, forward);
  21372. }
  21373. };
  21374. var deleteCaret$1 = function (editor, forward) {
  21375. var fromPos = CaretPosition$1.fromRangeStart(editor.selection.getRng());
  21376. return fromPosition(forward, editor.getBody(), fromPos).filter(function (pos) {
  21377. return forward ? isBeforeImageBlock(pos) : isAfterImageBlock(pos);
  21378. }).bind(function (pos) {
  21379. return Optional.from(getChildNodeAtRelativeOffset(forward ? 0 : -1, pos));
  21380. }).exists(function (elm) {
  21381. editor.selection.select(elm);
  21382. return true;
  21383. });
  21384. };
  21385. var backspaceDelete$5 = function (editor, forward) {
  21386. return editor.selection.isCollapsed() ? deleteCaret$1(editor, forward) : false;
  21387. };
  21388. var isText$8 = isText$1;
  21389. var startsWithCaretContainer$1 = function (node) {
  21390. return isText$8(node) && node.data[0] === ZWSP;
  21391. };
  21392. var endsWithCaretContainer$1 = function (node) {
  21393. return isText$8(node) && node.data[node.data.length - 1] === ZWSP;
  21394. };
  21395. var createZwsp = function (node) {
  21396. return node.ownerDocument.createTextNode(ZWSP);
  21397. };
  21398. var insertBefore$1 = function (node) {
  21399. if (isText$8(node.previousSibling)) {
  21400. if (endsWithCaretContainer$1(node.previousSibling)) {
  21401. return node.previousSibling;
  21402. } else {
  21403. node.previousSibling.appendData(ZWSP);
  21404. return node.previousSibling;
  21405. }
  21406. } else if (isText$8(node)) {
  21407. if (startsWithCaretContainer$1(node)) {
  21408. return node;
  21409. } else {
  21410. node.insertData(0, ZWSP);
  21411. return node;
  21412. }
  21413. } else {
  21414. var newNode = createZwsp(node);
  21415. node.parentNode.insertBefore(newNode, node);
  21416. return newNode;
  21417. }
  21418. };
  21419. var insertAfter$1 = function (node) {
  21420. if (isText$8(node.nextSibling)) {
  21421. if (startsWithCaretContainer$1(node.nextSibling)) {
  21422. return node.nextSibling;
  21423. } else {
  21424. node.nextSibling.insertData(0, ZWSP);
  21425. return node.nextSibling;
  21426. }
  21427. } else if (isText$8(node)) {
  21428. if (endsWithCaretContainer$1(node)) {
  21429. return node;
  21430. } else {
  21431. node.appendData(ZWSP);
  21432. return node;
  21433. }
  21434. } else {
  21435. var newNode = createZwsp(node);
  21436. if (node.nextSibling) {
  21437. node.parentNode.insertBefore(newNode, node.nextSibling);
  21438. } else {
  21439. node.parentNode.appendChild(newNode);
  21440. }
  21441. return newNode;
  21442. }
  21443. };
  21444. var insertInline$1 = function (before, node) {
  21445. return before ? insertBefore$1(node) : insertAfter$1(node);
  21446. };
  21447. var insertInlineBefore = curry(insertInline$1, true);
  21448. var insertInlineAfter = curry(insertInline$1, false);
  21449. var insertInlinePos = function (pos, before) {
  21450. if (isText$1(pos.container())) {
  21451. return insertInline$1(before, pos.container());
  21452. } else {
  21453. return insertInline$1(before, pos.getNode());
  21454. }
  21455. };
  21456. var isPosCaretContainer = function (pos, caret) {
  21457. var caretNode = caret.get();
  21458. return caretNode && pos.container() === caretNode && isCaretContainerInline(caretNode);
  21459. };
  21460. var renderCaret = function (caret, location) {
  21461. return location.fold(function (element) {
  21462. remove$5(caret.get());
  21463. var text = insertInlineBefore(element);
  21464. caret.set(text);
  21465. return Optional.some(CaretPosition$1(text, text.length - 1));
  21466. }, function (element) {
  21467. return firstPositionIn(element).map(function (pos) {
  21468. if (!isPosCaretContainer(pos, caret)) {
  21469. remove$5(caret.get());
  21470. var text = insertInlinePos(pos, true);
  21471. caret.set(text);
  21472. return CaretPosition$1(text, 1);
  21473. } else {
  21474. return CaretPosition$1(caret.get(), 1);
  21475. }
  21476. });
  21477. }, function (element) {
  21478. return lastPositionIn(element).map(function (pos) {
  21479. if (!isPosCaretContainer(pos, caret)) {
  21480. remove$5(caret.get());
  21481. var text = insertInlinePos(pos, false);
  21482. caret.set(text);
  21483. return CaretPosition$1(text, text.length - 1);
  21484. } else {
  21485. return CaretPosition$1(caret.get(), caret.get().length - 1);
  21486. }
  21487. });
  21488. }, function (element) {
  21489. remove$5(caret.get());
  21490. var text = insertInlineAfter(element);
  21491. caret.set(text);
  21492. return Optional.some(CaretPosition$1(text, 1));
  21493. });
  21494. };
  21495. var evaluateUntil = function (fns, args) {
  21496. for (var i = 0; i < fns.length; i++) {
  21497. var result = fns[i].apply(null, args);
  21498. if (result.isSome()) {
  21499. return result;
  21500. }
  21501. }
  21502. return Optional.none();
  21503. };
  21504. var Location = Adt.generate([
  21505. { before: ['element'] },
  21506. { start: ['element'] },
  21507. { end: ['element'] },
  21508. { after: ['element'] }
  21509. ]);
  21510. var rescope = function (rootNode, node) {
  21511. var parentBlock = getParentBlock(node, rootNode);
  21512. return parentBlock ? parentBlock : rootNode;
  21513. };
  21514. var before$4 = function (isInlineTarget, rootNode, pos) {
  21515. var nPos = normalizeForwards(pos);
  21516. var scope = rescope(rootNode, nPos.container());
  21517. return findRootInline(isInlineTarget, scope, nPos).fold(function () {
  21518. return nextPosition(scope, nPos).bind(curry(findRootInline, isInlineTarget, scope)).map(function (inline) {
  21519. return Location.before(inline);
  21520. });
  21521. }, Optional.none);
  21522. };
  21523. var isNotInsideFormatCaretContainer = function (rootNode, elm) {
  21524. return getParentCaretContainer(rootNode, elm) === null;
  21525. };
  21526. var findInsideRootInline = function (isInlineTarget, rootNode, pos) {
  21527. return findRootInline(isInlineTarget, rootNode, pos).filter(curry(isNotInsideFormatCaretContainer, rootNode));
  21528. };
  21529. var start = function (isInlineTarget, rootNode, pos) {
  21530. var nPos = normalizeBackwards(pos);
  21531. return findInsideRootInline(isInlineTarget, rootNode, nPos).bind(function (inline) {
  21532. var prevPos = prevPosition(inline, nPos);
  21533. return prevPos.isNone() ? Optional.some(Location.start(inline)) : Optional.none();
  21534. });
  21535. };
  21536. var end = function (isInlineTarget, rootNode, pos) {
  21537. var nPos = normalizeForwards(pos);
  21538. return findInsideRootInline(isInlineTarget, rootNode, nPos).bind(function (inline) {
  21539. var nextPos = nextPosition(inline, nPos);
  21540. return nextPos.isNone() ? Optional.some(Location.end(inline)) : Optional.none();
  21541. });
  21542. };
  21543. var after$3 = function (isInlineTarget, rootNode, pos) {
  21544. var nPos = normalizeBackwards(pos);
  21545. var scope = rescope(rootNode, nPos.container());
  21546. return findRootInline(isInlineTarget, scope, nPos).fold(function () {
  21547. return prevPosition(scope, nPos).bind(curry(findRootInline, isInlineTarget, scope)).map(function (inline) {
  21548. return Location.after(inline);
  21549. });
  21550. }, Optional.none);
  21551. };
  21552. var isValidLocation = function (location) {
  21553. return isRtl$1(getElement(location)) === false;
  21554. };
  21555. var readLocation = function (isInlineTarget, rootNode, pos) {
  21556. var location = evaluateUntil([
  21557. before$4,
  21558. start,
  21559. end,
  21560. after$3
  21561. ], [
  21562. isInlineTarget,
  21563. rootNode,
  21564. pos
  21565. ]);
  21566. return location.filter(isValidLocation);
  21567. };
  21568. var getElement = function (location) {
  21569. return location.fold(identity, identity, identity, identity);
  21570. };
  21571. var getName = function (location) {
  21572. return location.fold(constant('before'), constant('start'), constant('end'), constant('after'));
  21573. };
  21574. var outside = function (location) {
  21575. return location.fold(Location.before, Location.before, Location.after, Location.after);
  21576. };
  21577. var inside = function (location) {
  21578. return location.fold(Location.start, Location.start, Location.end, Location.end);
  21579. };
  21580. var isEq$5 = function (location1, location2) {
  21581. return getName(location1) === getName(location2) && getElement(location1) === getElement(location2);
  21582. };
  21583. var betweenInlines = function (forward, isInlineTarget, rootNode, from, to, location) {
  21584. return lift2(findRootInline(isInlineTarget, rootNode, from), findRootInline(isInlineTarget, rootNode, to), function (fromInline, toInline) {
  21585. if (fromInline !== toInline && hasSameParentBlock(rootNode, fromInline, toInline)) {
  21586. return Location.after(forward ? fromInline : toInline);
  21587. } else {
  21588. return location;
  21589. }
  21590. }).getOr(location);
  21591. };
  21592. var skipNoMovement = function (fromLocation, toLocation) {
  21593. return fromLocation.fold(always, function (fromLocation) {
  21594. return !isEq$5(fromLocation, toLocation);
  21595. });
  21596. };
  21597. var findLocationTraverse = function (forward, isInlineTarget, rootNode, fromLocation, pos) {
  21598. var from = normalizePosition(forward, pos);
  21599. var to = fromPosition(forward, rootNode, from).map(curry(normalizePosition, forward));
  21600. var location = to.fold(function () {
  21601. return fromLocation.map(outside);
  21602. }, function (to) {
  21603. return readLocation(isInlineTarget, rootNode, to).map(curry(betweenInlines, forward, isInlineTarget, rootNode, from, to)).filter(curry(skipNoMovement, fromLocation));
  21604. });
  21605. return location.filter(isValidLocation);
  21606. };
  21607. var findLocationSimple = function (forward, location) {
  21608. if (forward) {
  21609. return location.fold(compose(Optional.some, Location.start), Optional.none, compose(Optional.some, Location.after), Optional.none);
  21610. } else {
  21611. return location.fold(Optional.none, compose(Optional.some, Location.before), Optional.none, compose(Optional.some, Location.end));
  21612. }
  21613. };
  21614. var findLocation = function (forward, isInlineTarget, rootNode, pos) {
  21615. var from = normalizePosition(forward, pos);
  21616. var fromLocation = readLocation(isInlineTarget, rootNode, from);
  21617. return readLocation(isInlineTarget, rootNode, from).bind(curry(findLocationSimple, forward)).orThunk(function () {
  21618. return findLocationTraverse(forward, isInlineTarget, rootNode, fromLocation, pos);
  21619. });
  21620. };
  21621. var prevLocation = curry(findLocation, false);
  21622. var nextLocation = curry(findLocation, true);
  21623. var hasSelectionModifyApi = function (editor) {
  21624. return isFunction(editor.selection.getSel().modify);
  21625. };
  21626. var moveRel = function (forward, selection, pos) {
  21627. var delta = forward ? 1 : -1;
  21628. selection.setRng(CaretPosition$1(pos.container(), pos.offset() + delta).toRange());
  21629. selection.getSel().modify('move', forward ? 'forward' : 'backward', 'word');
  21630. return true;
  21631. };
  21632. var moveByWord = function (forward, editor) {
  21633. var rng = editor.selection.getRng();
  21634. var pos = forward ? CaretPosition$1.fromRangeEnd(rng) : CaretPosition$1.fromRangeStart(rng);
  21635. if (!hasSelectionModifyApi(editor)) {
  21636. return false;
  21637. } else if (forward && isBeforeInline(pos)) {
  21638. return moveRel(true, editor.selection, pos);
  21639. } else if (!forward && isAfterInline(pos)) {
  21640. return moveRel(false, editor.selection, pos);
  21641. } else {
  21642. return false;
  21643. }
  21644. };
  21645. var setCaretPosition = function (editor, pos) {
  21646. var rng = editor.dom.createRng();
  21647. rng.setStart(pos.container(), pos.offset());
  21648. rng.setEnd(pos.container(), pos.offset());
  21649. editor.selection.setRng(rng);
  21650. };
  21651. var setSelected = function (state, elm) {
  21652. if (state) {
  21653. elm.setAttribute('data-mce-selected', 'inline-boundary');
  21654. } else {
  21655. elm.removeAttribute('data-mce-selected');
  21656. }
  21657. };
  21658. var renderCaretLocation = function (editor, caret, location) {
  21659. return renderCaret(caret, location).map(function (pos) {
  21660. setCaretPosition(editor, pos);
  21661. return location;
  21662. });
  21663. };
  21664. var findLocation$1 = function (editor, caret, forward) {
  21665. var rootNode = editor.getBody();
  21666. var from = CaretPosition$1.fromRangeStart(editor.selection.getRng());
  21667. var isInlineTarget$1 = curry(isInlineTarget, editor);
  21668. var location = findLocation(forward, isInlineTarget$1, rootNode, from);
  21669. return location.bind(function (location) {
  21670. return renderCaretLocation(editor, caret, location);
  21671. });
  21672. };
  21673. var toggleInlines = function (isInlineTarget, dom, elms) {
  21674. var inlineBoundaries = map(descendants$1(SugarElement.fromDom(dom.getRoot()), '*[data-mce-selected="inline-boundary"]'), function (e) {
  21675. return e.dom;
  21676. });
  21677. var selectedInlines = filter(inlineBoundaries, isInlineTarget);
  21678. var targetInlines = filter(elms, isInlineTarget);
  21679. each(difference(selectedInlines, targetInlines), curry(setSelected, false));
  21680. each(difference(targetInlines, selectedInlines), curry(setSelected, true));
  21681. };
  21682. var safeRemoveCaretContainer = function (editor, caret) {
  21683. if (editor.selection.isCollapsed() && editor.composing !== true && caret.get()) {
  21684. var pos = CaretPosition$1.fromRangeStart(editor.selection.getRng());
  21685. if (CaretPosition$1.isTextPosition(pos) && isAtZwsp(pos) === false) {
  21686. setCaretPosition(editor, removeAndReposition(caret.get(), pos));
  21687. caret.set(null);
  21688. }
  21689. }
  21690. };
  21691. var renderInsideInlineCaret = function (isInlineTarget, editor, caret, elms) {
  21692. if (editor.selection.isCollapsed()) {
  21693. var inlines = filter(elms, isInlineTarget);
  21694. each(inlines, function (_inline) {
  21695. var pos = CaretPosition$1.fromRangeStart(editor.selection.getRng());
  21696. readLocation(isInlineTarget, editor.getBody(), pos).bind(function (location) {
  21697. return renderCaretLocation(editor, caret, location);
  21698. });
  21699. });
  21700. }
  21701. };
  21702. var move = function (editor, caret, forward) {
  21703. return isInlineBoundariesEnabled(editor) ? findLocation$1(editor, caret, forward).isSome() : false;
  21704. };
  21705. var moveWord = function (forward, editor, _caret) {
  21706. return isInlineBoundariesEnabled(editor) ? moveByWord(forward, editor) : false;
  21707. };
  21708. var setupSelectedState = function (editor) {
  21709. var caret = Cell(null);
  21710. var isInlineTarget$1 = curry(isInlineTarget, editor);
  21711. editor.on('NodeChange', function (e) {
  21712. if (isInlineBoundariesEnabled(editor) && !(Env.browser.isIE() && e.initial)) {
  21713. toggleInlines(isInlineTarget$1, editor.dom, e.parents);
  21714. safeRemoveCaretContainer(editor, caret);
  21715. renderInsideInlineCaret(isInlineTarget$1, editor, caret, e.parents);
  21716. }
  21717. });
  21718. return caret;
  21719. };
  21720. var moveNextWord = curry(moveWord, true);
  21721. var movePrevWord = curry(moveWord, false);
  21722. var rangeFromPositions = function (from, to) {
  21723. var range = document.createRange();
  21724. range.setStart(from.container(), from.offset());
  21725. range.setEnd(to.container(), to.offset());
  21726. return range;
  21727. };
  21728. var hasOnlyTwoOrLessPositionsLeft = function (elm) {
  21729. return lift2(firstPositionIn(elm), lastPositionIn(elm), function (firstPos, lastPos) {
  21730. var normalizedFirstPos = normalizePosition(true, firstPos);
  21731. var normalizedLastPos = normalizePosition(false, lastPos);
  21732. return nextPosition(elm, normalizedFirstPos).forall(function (pos) {
  21733. return pos.isEqual(normalizedLastPos);
  21734. });
  21735. }).getOr(true);
  21736. };
  21737. var setCaretLocation = function (editor, caret) {
  21738. return function (location) {
  21739. return renderCaret(caret, location).exists(function (pos) {
  21740. setCaretPosition(editor, pos);
  21741. return true;
  21742. });
  21743. };
  21744. };
  21745. var deleteFromTo = function (editor, caret, from, to) {
  21746. var rootNode = editor.getBody();
  21747. var isInlineTarget$1 = curry(isInlineTarget, editor);
  21748. editor.undoManager.ignore(function () {
  21749. editor.selection.setRng(rangeFromPositions(from, to));
  21750. editor.execCommand('Delete');
  21751. readLocation(isInlineTarget$1, rootNode, CaretPosition$1.fromRangeStart(editor.selection.getRng())).map(inside).map(setCaretLocation(editor, caret));
  21752. });
  21753. editor.nodeChanged();
  21754. };
  21755. var rescope$1 = function (rootNode, node) {
  21756. var parentBlock = getParentBlock(node, rootNode);
  21757. return parentBlock ? parentBlock : rootNode;
  21758. };
  21759. var backspaceDeleteCollapsed = function (editor, caret, forward, from) {
  21760. var rootNode = rescope$1(editor.getBody(), from.container());
  21761. var isInlineTarget$1 = curry(isInlineTarget, editor);
  21762. var fromLocation = readLocation(isInlineTarget$1, rootNode, from);
  21763. return fromLocation.bind(function (location) {
  21764. if (forward) {
  21765. return location.fold(constant(Optional.some(inside(location))), Optional.none, constant(Optional.some(outside(location))), Optional.none);
  21766. } else {
  21767. return location.fold(Optional.none, constant(Optional.some(outside(location))), Optional.none, constant(Optional.some(inside(location))));
  21768. }
  21769. }).map(setCaretLocation(editor, caret)).getOrThunk(function () {
  21770. var toPosition = navigate(forward, rootNode, from);
  21771. var toLocation = toPosition.bind(function (pos) {
  21772. return readLocation(isInlineTarget$1, rootNode, pos);
  21773. });
  21774. return lift2(fromLocation, toLocation, function () {
  21775. return findRootInline(isInlineTarget$1, rootNode, from).exists(function (elm) {
  21776. if (hasOnlyTwoOrLessPositionsLeft(elm)) {
  21777. deleteElement(editor, forward, SugarElement.fromDom(elm));
  21778. return true;
  21779. } else {
  21780. return false;
  21781. }
  21782. });
  21783. }).orThunk(function () {
  21784. return toLocation.bind(function (_) {
  21785. return toPosition.map(function (to) {
  21786. if (forward) {
  21787. deleteFromTo(editor, caret, from, to);
  21788. } else {
  21789. deleteFromTo(editor, caret, to, from);
  21790. }
  21791. return true;
  21792. });
  21793. });
  21794. }).getOr(false);
  21795. });
  21796. };
  21797. var backspaceDelete$6 = function (editor, caret, forward) {
  21798. if (editor.selection.isCollapsed() && isInlineBoundariesEnabled(editor)) {
  21799. var from = CaretPosition$1.fromRangeStart(editor.selection.getRng());
  21800. return backspaceDeleteCollapsed(editor, caret, forward, from);
  21801. }
  21802. return false;
  21803. };
  21804. var getParentInlines = function (rootElm, startElm) {
  21805. var parents = parentsAndSelf(startElm, rootElm);
  21806. return findIndex(parents, isBlock).fold(constant(parents), function (index) {
  21807. return parents.slice(0, index);
  21808. });
  21809. };
  21810. var hasOnlyOneChild$1 = function (elm) {
  21811. return children(elm).length === 1;
  21812. };
  21813. var deleteLastPosition = function (forward, editor, target, parentInlines) {
  21814. var isFormatElement$1 = curry(isFormatElement, editor);
  21815. var formatNodes = map(filter(parentInlines, isFormatElement$1), function (elm) {
  21816. return elm.dom;
  21817. });
  21818. if (formatNodes.length === 0) {
  21819. deleteElement(editor, forward, target);
  21820. } else {
  21821. var pos = replaceWithCaretFormat(target.dom, formatNodes);
  21822. editor.selection.setRng(pos.toRange());
  21823. }
  21824. };
  21825. var deleteCaret$2 = function (editor, forward) {
  21826. var rootElm = SugarElement.fromDom(editor.getBody());
  21827. var startElm = SugarElement.fromDom(editor.selection.getStart());
  21828. var parentInlines = filter(getParentInlines(rootElm, startElm), hasOnlyOneChild$1);
  21829. return last(parentInlines).exists(function (target) {
  21830. var fromPos = CaretPosition$1.fromRangeStart(editor.selection.getRng());
  21831. if (willDeleteLastPositionInElement(forward, fromPos, target.dom) && !isEmptyCaretFormatElement(target)) {
  21832. deleteLastPosition(forward, editor, target, parentInlines);
  21833. return true;
  21834. } else {
  21835. return false;
  21836. }
  21837. });
  21838. };
  21839. var backspaceDelete$7 = function (editor, forward) {
  21840. return editor.selection.isCollapsed() ? deleteCaret$2(editor, forward) : false;
  21841. };
  21842. var deleteElement$2 = function (editor, forward, element) {
  21843. editor._selectionOverrides.hideFakeCaret();
  21844. deleteElement(editor, forward, SugarElement.fromDom(element));
  21845. return true;
  21846. };
  21847. var deleteCaret$3 = function (editor, forward) {
  21848. var isNearMedia = forward ? isBeforeMedia : isAfterMedia;
  21849. var direction = forward ? HDirection.Forwards : HDirection.Backwards;
  21850. var fromPos = getNormalizedRangeEndPoint(direction, editor.getBody(), editor.selection.getRng());
  21851. if (isNearMedia(fromPos)) {
  21852. return deleteElement$2(editor, forward, fromPos.getNode(!forward));
  21853. } else {
  21854. return Optional.from(normalizePosition(forward, fromPos)).filter(function (pos) {
  21855. return isNearMedia(pos) && isMoveInsideSameBlock(fromPos, pos);
  21856. }).exists(function (pos) {
  21857. return deleteElement$2(editor, forward, pos.getNode(!forward));
  21858. });
  21859. }
  21860. };
  21861. var deleteRange$2 = function (editor, forward) {
  21862. var selectedNode = editor.selection.getNode();
  21863. return isMedia(selectedNode) ? deleteElement$2(editor, forward, selectedNode) : false;
  21864. };
  21865. var backspaceDelete$8 = function (editor, forward) {
  21866. return editor.selection.isCollapsed() ? deleteCaret$3(editor, forward) : deleteRange$2(editor, forward);
  21867. };
  21868. var isEditable$1 = function (target) {
  21869. return closest(target, function (elm) {
  21870. return isContentEditableTrue(elm.dom) || isContentEditableFalse(elm.dom);
  21871. }).exists(function (elm) {
  21872. return isContentEditableTrue(elm.dom);
  21873. });
  21874. };
  21875. var parseIndentValue = function (value) {
  21876. var number = parseInt(value, 10);
  21877. return isNaN(number) ? 0 : number;
  21878. };
  21879. var getIndentStyleName = function (useMargin, element) {
  21880. var indentStyleName = useMargin || isTable$1(element) ? 'margin' : 'padding';
  21881. var suffix = get$4(element, 'direction') === 'rtl' ? '-right' : '-left';
  21882. return indentStyleName + suffix;
  21883. };
  21884. var indentElement = function (dom, command, useMargin, value, unit, element) {
  21885. var indentStyleName = getIndentStyleName(useMargin, SugarElement.fromDom(element));
  21886. if (command === 'outdent') {
  21887. var styleValue = Math.max(0, parseIndentValue(element.style[indentStyleName]) - value);
  21888. dom.setStyle(element, indentStyleName, styleValue ? styleValue + unit : '');
  21889. } else {
  21890. var styleValue = parseIndentValue(element.style[indentStyleName]) + value + unit;
  21891. dom.setStyle(element, indentStyleName, styleValue);
  21892. }
  21893. };
  21894. var validateBlocks = function (editor, blocks) {
  21895. return forall(blocks, function (block) {
  21896. var indentStyleName = getIndentStyleName(shouldIndentUseMargin(editor), block);
  21897. var intentValue = getRaw(block, indentStyleName).map(parseIndentValue).getOr(0);
  21898. var contentEditable = editor.dom.getContentEditable(block.dom);
  21899. return contentEditable !== 'false' && intentValue > 0;
  21900. });
  21901. };
  21902. var canOutdent = function (editor) {
  21903. var blocks = getBlocksToIndent(editor);
  21904. return !editor.mode.isReadOnly() && (blocks.length > 1 || validateBlocks(editor, blocks));
  21905. };
  21906. var isListComponent = function (el) {
  21907. return isList(el) || isListItem(el);
  21908. };
  21909. var parentIsListComponent = function (el) {
  21910. return parent(el).map(isListComponent).getOr(false);
  21911. };
  21912. var getBlocksToIndent = function (editor) {
  21913. return filter(map(editor.selection.getSelectedBlocks(), SugarElement.fromDom), function (el) {
  21914. return !isListComponent(el) && !parentIsListComponent(el) && isEditable$1(el);
  21915. });
  21916. };
  21917. var handle = function (editor, command) {
  21918. var dom = editor.dom, selection = editor.selection, formatter = editor.formatter;
  21919. var indentation = getIndentation(editor);
  21920. var indentUnit = /[a-z%]+$/i.exec(indentation)[0];
  21921. var indentValue = parseInt(indentation, 10);
  21922. var useMargin = shouldIndentUseMargin(editor);
  21923. var forcedRootBlock = getForcedRootBlock(editor);
  21924. if (!editor.queryCommandState('InsertUnorderedList') && !editor.queryCommandState('InsertOrderedList')) {
  21925. if (forcedRootBlock === '' && !dom.getParent(selection.getNode(), dom.isBlock)) {
  21926. formatter.apply('div');
  21927. }
  21928. }
  21929. each(getBlocksToIndent(editor), function (block) {
  21930. indentElement(dom, command, useMargin, indentValue, indentUnit, block.dom);
  21931. });
  21932. };
  21933. var backspaceDelete$9 = function (editor, _forward) {
  21934. if (editor.selection.isCollapsed() && canOutdent(editor)) {
  21935. var dom = editor.dom;
  21936. var rng = editor.selection.getRng();
  21937. var pos = CaretPosition$1.fromRangeStart(rng);
  21938. var block = dom.getParent(rng.startContainer, dom.isBlock);
  21939. if (block !== null && isAtStartOfBlock(SugarElement.fromDom(block), pos)) {
  21940. handle(editor, 'outdent');
  21941. return true;
  21942. }
  21943. }
  21944. return false;
  21945. };
  21946. var nativeCommand = function (editor, command) {
  21947. editor.getDoc().execCommand(command, false, null);
  21948. };
  21949. var deleteCommand = function (editor, caret) {
  21950. if (backspaceDelete$9(editor)) {
  21951. return;
  21952. } else if (backspaceDelete$4(editor, false)) {
  21953. return;
  21954. } else if (backspaceDelete$3(editor, false)) {
  21955. return;
  21956. } else if (backspaceDelete$6(editor, caret, false)) {
  21957. return;
  21958. } else if (backspaceDelete$1(editor, false)) {
  21959. return;
  21960. } else if (backspaceDelete(editor)) {
  21961. return;
  21962. } else if (backspaceDelete$5(editor, false)) {
  21963. return;
  21964. } else if (backspaceDelete$8(editor, false)) {
  21965. return;
  21966. } else if (backspaceDelete$2(editor)) {
  21967. return;
  21968. } else if (backspaceDelete$7(editor, false)) {
  21969. return;
  21970. } else {
  21971. nativeCommand(editor, 'Delete');
  21972. paddEmptyBody(editor);
  21973. }
  21974. };
  21975. var forwardDeleteCommand = function (editor, caret) {
  21976. if (backspaceDelete$4(editor, true)) {
  21977. return;
  21978. } else if (backspaceDelete$3(editor, true)) {
  21979. return;
  21980. } else if (backspaceDelete$6(editor, caret, true)) {
  21981. return;
  21982. } else if (backspaceDelete$1(editor, true)) {
  21983. return;
  21984. } else if (backspaceDelete(editor)) {
  21985. return;
  21986. } else if (backspaceDelete$5(editor, true)) {
  21987. return;
  21988. } else if (backspaceDelete$8(editor, true)) {
  21989. return;
  21990. } else if (backspaceDelete$2(editor)) {
  21991. return;
  21992. } else if (backspaceDelete$7(editor, true)) {
  21993. return;
  21994. } else {
  21995. nativeCommand(editor, 'ForwardDelete');
  21996. }
  21997. };
  21998. var setup$8 = function (editor, caret) {
  21999. editor.addCommand('delete', function () {
  22000. deleteCommand(editor, caret);
  22001. });
  22002. editor.addCommand('forwardDelete', function () {
  22003. forwardDeleteCommand(editor, caret);
  22004. });
  22005. };
  22006. var SIGNIFICANT_MOVE = 5;
  22007. var LONGPRESS_DELAY = 400;
  22008. var getTouch = function (event) {
  22009. if (event.touches === undefined || event.touches.length !== 1) {
  22010. return Optional.none();
  22011. }
  22012. return Optional.some(event.touches[0]);
  22013. };
  22014. var isFarEnough = function (touch, data) {
  22015. var distX = Math.abs(touch.clientX - data.x);
  22016. var distY = Math.abs(touch.clientY - data.y);
  22017. return distX > SIGNIFICANT_MOVE || distY > SIGNIFICANT_MOVE;
  22018. };
  22019. var setup$9 = function (editor) {
  22020. var startData = Cell(Optional.none());
  22021. var longpressFired = Cell(false);
  22022. var debounceLongpress = last$2(function (e) {
  22023. editor.fire('longpress', __assign(__assign({}, e), { type: 'longpress' }));
  22024. longpressFired.set(true);
  22025. }, LONGPRESS_DELAY);
  22026. editor.on('touchstart', function (e) {
  22027. getTouch(e).each(function (touch) {
  22028. debounceLongpress.cancel();
  22029. var data = {
  22030. x: touch.clientX,
  22031. y: touch.clientY,
  22032. target: e.target
  22033. };
  22034. debounceLongpress.throttle(e);
  22035. longpressFired.set(false);
  22036. startData.set(Optional.some(data));
  22037. });
  22038. }, true);
  22039. editor.on('touchmove', function (e) {
  22040. debounceLongpress.cancel();
  22041. getTouch(e).each(function (touch) {
  22042. startData.get().each(function (data) {
  22043. if (isFarEnough(touch, data)) {
  22044. startData.set(Optional.none());
  22045. longpressFired.set(false);
  22046. editor.fire('longpresscancel');
  22047. }
  22048. });
  22049. });
  22050. }, true);
  22051. editor.on('touchend touchcancel', function (e) {
  22052. debounceLongpress.cancel();
  22053. if (e.type === 'touchcancel') {
  22054. return;
  22055. }
  22056. startData.get().filter(function (data) {
  22057. return data.target.isEqualNode(e.target);
  22058. }).each(function () {
  22059. if (longpressFired.get()) {
  22060. e.preventDefault();
  22061. } else {
  22062. editor.fire('tap', __assign(__assign({}, e), { type: 'tap' }));
  22063. }
  22064. });
  22065. }, true);
  22066. };
  22067. var isBlockElement = function (blockElements, node) {
  22068. return blockElements.hasOwnProperty(node.nodeName);
  22069. };
  22070. var isValidTarget = function (blockElements, node) {
  22071. if (isText$1(node)) {
  22072. return true;
  22073. } else if (isElement$1(node)) {
  22074. return !isBlockElement(blockElements, node) && !isBookmarkNode$1(node);
  22075. } else {
  22076. return false;
  22077. }
  22078. };
  22079. var hasBlockParent = function (blockElements, root, node) {
  22080. return exists(parents$1(SugarElement.fromDom(node), SugarElement.fromDom(root)), function (elm) {
  22081. return isBlockElement(blockElements, elm.dom);
  22082. });
  22083. };
  22084. var shouldRemoveTextNode = function (blockElements, node) {
  22085. if (isText$1(node)) {
  22086. if (node.nodeValue.length === 0) {
  22087. return true;
  22088. } else if (/^\s+$/.test(node.nodeValue) && (!node.nextSibling || isBlockElement(blockElements, node.nextSibling))) {
  22089. return true;
  22090. }
  22091. }
  22092. return false;
  22093. };
  22094. var addRootBlocks = function (editor) {
  22095. var dom = editor.dom, selection = editor.selection;
  22096. var schema = editor.schema, blockElements = schema.getBlockElements();
  22097. var node = selection.getStart();
  22098. var rootNode = editor.getBody();
  22099. var rootBlockNode, tempNode, wrapped;
  22100. var forcedRootBlock = getForcedRootBlock(editor);
  22101. if (!node || !isElement$1(node) || !forcedRootBlock) {
  22102. return;
  22103. }
  22104. var rootNodeName = rootNode.nodeName.toLowerCase();
  22105. if (!schema.isValidChild(rootNodeName, forcedRootBlock.toLowerCase()) || hasBlockParent(blockElements, rootNode, node)) {
  22106. return;
  22107. }
  22108. var rng = selection.getRng();
  22109. var startContainer = rng.startContainer;
  22110. var startOffset = rng.startOffset;
  22111. var endContainer = rng.endContainer;
  22112. var endOffset = rng.endOffset;
  22113. var restoreSelection = hasFocus$1(editor);
  22114. node = rootNode.firstChild;
  22115. while (node) {
  22116. if (isValidTarget(blockElements, node)) {
  22117. if (shouldRemoveTextNode(blockElements, node)) {
  22118. tempNode = node;
  22119. node = node.nextSibling;
  22120. dom.remove(tempNode);
  22121. continue;
  22122. }
  22123. if (!rootBlockNode) {
  22124. rootBlockNode = dom.create(forcedRootBlock, getForcedRootBlockAttrs(editor));
  22125. node.parentNode.insertBefore(rootBlockNode, node);
  22126. wrapped = true;
  22127. }
  22128. tempNode = node;
  22129. node = node.nextSibling;
  22130. rootBlockNode.appendChild(tempNode);
  22131. } else {
  22132. rootBlockNode = null;
  22133. node = node.nextSibling;
  22134. }
  22135. }
  22136. if (wrapped && restoreSelection) {
  22137. rng.setStart(startContainer, startOffset);
  22138. rng.setEnd(endContainer, endOffset);
  22139. selection.setRng(rng);
  22140. editor.nodeChanged();
  22141. }
  22142. };
  22143. var setup$a = function (editor) {
  22144. if (getForcedRootBlock(editor)) {
  22145. editor.on('NodeChange', curry(addRootBlocks, editor));
  22146. }
  22147. };
  22148. var findBlockCaretContainer = function (editor) {
  22149. return descendant(SugarElement.fromDom(editor.getBody()), '*[data-mce-caret]').fold(constant(null), function (elm) {
  22150. return elm.dom;
  22151. });
  22152. };
  22153. var removeIeControlRect = function (editor) {
  22154. editor.selection.setRng(editor.selection.getRng());
  22155. };
  22156. var showBlockCaretContainer = function (editor, blockCaretContainer) {
  22157. if (blockCaretContainer.hasAttribute('data-mce-caret')) {
  22158. showCaretContainerBlock(blockCaretContainer);
  22159. removeIeControlRect(editor);
  22160. editor.selection.scrollIntoView(blockCaretContainer);
  22161. }
  22162. };
  22163. var handleBlockContainer = function (editor, e) {
  22164. var blockCaretContainer = findBlockCaretContainer(editor);
  22165. if (!blockCaretContainer) {
  22166. return;
  22167. }
  22168. if (e.type === 'compositionstart') {
  22169. e.preventDefault();
  22170. e.stopPropagation();
  22171. showBlockCaretContainer(editor, blockCaretContainer);
  22172. return;
  22173. }
  22174. if (hasContent(blockCaretContainer)) {
  22175. showBlockCaretContainer(editor, blockCaretContainer);
  22176. editor.undoManager.add();
  22177. }
  22178. };
  22179. var setup$b = function (editor) {
  22180. editor.on('keyup compositionstart', curry(handleBlockContainer, editor));
  22181. };
  22182. var BreakType;
  22183. (function (BreakType) {
  22184. BreakType[BreakType['Br'] = 0] = 'Br';
  22185. BreakType[BreakType['Block'] = 1] = 'Block';
  22186. BreakType[BreakType['Wrap'] = 2] = 'Wrap';
  22187. BreakType[BreakType['Eol'] = 3] = 'Eol';
  22188. }(BreakType || (BreakType = {})));
  22189. var flip = function (direction, positions) {
  22190. return direction === HDirection.Backwards ? reverse(positions) : positions;
  22191. };
  22192. var walk$3 = function (direction, caretWalker, pos) {
  22193. return direction === HDirection.Forwards ? caretWalker.next(pos) : caretWalker.prev(pos);
  22194. };
  22195. var getBreakType = function (scope, direction, currentPos, nextPos) {
  22196. if (isBr(nextPos.getNode(direction === HDirection.Forwards))) {
  22197. return BreakType.Br;
  22198. } else if (isInSameBlock(currentPos, nextPos) === false) {
  22199. return BreakType.Block;
  22200. } else {
  22201. return BreakType.Wrap;
  22202. }
  22203. };
  22204. var getPositionsUntil = function (predicate, direction, scope, start) {
  22205. var caretWalker = CaretWalker(scope);
  22206. var currentPos = start, nextPos;
  22207. var positions = [];
  22208. while (currentPos) {
  22209. nextPos = walk$3(direction, caretWalker, currentPos);
  22210. if (!nextPos) {
  22211. break;
  22212. }
  22213. if (isBr(nextPos.getNode(false))) {
  22214. if (direction === HDirection.Forwards) {
  22215. return {
  22216. positions: flip(direction, positions).concat([nextPos]),
  22217. breakType: BreakType.Br,
  22218. breakAt: Optional.some(nextPos)
  22219. };
  22220. } else {
  22221. return {
  22222. positions: flip(direction, positions),
  22223. breakType: BreakType.Br,
  22224. breakAt: Optional.some(nextPos)
  22225. };
  22226. }
  22227. }
  22228. if (!nextPos.isVisible()) {
  22229. currentPos = nextPos;
  22230. continue;
  22231. }
  22232. if (predicate(currentPos, nextPos)) {
  22233. var breakType = getBreakType(scope, direction, currentPos, nextPos);
  22234. return {
  22235. positions: flip(direction, positions),
  22236. breakType: breakType,
  22237. breakAt: Optional.some(nextPos)
  22238. };
  22239. }
  22240. positions.push(nextPos);
  22241. currentPos = nextPos;
  22242. }
  22243. return {
  22244. positions: flip(direction, positions),
  22245. breakType: BreakType.Eol,
  22246. breakAt: Optional.none()
  22247. };
  22248. };
  22249. var getAdjacentLinePositions = function (direction, getPositionsUntilBreak, scope, start) {
  22250. return getPositionsUntilBreak(scope, start).breakAt.map(function (pos) {
  22251. var positions = getPositionsUntilBreak(scope, pos).positions;
  22252. return direction === HDirection.Backwards ? positions.concat(pos) : [pos].concat(positions);
  22253. }).getOr([]);
  22254. };
  22255. var findClosestHorizontalPositionFromPoint = function (positions, x) {
  22256. return foldl(positions, function (acc, newPos) {
  22257. return acc.fold(function () {
  22258. return Optional.some(newPos);
  22259. }, function (lastPos) {
  22260. return lift2(head(lastPos.getClientRects()), head(newPos.getClientRects()), function (lastRect, newRect) {
  22261. var lastDist = Math.abs(x - lastRect.left);
  22262. var newDist = Math.abs(x - newRect.left);
  22263. return newDist <= lastDist ? newPos : lastPos;
  22264. }).or(acc);
  22265. });
  22266. }, Optional.none());
  22267. };
  22268. var findClosestHorizontalPosition = function (positions, pos) {
  22269. return head(pos.getClientRects()).bind(function (targetRect) {
  22270. return findClosestHorizontalPositionFromPoint(positions, targetRect.left);
  22271. });
  22272. };
  22273. var getPositionsUntilPreviousLine = curry(getPositionsUntil, CaretPosition.isAbove, -1);
  22274. var getPositionsUntilNextLine = curry(getPositionsUntil, CaretPosition.isBelow, 1);
  22275. var isAtFirstLine = function (scope, pos) {
  22276. return getPositionsUntilPreviousLine(scope, pos).breakAt.isNone();
  22277. };
  22278. var isAtLastLine = function (scope, pos) {
  22279. return getPositionsUntilNextLine(scope, pos).breakAt.isNone();
  22280. };
  22281. var getPositionsAbove = curry(getAdjacentLinePositions, -1, getPositionsUntilPreviousLine);
  22282. var getPositionsBelow = curry(getAdjacentLinePositions, 1, getPositionsUntilNextLine);
  22283. var getFirstLinePositions = function (scope) {
  22284. return firstPositionIn(scope).map(function (pos) {
  22285. return [pos].concat(getPositionsUntilNextLine(scope, pos).positions);
  22286. }).getOr([]);
  22287. };
  22288. var getLastLinePositions = function (scope) {
  22289. return lastPositionIn(scope).map(function (pos) {
  22290. return getPositionsUntilPreviousLine(scope, pos).positions.concat(pos);
  22291. }).getOr([]);
  22292. };
  22293. var getNodeClientRects = function (node) {
  22294. var toArrayWithNode = function (clientRects) {
  22295. return map(clientRects, function (clientRect) {
  22296. clientRect = clone$2(clientRect);
  22297. clientRect.node = node;
  22298. return clientRect;
  22299. });
  22300. };
  22301. if (isElement$1(node)) {
  22302. return toArrayWithNode(node.getClientRects());
  22303. }
  22304. if (isText$1(node)) {
  22305. var rng = node.ownerDocument.createRange();
  22306. rng.setStart(node, 0);
  22307. rng.setEnd(node, node.data.length);
  22308. return toArrayWithNode(rng.getClientRects());
  22309. }
  22310. };
  22311. var getClientRects = function (nodes) {
  22312. return bind(nodes, getNodeClientRects);
  22313. };
  22314. var VDirection;
  22315. (function (VDirection) {
  22316. VDirection[VDirection['Up'] = -1] = 'Up';
  22317. VDirection[VDirection['Down'] = 1] = 'Down';
  22318. }(VDirection || (VDirection = {})));
  22319. var findUntil$1 = function (direction, root, predicateFn, node) {
  22320. while (node = findNode(node, direction, isEditableCaretCandidate, root)) {
  22321. if (predicateFn(node)) {
  22322. return;
  22323. }
  22324. }
  22325. };
  22326. var walkUntil = function (direction, isAboveFn, isBeflowFn, root, predicateFn, caretPosition) {
  22327. var line = 0;
  22328. var result = [];
  22329. var add = function (node) {
  22330. var i, clientRect, clientRects;
  22331. clientRects = getClientRects([node]);
  22332. if (direction === -1) {
  22333. clientRects = clientRects.reverse();
  22334. }
  22335. for (i = 0; i < clientRects.length; i++) {
  22336. clientRect = clientRects[i];
  22337. if (isBeflowFn(clientRect, targetClientRect)) {
  22338. continue;
  22339. }
  22340. if (result.length > 0 && isAboveFn(clientRect, last$1(result))) {
  22341. line++;
  22342. }
  22343. clientRect.line = line;
  22344. if (predicateFn(clientRect)) {
  22345. return true;
  22346. }
  22347. result.push(clientRect);
  22348. }
  22349. };
  22350. var targetClientRect = last$1(caretPosition.getClientRects());
  22351. if (!targetClientRect) {
  22352. return result;
  22353. }
  22354. var node = caretPosition.getNode();
  22355. add(node);
  22356. findUntil$1(direction, root, add, node);
  22357. return result;
  22358. };
  22359. var aboveLineNumber = function (lineNumber, clientRect) {
  22360. return clientRect.line > lineNumber;
  22361. };
  22362. var isLineNumber = function (lineNumber, clientRect) {
  22363. return clientRect.line === lineNumber;
  22364. };
  22365. var upUntil = curry(walkUntil, VDirection.Up, isAbove, isBelow);
  22366. var downUntil = curry(walkUntil, VDirection.Down, isBelow, isAbove);
  22367. var positionsUntil = function (direction, root, predicateFn, node) {
  22368. var caretWalker = CaretWalker(root);
  22369. var walkFn, isBelowFn, isAboveFn, caretPosition;
  22370. var result = [];
  22371. var line = 0, clientRect;
  22372. var getClientRect = function (caretPosition) {
  22373. if (direction === 1) {
  22374. return last$1(caretPosition.getClientRects());
  22375. }
  22376. return last$1(caretPosition.getClientRects());
  22377. };
  22378. if (direction === 1) {
  22379. walkFn = caretWalker.next;
  22380. isBelowFn = isBelow;
  22381. isAboveFn = isAbove;
  22382. caretPosition = CaretPosition$1.after(node);
  22383. } else {
  22384. walkFn = caretWalker.prev;
  22385. isBelowFn = isAbove;
  22386. isAboveFn = isBelow;
  22387. caretPosition = CaretPosition$1.before(node);
  22388. }
  22389. var targetClientRect = getClientRect(caretPosition);
  22390. do {
  22391. if (!caretPosition.isVisible()) {
  22392. continue;
  22393. }
  22394. clientRect = getClientRect(caretPosition);
  22395. if (isAboveFn(clientRect, targetClientRect)) {
  22396. continue;
  22397. }
  22398. if (result.length > 0 && isBelowFn(clientRect, last$1(result))) {
  22399. line++;
  22400. }
  22401. clientRect = clone$2(clientRect);
  22402. clientRect.position = caretPosition;
  22403. clientRect.line = line;
  22404. if (predicateFn(clientRect)) {
  22405. return result;
  22406. }
  22407. result.push(clientRect);
  22408. } while (caretPosition = walkFn(caretPosition));
  22409. return result;
  22410. };
  22411. var isAboveLine = function (lineNumber) {
  22412. return function (clientRect) {
  22413. return aboveLineNumber(lineNumber, clientRect);
  22414. };
  22415. };
  22416. var isLine = function (lineNumber) {
  22417. return function (clientRect) {
  22418. return isLineNumber(lineNumber, clientRect);
  22419. };
  22420. };
  22421. var isContentEditableFalse$8 = isContentEditableFalse;
  22422. var findNode$1 = findNode;
  22423. var distanceToRectLeft = function (clientRect, clientX) {
  22424. return Math.abs(clientRect.left - clientX);
  22425. };
  22426. var distanceToRectRight = function (clientRect, clientX) {
  22427. return Math.abs(clientRect.right - clientX);
  22428. };
  22429. var isInsideX = function (clientX, clientRect) {
  22430. return clientX >= clientRect.left && clientX <= clientRect.right;
  22431. };
  22432. var isInsideY = function (clientY, clientRect) {
  22433. return clientY >= clientRect.top && clientY <= clientRect.bottom;
  22434. };
  22435. var findClosestClientRect = function (clientRects, clientX) {
  22436. return reduce(clientRects, function (oldClientRect, clientRect) {
  22437. var oldDistance = Math.min(distanceToRectLeft(oldClientRect, clientX), distanceToRectRight(oldClientRect, clientX));
  22438. var newDistance = Math.min(distanceToRectLeft(clientRect, clientX), distanceToRectRight(clientRect, clientX));
  22439. if (isInsideX(clientX, clientRect)) {
  22440. return clientRect;
  22441. }
  22442. if (isInsideX(clientX, oldClientRect)) {
  22443. return oldClientRect;
  22444. }
  22445. if (newDistance === oldDistance && isContentEditableFalse$8(clientRect.node)) {
  22446. return clientRect;
  22447. }
  22448. if (newDistance < oldDistance) {
  22449. return clientRect;
  22450. }
  22451. return oldClientRect;
  22452. });
  22453. };
  22454. var walkUntil$1 = function (direction, root, predicateFn, startNode, includeChildren) {
  22455. var node = findNode$1(startNode, direction, isEditableCaretCandidate, root, !includeChildren);
  22456. do {
  22457. if (!node || predicateFn(node)) {
  22458. return;
  22459. }
  22460. } while (node = findNode$1(node, direction, isEditableCaretCandidate, root));
  22461. };
  22462. var findLineNodeRects = function (root, targetNodeRect, includeChildren) {
  22463. if (includeChildren === void 0) {
  22464. includeChildren = true;
  22465. }
  22466. var clientRects = [];
  22467. var collect = function (checkPosFn, node) {
  22468. var lineRects = filter(getClientRects([node]), function (clientRect) {
  22469. return !checkPosFn(clientRect, targetNodeRect);
  22470. });
  22471. clientRects = clientRects.concat(lineRects);
  22472. return lineRects.length === 0;
  22473. };
  22474. clientRects.push(targetNodeRect);
  22475. walkUntil$1(VDirection.Up, root, curry(collect, isAbove), targetNodeRect.node, includeChildren);
  22476. walkUntil$1(VDirection.Down, root, curry(collect, isBelow), targetNodeRect.node, includeChildren);
  22477. return clientRects;
  22478. };
  22479. var getFakeCaretTargets = function (root) {
  22480. return filter(from$1(root.getElementsByTagName('*')), isFakeCaretTarget);
  22481. };
  22482. var caretInfo = function (clientRect, clientX) {
  22483. return {
  22484. node: clientRect.node,
  22485. before: distanceToRectLeft(clientRect, clientX) < distanceToRectRight(clientRect, clientX)
  22486. };
  22487. };
  22488. var closestFakeCaret = function (root, clientX, clientY) {
  22489. var fakeTargetNodeRects = getClientRects(getFakeCaretTargets(root));
  22490. var targetNodeRects = filter(fakeTargetNodeRects, curry(isInsideY, clientY));
  22491. var closestNodeRect = findClosestClientRect(targetNodeRects, clientX);
  22492. if (closestNodeRect) {
  22493. var includeChildren = !isTable(closestNodeRect.node) && !isMedia(closestNodeRect.node);
  22494. closestNodeRect = findClosestClientRect(findLineNodeRects(root, closestNodeRect, includeChildren), clientX);
  22495. if (closestNodeRect && isFakeCaretTarget(closestNodeRect.node)) {
  22496. return caretInfo(closestNodeRect, clientX);
  22497. }
  22498. }
  22499. return null;
  22500. };
  22501. var moveToRange = function (editor, rng) {
  22502. editor.selection.setRng(rng);
  22503. scrollRangeIntoView(editor, editor.selection.getRng());
  22504. };
  22505. var renderRangeCaretOpt = function (editor, range, scrollIntoView) {
  22506. return Optional.some(renderRangeCaret(editor, range, scrollIntoView));
  22507. };
  22508. var moveHorizontally = function (editor, direction, range, isBefore, isAfter, isElement) {
  22509. var forwards = direction === HDirection.Forwards;
  22510. var caretWalker = CaretWalker(editor.getBody());
  22511. var getNextPosFn = curry(getVisualCaretPosition, forwards ? caretWalker.next : caretWalker.prev);
  22512. var isBeforeFn = forwards ? isBefore : isAfter;
  22513. if (!range.collapsed) {
  22514. var node = getSelectedNode(range);
  22515. if (isElement(node)) {
  22516. return showCaret(direction, editor, node, direction === HDirection.Backwards, false);
  22517. }
  22518. }
  22519. var caretPosition = getNormalizedRangeEndPoint(direction, editor.getBody(), range);
  22520. if (isBeforeFn(caretPosition)) {
  22521. return selectNode(editor, caretPosition.getNode(!forwards));
  22522. }
  22523. var nextCaretPosition = normalizePosition(forwards, getNextPosFn(caretPosition));
  22524. var rangeIsInContainerBlock = isRangeInCaretContainerBlock(range);
  22525. if (!nextCaretPosition) {
  22526. return rangeIsInContainerBlock ? Optional.some(range) : Optional.none();
  22527. }
  22528. if (isBeforeFn(nextCaretPosition)) {
  22529. return showCaret(direction, editor, nextCaretPosition.getNode(!forwards), forwards, false);
  22530. }
  22531. var peekCaretPosition = getNextPosFn(nextCaretPosition);
  22532. if (peekCaretPosition && isBeforeFn(peekCaretPosition)) {
  22533. if (isMoveInsideSameBlock(nextCaretPosition, peekCaretPosition)) {
  22534. return showCaret(direction, editor, peekCaretPosition.getNode(!forwards), forwards, false);
  22535. }
  22536. }
  22537. if (rangeIsInContainerBlock) {
  22538. return renderRangeCaretOpt(editor, nextCaretPosition.toRange(), false);
  22539. }
  22540. return Optional.none();
  22541. };
  22542. var moveVertically = function (editor, direction, range, isBefore, isAfter, isElement) {
  22543. var caretPosition = getNormalizedRangeEndPoint(direction, editor.getBody(), range);
  22544. var caretClientRect = last$1(caretPosition.getClientRects());
  22545. var forwards = direction === VDirection.Down;
  22546. if (!caretClientRect) {
  22547. return Optional.none();
  22548. }
  22549. var walkerFn = forwards ? downUntil : upUntil;
  22550. var linePositions = walkerFn(editor.getBody(), isAboveLine(1), caretPosition);
  22551. var nextLinePositions = filter(linePositions, isLine(1));
  22552. var clientX = caretClientRect.left;
  22553. var nextLineRect = findClosestClientRect(nextLinePositions, clientX);
  22554. if (nextLineRect && isElement(nextLineRect.node)) {
  22555. var dist1 = Math.abs(clientX - nextLineRect.left);
  22556. var dist2 = Math.abs(clientX - nextLineRect.right);
  22557. return showCaret(direction, editor, nextLineRect.node, dist1 < dist2, false);
  22558. }
  22559. var currentNode;
  22560. if (isBefore(caretPosition)) {
  22561. currentNode = caretPosition.getNode();
  22562. } else if (isAfter(caretPosition)) {
  22563. currentNode = caretPosition.getNode(true);
  22564. } else {
  22565. currentNode = getSelectedNode(range);
  22566. }
  22567. if (currentNode) {
  22568. var caretPositions = positionsUntil(direction, editor.getBody(), isAboveLine(1), currentNode);
  22569. var closestNextLineRect = findClosestClientRect(filter(caretPositions, isLine(1)), clientX);
  22570. if (closestNextLineRect) {
  22571. return renderRangeCaretOpt(editor, closestNextLineRect.position.toRange(), false);
  22572. }
  22573. closestNextLineRect = last$1(filter(caretPositions, isLine(0)));
  22574. if (closestNextLineRect) {
  22575. return renderRangeCaretOpt(editor, closestNextLineRect.position.toRange(), false);
  22576. }
  22577. }
  22578. if (nextLinePositions.length === 0) {
  22579. return getLineEndPoint(editor, forwards).filter(forwards ? isAfter : isBefore).map(function (pos) {
  22580. return renderRangeCaret(editor, pos.toRange(), false);
  22581. });
  22582. }
  22583. return Optional.none();
  22584. };
  22585. var getLineEndPoint = function (editor, forward) {
  22586. var rng = editor.selection.getRng();
  22587. var body = editor.getBody();
  22588. if (forward) {
  22589. var from = CaretPosition$1.fromRangeEnd(rng);
  22590. var result = getPositionsUntilNextLine(body, from);
  22591. return last(result.positions);
  22592. } else {
  22593. var from = CaretPosition$1.fromRangeStart(rng);
  22594. var result = getPositionsUntilPreviousLine(body, from);
  22595. return head(result.positions);
  22596. }
  22597. };
  22598. var moveToLineEndPoint = function (editor, forward, isElementPosition) {
  22599. return getLineEndPoint(editor, forward).filter(isElementPosition).exists(function (pos) {
  22600. editor.selection.setRng(pos.toRange());
  22601. return true;
  22602. });
  22603. };
  22604. var isContentEditableFalse$9 = isContentEditableFalse;
  22605. var moveToCeFalseHorizontally = function (direction, editor, range) {
  22606. return moveHorizontally(editor, direction, range, isBeforeContentEditableFalse, isAfterContentEditableFalse, isContentEditableFalse$9);
  22607. };
  22608. var moveToCeFalseVertically = function (direction, editor, range) {
  22609. var isBefore = function (caretPosition) {
  22610. return isBeforeContentEditableFalse(caretPosition) || isBeforeTable(caretPosition);
  22611. };
  22612. var isAfter = function (caretPosition) {
  22613. return isAfterContentEditableFalse(caretPosition) || isAfterTable(caretPosition);
  22614. };
  22615. return moveVertically(editor, direction, range, isBefore, isAfter, isContentEditableFalse$9);
  22616. };
  22617. var createTextBlock = function (editor) {
  22618. var textBlock = editor.dom.create(getForcedRootBlock(editor));
  22619. if (!Env.ie || Env.ie >= 11) {
  22620. textBlock.innerHTML = '<br data-mce-bogus="1">';
  22621. }
  22622. return textBlock;
  22623. };
  22624. var exitPreBlock = function (editor, direction, range) {
  22625. var caretWalker = CaretWalker(editor.getBody());
  22626. var getVisualCaretPosition$1 = curry(getVisualCaretPosition, direction === 1 ? caretWalker.next : caretWalker.prev);
  22627. if (range.collapsed && hasForcedRootBlock(editor)) {
  22628. var pre = editor.dom.getParent(range.startContainer, 'PRE');
  22629. if (!pre) {
  22630. return;
  22631. }
  22632. var caretPos = getVisualCaretPosition$1(CaretPosition$1.fromRangeStart(range));
  22633. if (!caretPos) {
  22634. var newBlock = createTextBlock(editor);
  22635. if (direction === 1) {
  22636. editor.$(pre).after(newBlock);
  22637. } else {
  22638. editor.$(pre).before(newBlock);
  22639. }
  22640. editor.selection.select(newBlock, true);
  22641. editor.selection.collapse();
  22642. }
  22643. }
  22644. };
  22645. var getHorizontalRange = function (editor, forward) {
  22646. var direction = forward ? HDirection.Forwards : HDirection.Backwards;
  22647. var range = editor.selection.getRng();
  22648. return moveToCeFalseHorizontally(direction, editor, range).orThunk(function () {
  22649. exitPreBlock(editor, direction, range);
  22650. return Optional.none();
  22651. });
  22652. };
  22653. var getVerticalRange = function (editor, down) {
  22654. var direction = down ? 1 : -1;
  22655. var range = editor.selection.getRng();
  22656. return moveToCeFalseVertically(direction, editor, range).orThunk(function () {
  22657. exitPreBlock(editor, direction, range);
  22658. return Optional.none();
  22659. });
  22660. };
  22661. var moveH = function (editor, forward) {
  22662. return getHorizontalRange(editor, forward).exists(function (newRange) {
  22663. moveToRange(editor, newRange);
  22664. return true;
  22665. });
  22666. };
  22667. var moveV = function (editor, down) {
  22668. return getVerticalRange(editor, down).exists(function (newRange) {
  22669. moveToRange(editor, newRange);
  22670. return true;
  22671. });
  22672. };
  22673. var moveToLineEndPoint$1 = function (editor, forward) {
  22674. var isCefPosition = forward ? isAfterContentEditableFalse : isBeforeContentEditableFalse;
  22675. return moveToLineEndPoint(editor, forward, isCefPosition);
  22676. };
  22677. var isTarget = function (node) {
  22678. return contains(['figcaption'], name(node));
  22679. };
  22680. var rangeBefore = function (target) {
  22681. var rng = document.createRange();
  22682. rng.setStartBefore(target.dom);
  22683. rng.setEndBefore(target.dom);
  22684. return rng;
  22685. };
  22686. var insertElement = function (root, elm, forward) {
  22687. if (forward) {
  22688. append(root, elm);
  22689. } else {
  22690. prepend(root, elm);
  22691. }
  22692. };
  22693. var insertBr = function (root, forward) {
  22694. var br = SugarElement.fromTag('br');
  22695. insertElement(root, br, forward);
  22696. return rangeBefore(br);
  22697. };
  22698. var insertBlock$1 = function (root, forward, blockName, attrs) {
  22699. var block = SugarElement.fromTag(blockName);
  22700. var br = SugarElement.fromTag('br');
  22701. setAll(block, attrs);
  22702. append(block, br);
  22703. insertElement(root, block, forward);
  22704. return rangeBefore(br);
  22705. };
  22706. var insertEmptyLine = function (root, rootBlockName, attrs, forward) {
  22707. if (rootBlockName === '') {
  22708. return insertBr(root, forward);
  22709. } else {
  22710. return insertBlock$1(root, forward, rootBlockName, attrs);
  22711. }
  22712. };
  22713. var getClosestTargetBlock = function (pos, root) {
  22714. var isRoot = curry(eq$2, root);
  22715. return closest(SugarElement.fromDom(pos.container()), isBlock, isRoot).filter(isTarget);
  22716. };
  22717. var isAtFirstOrLastLine = function (root, forward, pos) {
  22718. return forward ? isAtLastLine(root.dom, pos) : isAtFirstLine(root.dom, pos);
  22719. };
  22720. var moveCaretToNewEmptyLine = function (editor, forward) {
  22721. var root = SugarElement.fromDom(editor.getBody());
  22722. var pos = CaretPosition$1.fromRangeStart(editor.selection.getRng());
  22723. var rootBlock = getForcedRootBlock(editor);
  22724. var rootBlockAttrs = getForcedRootBlockAttrs(editor);
  22725. return getClosestTargetBlock(pos, root).exists(function () {
  22726. if (isAtFirstOrLastLine(root, forward, pos)) {
  22727. var rng = insertEmptyLine(root, rootBlock, rootBlockAttrs, forward);
  22728. editor.selection.setRng(rng);
  22729. return true;
  22730. } else {
  22731. return false;
  22732. }
  22733. });
  22734. };
  22735. var moveV$1 = function (editor, forward) {
  22736. if (editor.selection.isCollapsed()) {
  22737. return moveCaretToNewEmptyLine(editor, forward);
  22738. } else {
  22739. return false;
  22740. }
  22741. };
  22742. var defaultPatterns = function (patterns) {
  22743. return map(patterns, function (pattern) {
  22744. return __assign({
  22745. shiftKey: false,
  22746. altKey: false,
  22747. ctrlKey: false,
  22748. metaKey: false,
  22749. keyCode: 0,
  22750. action: noop
  22751. }, pattern);
  22752. });
  22753. };
  22754. var matchesEvent = function (pattern, evt) {
  22755. return evt.keyCode === pattern.keyCode && evt.shiftKey === pattern.shiftKey && evt.altKey === pattern.altKey && evt.ctrlKey === pattern.ctrlKey && evt.metaKey === pattern.metaKey;
  22756. };
  22757. var match$1 = function (patterns, evt) {
  22758. return bind(defaultPatterns(patterns), function (pattern) {
  22759. return matchesEvent(pattern, evt) ? [pattern] : [];
  22760. });
  22761. };
  22762. var action = function (f) {
  22763. var x = [];
  22764. for (var _i = 1; _i < arguments.length; _i++) {
  22765. x[_i - 1] = arguments[_i];
  22766. }
  22767. return function () {
  22768. return f.apply(null, x);
  22769. };
  22770. };
  22771. var execute = function (patterns, evt) {
  22772. return find(match$1(patterns, evt), function (pattern) {
  22773. return pattern.action();
  22774. });
  22775. };
  22776. var moveH$1 = function (editor, forward) {
  22777. var direction = forward ? HDirection.Forwards : HDirection.Backwards;
  22778. var range = editor.selection.getRng();
  22779. return moveHorizontally(editor, direction, range, isBeforeMedia, isAfterMedia, isMedia).exists(function (newRange) {
  22780. moveToRange(editor, newRange);
  22781. return true;
  22782. });
  22783. };
  22784. var moveV$2 = function (editor, down) {
  22785. var direction = down ? 1 : -1;
  22786. var range = editor.selection.getRng();
  22787. return moveVertically(editor, direction, range, isBeforeMedia, isAfterMedia, isMedia).exists(function (newRange) {
  22788. moveToRange(editor, newRange);
  22789. return true;
  22790. });
  22791. };
  22792. var moveToLineEndPoint$2 = function (editor, forward) {
  22793. var isNearMedia = forward ? isAfterMedia : isBeforeMedia;
  22794. return moveToLineEndPoint(editor, forward, isNearMedia);
  22795. };
  22796. var deflate = function (rect, delta) {
  22797. return {
  22798. left: rect.left - delta,
  22799. top: rect.top - delta,
  22800. right: rect.right + delta * 2,
  22801. bottom: rect.bottom + delta * 2,
  22802. width: rect.width + delta,
  22803. height: rect.height + delta
  22804. };
  22805. };
  22806. var getCorners = function (getYAxisValue, tds) {
  22807. return bind(tds, function (td) {
  22808. var rect = deflate(clone$2(td.getBoundingClientRect()), -1);
  22809. return [
  22810. {
  22811. x: rect.left,
  22812. y: getYAxisValue(rect),
  22813. cell: td
  22814. },
  22815. {
  22816. x: rect.right,
  22817. y: getYAxisValue(rect),
  22818. cell: td
  22819. }
  22820. ];
  22821. });
  22822. };
  22823. var findClosestCorner = function (corners, x, y) {
  22824. return foldl(corners, function (acc, newCorner) {
  22825. return acc.fold(function () {
  22826. return Optional.some(newCorner);
  22827. }, function (oldCorner) {
  22828. var oldDist = Math.sqrt(Math.abs(oldCorner.x - x) + Math.abs(oldCorner.y - y));
  22829. var newDist = Math.sqrt(Math.abs(newCorner.x - x) + Math.abs(newCorner.y - y));
  22830. return Optional.some(newDist < oldDist ? newCorner : oldCorner);
  22831. });
  22832. }, Optional.none());
  22833. };
  22834. var getClosestCell$1 = function (getYAxisValue, isTargetCorner, table, x, y) {
  22835. var cells = descendants$1(SugarElement.fromDom(table), 'td,th,caption').map(function (e) {
  22836. return e.dom;
  22837. });
  22838. var corners = filter(getCorners(getYAxisValue, cells), function (corner) {
  22839. return isTargetCorner(corner, y);
  22840. });
  22841. return findClosestCorner(corners, x, y).map(function (corner) {
  22842. return corner.cell;
  22843. });
  22844. };
  22845. var getBottomValue = function (rect) {
  22846. return rect.bottom;
  22847. };
  22848. var getTopValue = function (rect) {
  22849. return rect.top;
  22850. };
  22851. var isAbove$1 = function (corner, y) {
  22852. return corner.y < y;
  22853. };
  22854. var isBelow$1 = function (corner, y) {
  22855. return corner.y > y;
  22856. };
  22857. var getClosestCellAbove = curry(getClosestCell$1, getBottomValue, isAbove$1);
  22858. var getClosestCellBelow = curry(getClosestCell$1, getTopValue, isBelow$1);
  22859. var findClosestPositionInAboveCell = function (table, pos) {
  22860. return head(pos.getClientRects()).bind(function (rect) {
  22861. return getClosestCellAbove(table, rect.left, rect.top);
  22862. }).bind(function (cell) {
  22863. return findClosestHorizontalPosition(getLastLinePositions(cell), pos);
  22864. });
  22865. };
  22866. var findClosestPositionInBelowCell = function (table, pos) {
  22867. return last(pos.getClientRects()).bind(function (rect) {
  22868. return getClosestCellBelow(table, rect.left, rect.top);
  22869. }).bind(function (cell) {
  22870. return findClosestHorizontalPosition(getFirstLinePositions(cell), pos);
  22871. });
  22872. };
  22873. var hasNextBreak = function (getPositionsUntil, scope, lineInfo) {
  22874. return lineInfo.breakAt.exists(function (breakPos) {
  22875. return getPositionsUntil(scope, breakPos).breakAt.isSome();
  22876. });
  22877. };
  22878. var startsWithWrapBreak = function (lineInfo) {
  22879. return lineInfo.breakType === BreakType.Wrap && lineInfo.positions.length === 0;
  22880. };
  22881. var startsWithBrBreak = function (lineInfo) {
  22882. return lineInfo.breakType === BreakType.Br && lineInfo.positions.length === 1;
  22883. };
  22884. var isAtTableCellLine = function (getPositionsUntil, scope, pos) {
  22885. var lineInfo = getPositionsUntil(scope, pos);
  22886. if (startsWithWrapBreak(lineInfo) || !isBr(pos.getNode()) && startsWithBrBreak(lineInfo)) {
  22887. return !hasNextBreak(getPositionsUntil, scope, lineInfo);
  22888. } else {
  22889. return lineInfo.breakAt.isNone();
  22890. }
  22891. };
  22892. var isAtFirstTableCellLine = curry(isAtTableCellLine, getPositionsUntilPreviousLine);
  22893. var isAtLastTableCellLine = curry(isAtTableCellLine, getPositionsUntilNextLine);
  22894. var isCaretAtStartOrEndOfTable = function (forward, rng, table) {
  22895. var caretPos = CaretPosition$1.fromRangeStart(rng);
  22896. return positionIn(!forward, table).exists(function (pos) {
  22897. return pos.isEqual(caretPos);
  22898. });
  22899. };
  22900. var navigateHorizontally = function (editor, forward, table, _td) {
  22901. var rng = editor.selection.getRng();
  22902. var direction = forward ? 1 : -1;
  22903. if (isFakeCaretTableBrowser() && isCaretAtStartOrEndOfTable(forward, rng, table)) {
  22904. showCaret(direction, editor, table, !forward, false).each(function (newRng) {
  22905. moveToRange(editor, newRng);
  22906. });
  22907. return true;
  22908. }
  22909. return false;
  22910. };
  22911. var getClosestAbovePosition = function (root, table, start) {
  22912. return findClosestPositionInAboveCell(table, start).orThunk(function () {
  22913. return head(start.getClientRects()).bind(function (rect) {
  22914. return findClosestHorizontalPositionFromPoint(getPositionsAbove(root, CaretPosition$1.before(table)), rect.left);
  22915. });
  22916. }).getOr(CaretPosition$1.before(table));
  22917. };
  22918. var getClosestBelowPosition = function (root, table, start) {
  22919. return findClosestPositionInBelowCell(table, start).orThunk(function () {
  22920. return head(start.getClientRects()).bind(function (rect) {
  22921. return findClosestHorizontalPositionFromPoint(getPositionsBelow(root, CaretPosition$1.after(table)), rect.left);
  22922. });
  22923. }).getOr(CaretPosition$1.after(table));
  22924. };
  22925. var getTable = function (previous, pos) {
  22926. var node = pos.getNode(previous);
  22927. return isElement$1(node) && node.nodeName === 'TABLE' ? Optional.some(node) : Optional.none();
  22928. };
  22929. var renderBlock = function (down, editor, table, pos) {
  22930. var forcedRootBlock = getForcedRootBlock(editor);
  22931. if (forcedRootBlock) {
  22932. editor.undoManager.transact(function () {
  22933. var element = SugarElement.fromTag(forcedRootBlock);
  22934. setAll(element, getForcedRootBlockAttrs(editor));
  22935. append(element, SugarElement.fromTag('br'));
  22936. if (down) {
  22937. after(SugarElement.fromDom(table), element);
  22938. } else {
  22939. before(SugarElement.fromDom(table), element);
  22940. }
  22941. var rng = editor.dom.createRng();
  22942. rng.setStart(element.dom, 0);
  22943. rng.setEnd(element.dom, 0);
  22944. moveToRange(editor, rng);
  22945. });
  22946. } else {
  22947. moveToRange(editor, pos.toRange());
  22948. }
  22949. };
  22950. var moveCaret = function (editor, down, pos) {
  22951. var table = down ? getTable(true, pos) : getTable(false, pos);
  22952. var last = down === false;
  22953. table.fold(function () {
  22954. return moveToRange(editor, pos.toRange());
  22955. }, function (table) {
  22956. return positionIn(last, editor.getBody()).filter(function (lastPos) {
  22957. return lastPos.isEqual(pos);
  22958. }).fold(function () {
  22959. return moveToRange(editor, pos.toRange());
  22960. }, function (_) {
  22961. return renderBlock(down, editor, table, pos);
  22962. });
  22963. });
  22964. };
  22965. var navigateVertically = function (editor, down, table, td) {
  22966. var rng = editor.selection.getRng();
  22967. var pos = CaretPosition$1.fromRangeStart(rng);
  22968. var root = editor.getBody();
  22969. if (!down && isAtFirstTableCellLine(td, pos)) {
  22970. var newPos = getClosestAbovePosition(root, table, pos);
  22971. moveCaret(editor, down, newPos);
  22972. return true;
  22973. } else if (down && isAtLastTableCellLine(td, pos)) {
  22974. var newPos = getClosestBelowPosition(root, table, pos);
  22975. moveCaret(editor, down, newPos);
  22976. return true;
  22977. } else {
  22978. return false;
  22979. }
  22980. };
  22981. var move$1 = function (editor, forward, mover) {
  22982. return Optional.from(editor.dom.getParent(editor.selection.getNode(), 'td,th')).bind(function (td) {
  22983. return Optional.from(editor.dom.getParent(td, 'table')).map(function (table) {
  22984. return mover(editor, forward, table, td);
  22985. });
  22986. }).getOr(false);
  22987. };
  22988. var moveH$2 = function (editor, forward) {
  22989. return move$1(editor, forward, navigateHorizontally);
  22990. };
  22991. var moveV$3 = function (editor, forward) {
  22992. return move$1(editor, forward, navigateVertically);
  22993. };
  22994. var executeKeydownOverride = function (editor, caret, evt) {
  22995. var os = detect$3().os;
  22996. execute([
  22997. {
  22998. keyCode: VK.RIGHT,
  22999. action: action(moveH, editor, true)
  23000. },
  23001. {
  23002. keyCode: VK.LEFT,
  23003. action: action(moveH, editor, false)
  23004. },
  23005. {
  23006. keyCode: VK.UP,
  23007. action: action(moveV, editor, false)
  23008. },
  23009. {
  23010. keyCode: VK.DOWN,
  23011. action: action(moveV, editor, true)
  23012. },
  23013. {
  23014. keyCode: VK.RIGHT,
  23015. action: action(moveH$2, editor, true)
  23016. },
  23017. {
  23018. keyCode: VK.LEFT,
  23019. action: action(moveH$2, editor, false)
  23020. },
  23021. {
  23022. keyCode: VK.UP,
  23023. action: action(moveV$3, editor, false)
  23024. },
  23025. {
  23026. keyCode: VK.DOWN,
  23027. action: action(moveV$3, editor, true)
  23028. },
  23029. {
  23030. keyCode: VK.RIGHT,
  23031. action: action(moveH$1, editor, true)
  23032. },
  23033. {
  23034. keyCode: VK.LEFT,
  23035. action: action(moveH$1, editor, false)
  23036. },
  23037. {
  23038. keyCode: VK.UP,
  23039. action: action(moveV$2, editor, false)
  23040. },
  23041. {
  23042. keyCode: VK.DOWN,
  23043. action: action(moveV$2, editor, true)
  23044. },
  23045. {
  23046. keyCode: VK.RIGHT,
  23047. action: action(move, editor, caret, true)
  23048. },
  23049. {
  23050. keyCode: VK.LEFT,
  23051. action: action(move, editor, caret, false)
  23052. },
  23053. {
  23054. keyCode: VK.RIGHT,
  23055. ctrlKey: !os.isOSX(),
  23056. altKey: os.isOSX(),
  23057. action: action(moveNextWord, editor, caret)
  23058. },
  23059. {
  23060. keyCode: VK.LEFT,
  23061. ctrlKey: !os.isOSX(),
  23062. altKey: os.isOSX(),
  23063. action: action(movePrevWord, editor, caret)
  23064. },
  23065. {
  23066. keyCode: VK.UP,
  23067. action: action(moveV$1, editor, false)
  23068. },
  23069. {
  23070. keyCode: VK.DOWN,
  23071. action: action(moveV$1, editor, true)
  23072. }
  23073. ], evt).each(function (_) {
  23074. evt.preventDefault();
  23075. });
  23076. };
  23077. var setup$c = function (editor, caret) {
  23078. editor.on('keydown', function (evt) {
  23079. if (evt.isDefaultPrevented() === false) {
  23080. executeKeydownOverride(editor, caret, evt);
  23081. }
  23082. });
  23083. };
  23084. var executeKeydownOverride$1 = function (editor, caret, evt) {
  23085. execute([
  23086. {
  23087. keyCode: VK.BACKSPACE,
  23088. action: action(backspaceDelete$9, editor, false)
  23089. },
  23090. {
  23091. keyCode: VK.BACKSPACE,
  23092. action: action(backspaceDelete$4, editor, false)
  23093. },
  23094. {
  23095. keyCode: VK.DELETE,
  23096. action: action(backspaceDelete$4, editor, true)
  23097. },
  23098. {
  23099. keyCode: VK.BACKSPACE,
  23100. action: action(backspaceDelete$3, editor, false)
  23101. },
  23102. {
  23103. keyCode: VK.DELETE,
  23104. action: action(backspaceDelete$3, editor, true)
  23105. },
  23106. {
  23107. keyCode: VK.BACKSPACE,
  23108. action: action(backspaceDelete$6, editor, caret, false)
  23109. },
  23110. {
  23111. keyCode: VK.DELETE,
  23112. action: action(backspaceDelete$6, editor, caret, true)
  23113. },
  23114. {
  23115. keyCode: VK.BACKSPACE,
  23116. action: action(backspaceDelete, editor, false)
  23117. },
  23118. {
  23119. keyCode: VK.DELETE,
  23120. action: action(backspaceDelete, editor, true)
  23121. },
  23122. {
  23123. keyCode: VK.BACKSPACE,
  23124. action: action(backspaceDelete$5, editor, false)
  23125. },
  23126. {
  23127. keyCode: VK.DELETE,
  23128. action: action(backspaceDelete$5, editor, true)
  23129. },
  23130. {
  23131. keyCode: VK.BACKSPACE,
  23132. action: action(backspaceDelete$8, editor, false)
  23133. },
  23134. {
  23135. keyCode: VK.DELETE,
  23136. action: action(backspaceDelete$8, editor, true)
  23137. },
  23138. {
  23139. keyCode: VK.BACKSPACE,
  23140. action: action(backspaceDelete$2, editor, false)
  23141. },
  23142. {
  23143. keyCode: VK.DELETE,
  23144. action: action(backspaceDelete$2, editor, true)
  23145. },
  23146. {
  23147. keyCode: VK.BACKSPACE,
  23148. action: action(backspaceDelete$1, editor, false)
  23149. },
  23150. {
  23151. keyCode: VK.DELETE,
  23152. action: action(backspaceDelete$1, editor, true)
  23153. },
  23154. {
  23155. keyCode: VK.BACKSPACE,
  23156. action: action(backspaceDelete$7, editor, false)
  23157. },
  23158. {
  23159. keyCode: VK.DELETE,
  23160. action: action(backspaceDelete$7, editor, true)
  23161. }
  23162. ], evt).each(function (_) {
  23163. evt.preventDefault();
  23164. });
  23165. };
  23166. var executeKeyupOverride = function (editor, evt) {
  23167. execute([
  23168. {
  23169. keyCode: VK.BACKSPACE,
  23170. action: action(paddEmptyElement, editor)
  23171. },
  23172. {
  23173. keyCode: VK.DELETE,
  23174. action: action(paddEmptyElement, editor)
  23175. }
  23176. ], evt);
  23177. };
  23178. var setup$d = function (editor, caret) {
  23179. editor.on('keydown', function (evt) {
  23180. if (evt.isDefaultPrevented() === false) {
  23181. executeKeydownOverride$1(editor, caret, evt);
  23182. }
  23183. });
  23184. editor.on('keyup', function (evt) {
  23185. if (evt.isDefaultPrevented() === false) {
  23186. executeKeyupOverride(editor, evt);
  23187. }
  23188. });
  23189. };
  23190. var firstNonWhiteSpaceNodeSibling = function (node) {
  23191. while (node) {
  23192. if (node.nodeType === 1 || node.nodeType === 3 && node.data && /[\r\n\s]/.test(node.data)) {
  23193. return node;
  23194. }
  23195. node = node.nextSibling;
  23196. }
  23197. };
  23198. var moveToCaretPosition = function (editor, root) {
  23199. var node, lastNode = root;
  23200. var dom = editor.dom;
  23201. var moveCaretBeforeOnEnterElementsMap = editor.schema.getMoveCaretBeforeOnEnterElements();
  23202. if (!root) {
  23203. return;
  23204. }
  23205. if (/^(LI|DT|DD)$/.test(root.nodeName)) {
  23206. var firstChild = firstNonWhiteSpaceNodeSibling(root.firstChild);
  23207. if (firstChild && /^(UL|OL|DL)$/.test(firstChild.nodeName)) {
  23208. root.insertBefore(dom.doc.createTextNode(nbsp), root.firstChild);
  23209. }
  23210. }
  23211. var rng = dom.createRng();
  23212. root.normalize();
  23213. if (root.hasChildNodes()) {
  23214. var walker = new DomTreeWalker(root, root);
  23215. while (node = walker.current()) {
  23216. if (isText$1(node)) {
  23217. rng.setStart(node, 0);
  23218. rng.setEnd(node, 0);
  23219. break;
  23220. }
  23221. if (moveCaretBeforeOnEnterElementsMap[node.nodeName.toLowerCase()]) {
  23222. rng.setStartBefore(node);
  23223. rng.setEndBefore(node);
  23224. break;
  23225. }
  23226. lastNode = node;
  23227. node = walker.next();
  23228. }
  23229. if (!node) {
  23230. rng.setStart(lastNode, 0);
  23231. rng.setEnd(lastNode, 0);
  23232. }
  23233. } else {
  23234. if (isBr(root)) {
  23235. if (root.nextSibling && dom.isBlock(root.nextSibling)) {
  23236. rng.setStartBefore(root);
  23237. rng.setEndBefore(root);
  23238. } else {
  23239. rng.setStartAfter(root);
  23240. rng.setEndAfter(root);
  23241. }
  23242. } else {
  23243. rng.setStart(root, 0);
  23244. rng.setEnd(root, 0);
  23245. }
  23246. }
  23247. editor.selection.setRng(rng);
  23248. scrollRangeIntoView(editor, rng);
  23249. };
  23250. var getEditableRoot = function (dom, node) {
  23251. var root = dom.getRoot();
  23252. var parent, editableRoot;
  23253. parent = node;
  23254. while (parent !== root && dom.getContentEditable(parent) !== 'false') {
  23255. if (dom.getContentEditable(parent) === 'true') {
  23256. editableRoot = parent;
  23257. }
  23258. parent = parent.parentNode;
  23259. }
  23260. return parent !== root ? editableRoot : root;
  23261. };
  23262. var getParentBlock$2 = function (editor) {
  23263. return Optional.from(editor.dom.getParent(editor.selection.getStart(true), editor.dom.isBlock));
  23264. };
  23265. var getParentBlockName = function (editor) {
  23266. return getParentBlock$2(editor).fold(constant(''), function (parentBlock) {
  23267. return parentBlock.nodeName.toUpperCase();
  23268. });
  23269. };
  23270. var isListItemParentBlock = function (editor) {
  23271. return getParentBlock$2(editor).filter(function (elm) {
  23272. return isListItem(SugarElement.fromDom(elm));
  23273. }).isSome();
  23274. };
  23275. var hasFirstChild = function (elm, name) {
  23276. return elm.firstChild && elm.firstChild.nodeName === name;
  23277. };
  23278. var hasParent$1 = function (elm, parentName) {
  23279. return elm && elm.parentNode && elm.parentNode.nodeName === parentName;
  23280. };
  23281. var isListBlock = function (elm) {
  23282. return elm && /^(OL|UL|LI)$/.test(elm.nodeName);
  23283. };
  23284. var isNestedList = function (elm) {
  23285. return isListBlock(elm) && isListBlock(elm.parentNode);
  23286. };
  23287. var getContainerBlock = function (containerBlock) {
  23288. var containerBlockParent = containerBlock.parentNode;
  23289. if (/^(LI|DT|DD)$/.test(containerBlockParent.nodeName)) {
  23290. return containerBlockParent;
  23291. }
  23292. return containerBlock;
  23293. };
  23294. var isFirstOrLastLi = function (containerBlock, parentBlock, first) {
  23295. var node = containerBlock[first ? 'firstChild' : 'lastChild'];
  23296. while (node) {
  23297. if (isElement$1(node)) {
  23298. break;
  23299. }
  23300. node = node[first ? 'nextSibling' : 'previousSibling'];
  23301. }
  23302. return node === parentBlock;
  23303. };
  23304. var insert = function (editor, createNewBlock, containerBlock, parentBlock, newBlockName) {
  23305. var dom = editor.dom;
  23306. var rng = editor.selection.getRng();
  23307. if (containerBlock === editor.getBody()) {
  23308. return;
  23309. }
  23310. if (isNestedList(containerBlock)) {
  23311. newBlockName = 'LI';
  23312. }
  23313. var newBlock = newBlockName ? createNewBlock(newBlockName) : dom.create('BR');
  23314. if (isFirstOrLastLi(containerBlock, parentBlock, true) && isFirstOrLastLi(containerBlock, parentBlock, false)) {
  23315. if (hasParent$1(containerBlock, 'LI')) {
  23316. dom.insertAfter(newBlock, getContainerBlock(containerBlock));
  23317. } else {
  23318. dom.replace(newBlock, containerBlock);
  23319. }
  23320. } else if (isFirstOrLastLi(containerBlock, parentBlock, true)) {
  23321. if (hasParent$1(containerBlock, 'LI')) {
  23322. dom.insertAfter(newBlock, getContainerBlock(containerBlock));
  23323. newBlock.appendChild(dom.doc.createTextNode(' '));
  23324. newBlock.appendChild(containerBlock);
  23325. } else {
  23326. containerBlock.parentNode.insertBefore(newBlock, containerBlock);
  23327. }
  23328. } else if (isFirstOrLastLi(containerBlock, parentBlock, false)) {
  23329. dom.insertAfter(newBlock, getContainerBlock(containerBlock));
  23330. } else {
  23331. containerBlock = getContainerBlock(containerBlock);
  23332. var tmpRng = rng.cloneRange();
  23333. tmpRng.setStartAfter(parentBlock);
  23334. tmpRng.setEndAfter(containerBlock);
  23335. var fragment = tmpRng.extractContents();
  23336. if (newBlockName === 'LI' && hasFirstChild(fragment, 'LI')) {
  23337. newBlock = fragment.firstChild;
  23338. dom.insertAfter(fragment, containerBlock);
  23339. } else {
  23340. dom.insertAfter(fragment, containerBlock);
  23341. dom.insertAfter(newBlock, containerBlock);
  23342. }
  23343. }
  23344. dom.remove(parentBlock);
  23345. moveToCaretPosition(editor, newBlock);
  23346. };
  23347. var trimZwsp = function (fragment) {
  23348. each(descendants(SugarElement.fromDom(fragment), isText), function (text) {
  23349. var rawNode = text.dom;
  23350. rawNode.nodeValue = trim$2(rawNode.nodeValue);
  23351. });
  23352. };
  23353. var isEmptyAnchor = function (dom, elm) {
  23354. return elm && elm.nodeName === 'A' && dom.isEmpty(elm);
  23355. };
  23356. var isTableCell$5 = function (node) {
  23357. return node && /^(TD|TH|CAPTION)$/.test(node.nodeName);
  23358. };
  23359. var emptyBlock = function (elm) {
  23360. elm.innerHTML = '<br data-mce-bogus="1">';
  23361. };
  23362. var containerAndSiblingName = function (container, nodeName) {
  23363. return container.nodeName === nodeName || container.previousSibling && container.previousSibling.nodeName === nodeName;
  23364. };
  23365. var canSplitBlock = function (dom, node) {
  23366. return node && dom.isBlock(node) && !/^(TD|TH|CAPTION|FORM)$/.test(node.nodeName) && !/^(fixed|absolute)/i.test(node.style.position) && dom.getContentEditable(node) !== 'true';
  23367. };
  23368. var trimInlineElementsOnLeftSideOfBlock = function (dom, nonEmptyElementsMap, block) {
  23369. var node = block;
  23370. var firstChilds = [];
  23371. var i;
  23372. if (!node) {
  23373. return;
  23374. }
  23375. while (node = node.firstChild) {
  23376. if (dom.isBlock(node)) {
  23377. return;
  23378. }
  23379. if (isElement$1(node) && !nonEmptyElementsMap[node.nodeName.toLowerCase()]) {
  23380. firstChilds.push(node);
  23381. }
  23382. }
  23383. i = firstChilds.length;
  23384. while (i--) {
  23385. node = firstChilds[i];
  23386. if (!node.hasChildNodes() || node.firstChild === node.lastChild && node.firstChild.nodeValue === '') {
  23387. dom.remove(node);
  23388. } else {
  23389. if (isEmptyAnchor(dom, node)) {
  23390. dom.remove(node);
  23391. }
  23392. }
  23393. }
  23394. };
  23395. var normalizeZwspOffset = function (start, container, offset) {
  23396. if (isText$1(container) === false) {
  23397. return offset;
  23398. } else if (start) {
  23399. return offset === 1 && container.data.charAt(offset - 1) === ZWSP ? 0 : offset;
  23400. } else {
  23401. return offset === container.data.length - 1 && container.data.charAt(offset) === ZWSP ? container.data.length : offset;
  23402. }
  23403. };
  23404. var includeZwspInRange = function (rng) {
  23405. var newRng = rng.cloneRange();
  23406. newRng.setStart(rng.startContainer, normalizeZwspOffset(true, rng.startContainer, rng.startOffset));
  23407. newRng.setEnd(rng.endContainer, normalizeZwspOffset(false, rng.endContainer, rng.endOffset));
  23408. return newRng;
  23409. };
  23410. var trimLeadingLineBreaks = function (node) {
  23411. do {
  23412. if (isText$1(node)) {
  23413. node.nodeValue = node.nodeValue.replace(/^[\r\n]+/, '');
  23414. }
  23415. node = node.firstChild;
  23416. } while (node);
  23417. };
  23418. var getEditableRoot$1 = function (dom, node) {
  23419. var root = dom.getRoot();
  23420. var parent, editableRoot;
  23421. parent = node;
  23422. while (parent !== root && dom.getContentEditable(parent) !== 'false') {
  23423. if (dom.getContentEditable(parent) === 'true') {
  23424. editableRoot = parent;
  23425. }
  23426. parent = parent.parentNode;
  23427. }
  23428. return parent !== root ? editableRoot : root;
  23429. };
  23430. var applyAttributes = function (editor, node, forcedRootBlockAttrs) {
  23431. var dom = editor.dom;
  23432. Optional.from(forcedRootBlockAttrs.style).map(dom.parseStyle).each(function (attrStyles) {
  23433. var currentStyles = getAllRaw(SugarElement.fromDom(node));
  23434. var newStyles = __assign(__assign({}, currentStyles), attrStyles);
  23435. dom.setStyles(node, newStyles);
  23436. });
  23437. var attrClassesOpt = Optional.from(forcedRootBlockAttrs.class).map(function (attrClasses) {
  23438. return attrClasses.split(/\s+/);
  23439. });
  23440. var currentClassesOpt = Optional.from(node.className).map(function (currentClasses) {
  23441. return filter(currentClasses.split(/\s+/), function (clazz) {
  23442. return clazz !== '';
  23443. });
  23444. });
  23445. lift2(attrClassesOpt, currentClassesOpt, function (attrClasses, currentClasses) {
  23446. var filteredClasses = filter(currentClasses, function (clazz) {
  23447. return !contains(attrClasses, clazz);
  23448. });
  23449. var newClasses = __spreadArrays(attrClasses, filteredClasses);
  23450. dom.setAttrib(node, 'class', newClasses.join(' '));
  23451. });
  23452. var appliedAttrs = [
  23453. 'style',
  23454. 'class'
  23455. ];
  23456. var remainingAttrs = filter$1(forcedRootBlockAttrs, function (_, attrs) {
  23457. return !contains(appliedAttrs, attrs);
  23458. });
  23459. dom.setAttribs(node, remainingAttrs);
  23460. };
  23461. var setForcedBlockAttrs = function (editor, node) {
  23462. var forcedRootBlockName = getForcedRootBlock(editor);
  23463. if (forcedRootBlockName && forcedRootBlockName.toLowerCase() === node.tagName.toLowerCase()) {
  23464. var forcedRootBlockAttrs = getForcedRootBlockAttrs(editor);
  23465. applyAttributes(editor, node, forcedRootBlockAttrs);
  23466. }
  23467. };
  23468. var wrapSelfAndSiblingsInDefaultBlock = function (editor, newBlockName, rng, container, offset) {
  23469. var newBlock, parentBlock, startNode, node, next, rootBlockName;
  23470. var blockName = newBlockName || 'P';
  23471. var dom = editor.dom, editableRoot = getEditableRoot$1(dom, container);
  23472. parentBlock = dom.getParent(container, dom.isBlock);
  23473. if (!parentBlock || !canSplitBlock(dom, parentBlock)) {
  23474. parentBlock = parentBlock || editableRoot;
  23475. if (parentBlock === editor.getBody() || isTableCell$5(parentBlock)) {
  23476. rootBlockName = parentBlock.nodeName.toLowerCase();
  23477. } else {
  23478. rootBlockName = parentBlock.parentNode.nodeName.toLowerCase();
  23479. }
  23480. if (!parentBlock.hasChildNodes()) {
  23481. newBlock = dom.create(blockName);
  23482. setForcedBlockAttrs(editor, newBlock);
  23483. parentBlock.appendChild(newBlock);
  23484. rng.setStart(newBlock, 0);
  23485. rng.setEnd(newBlock, 0);
  23486. return newBlock;
  23487. }
  23488. node = container;
  23489. while (node.parentNode !== parentBlock) {
  23490. node = node.parentNode;
  23491. }
  23492. while (node && !dom.isBlock(node)) {
  23493. startNode = node;
  23494. node = node.previousSibling;
  23495. }
  23496. if (startNode && editor.schema.isValidChild(rootBlockName, blockName.toLowerCase())) {
  23497. newBlock = dom.create(blockName);
  23498. setForcedBlockAttrs(editor, newBlock);
  23499. startNode.parentNode.insertBefore(newBlock, startNode);
  23500. node = startNode;
  23501. while (node && !dom.isBlock(node)) {
  23502. next = node.nextSibling;
  23503. newBlock.appendChild(node);
  23504. node = next;
  23505. }
  23506. rng.setStart(container, offset);
  23507. rng.setEnd(container, offset);
  23508. }
  23509. }
  23510. return container;
  23511. };
  23512. var addBrToBlockIfNeeded = function (dom, block) {
  23513. block.normalize();
  23514. var lastChild = block.lastChild;
  23515. if (!lastChild || /^(left|right)$/gi.test(dom.getStyle(lastChild, 'float', true))) {
  23516. dom.add(block, 'br');
  23517. }
  23518. };
  23519. var insert$1 = function (editor, evt) {
  23520. var tmpRng, container, offset, parentBlock;
  23521. var newBlock, fragment, containerBlock, parentBlockName, newBlockName, isAfterLastNodeInContainer;
  23522. var dom = editor.dom;
  23523. var schema = editor.schema, nonEmptyElementsMap = schema.getNonEmptyElements();
  23524. var rng = editor.selection.getRng();
  23525. var createNewBlock = function (name) {
  23526. var node = container, block, clonedNode, caretNode;
  23527. var textInlineElements = schema.getTextInlineElements();
  23528. if (name || parentBlockName === 'TABLE' || parentBlockName === 'HR') {
  23529. block = dom.create(name || newBlockName);
  23530. } else {
  23531. block = parentBlock.cloneNode(false);
  23532. }
  23533. caretNode = block;
  23534. if (shouldKeepStyles(editor) === false) {
  23535. dom.setAttrib(block, 'style', null);
  23536. dom.setAttrib(block, 'class', null);
  23537. } else {
  23538. do {
  23539. if (textInlineElements[node.nodeName]) {
  23540. if (isCaretNode(node) || isBookmarkNode$1(node)) {
  23541. continue;
  23542. }
  23543. clonedNode = node.cloneNode(false);
  23544. dom.setAttrib(clonedNode, 'id', '');
  23545. if (block.hasChildNodes()) {
  23546. clonedNode.appendChild(block.firstChild);
  23547. block.appendChild(clonedNode);
  23548. } else {
  23549. caretNode = clonedNode;
  23550. block.appendChild(clonedNode);
  23551. }
  23552. }
  23553. } while ((node = node.parentNode) && node !== editableRoot);
  23554. }
  23555. setForcedBlockAttrs(editor, block);
  23556. emptyBlock(caretNode);
  23557. return block;
  23558. };
  23559. var isCaretAtStartOrEndOfBlock = function (start) {
  23560. var node, name;
  23561. var normalizedOffset = normalizeZwspOffset(start, container, offset);
  23562. if (isText$1(container) && (start ? normalizedOffset > 0 : normalizedOffset < container.nodeValue.length)) {
  23563. return false;
  23564. }
  23565. if (container.parentNode === parentBlock && isAfterLastNodeInContainer && !start) {
  23566. return true;
  23567. }
  23568. if (start && isElement$1(container) && container === parentBlock.firstChild) {
  23569. return true;
  23570. }
  23571. if (containerAndSiblingName(container, 'TABLE') || containerAndSiblingName(container, 'HR')) {
  23572. return isAfterLastNodeInContainer && !start || !isAfterLastNodeInContainer && start;
  23573. }
  23574. var walker = new DomTreeWalker(container, parentBlock);
  23575. if (isText$1(container)) {
  23576. if (start && normalizedOffset === 0) {
  23577. walker.prev();
  23578. } else if (!start && normalizedOffset === container.nodeValue.length) {
  23579. walker.next();
  23580. }
  23581. }
  23582. while (node = walker.current()) {
  23583. if (isElement$1(node)) {
  23584. if (!node.getAttribute('data-mce-bogus')) {
  23585. name = node.nodeName.toLowerCase();
  23586. if (nonEmptyElementsMap[name] && name !== 'br') {
  23587. return false;
  23588. }
  23589. }
  23590. } else if (isText$1(node) && !isWhitespaceText(node.nodeValue)) {
  23591. return false;
  23592. }
  23593. if (start) {
  23594. walker.prev();
  23595. } else {
  23596. walker.next();
  23597. }
  23598. }
  23599. return true;
  23600. };
  23601. var insertNewBlockAfter = function () {
  23602. if (/^(H[1-6]|PRE|FIGURE)$/.test(parentBlockName) && containerBlockName !== 'HGROUP') {
  23603. newBlock = createNewBlock(newBlockName);
  23604. } else {
  23605. newBlock = createNewBlock();
  23606. }
  23607. if (shouldEndContainerOnEmptyBlock(editor) && canSplitBlock(dom, containerBlock) && dom.isEmpty(parentBlock)) {
  23608. newBlock = dom.split(containerBlock, parentBlock);
  23609. } else {
  23610. dom.insertAfter(newBlock, parentBlock);
  23611. }
  23612. moveToCaretPosition(editor, newBlock);
  23613. };
  23614. normalize(dom, rng).each(function (normRng) {
  23615. rng.setStart(normRng.startContainer, normRng.startOffset);
  23616. rng.setEnd(normRng.endContainer, normRng.endOffset);
  23617. });
  23618. container = rng.startContainer;
  23619. offset = rng.startOffset;
  23620. newBlockName = getForcedRootBlock(editor);
  23621. var shiftKey = !!(evt && evt.shiftKey);
  23622. var ctrlKey = !!(evt && evt.ctrlKey);
  23623. if (isElement$1(container) && container.hasChildNodes()) {
  23624. isAfterLastNodeInContainer = offset > container.childNodes.length - 1;
  23625. container = container.childNodes[Math.min(offset, container.childNodes.length - 1)] || container;
  23626. if (isAfterLastNodeInContainer && isText$1(container)) {
  23627. offset = container.nodeValue.length;
  23628. } else {
  23629. offset = 0;
  23630. }
  23631. }
  23632. var editableRoot = getEditableRoot$1(dom, container);
  23633. if (!editableRoot) {
  23634. return;
  23635. }
  23636. if (newBlockName && !shiftKey || !newBlockName && shiftKey) {
  23637. container = wrapSelfAndSiblingsInDefaultBlock(editor, newBlockName, rng, container, offset);
  23638. }
  23639. parentBlock = dom.getParent(container, dom.isBlock);
  23640. containerBlock = parentBlock ? dom.getParent(parentBlock.parentNode, dom.isBlock) : null;
  23641. parentBlockName = parentBlock ? parentBlock.nodeName.toUpperCase() : '';
  23642. var containerBlockName = containerBlock ? containerBlock.nodeName.toUpperCase() : '';
  23643. if (containerBlockName === 'LI' && !ctrlKey) {
  23644. parentBlock = containerBlock;
  23645. containerBlock = containerBlock.parentNode;
  23646. parentBlockName = containerBlockName;
  23647. }
  23648. if (/^(LI|DT|DD)$/.test(parentBlockName)) {
  23649. if (dom.isEmpty(parentBlock)) {
  23650. insert(editor, createNewBlock, containerBlock, parentBlock, newBlockName);
  23651. return;
  23652. }
  23653. }
  23654. if (newBlockName && parentBlock === editor.getBody()) {
  23655. return;
  23656. }
  23657. newBlockName = newBlockName || 'P';
  23658. if (isCaretContainerBlock(parentBlock)) {
  23659. newBlock = showCaretContainerBlock(parentBlock);
  23660. if (dom.isEmpty(parentBlock)) {
  23661. emptyBlock(parentBlock);
  23662. }
  23663. setForcedBlockAttrs(editor, newBlock);
  23664. moveToCaretPosition(editor, newBlock);
  23665. } else if (isCaretAtStartOrEndOfBlock()) {
  23666. insertNewBlockAfter();
  23667. } else if (isCaretAtStartOrEndOfBlock(true)) {
  23668. newBlock = parentBlock.parentNode.insertBefore(createNewBlock(), parentBlock);
  23669. moveToCaretPosition(editor, containerAndSiblingName(parentBlock, 'HR') ? newBlock : parentBlock);
  23670. } else {
  23671. tmpRng = includeZwspInRange(rng).cloneRange();
  23672. tmpRng.setEndAfter(parentBlock);
  23673. fragment = tmpRng.extractContents();
  23674. trimZwsp(fragment);
  23675. trimLeadingLineBreaks(fragment);
  23676. newBlock = fragment.firstChild;
  23677. dom.insertAfter(fragment, parentBlock);
  23678. trimInlineElementsOnLeftSideOfBlock(dom, nonEmptyElementsMap, newBlock);
  23679. addBrToBlockIfNeeded(dom, parentBlock);
  23680. if (dom.isEmpty(parentBlock)) {
  23681. emptyBlock(parentBlock);
  23682. }
  23683. newBlock.normalize();
  23684. if (dom.isEmpty(newBlock)) {
  23685. dom.remove(newBlock);
  23686. insertNewBlockAfter();
  23687. } else {
  23688. setForcedBlockAttrs(editor, newBlock);
  23689. moveToCaretPosition(editor, newBlock);
  23690. }
  23691. }
  23692. dom.setAttrib(newBlock, 'id', '');
  23693. editor.fire('NewBlock', { newBlock: newBlock });
  23694. };
  23695. var hasRightSideContent = function (schema, container, parentBlock) {
  23696. var walker = new DomTreeWalker(container, parentBlock);
  23697. var node;
  23698. var nonEmptyElementsMap = schema.getNonEmptyElements();
  23699. while (node = walker.next()) {
  23700. if (nonEmptyElementsMap[node.nodeName.toLowerCase()] || node.length > 0) {
  23701. return true;
  23702. }
  23703. }
  23704. };
  23705. var scrollToBr = function (dom, selection, brElm) {
  23706. var marker = dom.create('span', {}, '&nbsp;');
  23707. brElm.parentNode.insertBefore(marker, brElm);
  23708. selection.scrollIntoView(marker);
  23709. dom.remove(marker);
  23710. };
  23711. var moveSelectionToBr = function (dom, selection, brElm, extraBr) {
  23712. var rng = dom.createRng();
  23713. if (!extraBr) {
  23714. rng.setStartAfter(brElm);
  23715. rng.setEndAfter(brElm);
  23716. } else {
  23717. rng.setStartBefore(brElm);
  23718. rng.setEndBefore(brElm);
  23719. }
  23720. selection.setRng(rng);
  23721. };
  23722. var insertBrAtCaret = function (editor, evt) {
  23723. var selection = editor.selection;
  23724. var dom = editor.dom;
  23725. var rng = selection.getRng();
  23726. var brElm;
  23727. var extraBr;
  23728. normalize(dom, rng).each(function (normRng) {
  23729. rng.setStart(normRng.startContainer, normRng.startOffset);
  23730. rng.setEnd(normRng.endContainer, normRng.endOffset);
  23731. });
  23732. var offset = rng.startOffset;
  23733. var container = rng.startContainer;
  23734. if (container.nodeType === 1 && container.hasChildNodes()) {
  23735. var isAfterLastNodeInContainer = offset > container.childNodes.length - 1;
  23736. container = container.childNodes[Math.min(offset, container.childNodes.length - 1)] || container;
  23737. if (isAfterLastNodeInContainer && container.nodeType === 3) {
  23738. offset = container.nodeValue.length;
  23739. } else {
  23740. offset = 0;
  23741. }
  23742. }
  23743. var parentBlock = dom.getParent(container, dom.isBlock);
  23744. var containerBlock = parentBlock ? dom.getParent(parentBlock.parentNode, dom.isBlock) : null;
  23745. var containerBlockName = containerBlock ? containerBlock.nodeName.toUpperCase() : '';
  23746. var isControlKey = !!(evt && evt.ctrlKey);
  23747. if (containerBlockName === 'LI' && !isControlKey) {
  23748. parentBlock = containerBlock;
  23749. }
  23750. if (container && container.nodeType === 3 && offset >= container.nodeValue.length) {
  23751. if (!hasRightSideContent(editor.schema, container, parentBlock)) {
  23752. brElm = dom.create('br');
  23753. rng.insertNode(brElm);
  23754. rng.setStartAfter(brElm);
  23755. rng.setEndAfter(brElm);
  23756. extraBr = true;
  23757. }
  23758. }
  23759. brElm = dom.create('br');
  23760. rangeInsertNode(dom, rng, brElm);
  23761. scrollToBr(dom, selection, brElm);
  23762. moveSelectionToBr(dom, selection, brElm, extraBr);
  23763. editor.undoManager.add();
  23764. };
  23765. var insertBrBefore = function (editor, inline) {
  23766. var br = SugarElement.fromTag('br');
  23767. before(SugarElement.fromDom(inline), br);
  23768. editor.undoManager.add();
  23769. };
  23770. var insertBrAfter = function (editor, inline) {
  23771. if (!hasBrAfter(editor.getBody(), inline)) {
  23772. after(SugarElement.fromDom(inline), SugarElement.fromTag('br'));
  23773. }
  23774. var br = SugarElement.fromTag('br');
  23775. after(SugarElement.fromDom(inline), br);
  23776. scrollToBr(editor.dom, editor.selection, br.dom);
  23777. moveSelectionToBr(editor.dom, editor.selection, br.dom, false);
  23778. editor.undoManager.add();
  23779. };
  23780. var isBeforeBr$1 = function (pos) {
  23781. return isBr(pos.getNode());
  23782. };
  23783. var hasBrAfter = function (rootNode, startNode) {
  23784. if (isBeforeBr$1(CaretPosition$1.after(startNode))) {
  23785. return true;
  23786. } else {
  23787. return nextPosition(rootNode, CaretPosition$1.after(startNode)).map(function (pos) {
  23788. return isBr(pos.getNode());
  23789. }).getOr(false);
  23790. }
  23791. };
  23792. var isAnchorLink = function (elm) {
  23793. return elm && elm.nodeName === 'A' && 'href' in elm;
  23794. };
  23795. var isInsideAnchor = function (location) {
  23796. return location.fold(never, isAnchorLink, isAnchorLink, never);
  23797. };
  23798. var readInlineAnchorLocation = function (editor) {
  23799. var isInlineTarget$1 = curry(isInlineTarget, editor);
  23800. var position = CaretPosition$1.fromRangeStart(editor.selection.getRng());
  23801. return readLocation(isInlineTarget$1, editor.getBody(), position).filter(isInsideAnchor);
  23802. };
  23803. var insertBrOutsideAnchor = function (editor, location) {
  23804. location.fold(noop, curry(insertBrBefore, editor), curry(insertBrAfter, editor), noop);
  23805. };
  23806. var insert$2 = function (editor, evt) {
  23807. var anchorLocation = readInlineAnchorLocation(editor);
  23808. if (anchorLocation.isSome()) {
  23809. anchorLocation.each(curry(insertBrOutsideAnchor, editor));
  23810. } else {
  23811. insertBrAtCaret(editor, evt);
  23812. }
  23813. };
  23814. var matchesSelector = function (editor, selector) {
  23815. return getParentBlock$2(editor).filter(function (parentBlock) {
  23816. return selector.length > 0 && is$1(SugarElement.fromDom(parentBlock), selector);
  23817. }).isSome();
  23818. };
  23819. var shouldInsertBr = function (editor) {
  23820. return matchesSelector(editor, getBrNewLineSelector(editor));
  23821. };
  23822. var shouldBlockNewLine = function (editor) {
  23823. return matchesSelector(editor, getNoNewLineSelector(editor));
  23824. };
  23825. var newLineAction = Adt.generate([
  23826. { br: [] },
  23827. { block: [] },
  23828. { none: [] }
  23829. ]);
  23830. var shouldBlockNewLine$1 = function (editor, _shiftKey) {
  23831. return shouldBlockNewLine(editor);
  23832. };
  23833. var isBrMode = function (requiredState) {
  23834. return function (editor, _shiftKey) {
  23835. var brMode = getForcedRootBlock(editor) === '';
  23836. return brMode === requiredState;
  23837. };
  23838. };
  23839. var inListBlock = function (requiredState) {
  23840. return function (editor, _shiftKey) {
  23841. return isListItemParentBlock(editor) === requiredState;
  23842. };
  23843. };
  23844. var inBlock = function (blockName, requiredState) {
  23845. return function (editor, _shiftKey) {
  23846. var state = getParentBlockName(editor) === blockName.toUpperCase();
  23847. return state === requiredState;
  23848. };
  23849. };
  23850. var inPreBlock = function (requiredState) {
  23851. return inBlock('pre', requiredState);
  23852. };
  23853. var inSummaryBlock = function () {
  23854. return inBlock('summary', true);
  23855. };
  23856. var shouldPutBrInPre$1 = function (requiredState) {
  23857. return function (editor, _shiftKey) {
  23858. return shouldPutBrInPre(editor) === requiredState;
  23859. };
  23860. };
  23861. var inBrContext = function (editor, _shiftKey) {
  23862. return shouldInsertBr(editor);
  23863. };
  23864. var hasShiftKey = function (_editor, shiftKey) {
  23865. return shiftKey;
  23866. };
  23867. var canInsertIntoEditableRoot = function (editor) {
  23868. var forcedRootBlock = getForcedRootBlock(editor);
  23869. var rootEditable = getEditableRoot(editor.dom, editor.selection.getStart());
  23870. return rootEditable && editor.schema.isValidChild(rootEditable.nodeName, forcedRootBlock ? forcedRootBlock : 'P');
  23871. };
  23872. var match$2 = function (predicates, action) {
  23873. return function (editor, shiftKey) {
  23874. var isMatch = foldl(predicates, function (res, p) {
  23875. return res && p(editor, shiftKey);
  23876. }, true);
  23877. return isMatch ? Optional.some(action) : Optional.none();
  23878. };
  23879. };
  23880. var getAction$1 = function (editor, evt) {
  23881. return evaluateUntil([
  23882. match$2([shouldBlockNewLine$1], newLineAction.none()),
  23883. match$2([inSummaryBlock()], newLineAction.br()),
  23884. match$2([
  23885. inPreBlock(true),
  23886. shouldPutBrInPre$1(false),
  23887. hasShiftKey
  23888. ], newLineAction.br()),
  23889. match$2([
  23890. inPreBlock(true),
  23891. shouldPutBrInPre$1(false)
  23892. ], newLineAction.block()),
  23893. match$2([
  23894. inPreBlock(true),
  23895. shouldPutBrInPre$1(true),
  23896. hasShiftKey
  23897. ], newLineAction.block()),
  23898. match$2([
  23899. inPreBlock(true),
  23900. shouldPutBrInPre$1(true)
  23901. ], newLineAction.br()),
  23902. match$2([
  23903. inListBlock(true),
  23904. hasShiftKey
  23905. ], newLineAction.br()),
  23906. match$2([inListBlock(true)], newLineAction.block()),
  23907. match$2([
  23908. isBrMode(true),
  23909. hasShiftKey,
  23910. canInsertIntoEditableRoot
  23911. ], newLineAction.block()),
  23912. match$2([isBrMode(true)], newLineAction.br()),
  23913. match$2([inBrContext], newLineAction.br()),
  23914. match$2([
  23915. isBrMode(false),
  23916. hasShiftKey
  23917. ], newLineAction.br()),
  23918. match$2([canInsertIntoEditableRoot], newLineAction.block())
  23919. ], [
  23920. editor,
  23921. !!(evt && evt.shiftKey)
  23922. ]).getOr(newLineAction.none());
  23923. };
  23924. var insert$3 = function (editor, evt) {
  23925. getAction$1(editor, evt).fold(function () {
  23926. insert$2(editor, evt);
  23927. }, function () {
  23928. insert$1(editor, evt);
  23929. }, noop);
  23930. };
  23931. var handleEnterKeyEvent = function (editor, event) {
  23932. if (event.isDefaultPrevented()) {
  23933. return;
  23934. }
  23935. event.preventDefault();
  23936. endTypingLevelIgnoreLocks(editor.undoManager);
  23937. editor.undoManager.transact(function () {
  23938. if (editor.selection.isCollapsed() === false) {
  23939. editor.execCommand('Delete');
  23940. }
  23941. insert$3(editor, event);
  23942. });
  23943. };
  23944. var setup$e = function (editor) {
  23945. editor.on('keydown', function (event) {
  23946. if (event.keyCode === VK.ENTER) {
  23947. handleEnterKeyEvent(editor, event);
  23948. }
  23949. });
  23950. };
  23951. var executeKeydownOverride$2 = function (editor, evt) {
  23952. execute([
  23953. {
  23954. keyCode: VK.END,
  23955. action: action(moveToLineEndPoint$1, editor, true)
  23956. },
  23957. {
  23958. keyCode: VK.HOME,
  23959. action: action(moveToLineEndPoint$1, editor, false)
  23960. },
  23961. {
  23962. keyCode: VK.END,
  23963. action: action(moveToLineEndPoint$2, editor, true)
  23964. },
  23965. {
  23966. keyCode: VK.HOME,
  23967. action: action(moveToLineEndPoint$2, editor, false)
  23968. }
  23969. ], evt).each(function (_) {
  23970. evt.preventDefault();
  23971. });
  23972. };
  23973. var setup$f = function (editor) {
  23974. editor.on('keydown', function (evt) {
  23975. if (evt.isDefaultPrevented() === false) {
  23976. executeKeydownOverride$2(editor, evt);
  23977. }
  23978. });
  23979. };
  23980. var browser$4 = detect$3().browser;
  23981. var setupIeInput = function (editor) {
  23982. var keypressThrotter = first(function () {
  23983. if (!editor.composing) {
  23984. normalizeNbspsInEditor(editor);
  23985. }
  23986. }, 0);
  23987. if (browser$4.isIE()) {
  23988. editor.on('keypress', function (_e) {
  23989. keypressThrotter.throttle();
  23990. });
  23991. editor.on('remove', function (_e) {
  23992. keypressThrotter.cancel();
  23993. });
  23994. }
  23995. };
  23996. var setup$g = function (editor) {
  23997. setupIeInput(editor);
  23998. editor.on('input', function (e) {
  23999. if (e.isComposing === false) {
  24000. normalizeNbspsInEditor(editor);
  24001. }
  24002. });
  24003. };
  24004. var insertTextAtPosition = function (text, pos) {
  24005. var container = pos.container();
  24006. var offset = pos.offset();
  24007. if (isText$1(container)) {
  24008. container.insertData(offset, text);
  24009. return Optional.some(CaretPosition(container, offset + text.length));
  24010. } else {
  24011. return getElementFromPosition(pos).map(function (elm) {
  24012. var textNode = SugarElement.fromText(text);
  24013. if (pos.isAtEnd()) {
  24014. after(elm, textNode);
  24015. } else {
  24016. before(elm, textNode);
  24017. }
  24018. return CaretPosition(textNode.dom, text.length);
  24019. });
  24020. }
  24021. };
  24022. var insertNbspAtPosition = curry(insertTextAtPosition, nbsp);
  24023. var insertSpaceAtPosition = curry(insertTextAtPosition, ' ');
  24024. var locationToCaretPosition = function (root) {
  24025. return function (location) {
  24026. return location.fold(function (element) {
  24027. return prevPosition(root.dom, CaretPosition$1.before(element));
  24028. }, function (element) {
  24029. return firstPositionIn(element);
  24030. }, function (element) {
  24031. return lastPositionIn(element);
  24032. }, function (element) {
  24033. return nextPosition(root.dom, CaretPosition$1.after(element));
  24034. });
  24035. };
  24036. };
  24037. var insertInlineBoundarySpaceOrNbsp = function (root, pos) {
  24038. return function (checkPos) {
  24039. return needsToHaveNbsp(root, checkPos) ? insertNbspAtPosition(pos) : insertSpaceAtPosition(pos);
  24040. };
  24041. };
  24042. var setSelection$1 = function (editor) {
  24043. return function (pos) {
  24044. editor.selection.setRng(pos.toRange());
  24045. editor.nodeChanged();
  24046. return true;
  24047. };
  24048. };
  24049. var insertSpaceOrNbspAtSelection = function (editor) {
  24050. var pos = CaretPosition$1.fromRangeStart(editor.selection.getRng());
  24051. var root = SugarElement.fromDom(editor.getBody());
  24052. if (editor.selection.isCollapsed()) {
  24053. var isInlineTarget$1 = curry(isInlineTarget, editor);
  24054. var caretPosition = CaretPosition$1.fromRangeStart(editor.selection.getRng());
  24055. return readLocation(isInlineTarget$1, editor.getBody(), caretPosition).bind(locationToCaretPosition(root)).bind(insertInlineBoundarySpaceOrNbsp(root, pos)).exists(setSelection$1(editor));
  24056. } else {
  24057. return false;
  24058. }
  24059. };
  24060. var executeKeydownOverride$3 = function (editor, evt) {
  24061. execute([{
  24062. keyCode: VK.SPACEBAR,
  24063. action: action(insertSpaceOrNbspAtSelection, editor)
  24064. }], evt).each(function (_) {
  24065. evt.preventDefault();
  24066. });
  24067. };
  24068. var setup$h = function (editor) {
  24069. editor.on('keydown', function (evt) {
  24070. if (evt.isDefaultPrevented() === false) {
  24071. executeKeydownOverride$3(editor, evt);
  24072. }
  24073. });
  24074. };
  24075. var registerKeyboardOverrides = function (editor) {
  24076. var caret = setupSelectedState(editor);
  24077. setup$b(editor);
  24078. setup$c(editor, caret);
  24079. setup$d(editor, caret);
  24080. setup$e(editor);
  24081. setup$h(editor);
  24082. setup$g(editor);
  24083. setup$f(editor);
  24084. return caret;
  24085. };
  24086. var setup$i = function (editor) {
  24087. if (!isRtc(editor)) {
  24088. return registerKeyboardOverrides(editor);
  24089. } else {
  24090. return Cell(null);
  24091. }
  24092. };
  24093. var NodeChange = function () {
  24094. function NodeChange(editor) {
  24095. this.lastPath = [];
  24096. this.editor = editor;
  24097. var lastRng;
  24098. var self = this;
  24099. if (!('onselectionchange' in editor.getDoc())) {
  24100. editor.on('NodeChange click mouseup keyup focus', function (e) {
  24101. var nativeRng = editor.selection.getRng();
  24102. var fakeRng = {
  24103. startContainer: nativeRng.startContainer,
  24104. startOffset: nativeRng.startOffset,
  24105. endContainer: nativeRng.endContainer,
  24106. endOffset: nativeRng.endOffset
  24107. };
  24108. if (e.type === 'nodechange' || !isEq$1(fakeRng, lastRng)) {
  24109. editor.fire('SelectionChange');
  24110. }
  24111. lastRng = fakeRng;
  24112. });
  24113. }
  24114. editor.on('contextmenu', function () {
  24115. editor.fire('SelectionChange');
  24116. });
  24117. editor.on('SelectionChange', function () {
  24118. var startElm = editor.selection.getStart(true);
  24119. if (!startElm || !Env.range && editor.selection.isCollapsed()) {
  24120. return;
  24121. }
  24122. if (hasAnyRanges(editor) && !self.isSameElementPath(startElm) && editor.dom.isChildOf(startElm, editor.getBody())) {
  24123. editor.nodeChanged({ selectionChange: true });
  24124. }
  24125. });
  24126. editor.on('mouseup', function (e) {
  24127. if (!e.isDefaultPrevented() && hasAnyRanges(editor)) {
  24128. if (editor.selection.getNode().nodeName === 'IMG') {
  24129. Delay.setEditorTimeout(editor, function () {
  24130. editor.nodeChanged();
  24131. });
  24132. } else {
  24133. editor.nodeChanged();
  24134. }
  24135. }
  24136. });
  24137. }
  24138. NodeChange.prototype.nodeChanged = function (args) {
  24139. var selection = this.editor.selection;
  24140. var node, parents, root;
  24141. if (this.editor.initialized && selection && !shouldDisableNodeChange(this.editor) && !this.editor.mode.isReadOnly()) {
  24142. root = this.editor.getBody();
  24143. node = selection.getStart(true) || root;
  24144. if (node.ownerDocument !== this.editor.getDoc() || !this.editor.dom.isChildOf(node, root)) {
  24145. node = root;
  24146. }
  24147. parents = [];
  24148. this.editor.dom.getParent(node, function (node) {
  24149. if (node === root) {
  24150. return true;
  24151. }
  24152. parents.push(node);
  24153. });
  24154. args = args || {};
  24155. args.element = node;
  24156. args.parents = parents;
  24157. this.editor.fire('NodeChange', args);
  24158. }
  24159. };
  24160. NodeChange.prototype.isSameElementPath = function (startElm) {
  24161. var i;
  24162. var currentPath = this.editor.$(startElm).parentsUntil(this.editor.getBody()).add(startElm);
  24163. if (currentPath.length === this.lastPath.length) {
  24164. for (i = currentPath.length; i >= 0; i--) {
  24165. if (currentPath[i] !== this.lastPath[i]) {
  24166. break;
  24167. }
  24168. }
  24169. if (i === -1) {
  24170. this.lastPath = currentPath;
  24171. return true;
  24172. }
  24173. }
  24174. this.lastPath = currentPath;
  24175. return false;
  24176. };
  24177. return NodeChange;
  24178. }();
  24179. var preventSummaryToggle = function (editor) {
  24180. editor.on('click', function (e) {
  24181. if (editor.dom.getParent(e.target, 'details')) {
  24182. e.preventDefault();
  24183. }
  24184. });
  24185. };
  24186. var filterDetails = function (editor) {
  24187. editor.parser.addNodeFilter('details', function (elms) {
  24188. each(elms, function (details) {
  24189. details.attr('data-mce-open', details.attr('open'));
  24190. details.attr('open', 'open');
  24191. });
  24192. });
  24193. editor.serializer.addNodeFilter('details', function (elms) {
  24194. each(elms, function (details) {
  24195. var open = details.attr('data-mce-open');
  24196. details.attr('open', isString(open) ? open : null);
  24197. details.attr('data-mce-open', null);
  24198. });
  24199. });
  24200. };
  24201. var setup$j = function (editor) {
  24202. preventSummaryToggle(editor);
  24203. filterDetails(editor);
  24204. };
  24205. var isTextBlockNode = function (node) {
  24206. return isElement$1(node) && isTextBlock(SugarElement.fromDom(node));
  24207. };
  24208. var normalizeSelection$1 = function (editor) {
  24209. var rng = editor.selection.getRng();
  24210. var startPos = CaretPosition.fromRangeStart(rng);
  24211. var endPos = CaretPosition.fromRangeEnd(rng);
  24212. if (CaretPosition.isElementPosition(startPos)) {
  24213. var container = startPos.container();
  24214. if (isTextBlockNode(container)) {
  24215. firstPositionIn(container).each(function (pos) {
  24216. return rng.setStart(pos.container(), pos.offset());
  24217. });
  24218. }
  24219. }
  24220. if (CaretPosition.isElementPosition(endPos)) {
  24221. var container = startPos.container();
  24222. if (isTextBlockNode(container)) {
  24223. lastPositionIn(container).each(function (pos) {
  24224. return rng.setEnd(pos.container(), pos.offset());
  24225. });
  24226. }
  24227. }
  24228. editor.selection.setRng(normalize$2(rng));
  24229. };
  24230. var setup$k = function (editor) {
  24231. editor.on('click', function (e) {
  24232. if (e.detail >= 3) {
  24233. normalizeSelection$1(editor);
  24234. }
  24235. });
  24236. };
  24237. var value$1 = function () {
  24238. var subject = Cell(Optional.none());
  24239. var clear = function () {
  24240. return subject.set(Optional.none());
  24241. };
  24242. var set = function (s) {
  24243. return subject.set(Optional.some(s));
  24244. };
  24245. var isSet = function () {
  24246. return subject.get().isSome();
  24247. };
  24248. var on = function (f) {
  24249. return subject.get().each(f);
  24250. };
  24251. return {
  24252. clear: clear,
  24253. set: set,
  24254. isSet: isSet,
  24255. on: on
  24256. };
  24257. };
  24258. var getAbsolutePosition = function (elm) {
  24259. var clientRect = elm.getBoundingClientRect();
  24260. var doc = elm.ownerDocument;
  24261. var docElem = doc.documentElement;
  24262. var win = doc.defaultView;
  24263. return {
  24264. top: clientRect.top + win.pageYOffset - docElem.clientTop,
  24265. left: clientRect.left + win.pageXOffset - docElem.clientLeft
  24266. };
  24267. };
  24268. var getBodyPosition = function (editor) {
  24269. return editor.inline ? getAbsolutePosition(editor.getBody()) : {
  24270. left: 0,
  24271. top: 0
  24272. };
  24273. };
  24274. var getScrollPosition = function (editor) {
  24275. var body = editor.getBody();
  24276. return editor.inline ? {
  24277. left: body.scrollLeft,
  24278. top: body.scrollTop
  24279. } : {
  24280. left: 0,
  24281. top: 0
  24282. };
  24283. };
  24284. var getBodyScroll = function (editor) {
  24285. var body = editor.getBody(), docElm = editor.getDoc().documentElement;
  24286. var inlineScroll = {
  24287. left: body.scrollLeft,
  24288. top: body.scrollTop
  24289. };
  24290. var iframeScroll = {
  24291. left: body.scrollLeft || docElm.scrollLeft,
  24292. top: body.scrollTop || docElm.scrollTop
  24293. };
  24294. return editor.inline ? inlineScroll : iframeScroll;
  24295. };
  24296. var getMousePosition = function (editor, event) {
  24297. if (event.target.ownerDocument !== editor.getDoc()) {
  24298. var iframePosition = getAbsolutePosition(editor.getContentAreaContainer());
  24299. var scrollPosition = getBodyScroll(editor);
  24300. return {
  24301. left: event.pageX - iframePosition.left + scrollPosition.left,
  24302. top: event.pageY - iframePosition.top + scrollPosition.top
  24303. };
  24304. }
  24305. return {
  24306. left: event.pageX,
  24307. top: event.pageY
  24308. };
  24309. };
  24310. var calculatePosition = function (bodyPosition, scrollPosition, mousePosition) {
  24311. return {
  24312. pageX: mousePosition.left - bodyPosition.left + scrollPosition.left,
  24313. pageY: mousePosition.top - bodyPosition.top + scrollPosition.top
  24314. };
  24315. };
  24316. var calc = function (editor, event) {
  24317. return calculatePosition(getBodyPosition(editor), getScrollPosition(editor), getMousePosition(editor, event));
  24318. };
  24319. var isContentEditableFalse$a = isContentEditableFalse, isContentEditableTrue$3 = isContentEditableTrue;
  24320. var isDraggable = function (rootElm, elm) {
  24321. return isContentEditableFalse$a(elm) && elm !== rootElm;
  24322. };
  24323. var isValidDropTarget = function (editor, targetElement, dragElement) {
  24324. if (targetElement === dragElement || editor.dom.isChildOf(targetElement, dragElement)) {
  24325. return false;
  24326. }
  24327. return !isContentEditableFalse$a(targetElement);
  24328. };
  24329. var cloneElement = function (elm) {
  24330. var cloneElm = elm.cloneNode(true);
  24331. cloneElm.removeAttribute('data-mce-selected');
  24332. return cloneElm;
  24333. };
  24334. var createGhost = function (editor, elm, width, height) {
  24335. var dom = editor.dom;
  24336. var clonedElm = elm.cloneNode(true);
  24337. dom.setStyles(clonedElm, {
  24338. width: width,
  24339. height: height
  24340. });
  24341. dom.setAttrib(clonedElm, 'data-mce-selected', null);
  24342. var ghostElm = dom.create('div', {
  24343. 'class': 'mce-drag-container',
  24344. 'data-mce-bogus': 'all',
  24345. 'unselectable': 'on',
  24346. 'contenteditable': 'false'
  24347. });
  24348. dom.setStyles(ghostElm, {
  24349. position: 'absolute',
  24350. opacity: 0.5,
  24351. overflow: 'hidden',
  24352. border: 0,
  24353. padding: 0,
  24354. margin: 0,
  24355. width: width,
  24356. height: height
  24357. });
  24358. dom.setStyles(clonedElm, {
  24359. margin: 0,
  24360. boxSizing: 'border-box'
  24361. });
  24362. ghostElm.appendChild(clonedElm);
  24363. return ghostElm;
  24364. };
  24365. var appendGhostToBody = function (ghostElm, bodyElm) {
  24366. if (ghostElm.parentNode !== bodyElm) {
  24367. bodyElm.appendChild(ghostElm);
  24368. }
  24369. };
  24370. var moveGhost = function (ghostElm, position, width, height, maxX, maxY) {
  24371. var overflowX = 0, overflowY = 0;
  24372. ghostElm.style.left = position.pageX + 'px';
  24373. ghostElm.style.top = position.pageY + 'px';
  24374. if (position.pageX + width > maxX) {
  24375. overflowX = position.pageX + width - maxX;
  24376. }
  24377. if (position.pageY + height > maxY) {
  24378. overflowY = position.pageY + height - maxY;
  24379. }
  24380. ghostElm.style.width = width - overflowX + 'px';
  24381. ghostElm.style.height = height - overflowY + 'px';
  24382. };
  24383. var removeElement = function (elm) {
  24384. if (elm && elm.parentNode) {
  24385. elm.parentNode.removeChild(elm);
  24386. }
  24387. };
  24388. var isLeftMouseButtonPressed = function (e) {
  24389. return e.button === 0;
  24390. };
  24391. var applyRelPos = function (state, position) {
  24392. return {
  24393. pageX: position.pageX - state.relX,
  24394. pageY: position.pageY + 5
  24395. };
  24396. };
  24397. var start$1 = function (state, editor) {
  24398. return function (e) {
  24399. if (isLeftMouseButtonPressed(e)) {
  24400. var ceElm = find(editor.dom.getParents(e.target), or(isContentEditableFalse$a, isContentEditableTrue$3)).getOr(null);
  24401. if (isDraggable(editor.getBody(), ceElm)) {
  24402. var elmPos = editor.dom.getPos(ceElm);
  24403. var bodyElm = editor.getBody();
  24404. var docElm = editor.getDoc().documentElement;
  24405. state.set({
  24406. element: ceElm,
  24407. dragging: false,
  24408. screenX: e.screenX,
  24409. screenY: e.screenY,
  24410. maxX: (editor.inline ? bodyElm.scrollWidth : docElm.offsetWidth) - 2,
  24411. maxY: (editor.inline ? bodyElm.scrollHeight : docElm.offsetHeight) - 2,
  24412. relX: e.pageX - elmPos.x,
  24413. relY: e.pageY - elmPos.y,
  24414. width: ceElm.offsetWidth,
  24415. height: ceElm.offsetHeight,
  24416. ghost: createGhost(editor, ceElm, ceElm.offsetWidth, ceElm.offsetHeight)
  24417. });
  24418. }
  24419. }
  24420. };
  24421. };
  24422. var move$2 = function (state, editor) {
  24423. var throttledPlaceCaretAt = Delay.throttle(function (clientX, clientY) {
  24424. editor._selectionOverrides.hideFakeCaret();
  24425. editor.selection.placeCaretAt(clientX, clientY);
  24426. }, 0);
  24427. return function (e) {
  24428. return state.on(function (state) {
  24429. var movement = Math.max(Math.abs(e.screenX - state.screenX), Math.abs(e.screenY - state.screenY));
  24430. if (!state.dragging && movement > 10) {
  24431. var args = editor.fire('dragstart', { target: state.element });
  24432. if (args.isDefaultPrevented()) {
  24433. return;
  24434. }
  24435. state.dragging = true;
  24436. editor.focus();
  24437. }
  24438. if (state.dragging) {
  24439. var targetPos = applyRelPos(state, calc(editor, e));
  24440. appendGhostToBody(state.ghost, editor.getBody());
  24441. moveGhost(state.ghost, targetPos, state.width, state.height, state.maxX, state.maxY);
  24442. throttledPlaceCaretAt(e.clientX, e.clientY);
  24443. }
  24444. });
  24445. };
  24446. };
  24447. var getRawTarget = function (selection) {
  24448. var rng = selection.getSel().getRangeAt(0);
  24449. var startContainer = rng.startContainer;
  24450. return startContainer.nodeType === 3 ? startContainer.parentNode : startContainer;
  24451. };
  24452. var drop = function (state, editor) {
  24453. return function (e) {
  24454. state.on(function (state) {
  24455. if (state.dragging) {
  24456. if (isValidDropTarget(editor, getRawTarget(editor.selection), state.element)) {
  24457. var targetClone_1 = cloneElement(state.element);
  24458. var args = editor.fire('drop', {
  24459. clientX: e.clientX,
  24460. clientY: e.clientY
  24461. });
  24462. if (!args.isDefaultPrevented()) {
  24463. editor.undoManager.transact(function () {
  24464. removeElement(state.element);
  24465. editor.insertContent(editor.dom.getOuterHTML(targetClone_1));
  24466. editor._selectionOverrides.hideFakeCaret();
  24467. });
  24468. }
  24469. }
  24470. }
  24471. });
  24472. removeDragState(state);
  24473. };
  24474. };
  24475. var stop = function (state, editor) {
  24476. return function () {
  24477. state.on(function (state) {
  24478. if (state.dragging) {
  24479. editor.fire('dragend');
  24480. }
  24481. });
  24482. removeDragState(state);
  24483. };
  24484. };
  24485. var removeDragState = function (state) {
  24486. state.on(function (state) {
  24487. removeElement(state.ghost);
  24488. });
  24489. state.clear();
  24490. };
  24491. var bindFakeDragEvents = function (editor) {
  24492. var state = value$1();
  24493. var pageDom = DOMUtils$1.DOM;
  24494. var rootDocument = document;
  24495. var dragStartHandler = start$1(state, editor);
  24496. var dragHandler = move$2(state, editor);
  24497. var dropHandler = drop(state, editor);
  24498. var dragEndHandler = stop(state, editor);
  24499. editor.on('mousedown', dragStartHandler);
  24500. editor.on('mousemove', dragHandler);
  24501. editor.on('mouseup', dropHandler);
  24502. pageDom.bind(rootDocument, 'mousemove', dragHandler);
  24503. pageDom.bind(rootDocument, 'mouseup', dragEndHandler);
  24504. editor.on('remove', function () {
  24505. pageDom.unbind(rootDocument, 'mousemove', dragHandler);
  24506. pageDom.unbind(rootDocument, 'mouseup', dragEndHandler);
  24507. });
  24508. };
  24509. var blockIeDrop = function (editor) {
  24510. editor.on('drop', function (e) {
  24511. var realTarget = typeof e.clientX !== 'undefined' ? editor.getDoc().elementFromPoint(e.clientX, e.clientY) : null;
  24512. if (isContentEditableFalse$a(realTarget) || editor.dom.getContentEditableParent(realTarget) === 'false') {
  24513. e.preventDefault();
  24514. }
  24515. });
  24516. };
  24517. var blockUnsupportedFileDrop = function (editor) {
  24518. var preventFileDrop = function (e) {
  24519. if (!e.defaultPrevented) {
  24520. var dataTransfer = e.dataTransfer;
  24521. if (dataTransfer && (contains(dataTransfer.types, 'Files') || dataTransfer.files.length > 0)) {
  24522. e.preventDefault();
  24523. if (e.type === 'drop') {
  24524. displayError(editor, 'Dropped file type is not supported');
  24525. }
  24526. }
  24527. }
  24528. };
  24529. var preventFileDropIfUIElement = function (e) {
  24530. if (isUIElement(editor, e.target)) {
  24531. preventFileDrop(e);
  24532. }
  24533. };
  24534. var setup = function () {
  24535. var pageDom = DOMUtils$1.DOM;
  24536. var dom = editor.dom;
  24537. var doc = document;
  24538. var editorRoot = editor.inline ? editor.getBody() : editor.getDoc();
  24539. var eventNames = [
  24540. 'drop',
  24541. 'dragover'
  24542. ];
  24543. each(eventNames, function (name) {
  24544. pageDom.bind(doc, name, preventFileDropIfUIElement);
  24545. dom.bind(editorRoot, name, preventFileDrop);
  24546. });
  24547. editor.on('remove', function () {
  24548. each(eventNames, function (name) {
  24549. pageDom.unbind(doc, name, preventFileDropIfUIElement);
  24550. dom.unbind(editorRoot, name, preventFileDrop);
  24551. });
  24552. });
  24553. };
  24554. editor.on('init', function () {
  24555. Delay.setEditorTimeout(editor, setup, 0);
  24556. });
  24557. };
  24558. var init = function (editor) {
  24559. bindFakeDragEvents(editor);
  24560. blockIeDrop(editor);
  24561. if (shouldBlockUnsupportedDrop(editor)) {
  24562. blockUnsupportedFileDrop(editor);
  24563. }
  24564. };
  24565. var setup$l = function (editor) {
  24566. var renderFocusCaret = first(function () {
  24567. if (!editor.removed && editor.getBody().contains(document.activeElement)) {
  24568. var rng = editor.selection.getRng();
  24569. if (rng.collapsed) {
  24570. var caretRange = renderRangeCaret(editor, rng, false);
  24571. editor.selection.setRng(caretRange);
  24572. }
  24573. }
  24574. }, 0);
  24575. editor.on('focus', function () {
  24576. renderFocusCaret.throttle();
  24577. });
  24578. editor.on('blur', function () {
  24579. renderFocusCaret.cancel();
  24580. });
  24581. };
  24582. var setup$m = function (editor) {
  24583. editor.on('init', function () {
  24584. editor.on('focusin', function (e) {
  24585. var target = e.target;
  24586. if (isMedia(target)) {
  24587. var ceRoot = getContentEditableRoot(editor.getBody(), target);
  24588. var node = isContentEditableFalse(ceRoot) ? ceRoot : target;
  24589. if (editor.selection.getNode() !== node) {
  24590. selectNode(editor, node).each(function (rng) {
  24591. return editor.selection.setRng(rng);
  24592. });
  24593. }
  24594. }
  24595. });
  24596. });
  24597. };
  24598. var isContentEditableTrue$4 = isContentEditableTrue;
  24599. var isContentEditableFalse$b = isContentEditableFalse;
  24600. var getContentEditableRoot$1 = function (editor, node) {
  24601. return getContentEditableRoot(editor.getBody(), node);
  24602. };
  24603. var SelectionOverrides = function (editor) {
  24604. var selection = editor.selection, dom = editor.dom;
  24605. var isBlock = dom.isBlock;
  24606. var rootNode = editor.getBody();
  24607. var fakeCaret = FakeCaret(editor, rootNode, isBlock, function () {
  24608. return hasFocus$1(editor);
  24609. });
  24610. var realSelectionId = 'sel-' + dom.uniqueId();
  24611. var elementSelectionAttr = 'data-mce-selected';
  24612. var selectedElement;
  24613. var isFakeSelectionElement = function (node) {
  24614. return dom.hasClass(node, 'mce-offscreen-selection');
  24615. };
  24616. var isFakeSelectionTargetElement = function (node) {
  24617. return isContentEditableFalse$b(node) || isMedia(node);
  24618. };
  24619. var isNearFakeSelectionElement = function (pos) {
  24620. return isBeforeContentEditableFalse(pos) || isAfterContentEditableFalse(pos) || isBeforeMedia(pos) || isAfterMedia(pos);
  24621. };
  24622. var getRealSelectionElement = function () {
  24623. var container = dom.get(realSelectionId);
  24624. return container ? container.getElementsByTagName('*')[0] : container;
  24625. };
  24626. var setRange = function (range) {
  24627. if (range) {
  24628. selection.setRng(range);
  24629. }
  24630. };
  24631. var getRange = selection.getRng;
  24632. var showCaret = function (direction, node, before, scrollIntoView) {
  24633. if (scrollIntoView === void 0) {
  24634. scrollIntoView = true;
  24635. }
  24636. var e = editor.fire('ShowCaret', {
  24637. target: node,
  24638. direction: direction,
  24639. before: before
  24640. });
  24641. if (e.isDefaultPrevented()) {
  24642. return null;
  24643. }
  24644. if (scrollIntoView) {
  24645. selection.scrollIntoView(node, direction === -1);
  24646. }
  24647. return fakeCaret.show(before, node);
  24648. };
  24649. var showBlockCaretContainer = function (blockCaretContainer) {
  24650. if (blockCaretContainer.hasAttribute('data-mce-caret')) {
  24651. showCaretContainerBlock(blockCaretContainer);
  24652. setRange(getRange());
  24653. selection.scrollIntoView(blockCaretContainer);
  24654. }
  24655. };
  24656. var registerEvents = function () {
  24657. editor.on('mouseup', function (e) {
  24658. var range = getRange();
  24659. if (range.collapsed && isXYInContentArea(editor, e.clientX, e.clientY)) {
  24660. renderCaretAtRange(editor, range, false).each(setRange);
  24661. }
  24662. });
  24663. editor.on('click', function (e) {
  24664. var contentEditableRoot = getContentEditableRoot$1(editor, e.target);
  24665. if (contentEditableRoot) {
  24666. if (isContentEditableFalse$b(contentEditableRoot)) {
  24667. e.preventDefault();
  24668. editor.focus();
  24669. }
  24670. if (isContentEditableTrue$4(contentEditableRoot)) {
  24671. if (dom.isChildOf(contentEditableRoot, selection.getNode())) {
  24672. removeElementSelection();
  24673. }
  24674. }
  24675. }
  24676. });
  24677. editor.on('blur NewBlock', removeElementSelection);
  24678. editor.on('ResizeWindow FullscreenStateChanged', fakeCaret.reposition);
  24679. var hasNormalCaretPosition = function (elm) {
  24680. var caretWalker = CaretWalker(elm);
  24681. if (!elm.firstChild) {
  24682. return false;
  24683. }
  24684. var startPos = CaretPosition$1.before(elm.firstChild);
  24685. var newPos = caretWalker.next(startPos);
  24686. return newPos && !isNearFakeSelectionElement(newPos);
  24687. };
  24688. var isInSameBlock = function (node1, node2) {
  24689. var block1 = dom.getParent(node1, isBlock);
  24690. var block2 = dom.getParent(node2, isBlock);
  24691. return block1 === block2;
  24692. };
  24693. var hasBetterMouseTarget = function (targetNode, caretNode) {
  24694. var targetBlock = dom.getParent(targetNode, isBlock);
  24695. var caretBlock = dom.getParent(caretNode, isBlock);
  24696. if (targetBlock && targetNode !== caretBlock && dom.isChildOf(targetBlock, caretBlock) && isContentEditableFalse$b(getContentEditableRoot$1(editor, targetBlock)) === false) {
  24697. return true;
  24698. }
  24699. return targetBlock && !isInSameBlock(targetBlock, caretBlock) && hasNormalCaretPosition(targetBlock);
  24700. };
  24701. editor.on('tap', function (e) {
  24702. var targetElm = e.target;
  24703. var contentEditableRoot = getContentEditableRoot$1(editor, targetElm);
  24704. if (isContentEditableFalse$b(contentEditableRoot)) {
  24705. e.preventDefault();
  24706. selectNode(editor, contentEditableRoot).each(setElementSelection);
  24707. } else if (isFakeSelectionTargetElement(targetElm)) {
  24708. selectNode(editor, targetElm).each(setElementSelection);
  24709. }
  24710. }, true);
  24711. editor.on('mousedown', function (e) {
  24712. var targetElm = e.target;
  24713. if (targetElm !== rootNode && targetElm.nodeName !== 'HTML' && !dom.isChildOf(targetElm, rootNode)) {
  24714. return;
  24715. }
  24716. if (isXYInContentArea(editor, e.clientX, e.clientY) === false) {
  24717. return;
  24718. }
  24719. var contentEditableRoot = getContentEditableRoot$1(editor, targetElm);
  24720. if (contentEditableRoot) {
  24721. if (isContentEditableFalse$b(contentEditableRoot)) {
  24722. e.preventDefault();
  24723. selectNode(editor, contentEditableRoot).each(setElementSelection);
  24724. } else {
  24725. removeElementSelection();
  24726. if (!(isContentEditableTrue$4(contentEditableRoot) && e.shiftKey) && !isXYWithinRange(e.clientX, e.clientY, selection.getRng())) {
  24727. hideFakeCaret();
  24728. selection.placeCaretAt(e.clientX, e.clientY);
  24729. }
  24730. }
  24731. } else if (isFakeSelectionTargetElement(targetElm)) {
  24732. selectNode(editor, targetElm).each(setElementSelection);
  24733. } else if (isFakeCaretTarget(targetElm) === false) {
  24734. removeElementSelection();
  24735. hideFakeCaret();
  24736. var fakeCaretInfo = closestFakeCaret(rootNode, e.clientX, e.clientY);
  24737. if (fakeCaretInfo) {
  24738. if (!hasBetterMouseTarget(targetElm, fakeCaretInfo.node)) {
  24739. e.preventDefault();
  24740. var range = showCaret(1, fakeCaretInfo.node, fakeCaretInfo.before, false);
  24741. editor.getBody().focus();
  24742. setRange(range);
  24743. }
  24744. }
  24745. }
  24746. });
  24747. editor.on('keypress', function (e) {
  24748. if (VK.modifierPressed(e)) {
  24749. return;
  24750. }
  24751. if (isContentEditableFalse$b(selection.getNode())) {
  24752. e.preventDefault();
  24753. }
  24754. });
  24755. editor.on('GetSelectionRange', function (e) {
  24756. var rng = e.range;
  24757. if (selectedElement) {
  24758. if (!selectedElement.parentNode) {
  24759. selectedElement = null;
  24760. return;
  24761. }
  24762. rng = rng.cloneRange();
  24763. rng.selectNode(selectedElement);
  24764. e.range = rng;
  24765. }
  24766. });
  24767. editor.on('SetSelectionRange', function (e) {
  24768. e.range = normalizeShortEndedElementSelection(e.range);
  24769. var rng = setElementSelection(e.range, e.forward);
  24770. if (rng) {
  24771. e.range = rng;
  24772. }
  24773. });
  24774. var isPasteBin = function (node) {
  24775. return node.id === 'mcepastebin';
  24776. };
  24777. editor.on('AfterSetSelectionRange', function (e) {
  24778. var rng = e.range;
  24779. var parentNode = rng.startContainer.parentNode;
  24780. if (!isRangeInCaretContainer(rng) && !isPasteBin(parentNode)) {
  24781. hideFakeCaret();
  24782. }
  24783. if (!isFakeSelectionElement(parentNode)) {
  24784. removeElementSelection();
  24785. }
  24786. });
  24787. editor.on('copy', function (e) {
  24788. var clipboardData = e.clipboardData;
  24789. if (!e.isDefaultPrevented() && e.clipboardData && !Env.ie) {
  24790. var realSelectionElement = getRealSelectionElement();
  24791. if (realSelectionElement) {
  24792. e.preventDefault();
  24793. clipboardData.clearData();
  24794. clipboardData.setData('text/html', realSelectionElement.outerHTML);
  24795. clipboardData.setData('text/plain', realSelectionElement.outerText || realSelectionElement.innerText);
  24796. }
  24797. }
  24798. });
  24799. init(editor);
  24800. setup$l(editor);
  24801. setup$m(editor);
  24802. };
  24803. var isWithinCaretContainer = function (node) {
  24804. return isCaretContainer(node) || startsWithCaretContainer(node) || endsWithCaretContainer(node);
  24805. };
  24806. var isRangeInCaretContainer = function (rng) {
  24807. return isWithinCaretContainer(rng.startContainer) || isWithinCaretContainer(rng.endContainer);
  24808. };
  24809. var normalizeShortEndedElementSelection = function (rng) {
  24810. var shortEndedElements = editor.schema.getShortEndedElements();
  24811. var newRng = dom.createRng();
  24812. var startContainer = rng.startContainer;
  24813. var startOffset = rng.startOffset;
  24814. var endContainer = rng.endContainer;
  24815. var endOffset = rng.endOffset;
  24816. if (has(shortEndedElements, startContainer.nodeName.toLowerCase())) {
  24817. if (startOffset === 0) {
  24818. newRng.setStartBefore(startContainer);
  24819. } else {
  24820. newRng.setStartAfter(startContainer);
  24821. }
  24822. } else {
  24823. newRng.setStart(startContainer, startOffset);
  24824. }
  24825. if (has(shortEndedElements, endContainer.nodeName.toLowerCase())) {
  24826. if (endOffset === 0) {
  24827. newRng.setEndBefore(endContainer);
  24828. } else {
  24829. newRng.setEndAfter(endContainer);
  24830. }
  24831. } else {
  24832. newRng.setEnd(endContainer, endOffset);
  24833. }
  24834. return newRng;
  24835. };
  24836. var setupOffscreenSelection = function (node, targetClone, origTargetClone) {
  24837. var $ = editor.$;
  24838. var $realSelectionContainer = descendant(SugarElement.fromDom(editor.getBody()), '#' + realSelectionId).fold(function () {
  24839. return $([]);
  24840. }, function (elm) {
  24841. return $([elm.dom]);
  24842. });
  24843. if ($realSelectionContainer.length === 0) {
  24844. $realSelectionContainer = $('<div data-mce-bogus="all" class="mce-offscreen-selection"></div>').attr('id', realSelectionId);
  24845. $realSelectionContainer.appendTo(editor.getBody());
  24846. }
  24847. var newRange = dom.createRng();
  24848. if (targetClone === origTargetClone && Env.ie) {
  24849. $realSelectionContainer.empty().append('<p style="font-size: 0" data-mce-bogus="all">\xA0</p>').append(targetClone);
  24850. newRange.setStartAfter($realSelectionContainer[0].firstChild.firstChild);
  24851. newRange.setEndAfter(targetClone);
  24852. } else {
  24853. $realSelectionContainer.empty().append(nbsp).append(targetClone).append(nbsp);
  24854. newRange.setStart($realSelectionContainer[0].firstChild, 1);
  24855. newRange.setEnd($realSelectionContainer[0].lastChild, 0);
  24856. }
  24857. $realSelectionContainer.css({ top: dom.getPos(node, editor.getBody()).y });
  24858. $realSelectionContainer[0].focus();
  24859. var sel = selection.getSel();
  24860. sel.removeAllRanges();
  24861. sel.addRange(newRange);
  24862. return newRange;
  24863. };
  24864. var selectElement = function (elm) {
  24865. var targetClone = elm.cloneNode(true);
  24866. var e = editor.fire('ObjectSelected', {
  24867. target: elm,
  24868. targetClone: targetClone
  24869. });
  24870. if (e.isDefaultPrevented()) {
  24871. return null;
  24872. }
  24873. var range = setupOffscreenSelection(elm, e.targetClone, targetClone);
  24874. var nodeElm = SugarElement.fromDom(elm);
  24875. each(descendants$1(SugarElement.fromDom(editor.getBody()), '*[data-mce-selected]'), function (elm) {
  24876. if (!eq$2(nodeElm, elm)) {
  24877. remove$1(elm, elementSelectionAttr);
  24878. }
  24879. });
  24880. if (!dom.getAttrib(elm, elementSelectionAttr)) {
  24881. elm.setAttribute(elementSelectionAttr, '1');
  24882. }
  24883. selectedElement = elm;
  24884. hideFakeCaret();
  24885. return range;
  24886. };
  24887. var setElementSelection = function (range, forward) {
  24888. if (!range) {
  24889. return null;
  24890. }
  24891. if (range.collapsed) {
  24892. if (!isRangeInCaretContainer(range)) {
  24893. var dir = forward ? 1 : -1;
  24894. var caretPosition = getNormalizedRangeEndPoint(dir, rootNode, range);
  24895. var beforeNode = caretPosition.getNode(!forward);
  24896. if (isFakeCaretTarget(beforeNode)) {
  24897. return showCaret(dir, beforeNode, forward ? !caretPosition.isAtEnd() : false, false);
  24898. }
  24899. var afterNode = caretPosition.getNode(forward);
  24900. if (isFakeCaretTarget(afterNode)) {
  24901. return showCaret(dir, afterNode, forward ? false : !caretPosition.isAtEnd(), false);
  24902. }
  24903. }
  24904. return null;
  24905. }
  24906. var startContainer = range.startContainer;
  24907. var startOffset = range.startOffset;
  24908. var endOffset = range.endOffset;
  24909. if (startContainer.nodeType === 3 && startOffset === 0 && isContentEditableFalse$b(startContainer.parentNode)) {
  24910. startContainer = startContainer.parentNode;
  24911. startOffset = dom.nodeIndex(startContainer);
  24912. startContainer = startContainer.parentNode;
  24913. }
  24914. if (startContainer.nodeType !== 1) {
  24915. return null;
  24916. }
  24917. if (endOffset === startOffset + 1 && startContainer === range.endContainer) {
  24918. var node = startContainer.childNodes[startOffset];
  24919. if (isFakeSelectionTargetElement(node)) {
  24920. return selectElement(node);
  24921. }
  24922. }
  24923. return null;
  24924. };
  24925. var removeElementSelection = function () {
  24926. if (selectedElement) {
  24927. selectedElement.removeAttribute(elementSelectionAttr);
  24928. }
  24929. descendant(SugarElement.fromDom(editor.getBody()), '#' + realSelectionId).each(remove);
  24930. selectedElement = null;
  24931. };
  24932. var destroy = function () {
  24933. fakeCaret.destroy();
  24934. selectedElement = null;
  24935. };
  24936. var hideFakeCaret = function () {
  24937. fakeCaret.hide();
  24938. };
  24939. if (Env.ceFalse) {
  24940. registerEvents();
  24941. }
  24942. return {
  24943. showCaret: showCaret,
  24944. showBlockCaretContainer: showBlockCaretContainer,
  24945. hideFakeCaret: hideFakeCaret,
  24946. destroy: destroy
  24947. };
  24948. };
  24949. var Quirks = function (editor) {
  24950. var each = Tools.each;
  24951. var BACKSPACE = VK.BACKSPACE, DELETE = VK.DELETE, dom = editor.dom, selection = editor.selection, parser = editor.parser;
  24952. var isGecko = Env.gecko, isIE = Env.ie, isWebKit = Env.webkit;
  24953. var mceInternalUrlPrefix = 'data:text/mce-internal,';
  24954. var mceInternalDataType = isIE ? 'Text' : 'URL';
  24955. var setEditorCommandState = function (cmd, state) {
  24956. try {
  24957. editor.getDoc().execCommand(cmd, false, state);
  24958. } catch (ex) {
  24959. }
  24960. };
  24961. var isDefaultPrevented = function (e) {
  24962. return e.isDefaultPrevented();
  24963. };
  24964. var setMceInternalContent = function (e) {
  24965. var selectionHtml, internalContent;
  24966. if (e.dataTransfer) {
  24967. if (editor.selection.isCollapsed() && e.target.tagName === 'IMG') {
  24968. selection.select(e.target);
  24969. }
  24970. selectionHtml = editor.selection.getContent();
  24971. if (selectionHtml.length > 0) {
  24972. internalContent = mceInternalUrlPrefix + escape(editor.id) + ',' + escape(selectionHtml);
  24973. e.dataTransfer.setData(mceInternalDataType, internalContent);
  24974. }
  24975. }
  24976. };
  24977. var getMceInternalContent = function (e) {
  24978. var internalContent;
  24979. if (e.dataTransfer) {
  24980. internalContent = e.dataTransfer.getData(mceInternalDataType);
  24981. if (internalContent && internalContent.indexOf(mceInternalUrlPrefix) >= 0) {
  24982. internalContent = internalContent.substr(mceInternalUrlPrefix.length).split(',');
  24983. return {
  24984. id: unescape(internalContent[0]),
  24985. html: unescape(internalContent[1])
  24986. };
  24987. }
  24988. }
  24989. return null;
  24990. };
  24991. var insertClipboardContents = function (content, internal) {
  24992. if (editor.queryCommandSupported('mceInsertClipboardContent')) {
  24993. editor.execCommand('mceInsertClipboardContent', false, {
  24994. content: content,
  24995. internal: internal
  24996. });
  24997. } else {
  24998. editor.execCommand('mceInsertContent', false, content);
  24999. }
  25000. };
  25001. var emptyEditorWhenDeleting = function () {
  25002. var serializeRng = function (rng) {
  25003. var body = dom.create('body');
  25004. var contents = rng.cloneContents();
  25005. body.appendChild(contents);
  25006. return selection.serializer.serialize(body, { format: 'html' });
  25007. };
  25008. var allContentsSelected = function (rng) {
  25009. var selection = serializeRng(rng);
  25010. var allRng = dom.createRng();
  25011. allRng.selectNode(editor.getBody());
  25012. var allSelection = serializeRng(allRng);
  25013. return selection === allSelection;
  25014. };
  25015. editor.on('keydown', function (e) {
  25016. var keyCode = e.keyCode;
  25017. var isCollapsed, body;
  25018. if (!isDefaultPrevented(e) && (keyCode === DELETE || keyCode === BACKSPACE)) {
  25019. isCollapsed = editor.selection.isCollapsed();
  25020. body = editor.getBody();
  25021. if (isCollapsed && !dom.isEmpty(body)) {
  25022. return;
  25023. }
  25024. if (!isCollapsed && !allContentsSelected(editor.selection.getRng())) {
  25025. return;
  25026. }
  25027. e.preventDefault();
  25028. editor.setContent('');
  25029. if (body.firstChild && dom.isBlock(body.firstChild)) {
  25030. editor.selection.setCursorLocation(body.firstChild, 0);
  25031. } else {
  25032. editor.selection.setCursorLocation(body, 0);
  25033. }
  25034. editor.nodeChanged();
  25035. }
  25036. });
  25037. };
  25038. var selectAll = function () {
  25039. editor.shortcuts.add('meta+a', null, 'SelectAll');
  25040. };
  25041. var inputMethodFocus = function () {
  25042. if (!editor.inline) {
  25043. dom.bind(editor.getDoc(), 'mousedown mouseup', function (e) {
  25044. var rng;
  25045. if (e.target === editor.getDoc().documentElement) {
  25046. rng = selection.getRng();
  25047. editor.getBody().focus();
  25048. if (e.type === 'mousedown') {
  25049. if (isCaretContainer(rng.startContainer)) {
  25050. return;
  25051. }
  25052. selection.placeCaretAt(e.clientX, e.clientY);
  25053. } else {
  25054. selection.setRng(rng);
  25055. }
  25056. }
  25057. });
  25058. }
  25059. };
  25060. var removeHrOnBackspace = function () {
  25061. editor.on('keydown', function (e) {
  25062. if (!isDefaultPrevented(e) && e.keyCode === BACKSPACE) {
  25063. if (!editor.getBody().getElementsByTagName('hr').length) {
  25064. return;
  25065. }
  25066. if (selection.isCollapsed() && selection.getRng().startOffset === 0) {
  25067. var node = selection.getNode();
  25068. var previousSibling = node.previousSibling;
  25069. if (node.nodeName === 'HR') {
  25070. dom.remove(node);
  25071. e.preventDefault();
  25072. return;
  25073. }
  25074. if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === 'hr') {
  25075. dom.remove(previousSibling);
  25076. e.preventDefault();
  25077. }
  25078. }
  25079. }
  25080. });
  25081. };
  25082. var focusBody = function () {
  25083. if (!Range.prototype.getClientRects) {
  25084. editor.on('mousedown', function (e) {
  25085. if (!isDefaultPrevented(e) && e.target.nodeName === 'HTML') {
  25086. var body_1 = editor.getBody();
  25087. body_1.blur();
  25088. Delay.setEditorTimeout(editor, function () {
  25089. body_1.focus();
  25090. });
  25091. }
  25092. });
  25093. }
  25094. };
  25095. var selectControlElements = function () {
  25096. editor.on('click', function (e) {
  25097. var target = e.target;
  25098. if (/^(IMG|HR)$/.test(target.nodeName) && dom.getContentEditableParent(target) !== 'false') {
  25099. e.preventDefault();
  25100. editor.selection.select(target);
  25101. editor.nodeChanged();
  25102. }
  25103. if (target.nodeName === 'A' && dom.hasClass(target, 'mce-item-anchor')) {
  25104. e.preventDefault();
  25105. selection.select(target);
  25106. }
  25107. });
  25108. };
  25109. var removeStylesWhenDeletingAcrossBlockElements = function () {
  25110. var getAttributeApplyFunction = function () {
  25111. var template = dom.getAttribs(selection.getStart().cloneNode(false));
  25112. return function () {
  25113. var target = selection.getStart();
  25114. if (target !== editor.getBody()) {
  25115. dom.setAttrib(target, 'style', null);
  25116. each(template, function (attr) {
  25117. target.setAttributeNode(attr.cloneNode(true));
  25118. });
  25119. }
  25120. };
  25121. };
  25122. var isSelectionAcrossElements = function () {
  25123. return !selection.isCollapsed() && dom.getParent(selection.getStart(), dom.isBlock) !== dom.getParent(selection.getEnd(), dom.isBlock);
  25124. };
  25125. editor.on('keypress', function (e) {
  25126. var applyAttributes;
  25127. if (!isDefaultPrevented(e) && (e.keyCode === 8 || e.keyCode === 46) && isSelectionAcrossElements()) {
  25128. applyAttributes = getAttributeApplyFunction();
  25129. editor.getDoc().execCommand('delete', false, null);
  25130. applyAttributes();
  25131. e.preventDefault();
  25132. return false;
  25133. }
  25134. });
  25135. dom.bind(editor.getDoc(), 'cut', function (e) {
  25136. var applyAttributes;
  25137. if (!isDefaultPrevented(e) && isSelectionAcrossElements()) {
  25138. applyAttributes = getAttributeApplyFunction();
  25139. Delay.setEditorTimeout(editor, function () {
  25140. applyAttributes();
  25141. });
  25142. }
  25143. });
  25144. };
  25145. var disableBackspaceIntoATable = function () {
  25146. editor.on('keydown', function (e) {
  25147. if (!isDefaultPrevented(e) && e.keyCode === BACKSPACE) {
  25148. if (selection.isCollapsed() && selection.getRng().startOffset === 0) {
  25149. var previousSibling = selection.getNode().previousSibling;
  25150. if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === 'table') {
  25151. e.preventDefault();
  25152. return false;
  25153. }
  25154. }
  25155. }
  25156. });
  25157. };
  25158. var removeBlockQuoteOnBackSpace = function () {
  25159. editor.on('keydown', function (e) {
  25160. var rng, parent;
  25161. if (isDefaultPrevented(e) || e.keyCode !== VK.BACKSPACE) {
  25162. return;
  25163. }
  25164. rng = selection.getRng();
  25165. var container = rng.startContainer;
  25166. var offset = rng.startOffset;
  25167. var root = dom.getRoot();
  25168. parent = container;
  25169. if (!rng.collapsed || offset !== 0) {
  25170. return;
  25171. }
  25172. while (parent && parent.parentNode && parent.parentNode.firstChild === parent && parent.parentNode !== root) {
  25173. parent = parent.parentNode;
  25174. }
  25175. if (parent.tagName === 'BLOCKQUOTE') {
  25176. editor.formatter.toggle('blockquote', null, parent);
  25177. rng = dom.createRng();
  25178. rng.setStart(container, 0);
  25179. rng.setEnd(container, 0);
  25180. selection.setRng(rng);
  25181. }
  25182. });
  25183. };
  25184. var setGeckoEditingOptions = function () {
  25185. var setOpts = function () {
  25186. setEditorCommandState('StyleWithCSS', false);
  25187. setEditorCommandState('enableInlineTableEditing', false);
  25188. if (!getObjectResizing(editor)) {
  25189. setEditorCommandState('enableObjectResizing', false);
  25190. }
  25191. };
  25192. if (!isReadOnly(editor)) {
  25193. editor.on('BeforeExecCommand mousedown', setOpts);
  25194. }
  25195. };
  25196. var addBrAfterLastLinks = function () {
  25197. var fixLinks = function () {
  25198. each(dom.select('a'), function (node) {
  25199. var parentNode = node.parentNode;
  25200. var root = dom.getRoot();
  25201. if (parentNode.lastChild === node) {
  25202. while (parentNode && !dom.isBlock(parentNode)) {
  25203. if (parentNode.parentNode.lastChild !== parentNode || parentNode === root) {
  25204. return;
  25205. }
  25206. parentNode = parentNode.parentNode;
  25207. }
  25208. dom.add(parentNode, 'br', { 'data-mce-bogus': 1 });
  25209. }
  25210. });
  25211. };
  25212. editor.on('SetContent ExecCommand', function (e) {
  25213. if (e.type === 'setcontent' || e.command === 'mceInsertLink') {
  25214. fixLinks();
  25215. }
  25216. });
  25217. };
  25218. var setDefaultBlockType = function () {
  25219. if (getForcedRootBlock(editor)) {
  25220. editor.on('init', function () {
  25221. setEditorCommandState('DefaultParagraphSeparator', getForcedRootBlock(editor));
  25222. });
  25223. }
  25224. };
  25225. var normalizeSelection = function () {
  25226. editor.on('keyup focusin mouseup', function (e) {
  25227. if (!VK.modifierPressed(e)) {
  25228. selection.normalize();
  25229. }
  25230. }, true);
  25231. };
  25232. var showBrokenImageIcon = function () {
  25233. editor.contentStyles.push('img:-moz-broken {' + '-moz-force-broken-image-icon:1;' + 'min-width:24px;' + 'min-height:24px' + '}');
  25234. };
  25235. var restoreFocusOnKeyDown = function () {
  25236. if (!editor.inline) {
  25237. editor.on('keydown', function () {
  25238. if (document.activeElement === document.body) {
  25239. editor.getWin().focus();
  25240. }
  25241. });
  25242. }
  25243. };
  25244. var bodyHeight = function () {
  25245. if (!editor.inline) {
  25246. editor.contentStyles.push('body {min-height: 150px}');
  25247. editor.on('click', function (e) {
  25248. var rng;
  25249. if (e.target.nodeName === 'HTML') {
  25250. if (Env.ie > 11) {
  25251. editor.getBody().focus();
  25252. return;
  25253. }
  25254. rng = editor.selection.getRng();
  25255. editor.getBody().focus();
  25256. editor.selection.setRng(rng);
  25257. editor.selection.normalize();
  25258. editor.nodeChanged();
  25259. }
  25260. });
  25261. }
  25262. };
  25263. var blockCmdArrowNavigation = function () {
  25264. if (Env.mac) {
  25265. editor.on('keydown', function (e) {
  25266. if (VK.metaKeyPressed(e) && !e.shiftKey && (e.keyCode === 37 || e.keyCode === 39)) {
  25267. e.preventDefault();
  25268. var selection_1 = editor.selection.getSel();
  25269. selection_1.modify('move', e.keyCode === 37 ? 'backward' : 'forward', 'lineboundary');
  25270. }
  25271. });
  25272. }
  25273. };
  25274. var disableAutoUrlDetect = function () {
  25275. setEditorCommandState('AutoUrlDetect', false);
  25276. };
  25277. var tapLinksAndImages = function () {
  25278. editor.on('click', function (e) {
  25279. var elm = e.target;
  25280. do {
  25281. if (elm.tagName === 'A') {
  25282. e.preventDefault();
  25283. return;
  25284. }
  25285. } while (elm = elm.parentNode);
  25286. });
  25287. editor.contentStyles.push('.mce-content-body {-webkit-touch-callout: none}');
  25288. };
  25289. var blockFormSubmitInsideEditor = function () {
  25290. editor.on('init', function () {
  25291. editor.dom.bind(editor.getBody(), 'submit', function (e) {
  25292. e.preventDefault();
  25293. });
  25294. });
  25295. };
  25296. var removeAppleInterchangeBrs = function () {
  25297. parser.addNodeFilter('br', function (nodes) {
  25298. var i = nodes.length;
  25299. while (i--) {
  25300. if (nodes[i].attr('class') === 'Apple-interchange-newline') {
  25301. nodes[i].remove();
  25302. }
  25303. }
  25304. });
  25305. };
  25306. var ieInternalDragAndDrop = function () {
  25307. editor.on('dragstart', function (e) {
  25308. setMceInternalContent(e);
  25309. });
  25310. editor.on('drop', function (e) {
  25311. if (!isDefaultPrevented(e)) {
  25312. var internalContent = getMceInternalContent(e);
  25313. if (internalContent && internalContent.id !== editor.id) {
  25314. e.preventDefault();
  25315. var rng = fromPoint$1(e.x, e.y, editor.getDoc());
  25316. selection.setRng(rng);
  25317. insertClipboardContents(internalContent.html, true);
  25318. }
  25319. }
  25320. });
  25321. };
  25322. var refreshContentEditable = function () {
  25323. };
  25324. var isHidden = function () {
  25325. if (!isGecko || editor.removed) {
  25326. return false;
  25327. }
  25328. var sel = editor.selection.getSel();
  25329. return !sel || !sel.rangeCount || sel.rangeCount === 0;
  25330. };
  25331. removeBlockQuoteOnBackSpace();
  25332. emptyEditorWhenDeleting();
  25333. if (!Env.windowsPhone) {
  25334. normalizeSelection();
  25335. }
  25336. if (isWebKit) {
  25337. inputMethodFocus();
  25338. selectControlElements();
  25339. setDefaultBlockType();
  25340. blockFormSubmitInsideEditor();
  25341. disableBackspaceIntoATable();
  25342. removeAppleInterchangeBrs();
  25343. if (Env.iOS) {
  25344. restoreFocusOnKeyDown();
  25345. bodyHeight();
  25346. tapLinksAndImages();
  25347. } else {
  25348. selectAll();
  25349. }
  25350. }
  25351. if (Env.ie >= 11) {
  25352. bodyHeight();
  25353. disableBackspaceIntoATable();
  25354. }
  25355. if (Env.ie) {
  25356. selectAll();
  25357. disableAutoUrlDetect();
  25358. ieInternalDragAndDrop();
  25359. }
  25360. if (isGecko) {
  25361. removeHrOnBackspace();
  25362. focusBody();
  25363. removeStylesWhenDeletingAcrossBlockElements();
  25364. setGeckoEditingOptions();
  25365. addBrAfterLastLinks();
  25366. showBrokenImageIcon();
  25367. blockCmdArrowNavigation();
  25368. disableBackspaceIntoATable();
  25369. }
  25370. return {
  25371. refreshContentEditable: refreshContentEditable,
  25372. isHidden: isHidden
  25373. };
  25374. };
  25375. var DOM$4 = DOMUtils$1.DOM;
  25376. var appendStyle = function (editor, text) {
  25377. var body = SugarElement.fromDom(editor.getBody());
  25378. var container = getStyleContainer(getRootNode(body));
  25379. var style = SugarElement.fromTag('style');
  25380. set(style, 'type', 'text/css');
  25381. append(style, SugarElement.fromText(text));
  25382. append(container, style);
  25383. editor.on('remove', function () {
  25384. remove(style);
  25385. });
  25386. };
  25387. var getRootName = function (editor) {
  25388. return editor.inline ? editor.getElement().nodeName.toLowerCase() : undefined;
  25389. };
  25390. var removeUndefined = function (obj) {
  25391. return filter$1(obj, function (v) {
  25392. return isUndefined(v) === false;
  25393. });
  25394. };
  25395. var mkParserSettings = function (editor) {
  25396. var settings = editor.settings;
  25397. var blobCache = editor.editorUpload.blobCache;
  25398. return removeUndefined({
  25399. allow_conditional_comments: settings.allow_conditional_comments,
  25400. allow_html_data_urls: settings.allow_html_data_urls,
  25401. allow_html_in_named_anchor: settings.allow_html_in_named_anchor,
  25402. allow_script_urls: settings.allow_script_urls,
  25403. allow_unsafe_link_target: settings.allow_unsafe_link_target,
  25404. convert_fonts_to_spans: settings.convert_fonts_to_spans,
  25405. fix_list_elements: settings.fix_list_elements,
  25406. font_size_legacy_values: settings.font_size_legacy_values,
  25407. forced_root_block: settings.forced_root_block,
  25408. forced_root_block_attrs: settings.forced_root_block_attrs,
  25409. padd_empty_with_br: settings.padd_empty_with_br,
  25410. preserve_cdata: settings.preserve_cdata,
  25411. remove_trailing_brs: settings.remove_trailing_brs,
  25412. inline_styles: settings.inline_styles,
  25413. root_name: getRootName(editor),
  25414. validate: true,
  25415. blob_cache: blobCache,
  25416. images_dataimg_filter: settings.images_dataimg_filter
  25417. });
  25418. };
  25419. var mkSerializerSettings = function (editor) {
  25420. var settings = editor.settings;
  25421. return __assign(__assign({}, mkParserSettings(editor)), removeUndefined({
  25422. url_converter: settings.url_converter,
  25423. url_converter_scope: settings.url_converter_scope,
  25424. element_format: settings.element_format,
  25425. entities: settings.entities,
  25426. entity_encoding: settings.entity_encoding,
  25427. indent: settings.indent,
  25428. indent_after: settings.indent_after,
  25429. indent_before: settings.indent_before,
  25430. block_elements: settings.block_elements,
  25431. boolean_attributes: settings.boolean_attributes,
  25432. custom_elements: settings.custom_elements,
  25433. extended_valid_elements: settings.extended_valid_elements,
  25434. invalid_elements: settings.invalid_elements,
  25435. invalid_styles: settings.invalid_styles,
  25436. move_caret_before_on_enter_elements: settings.move_caret_before_on_enter_elements,
  25437. non_empty_elements: settings.non_empty_elements,
  25438. schema: settings.schema,
  25439. self_closing_elements: settings.self_closing_elements,
  25440. short_ended_elements: settings.short_ended_elements,
  25441. special: settings.special,
  25442. text_block_elements: settings.text_block_elements,
  25443. text_inline_elements: settings.text_inline_elements,
  25444. valid_children: settings.valid_children,
  25445. valid_classes: settings.valid_classes,
  25446. valid_elements: settings.valid_elements,
  25447. valid_styles: settings.valid_styles,
  25448. verify_html: settings.verify_html,
  25449. whitespace_elements: settings.whitespace_elements
  25450. }));
  25451. };
  25452. var createParser = function (editor) {
  25453. var parser = DomParser(mkParserSettings(editor), editor.schema);
  25454. parser.addAttributeFilter('src,href,style,tabindex', function (nodes, name) {
  25455. var i = nodes.length, node, value;
  25456. var dom = editor.dom;
  25457. var internalName = 'data-mce-' + name;
  25458. while (i--) {
  25459. node = nodes[i];
  25460. value = node.attr(name);
  25461. if (value && !node.attr(internalName)) {
  25462. if (value.indexOf('data:') === 0 || value.indexOf('blob:') === 0) {
  25463. continue;
  25464. }
  25465. if (name === 'style') {
  25466. value = dom.serializeStyle(dom.parseStyle(value), node.name);
  25467. if (!value.length) {
  25468. value = null;
  25469. }
  25470. node.attr(internalName, value);
  25471. node.attr(name, value);
  25472. } else if (name === 'tabindex') {
  25473. node.attr(internalName, value);
  25474. node.attr(name, null);
  25475. } else {
  25476. node.attr(internalName, editor.convertURL(value, name, node.name));
  25477. }
  25478. }
  25479. }
  25480. });
  25481. parser.addNodeFilter('script', function (nodes) {
  25482. var i = nodes.length;
  25483. while (i--) {
  25484. var node = nodes[i];
  25485. var type = node.attr('type') || 'no/type';
  25486. if (type.indexOf('mce-') !== 0) {
  25487. node.attr('type', 'mce-' + type);
  25488. }
  25489. }
  25490. });
  25491. if (editor.settings.preserve_cdata) {
  25492. parser.addNodeFilter('#cdata', function (nodes) {
  25493. var i = nodes.length;
  25494. while (i--) {
  25495. var node = nodes[i];
  25496. node.type = 8;
  25497. node.name = '#comment';
  25498. node.value = '[CDATA[' + editor.dom.encode(node.value) + ']]';
  25499. }
  25500. });
  25501. }
  25502. parser.addNodeFilter('p,h1,h2,h3,h4,h5,h6,div', function (nodes) {
  25503. var i = nodes.length;
  25504. var nonEmptyElements = editor.schema.getNonEmptyElements();
  25505. while (i--) {
  25506. var node = nodes[i];
  25507. if (node.isEmpty(nonEmptyElements) && node.getAll('br').length === 0) {
  25508. node.append(new AstNode('br', 1)).shortEnded = true;
  25509. }
  25510. }
  25511. });
  25512. return parser;
  25513. };
  25514. var autoFocus = function (editor) {
  25515. if (editor.settings.auto_focus) {
  25516. Delay.setEditorTimeout(editor, function () {
  25517. var focusEditor;
  25518. if (editor.settings.auto_focus === true) {
  25519. focusEditor = editor;
  25520. } else {
  25521. focusEditor = editor.editorManager.get(editor.settings.auto_focus);
  25522. }
  25523. if (!focusEditor.destroyed) {
  25524. focusEditor.focus();
  25525. }
  25526. }, 100);
  25527. }
  25528. };
  25529. var moveSelectionToFirstCaretPosition = function (editor) {
  25530. var root = editor.dom.getRoot();
  25531. if (!editor.inline && (!hasAnyRanges(editor) || editor.selection.getStart(true) === root)) {
  25532. firstPositionIn(root).each(function (pos) {
  25533. var node = pos.getNode();
  25534. var caretPos = isTable(node) ? firstPositionIn(node).getOr(pos) : pos;
  25535. if (Env.browser.isIE()) {
  25536. storeNative(editor, caretPos.toRange());
  25537. } else {
  25538. editor.selection.setRng(caretPos.toRange());
  25539. }
  25540. });
  25541. }
  25542. };
  25543. var initEditor = function (editor) {
  25544. editor.bindPendingEventDelegates();
  25545. editor.initialized = true;
  25546. fireInit(editor);
  25547. editor.focus(true);
  25548. moveSelectionToFirstCaretPosition(editor);
  25549. editor.nodeChanged({ initial: true });
  25550. editor.execCallback('init_instance_callback', editor);
  25551. autoFocus(editor);
  25552. };
  25553. var getStyleSheetLoader = function (editor) {
  25554. return editor.inline ? editor.ui.styleSheetLoader : editor.dom.styleSheetLoader;
  25555. };
  25556. var loadContentCss = function (editor, css) {
  25557. var styleSheetLoader = getStyleSheetLoader(editor);
  25558. var loaded = function () {
  25559. editor.on('remove', function () {
  25560. return styleSheetLoader.unloadAll(css);
  25561. });
  25562. initEditor(editor);
  25563. };
  25564. styleSheetLoader.loadAll(css, loaded, loaded);
  25565. };
  25566. var preInit = function (editor, rtcMode) {
  25567. var settings = editor.settings, doc = editor.getDoc(), body = editor.getBody();
  25568. if (!settings.browser_spellcheck && !settings.gecko_spellcheck) {
  25569. doc.body.spellcheck = false;
  25570. DOM$4.setAttrib(body, 'spellcheck', 'false');
  25571. }
  25572. editor.quirks = Quirks(editor);
  25573. firePostRender(editor);
  25574. var directionality = getDirectionality(editor);
  25575. if (directionality !== undefined) {
  25576. body.dir = directionality;
  25577. }
  25578. if (settings.protect) {
  25579. editor.on('BeforeSetContent', function (e) {
  25580. Tools.each(settings.protect, function (pattern) {
  25581. e.content = e.content.replace(pattern, function (str) {
  25582. return '<!--mce:protected ' + escape(str) + '-->';
  25583. });
  25584. });
  25585. });
  25586. }
  25587. editor.on('SetContent', function () {
  25588. editor.addVisual(editor.getBody());
  25589. });
  25590. if (rtcMode === false) {
  25591. editor.load({
  25592. initial: true,
  25593. format: 'html'
  25594. });
  25595. }
  25596. editor.startContent = editor.getContent({ format: 'raw' });
  25597. editor.on('compositionstart compositionend', function (e) {
  25598. editor.composing = e.type === 'compositionstart';
  25599. });
  25600. if (editor.contentStyles.length > 0) {
  25601. var contentCssText_1 = '';
  25602. Tools.each(editor.contentStyles, function (style) {
  25603. contentCssText_1 += style + '\r\n';
  25604. });
  25605. editor.dom.addStyle(contentCssText_1);
  25606. }
  25607. loadContentCss(editor, editor.contentCSS);
  25608. if (settings.content_style) {
  25609. appendStyle(editor, settings.content_style);
  25610. }
  25611. };
  25612. var initContentBody = function (editor, skipWrite) {
  25613. var settings = editor.settings;
  25614. var targetElm = editor.getElement();
  25615. var doc = editor.getDoc();
  25616. if (!settings.inline) {
  25617. editor.getElement().style.visibility = editor.orgVisibility;
  25618. }
  25619. if (!skipWrite && !editor.inline) {
  25620. doc.open();
  25621. doc.write(editor.iframeHTML);
  25622. doc.close();
  25623. }
  25624. if (editor.inline) {
  25625. DOM$4.addClass(targetElm, 'mce-content-body');
  25626. editor.contentDocument = doc = document;
  25627. editor.contentWindow = window;
  25628. editor.bodyElement = targetElm;
  25629. editor.contentAreaContainer = targetElm;
  25630. }
  25631. var body = editor.getBody();
  25632. body.disabled = true;
  25633. editor.readonly = !!settings.readonly;
  25634. if (!editor.readonly) {
  25635. if (editor.inline && DOM$4.getStyle(body, 'position', true) === 'static') {
  25636. body.style.position = 'relative';
  25637. }
  25638. body.contentEditable = editor.getParam('content_editable_state', true);
  25639. }
  25640. body.disabled = false;
  25641. editor.editorUpload = EditorUpload(editor);
  25642. editor.schema = Schema(settings);
  25643. editor.dom = DOMUtils$1(doc, {
  25644. keep_values: true,
  25645. url_converter: editor.convertURL,
  25646. url_converter_scope: editor,
  25647. hex_colors: settings.force_hex_style_colors,
  25648. update_styles: true,
  25649. root_element: editor.inline ? editor.getBody() : null,
  25650. collect: function () {
  25651. return editor.inline;
  25652. },
  25653. schema: editor.schema,
  25654. contentCssCors: shouldUseContentCssCors(editor),
  25655. referrerPolicy: getReferrerPolicy(editor),
  25656. onSetAttrib: function (e) {
  25657. editor.fire('SetAttrib', e);
  25658. }
  25659. });
  25660. editor.parser = createParser(editor);
  25661. editor.serializer = DomSerializer(mkSerializerSettings(editor), editor);
  25662. editor.selection = EditorSelection(editor.dom, editor.getWin(), editor.serializer, editor);
  25663. editor.annotator = Annotator(editor);
  25664. editor.formatter = Formatter(editor);
  25665. editor.undoManager = UndoManager(editor);
  25666. editor._nodeChangeDispatcher = new NodeChange(editor);
  25667. editor._selectionOverrides = SelectionOverrides(editor);
  25668. setup$9(editor);
  25669. setup$j(editor);
  25670. if (!isRtc(editor)) {
  25671. setup$k(editor);
  25672. }
  25673. var caret = setup$i(editor);
  25674. setup$8(editor, caret);
  25675. setup$a(editor);
  25676. setup$7(editor);
  25677. firePreInit(editor);
  25678. setup$4(editor).fold(function () {
  25679. preInit(editor, false);
  25680. }, function (loadingRtc) {
  25681. editor.setProgressState(true);
  25682. loadingRtc.then(function (rtcMode) {
  25683. editor.setProgressState(false);
  25684. preInit(editor, rtcMode);
  25685. });
  25686. });
  25687. };
  25688. var DOM$5 = DOMUtils$1.DOM;
  25689. var relaxDomain = function (editor, ifr) {
  25690. if (document.domain !== window.location.hostname && Env.browser.isIE()) {
  25691. var bodyUuid = uuid('mce');
  25692. editor[bodyUuid] = function () {
  25693. initContentBody(editor);
  25694. };
  25695. var domainRelaxUrl = 'javascript:(function(){' + 'document.open();document.domain="' + document.domain + '";' + 'var ed = window.parent.tinymce.get("' + editor.id + '");document.write(ed.iframeHTML);' + 'document.close();ed.' + bodyUuid + '(true);})()';
  25696. DOM$5.setAttrib(ifr, 'src', domainRelaxUrl);
  25697. return true;
  25698. }
  25699. return false;
  25700. };
  25701. var createIframeElement = function (id, title, height, customAttrs) {
  25702. var iframe = SugarElement.fromTag('iframe');
  25703. setAll(iframe, customAttrs);
  25704. setAll(iframe, {
  25705. id: id + '_ifr',
  25706. frameBorder: '0',
  25707. allowTransparency: 'true',
  25708. title: title
  25709. });
  25710. add$3(iframe, 'tox-edit-area__iframe');
  25711. return iframe;
  25712. };
  25713. var getIframeHtml = function (editor) {
  25714. var iframeHTML = getDocType(editor) + '<html><head>';
  25715. if (getDocumentBaseUrl(editor) !== editor.documentBaseUrl) {
  25716. iframeHTML += '<base href="' + editor.documentBaseURI.getURI() + '" />';
  25717. }
  25718. iframeHTML += '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
  25719. var bodyId = getBodyId(editor);
  25720. var bodyClass = getBodyClass(editor);
  25721. if (getContentSecurityPolicy(editor)) {
  25722. iframeHTML += '<meta http-equiv="Content-Security-Policy" content="' + getContentSecurityPolicy(editor) + '" />';
  25723. }
  25724. iframeHTML += '</head><body id="' + bodyId + '" class="mce-content-body ' + bodyClass + '" data-id="' + editor.id + '"><br></body></html>';
  25725. return iframeHTML;
  25726. };
  25727. var createIframe = function (editor, o) {
  25728. var title = editor.editorManager.translate('Rich Text Area. Press ALT-0 for help.');
  25729. var ifr = createIframeElement(editor.id, title, o.height, getIframeAttrs(editor)).dom;
  25730. ifr.onload = function () {
  25731. ifr.onload = null;
  25732. editor.fire('load');
  25733. };
  25734. var isDomainRelaxed = relaxDomain(editor, ifr);
  25735. editor.contentAreaContainer = o.iframeContainer;
  25736. editor.iframeElement = ifr;
  25737. editor.iframeHTML = getIframeHtml(editor);
  25738. DOM$5.add(o.iframeContainer, ifr);
  25739. return isDomainRelaxed;
  25740. };
  25741. var init$1 = function (editor, boxInfo) {
  25742. var isDomainRelaxed = createIframe(editor, boxInfo);
  25743. if (boxInfo.editorContainer) {
  25744. DOM$5.get(boxInfo.editorContainer).style.display = editor.orgDisplay;
  25745. editor.hidden = DOM$5.isHidden(boxInfo.editorContainer);
  25746. }
  25747. editor.getElement().style.display = 'none';
  25748. DOM$5.setAttrib(editor.id, 'aria-hidden', 'true');
  25749. if (!isDomainRelaxed) {
  25750. initContentBody(editor);
  25751. }
  25752. };
  25753. var DOM$6 = DOMUtils$1.DOM;
  25754. var initPlugin = function (editor, initializedPlugins, plugin) {
  25755. var Plugin = PluginManager.get(plugin);
  25756. var pluginUrl = PluginManager.urls[plugin] || editor.documentBaseUrl.replace(/\/$/, '');
  25757. plugin = Tools.trim(plugin);
  25758. if (Plugin && Tools.inArray(initializedPlugins, plugin) === -1) {
  25759. Tools.each(PluginManager.dependencies(plugin), function (dep) {
  25760. initPlugin(editor, initializedPlugins, dep);
  25761. });
  25762. if (editor.plugins[plugin]) {
  25763. return;
  25764. }
  25765. try {
  25766. var pluginInstance = new Plugin(editor, pluginUrl, editor.$);
  25767. editor.plugins[plugin] = pluginInstance;
  25768. if (pluginInstance.init) {
  25769. pluginInstance.init(editor, pluginUrl);
  25770. initializedPlugins.push(plugin);
  25771. }
  25772. } catch (e) {
  25773. pluginInitError(editor, plugin, e);
  25774. }
  25775. }
  25776. };
  25777. var trimLegacyPrefix = function (name) {
  25778. return name.replace(/^\-/, '');
  25779. };
  25780. var initPlugins = function (editor) {
  25781. var initializedPlugins = [];
  25782. Tools.each(getPlugins(editor).split(/[ ,]/), function (name) {
  25783. initPlugin(editor, initializedPlugins, trimLegacyPrefix(name));
  25784. });
  25785. };
  25786. var initIcons = function (editor) {
  25787. var iconPackName = Tools.trim(getIconPackName(editor));
  25788. var currentIcons = editor.ui.registry.getAll().icons;
  25789. var loadIcons = __assign(__assign({}, IconManager.get('default').icons), IconManager.get(iconPackName).icons);
  25790. each$1(loadIcons, function (svgData, icon) {
  25791. if (!has(currentIcons, icon)) {
  25792. editor.ui.registry.addIcon(icon, svgData);
  25793. }
  25794. });
  25795. };
  25796. var initTheme = function (editor) {
  25797. var theme = getTheme(editor);
  25798. if (isString(theme)) {
  25799. editor.settings.theme = trimLegacyPrefix(theme);
  25800. var Theme = ThemeManager.get(theme);
  25801. editor.theme = new Theme(editor, ThemeManager.urls[theme]);
  25802. if (editor.theme.init) {
  25803. editor.theme.init(editor, ThemeManager.urls[theme] || editor.documentBaseUrl.replace(/\/$/, ''), editor.$);
  25804. }
  25805. } else {
  25806. editor.theme = {};
  25807. }
  25808. };
  25809. var renderFromLoadedTheme = function (editor) {
  25810. return editor.theme.renderUI();
  25811. };
  25812. var renderFromThemeFunc = function (editor) {
  25813. var elm = editor.getElement();
  25814. var theme = getTheme(editor);
  25815. var info = theme(editor, elm);
  25816. if (info.editorContainer.nodeType) {
  25817. info.editorContainer.id = info.editorContainer.id || editor.id + '_parent';
  25818. }
  25819. if (info.iframeContainer && info.iframeContainer.nodeType) {
  25820. info.iframeContainer.id = info.iframeContainer.id || editor.id + '_iframecontainer';
  25821. }
  25822. info.height = info.iframeHeight ? info.iframeHeight : elm.offsetHeight;
  25823. return info;
  25824. };
  25825. var createThemeFalseResult = function (element) {
  25826. return {
  25827. editorContainer: element,
  25828. iframeContainer: element,
  25829. api: {}
  25830. };
  25831. };
  25832. var renderThemeFalseIframe = function (targetElement) {
  25833. var iframeContainer = DOM$6.create('div');
  25834. DOM$6.insertAfter(iframeContainer, targetElement);
  25835. return createThemeFalseResult(iframeContainer);
  25836. };
  25837. var renderThemeFalse = function (editor) {
  25838. var targetElement = editor.getElement();
  25839. return editor.inline ? createThemeFalseResult(null) : renderThemeFalseIframe(targetElement);
  25840. };
  25841. var renderThemeUi = function (editor) {
  25842. var elm = editor.getElement();
  25843. editor.orgDisplay = elm.style.display;
  25844. if (isString(getTheme(editor))) {
  25845. return renderFromLoadedTheme(editor);
  25846. } else if (isFunction(getTheme(editor))) {
  25847. return renderFromThemeFunc(editor);
  25848. } else {
  25849. return renderThemeFalse(editor);
  25850. }
  25851. };
  25852. var init$2 = function (editor) {
  25853. editor.fire('ScriptsLoaded');
  25854. initIcons(editor);
  25855. initTheme(editor);
  25856. initPlugins(editor);
  25857. var renderInfo = renderThemeUi(editor);
  25858. editor.ui = __assign(__assign({}, editor.ui), renderInfo.api);
  25859. var boxInfo = {
  25860. editorContainer: renderInfo.editorContainer,
  25861. iframeContainer: renderInfo.iframeContainer
  25862. };
  25863. editor.editorContainer = boxInfo.editorContainer ? boxInfo.editorContainer : null;
  25864. appendContentCssFromSettings(editor);
  25865. if (editor.inline) {
  25866. return initContentBody(editor);
  25867. } else {
  25868. return init$1(editor, boxInfo);
  25869. }
  25870. };
  25871. var DOM$7 = DOMUtils$1.DOM;
  25872. var hasSkipLoadPrefix = function (name) {
  25873. return name.charAt(0) === '-';
  25874. };
  25875. var loadLanguage = function (scriptLoader, editor) {
  25876. var languageCode = getLanguageCode(editor);
  25877. var languageUrl = getLanguageUrl(editor);
  25878. if (I18n.hasCode(languageCode) === false && languageCode !== 'en') {
  25879. var url_1 = languageUrl !== '' ? languageUrl : editor.editorManager.baseURL + '/langs/' + languageCode + '.js';
  25880. scriptLoader.add(url_1, noop, undefined, function () {
  25881. languageLoadError(editor, url_1, languageCode);
  25882. });
  25883. }
  25884. };
  25885. var loadTheme = function (scriptLoader, editor, suffix, callback) {
  25886. var theme = getTheme(editor);
  25887. if (isString(theme)) {
  25888. if (!hasSkipLoadPrefix(theme) && !ThemeManager.urls.hasOwnProperty(theme)) {
  25889. var themeUrl = getThemeUrl(editor);
  25890. if (themeUrl) {
  25891. ThemeManager.load(theme, editor.documentBaseURI.toAbsolute(themeUrl));
  25892. } else {
  25893. ThemeManager.load(theme, 'themes/' + theme + '/theme' + suffix + '.js');
  25894. }
  25895. }
  25896. scriptLoader.loadQueue(function () {
  25897. ThemeManager.waitFor(theme, callback);
  25898. });
  25899. } else {
  25900. callback();
  25901. }
  25902. };
  25903. var getIconsUrlMetaFromUrl = function (editor) {
  25904. return Optional.from(getIconsUrl(editor)).filter(function (url) {
  25905. return url.length > 0;
  25906. }).map(function (url) {
  25907. return {
  25908. url: url,
  25909. name: Optional.none()
  25910. };
  25911. });
  25912. };
  25913. var getIconsUrlMetaFromName = function (editor, name, suffix) {
  25914. return Optional.from(name).filter(function (name) {
  25915. return name.length > 0 && !IconManager.has(name);
  25916. }).map(function (name) {
  25917. return {
  25918. url: editor.editorManager.baseURL + '/icons/' + name + '/icons' + suffix + '.js',
  25919. name: Optional.some(name)
  25920. };
  25921. });
  25922. };
  25923. var loadIcons = function (scriptLoader, editor, suffix) {
  25924. var defaultIconsUrl = getIconsUrlMetaFromName(editor, 'default', suffix);
  25925. var customIconsUrl = getIconsUrlMetaFromUrl(editor).orThunk(function () {
  25926. return getIconsUrlMetaFromName(editor, getIconPackName(editor), '');
  25927. });
  25928. each(cat([
  25929. defaultIconsUrl,
  25930. customIconsUrl
  25931. ]), function (urlMeta) {
  25932. scriptLoader.add(urlMeta.url, noop, undefined, function () {
  25933. iconsLoadError(editor, urlMeta.url, urlMeta.name.getOrUndefined());
  25934. });
  25935. });
  25936. };
  25937. var loadPlugins = function (editor, suffix) {
  25938. Tools.each(getExternalPlugins(editor), function (url, name) {
  25939. PluginManager.load(name, url, noop, undefined, function () {
  25940. pluginLoadError(editor, url, name);
  25941. });
  25942. editor.settings.plugins += ' ' + name;
  25943. });
  25944. Tools.each(getPlugins(editor).split(/[ ,]/), function (plugin) {
  25945. plugin = Tools.trim(plugin);
  25946. if (plugin && !PluginManager.urls[plugin]) {
  25947. if (hasSkipLoadPrefix(plugin)) {
  25948. plugin = plugin.substr(1, plugin.length);
  25949. var dependencies = PluginManager.dependencies(plugin);
  25950. Tools.each(dependencies, function (depPlugin) {
  25951. var defaultSettings = {
  25952. prefix: 'plugins/',
  25953. resource: depPlugin,
  25954. suffix: '/plugin' + suffix + '.js'
  25955. };
  25956. var dep = PluginManager.createUrl(defaultSettings, depPlugin);
  25957. PluginManager.load(dep.resource, dep, noop, undefined, function () {
  25958. pluginLoadError(editor, dep.prefix + dep.resource + dep.suffix, dep.resource);
  25959. });
  25960. });
  25961. } else {
  25962. var url_2 = {
  25963. prefix: 'plugins/',
  25964. resource: plugin,
  25965. suffix: '/plugin' + suffix + '.js'
  25966. };
  25967. PluginManager.load(plugin, url_2, noop, undefined, function () {
  25968. pluginLoadError(editor, url_2.prefix + url_2.resource + url_2.suffix, plugin);
  25969. });
  25970. }
  25971. }
  25972. });
  25973. };
  25974. var loadScripts = function (editor, suffix) {
  25975. var scriptLoader = ScriptLoader.ScriptLoader;
  25976. loadTheme(scriptLoader, editor, suffix, function () {
  25977. loadLanguage(scriptLoader, editor);
  25978. loadIcons(scriptLoader, editor, suffix);
  25979. loadPlugins(editor, suffix);
  25980. scriptLoader.loadQueue(function () {
  25981. if (!editor.removed) {
  25982. init$2(editor);
  25983. }
  25984. }, editor, function () {
  25985. if (!editor.removed) {
  25986. init$2(editor);
  25987. }
  25988. });
  25989. });
  25990. };
  25991. var getStyleSheetLoader$1 = function (element, editor) {
  25992. return instance.forElement(element, {
  25993. contentCssCors: hasContentCssCors(editor),
  25994. referrerPolicy: getReferrerPolicy(editor)
  25995. });
  25996. };
  25997. var render = function (editor) {
  25998. var id = editor.id;
  25999. I18n.setCode(getLanguageCode(editor));
  26000. var readyHandler = function () {
  26001. DOM$7.unbind(window, 'ready', readyHandler);
  26002. editor.render();
  26003. };
  26004. if (!EventUtils.Event.domLoaded) {
  26005. DOM$7.bind(window, 'ready', readyHandler);
  26006. return;
  26007. }
  26008. if (!editor.getElement()) {
  26009. return;
  26010. }
  26011. if (!Env.contentEditable) {
  26012. return;
  26013. }
  26014. var element = SugarElement.fromDom(editor.getElement());
  26015. var snapshot = clone(element);
  26016. editor.on('remove', function () {
  26017. eachr(element.dom.attributes, function (attr) {
  26018. return remove$1(element, attr.name);
  26019. });
  26020. setAll(element, snapshot);
  26021. });
  26022. editor.ui.styleSheetLoader = getStyleSheetLoader$1(element, editor);
  26023. if (!isInline$1(editor)) {
  26024. editor.orgVisibility = editor.getElement().style.visibility;
  26025. editor.getElement().style.visibility = 'hidden';
  26026. } else {
  26027. editor.inline = true;
  26028. }
  26029. var form = editor.getElement().form || DOM$7.getParent(id, 'form');
  26030. if (form) {
  26031. editor.formElement = form;
  26032. if (hasHiddenInput(editor) && !isTextareaOrInput(editor.getElement())) {
  26033. DOM$7.insertAfter(DOM$7.create('input', {
  26034. type: 'hidden',
  26035. name: id
  26036. }), id);
  26037. editor.hasHiddenInput = true;
  26038. }
  26039. editor.formEventDelegate = function (e) {
  26040. editor.fire(e.type, e);
  26041. };
  26042. DOM$7.bind(form, 'submit reset', editor.formEventDelegate);
  26043. editor.on('reset', function () {
  26044. editor.resetContent();
  26045. });
  26046. if (shouldPatchSubmit(editor) && !form.submit.nodeType && !form.submit.length && !form._mceOldSubmit) {
  26047. form._mceOldSubmit = form.submit;
  26048. form.submit = function () {
  26049. editor.editorManager.triggerSave();
  26050. editor.setDirty(false);
  26051. return form._mceOldSubmit(form);
  26052. };
  26053. }
  26054. }
  26055. editor.windowManager = WindowManager(editor);
  26056. editor.notificationManager = NotificationManager(editor);
  26057. if (isEncodingXml(editor)) {
  26058. editor.on('GetContent', function (e) {
  26059. if (e.save) {
  26060. e.content = DOM$7.encode(e.content);
  26061. }
  26062. });
  26063. }
  26064. if (shouldAddFormSubmitTrigger(editor)) {
  26065. editor.on('submit', function () {
  26066. if (editor.initialized) {
  26067. editor.save();
  26068. }
  26069. });
  26070. }
  26071. if (shouldAddUnloadTrigger(editor)) {
  26072. editor._beforeUnload = function () {
  26073. if (editor.initialized && !editor.destroyed && !editor.isHidden()) {
  26074. editor.save({
  26075. format: 'raw',
  26076. no_events: true,
  26077. set_dirty: false
  26078. });
  26079. }
  26080. };
  26081. editor.editorManager.on('BeforeUnload', editor._beforeUnload);
  26082. }
  26083. editor.editorManager.add(editor);
  26084. loadScripts(editor, editor.suffix);
  26085. };
  26086. var ensureIsRoot = function (isRoot) {
  26087. return isFunction(isRoot) ? isRoot : never;
  26088. };
  26089. var ancestor$3 = function (scope, transform, isRoot) {
  26090. var element = scope.dom;
  26091. var stop = ensureIsRoot(isRoot);
  26092. while (element.parentNode) {
  26093. element = element.parentNode;
  26094. var el = SugarElement.fromDom(element);
  26095. var transformed = transform(el);
  26096. if (transformed.isSome()) {
  26097. return transformed;
  26098. } else if (stop(el)) {
  26099. break;
  26100. }
  26101. }
  26102. return Optional.none();
  26103. };
  26104. var closest$2 = function (scope, transform, isRoot) {
  26105. var current = transform(scope);
  26106. var stop = ensureIsRoot(isRoot);
  26107. return current.orThunk(function () {
  26108. return stop(scope) ? Optional.none() : ancestor$3(scope, transform, stop);
  26109. });
  26110. };
  26111. var legacyPropNames = {
  26112. 'font-size': 'size',
  26113. 'font-family': 'face'
  26114. };
  26115. var getSpecifiedFontProp = function (propName, rootElm, elm) {
  26116. var getProperty = function (elm) {
  26117. return getRaw(elm, propName).orThunk(function () {
  26118. if (name(elm) === 'font') {
  26119. return get(legacyPropNames, propName).bind(function (legacyPropName) {
  26120. return getOpt(elm, legacyPropName);
  26121. });
  26122. } else {
  26123. return Optional.none();
  26124. }
  26125. });
  26126. };
  26127. var isRoot = function (elm) {
  26128. return eq$2(SugarElement.fromDom(rootElm), elm);
  26129. };
  26130. return closest$2(SugarElement.fromDom(elm), function (elm) {
  26131. return getProperty(elm);
  26132. }, isRoot);
  26133. };
  26134. var normalizeFontFamily = function (fontFamily) {
  26135. return fontFamily.replace(/[\'\"\\]/g, '').replace(/,\s+/g, ',');
  26136. };
  26137. var getComputedFontProp = function (propName, elm) {
  26138. return Optional.from(DOMUtils$1.DOM.getStyle(elm, propName, true));
  26139. };
  26140. var getFontProp = function (propName) {
  26141. return function (rootElm, elm) {
  26142. return Optional.from(elm).map(SugarElement.fromDom).filter(isElement).bind(function (element) {
  26143. return getSpecifiedFontProp(propName, rootElm, element.dom).or(getComputedFontProp(propName, element.dom));
  26144. }).getOr('');
  26145. };
  26146. };
  26147. var getFontSize = getFontProp('font-size');
  26148. var getFontFamily = compose(normalizeFontFamily, getFontProp('font-family'));
  26149. var findFirstCaretElement = function (editor) {
  26150. return firstPositionIn(editor.getBody()).map(function (caret) {
  26151. var container = caret.container();
  26152. return isText$1(container) ? container.parentNode : container;
  26153. });
  26154. };
  26155. var getCaretElement = function (editor) {
  26156. return Optional.from(editor.selection.getRng()).bind(function (rng) {
  26157. var root = editor.getBody();
  26158. var atStartOfNode = rng.startContainer === root && rng.startOffset === 0;
  26159. return atStartOfNode ? Optional.none() : Optional.from(editor.selection.getStart(true));
  26160. });
  26161. };
  26162. var mapRange = function (editor, mapper) {
  26163. return getCaretElement(editor).orThunk(curry(findFirstCaretElement, editor)).map(SugarElement.fromDom).filter(isElement).map(mapper);
  26164. };
  26165. var fromFontSizeNumber = function (editor, value) {
  26166. if (/^[0-9.]+$/.test(value)) {
  26167. var fontSizeNumber = parseInt(value, 10);
  26168. if (fontSizeNumber >= 1 && fontSizeNumber <= 7) {
  26169. var fontSizes = getFontStyleValues(editor);
  26170. var fontClasses = getFontSizeClasses(editor);
  26171. if (fontClasses) {
  26172. return fontClasses[fontSizeNumber - 1] || value;
  26173. } else {
  26174. return fontSizes[fontSizeNumber - 1] || value;
  26175. }
  26176. } else {
  26177. return value;
  26178. }
  26179. } else {
  26180. return value;
  26181. }
  26182. };
  26183. var normalizeFontNames = function (font) {
  26184. var fonts = font.split(/\s*,\s*/);
  26185. return map(fonts, function (font) {
  26186. if (font.indexOf(' ') !== -1 && !(startsWith(font, '"') || startsWith(font, '\''))) {
  26187. return '\'' + font + '\'';
  26188. } else {
  26189. return font;
  26190. }
  26191. }).join(',');
  26192. };
  26193. var fontNameAction = function (editor, value) {
  26194. var font = fromFontSizeNumber(editor, value);
  26195. editor.formatter.toggle('fontname', { value: normalizeFontNames(font) });
  26196. editor.nodeChanged();
  26197. };
  26198. var fontNameQuery = function (editor) {
  26199. return mapRange(editor, function (elm) {
  26200. return getFontFamily(editor.getBody(), elm.dom);
  26201. }).getOr('');
  26202. };
  26203. var fontSizeAction = function (editor, value) {
  26204. editor.formatter.toggle('fontsize', { value: fromFontSizeNumber(editor, value) });
  26205. editor.nodeChanged();
  26206. };
  26207. var fontSizeQuery = function (editor) {
  26208. return mapRange(editor, function (elm) {
  26209. return getFontSize(editor.getBody(), elm.dom);
  26210. }).getOr('');
  26211. };
  26212. var lineHeightQuery = function (editor) {
  26213. return mapRange(editor, function (elm) {
  26214. var root = SugarElement.fromDom(editor.getBody());
  26215. var specifiedStyle = closest$2(elm, function (elm) {
  26216. return getRaw(elm, 'line-height');
  26217. }, curry(eq$2, root));
  26218. var computedStyle = function () {
  26219. var lineHeight = parseFloat(get$4(elm, 'line-height'));
  26220. var fontSize = parseFloat(get$4(elm, 'font-size'));
  26221. return String(lineHeight / fontSize);
  26222. };
  26223. return specifiedStyle.getOrThunk(computedStyle);
  26224. }).getOr('');
  26225. };
  26226. var lineHeightAction = function (editor, lineHeight) {
  26227. editor.undoManager.transact(function () {
  26228. editor.formatter.toggle('lineheight', { value: String(lineHeight) });
  26229. editor.nodeChanged();
  26230. });
  26231. };
  26232. var processValue = function (value) {
  26233. var details;
  26234. if (typeof value !== 'string') {
  26235. details = Tools.extend({
  26236. paste: value.paste,
  26237. data: { paste: value.paste }
  26238. }, value);
  26239. return {
  26240. content: value.content,
  26241. details: details
  26242. };
  26243. }
  26244. return {
  26245. content: value,
  26246. details: {}
  26247. };
  26248. };
  26249. var insertAtCaret$1 = function (editor, value) {
  26250. var result = processValue(value);
  26251. insertContent(editor, result.content, result.details);
  26252. };
  26253. var each$f = Tools.each;
  26254. var map$3 = Tools.map, inArray$2 = Tools.inArray;
  26255. var EditorCommands = function () {
  26256. function EditorCommands(editor) {
  26257. this.commands = {
  26258. state: {},
  26259. exec: {},
  26260. value: {}
  26261. };
  26262. this.editor = editor;
  26263. this.setupCommands(editor);
  26264. }
  26265. EditorCommands.prototype.execCommand = function (command, ui, value, args) {
  26266. var func, state = false;
  26267. var self = this;
  26268. if (self.editor.removed) {
  26269. return;
  26270. }
  26271. if (!/^(mceAddUndoLevel|mceEndUndoLevel|mceBeginUndoLevel|mceRepaint)$/.test(command) && (!args || !args.skip_focus)) {
  26272. self.editor.focus();
  26273. } else {
  26274. restore(self.editor);
  26275. }
  26276. args = self.editor.fire('BeforeExecCommand', {
  26277. command: command,
  26278. ui: ui,
  26279. value: value
  26280. });
  26281. if (args.isDefaultPrevented()) {
  26282. return false;
  26283. }
  26284. var customCommand = command.toLowerCase();
  26285. if (func = self.commands.exec[customCommand]) {
  26286. func(customCommand, ui, value);
  26287. self.editor.fire('ExecCommand', {
  26288. command: command,
  26289. ui: ui,
  26290. value: value
  26291. });
  26292. return true;
  26293. }
  26294. each$f(this.editor.plugins, function (p) {
  26295. if (p.execCommand && p.execCommand(command, ui, value)) {
  26296. self.editor.fire('ExecCommand', {
  26297. command: command,
  26298. ui: ui,
  26299. value: value
  26300. });
  26301. state = true;
  26302. return false;
  26303. }
  26304. });
  26305. if (state) {
  26306. return state;
  26307. }
  26308. if (self.editor.theme && self.editor.theme.execCommand && self.editor.theme.execCommand(command, ui, value)) {
  26309. self.editor.fire('ExecCommand', {
  26310. command: command,
  26311. ui: ui,
  26312. value: value
  26313. });
  26314. return true;
  26315. }
  26316. try {
  26317. state = self.editor.getDoc().execCommand(command, ui, value);
  26318. } catch (ex) {
  26319. }
  26320. if (state) {
  26321. self.editor.fire('ExecCommand', {
  26322. command: command,
  26323. ui: ui,
  26324. value: value
  26325. });
  26326. return true;
  26327. }
  26328. return false;
  26329. };
  26330. EditorCommands.prototype.queryCommandState = function (command) {
  26331. var func;
  26332. if (this.editor.quirks.isHidden() || this.editor.removed) {
  26333. return;
  26334. }
  26335. command = command.toLowerCase();
  26336. if (func = this.commands.state[command]) {
  26337. return func(command);
  26338. }
  26339. try {
  26340. return this.editor.getDoc().queryCommandState(command);
  26341. } catch (ex) {
  26342. }
  26343. return false;
  26344. };
  26345. EditorCommands.prototype.queryCommandValue = function (command) {
  26346. var func;
  26347. if (this.editor.quirks.isHidden() || this.editor.removed) {
  26348. return;
  26349. }
  26350. command = command.toLowerCase();
  26351. if (func = this.commands.value[command]) {
  26352. return func(command);
  26353. }
  26354. try {
  26355. return this.editor.getDoc().queryCommandValue(command);
  26356. } catch (ex) {
  26357. }
  26358. };
  26359. EditorCommands.prototype.addCommands = function (commandList, type) {
  26360. if (type === void 0) {
  26361. type = 'exec';
  26362. }
  26363. var self = this;
  26364. each$f(commandList, function (callback, command) {
  26365. each$f(command.toLowerCase().split(','), function (command) {
  26366. self.commands[type][command] = callback;
  26367. });
  26368. });
  26369. };
  26370. EditorCommands.prototype.addCommand = function (command, callback, scope) {
  26371. var _this = this;
  26372. command = command.toLowerCase();
  26373. this.commands.exec[command] = function (command, ui, value, args) {
  26374. return callback.call(scope || _this.editor, ui, value, args);
  26375. };
  26376. };
  26377. EditorCommands.prototype.queryCommandSupported = function (command) {
  26378. command = command.toLowerCase();
  26379. if (this.commands.exec[command]) {
  26380. return true;
  26381. }
  26382. try {
  26383. return this.editor.getDoc().queryCommandSupported(command);
  26384. } catch (ex) {
  26385. }
  26386. return false;
  26387. };
  26388. EditorCommands.prototype.addQueryStateHandler = function (command, callback, scope) {
  26389. var _this = this;
  26390. command = command.toLowerCase();
  26391. this.commands.state[command] = function () {
  26392. return callback.call(scope || _this.editor);
  26393. };
  26394. };
  26395. EditorCommands.prototype.addQueryValueHandler = function (command, callback, scope) {
  26396. var _this = this;
  26397. command = command.toLowerCase();
  26398. this.commands.value[command] = function () {
  26399. return callback.call(scope || _this.editor);
  26400. };
  26401. };
  26402. EditorCommands.prototype.hasCustomCommand = function (command) {
  26403. command = command.toLowerCase();
  26404. return !!this.commands.exec[command];
  26405. };
  26406. EditorCommands.prototype.execNativeCommand = function (command, ui, value) {
  26407. if (ui === undefined) {
  26408. ui = false;
  26409. }
  26410. if (value === undefined) {
  26411. value = null;
  26412. }
  26413. return this.editor.getDoc().execCommand(command, ui, value);
  26414. };
  26415. EditorCommands.prototype.isFormatMatch = function (name) {
  26416. return this.editor.formatter.match(name);
  26417. };
  26418. EditorCommands.prototype.toggleFormat = function (name, value) {
  26419. this.editor.formatter.toggle(name, value ? { value: value } : undefined);
  26420. this.editor.nodeChanged();
  26421. };
  26422. EditorCommands.prototype.storeSelection = function (type) {
  26423. this.selectionBookmark = this.editor.selection.getBookmark(type);
  26424. };
  26425. EditorCommands.prototype.restoreSelection = function () {
  26426. this.editor.selection.moveToBookmark(this.selectionBookmark);
  26427. };
  26428. EditorCommands.prototype.setupCommands = function (editor) {
  26429. var self = this;
  26430. this.addCommands({
  26431. 'mceResetDesignMode,mceBeginUndoLevel': function () {
  26432. },
  26433. 'mceEndUndoLevel,mceAddUndoLevel': function () {
  26434. editor.undoManager.add();
  26435. },
  26436. 'Cut,Copy,Paste': function (command) {
  26437. var doc = editor.getDoc();
  26438. var failed;
  26439. try {
  26440. self.execNativeCommand(command);
  26441. } catch (ex) {
  26442. failed = true;
  26443. }
  26444. if (command === 'paste' && !doc.queryCommandEnabled(command)) {
  26445. failed = true;
  26446. }
  26447. if (failed || !doc.queryCommandSupported(command)) {
  26448. var msg = editor.translate('Your browser doesn\'t support direct access to the clipboard. ' + 'Please use the Ctrl+X/C/V keyboard shortcuts instead.');
  26449. if (Env.mac) {
  26450. msg = msg.replace(/Ctrl\+/g, '\u2318+');
  26451. }
  26452. editor.notificationManager.open({
  26453. text: msg,
  26454. type: 'error'
  26455. });
  26456. }
  26457. },
  26458. 'unlink': function () {
  26459. if (editor.selection.isCollapsed()) {
  26460. var elm = editor.dom.getParent(editor.selection.getStart(), 'a');
  26461. if (elm) {
  26462. editor.dom.remove(elm, true);
  26463. }
  26464. return;
  26465. }
  26466. editor.formatter.remove('link');
  26467. },
  26468. 'JustifyLeft,JustifyCenter,JustifyRight,JustifyFull,JustifyNone': function (command) {
  26469. var align = command.substring(7);
  26470. if (align === 'full') {
  26471. align = 'justify';
  26472. }
  26473. each$f('left,center,right,justify'.split(','), function (name) {
  26474. if (align !== name) {
  26475. editor.formatter.remove('align' + name);
  26476. }
  26477. });
  26478. if (align !== 'none') {
  26479. self.toggleFormat('align' + align);
  26480. }
  26481. },
  26482. 'InsertUnorderedList,InsertOrderedList': function (command) {
  26483. var listParent;
  26484. self.execNativeCommand(command);
  26485. var listElm = editor.dom.getParent(editor.selection.getNode(), 'ol,ul');
  26486. if (listElm) {
  26487. listParent = listElm.parentNode;
  26488. if (/^(H[1-6]|P|ADDRESS|PRE)$/.test(listParent.nodeName)) {
  26489. self.storeSelection();
  26490. editor.dom.split(listParent, listElm);
  26491. self.restoreSelection();
  26492. }
  26493. }
  26494. },
  26495. 'Bold,Italic,Underline,Strikethrough,Superscript,Subscript': function (command) {
  26496. self.toggleFormat(command);
  26497. },
  26498. 'ForeColor,HiliteColor': function (command, ui, value) {
  26499. self.toggleFormat(command, value);
  26500. },
  26501. 'FontName': function (command, ui, value) {
  26502. fontNameAction(editor, value);
  26503. },
  26504. 'FontSize': function (command, ui, value) {
  26505. fontSizeAction(editor, value);
  26506. },
  26507. 'LineHeight': function (command, ui, value) {
  26508. lineHeightAction(editor, value);
  26509. },
  26510. 'RemoveFormat': function (command) {
  26511. editor.formatter.remove(command);
  26512. },
  26513. 'mceBlockQuote': function () {
  26514. self.toggleFormat('blockquote');
  26515. },
  26516. 'FormatBlock': function (command, ui, value) {
  26517. return self.toggleFormat(value || 'p');
  26518. },
  26519. 'mceCleanup': function () {
  26520. var bookmark = editor.selection.getBookmark();
  26521. editor.setContent(editor.getContent());
  26522. editor.selection.moveToBookmark(bookmark);
  26523. },
  26524. 'mceRemoveNode': function (command, ui, value) {
  26525. var node = value || editor.selection.getNode();
  26526. if (node !== editor.getBody()) {
  26527. self.storeSelection();
  26528. editor.dom.remove(node, true);
  26529. self.restoreSelection();
  26530. }
  26531. },
  26532. 'mceSelectNodeDepth': function (command, ui, value) {
  26533. var counter = 0;
  26534. editor.dom.getParent(editor.selection.getNode(), function (node) {
  26535. if (node.nodeType === 1 && counter++ === value) {
  26536. editor.selection.select(node);
  26537. return false;
  26538. }
  26539. }, editor.getBody());
  26540. },
  26541. 'mceSelectNode': function (command, ui, value) {
  26542. editor.selection.select(value);
  26543. },
  26544. 'mceInsertContent': function (command, ui, value) {
  26545. insertAtCaret$1(editor, value);
  26546. },
  26547. 'mceInsertRawHTML': function (command, ui, value) {
  26548. editor.selection.setContent('tiny_mce_marker');
  26549. var content = editor.getContent();
  26550. editor.setContent(content.replace(/tiny_mce_marker/g, function () {
  26551. return value;
  26552. }));
  26553. },
  26554. 'mceInsertNewLine': function (command, ui, value) {
  26555. insert$3(editor, value);
  26556. },
  26557. 'mceToggleFormat': function (command, ui, value) {
  26558. self.toggleFormat(value);
  26559. },
  26560. 'mceSetContent': function (command, ui, value) {
  26561. editor.setContent(value);
  26562. },
  26563. 'Indent,Outdent': function (command) {
  26564. handle(editor, command);
  26565. },
  26566. 'mceRepaint': function () {
  26567. },
  26568. 'InsertHorizontalRule': function () {
  26569. editor.execCommand('mceInsertContent', false, '<hr />');
  26570. },
  26571. 'mceToggleVisualAid': function () {
  26572. editor.hasVisual = !editor.hasVisual;
  26573. editor.addVisual();
  26574. },
  26575. 'mceReplaceContent': function (command, ui, value) {
  26576. editor.execCommand('mceInsertContent', false, value.replace(/\{\$selection\}/g, editor.selection.getContent({ format: 'text' })));
  26577. },
  26578. 'mceInsertLink': function (command, ui, value) {
  26579. if (typeof value === 'string') {
  26580. value = { href: value };
  26581. }
  26582. var anchor = editor.dom.getParent(editor.selection.getNode(), 'a');
  26583. value.href = value.href.replace(/ /g, '%20');
  26584. if (!anchor || !value.href) {
  26585. editor.formatter.remove('link');
  26586. }
  26587. if (value.href) {
  26588. editor.formatter.apply('link', value, anchor);
  26589. }
  26590. },
  26591. 'selectAll': function () {
  26592. var editingHost = editor.dom.getParent(editor.selection.getStart(), isContentEditableTrue);
  26593. if (editingHost) {
  26594. var rng = editor.dom.createRng();
  26595. rng.selectNodeContents(editingHost);
  26596. editor.selection.setRng(rng);
  26597. }
  26598. },
  26599. 'mceNewDocument': function () {
  26600. editor.setContent('');
  26601. },
  26602. 'InsertLineBreak': function (command, ui, value) {
  26603. insert$2(editor, value);
  26604. return true;
  26605. }
  26606. });
  26607. var alignStates = function (name) {
  26608. return function () {
  26609. var selection = editor.selection;
  26610. var nodes = selection.isCollapsed() ? [editor.dom.getParent(selection.getNode(), editor.dom.isBlock)] : selection.getSelectedBlocks();
  26611. var matches = map$3(nodes, function (node) {
  26612. return !!editor.formatter.matchNode(node, name);
  26613. });
  26614. return inArray$2(matches, true) !== -1;
  26615. };
  26616. };
  26617. self.addCommands({
  26618. 'JustifyLeft': alignStates('alignleft'),
  26619. 'JustifyCenter': alignStates('aligncenter'),
  26620. 'JustifyRight': alignStates('alignright'),
  26621. 'JustifyFull': alignStates('alignjustify'),
  26622. 'Bold,Italic,Underline,Strikethrough,Superscript,Subscript': function (command) {
  26623. return self.isFormatMatch(command);
  26624. },
  26625. 'mceBlockQuote': function () {
  26626. return self.isFormatMatch('blockquote');
  26627. },
  26628. 'Outdent': function () {
  26629. return canOutdent(editor);
  26630. },
  26631. 'InsertUnorderedList,InsertOrderedList': function (command) {
  26632. var list = editor.dom.getParent(editor.selection.getNode(), 'ul,ol');
  26633. return list && (command === 'insertunorderedlist' && list.tagName === 'UL' || command === 'insertorderedlist' && list.tagName === 'OL');
  26634. }
  26635. }, 'state');
  26636. self.addCommands({
  26637. Undo: function () {
  26638. editor.undoManager.undo();
  26639. },
  26640. Redo: function () {
  26641. editor.undoManager.redo();
  26642. }
  26643. });
  26644. self.addQueryValueHandler('FontName', function () {
  26645. return fontNameQuery(editor);
  26646. }, this);
  26647. self.addQueryValueHandler('FontSize', function () {
  26648. return fontSizeQuery(editor);
  26649. }, this);
  26650. self.addQueryValueHandler('LineHeight', function () {
  26651. return lineHeightQuery(editor);
  26652. }, this);
  26653. };
  26654. return EditorCommands;
  26655. }();
  26656. var internalContentEditableAttr = 'data-mce-contenteditable';
  26657. var toggleClass = function (elm, cls, state) {
  26658. if (has$2(elm, cls) && state === false) {
  26659. remove$4(elm, cls);
  26660. } else if (state) {
  26661. add$3(elm, cls);
  26662. }
  26663. };
  26664. var setEditorCommandState = function (editor, cmd, state) {
  26665. try {
  26666. editor.getDoc().execCommand(cmd, false, String(state));
  26667. } catch (ex) {
  26668. }
  26669. };
  26670. var setContentEditable = function (elm, state) {
  26671. elm.dom.contentEditable = state ? 'true' : 'false';
  26672. };
  26673. var switchOffContentEditableTrue = function (elm) {
  26674. each(descendants$1(elm, '*[contenteditable="true"]'), function (elm) {
  26675. set(elm, internalContentEditableAttr, 'true');
  26676. setContentEditable(elm, false);
  26677. });
  26678. };
  26679. var switchOnContentEditableTrue = function (elm) {
  26680. each(descendants$1(elm, '*[' + internalContentEditableAttr + '="true"]'), function (elm) {
  26681. remove$1(elm, internalContentEditableAttr);
  26682. setContentEditable(elm, true);
  26683. });
  26684. };
  26685. var removeFakeSelection = function (editor) {
  26686. Optional.from(editor.selection.getNode()).each(function (elm) {
  26687. elm.removeAttribute('data-mce-selected');
  26688. });
  26689. };
  26690. var restoreFakeSelection = function (editor) {
  26691. editor.selection.setRng(editor.selection.getRng());
  26692. };
  26693. var toggleReadOnly = function (editor, state) {
  26694. var body = SugarElement.fromDom(editor.getBody());
  26695. toggleClass(body, 'mce-content-readonly', state);
  26696. if (state) {
  26697. editor.selection.controlSelection.hideResizeRect();
  26698. editor._selectionOverrides.hideFakeCaret();
  26699. removeFakeSelection(editor);
  26700. editor.readonly = true;
  26701. setContentEditable(body, false);
  26702. switchOffContentEditableTrue(body);
  26703. } else {
  26704. editor.readonly = false;
  26705. setContentEditable(body, true);
  26706. switchOnContentEditableTrue(body);
  26707. setEditorCommandState(editor, 'StyleWithCSS', false);
  26708. setEditorCommandState(editor, 'enableInlineTableEditing', false);
  26709. setEditorCommandState(editor, 'enableObjectResizing', false);
  26710. if (hasEditorOrUiFocus(editor)) {
  26711. editor.focus();
  26712. }
  26713. restoreFakeSelection(editor);
  26714. editor.nodeChanged();
  26715. }
  26716. };
  26717. var isReadOnly$1 = function (editor) {
  26718. return editor.readonly;
  26719. };
  26720. var registerFilters = function (editor) {
  26721. editor.parser.addAttributeFilter('contenteditable', function (nodes) {
  26722. if (isReadOnly$1(editor)) {
  26723. each(nodes, function (node) {
  26724. node.attr(internalContentEditableAttr, node.attr('contenteditable'));
  26725. node.attr('contenteditable', 'false');
  26726. });
  26727. }
  26728. });
  26729. editor.serializer.addAttributeFilter(internalContentEditableAttr, function (nodes) {
  26730. if (isReadOnly$1(editor)) {
  26731. each(nodes, function (node) {
  26732. node.attr('contenteditable', node.attr(internalContentEditableAttr));
  26733. });
  26734. }
  26735. });
  26736. editor.serializer.addTempAttr(internalContentEditableAttr);
  26737. };
  26738. var registerReadOnlyContentFilters = function (editor) {
  26739. if (editor.serializer) {
  26740. registerFilters(editor);
  26741. } else {
  26742. editor.on('PreInit', function () {
  26743. registerFilters(editor);
  26744. });
  26745. }
  26746. };
  26747. var isClickEvent = function (e) {
  26748. return e.type === 'click';
  26749. };
  26750. var isInAnchor = function (editor, target) {
  26751. return editor.dom.getParent(target, 'a') !== null;
  26752. };
  26753. var preventReadOnlyEvents = function (editor, e) {
  26754. var target = e.target;
  26755. if (isClickEvent(e) && !VK.metaKeyPressed(e) && isInAnchor(editor, target)) {
  26756. e.preventDefault();
  26757. }
  26758. };
  26759. var registerReadOnlySelectionBlockers = function (editor) {
  26760. editor.on('ShowCaret', function (e) {
  26761. if (isReadOnly$1(editor)) {
  26762. e.preventDefault();
  26763. }
  26764. });
  26765. editor.on('ObjectSelected', function (e) {
  26766. if (isReadOnly$1(editor)) {
  26767. e.preventDefault();
  26768. }
  26769. });
  26770. };
  26771. var nativeEvents = Tools.makeMap('focus blur focusin focusout click dblclick mousedown mouseup mousemove mouseover beforepaste paste cut copy selectionchange ' + 'mouseout mouseenter mouseleave wheel keydown keypress keyup input beforeinput contextmenu dragstart dragend dragover ' + 'draggesture dragdrop drop drag submit ' + 'compositionstart compositionend compositionupdate touchstart touchmove touchend touchcancel', ' ');
  26772. var EventDispatcher = function () {
  26773. function EventDispatcher(settings) {
  26774. this.bindings = {};
  26775. this.settings = settings || {};
  26776. this.scope = this.settings.scope || this;
  26777. this.toggleEvent = this.settings.toggleEvent || never;
  26778. }
  26779. EventDispatcher.isNative = function (name) {
  26780. return !!nativeEvents[name.toLowerCase()];
  26781. };
  26782. EventDispatcher.prototype.fire = function (nameIn, argsIn) {
  26783. var name = nameIn.toLowerCase();
  26784. var args = argsIn || {};
  26785. args.type = name;
  26786. if (!args.target) {
  26787. args.target = this.scope;
  26788. }
  26789. if (!args.preventDefault) {
  26790. args.preventDefault = function () {
  26791. args.isDefaultPrevented = always;
  26792. };
  26793. args.stopPropagation = function () {
  26794. args.isPropagationStopped = always;
  26795. };
  26796. args.stopImmediatePropagation = function () {
  26797. args.isImmediatePropagationStopped = always;
  26798. };
  26799. args.isDefaultPrevented = never;
  26800. args.isPropagationStopped = never;
  26801. args.isImmediatePropagationStopped = never;
  26802. }
  26803. if (this.settings.beforeFire) {
  26804. this.settings.beforeFire(args);
  26805. }
  26806. var handlers = this.bindings[name];
  26807. if (handlers) {
  26808. for (var i = 0, l = handlers.length; i < l; i++) {
  26809. var callback = handlers[i];
  26810. if (callback.once) {
  26811. this.off(name, callback.func);
  26812. }
  26813. if (args.isImmediatePropagationStopped()) {
  26814. args.stopPropagation();
  26815. return args;
  26816. }
  26817. if (callback.func.call(this.scope, args) === false) {
  26818. args.preventDefault();
  26819. return args;
  26820. }
  26821. }
  26822. }
  26823. return args;
  26824. };
  26825. EventDispatcher.prototype.on = function (name, callback, prepend, extra) {
  26826. if (callback === false) {
  26827. callback = never;
  26828. }
  26829. if (callback) {
  26830. var wrappedCallback = { func: callback };
  26831. if (extra) {
  26832. Tools.extend(wrappedCallback, extra);
  26833. }
  26834. var names = name.toLowerCase().split(' ');
  26835. var i = names.length;
  26836. while (i--) {
  26837. var currentName = names[i];
  26838. var handlers = this.bindings[currentName];
  26839. if (!handlers) {
  26840. handlers = this.bindings[currentName] = [];
  26841. this.toggleEvent(currentName, true);
  26842. }
  26843. if (prepend) {
  26844. handlers.unshift(wrappedCallback);
  26845. } else {
  26846. handlers.push(wrappedCallback);
  26847. }
  26848. }
  26849. }
  26850. return this;
  26851. };
  26852. EventDispatcher.prototype.off = function (name, callback) {
  26853. var _this = this;
  26854. if (name) {
  26855. var names = name.toLowerCase().split(' ');
  26856. var i = names.length;
  26857. while (i--) {
  26858. var currentName = names[i];
  26859. var handlers = this.bindings[currentName];
  26860. if (!currentName) {
  26861. each$1(this.bindings, function (_value, bindingName) {
  26862. _this.toggleEvent(bindingName, false);
  26863. delete _this.bindings[bindingName];
  26864. });
  26865. return this;
  26866. }
  26867. if (handlers) {
  26868. if (!callback) {
  26869. handlers.length = 0;
  26870. } else {
  26871. var hi = handlers.length;
  26872. while (hi--) {
  26873. if (handlers[hi].func === callback) {
  26874. handlers = handlers.slice(0, hi).concat(handlers.slice(hi + 1));
  26875. this.bindings[currentName] = handlers;
  26876. }
  26877. }
  26878. }
  26879. if (!handlers.length) {
  26880. this.toggleEvent(name, false);
  26881. delete this.bindings[currentName];
  26882. }
  26883. }
  26884. }
  26885. } else {
  26886. each$1(this.bindings, function (_value, name) {
  26887. _this.toggleEvent(name, false);
  26888. });
  26889. this.bindings = {};
  26890. }
  26891. return this;
  26892. };
  26893. EventDispatcher.prototype.once = function (name, callback, prepend) {
  26894. return this.on(name, callback, prepend, { once: true });
  26895. };
  26896. EventDispatcher.prototype.has = function (name) {
  26897. name = name.toLowerCase();
  26898. return !(!this.bindings[name] || this.bindings[name].length === 0);
  26899. };
  26900. return EventDispatcher;
  26901. }();
  26902. var getEventDispatcher = function (obj) {
  26903. if (!obj._eventDispatcher) {
  26904. obj._eventDispatcher = new EventDispatcher({
  26905. scope: obj,
  26906. toggleEvent: function (name, state) {
  26907. if (EventDispatcher.isNative(name) && obj.toggleNativeEvent) {
  26908. obj.toggleNativeEvent(name, state);
  26909. }
  26910. }
  26911. });
  26912. }
  26913. return obj._eventDispatcher;
  26914. };
  26915. var Observable = {
  26916. fire: function (name, args, bubble) {
  26917. var self = this;
  26918. if (self.removed && name !== 'remove' && name !== 'detach') {
  26919. return args;
  26920. }
  26921. var dispatcherArgs = getEventDispatcher(self).fire(name, args);
  26922. if (bubble !== false && self.parent) {
  26923. var parent_1 = self.parent();
  26924. while (parent_1 && !dispatcherArgs.isPropagationStopped()) {
  26925. parent_1.fire(name, dispatcherArgs, false);
  26926. parent_1 = parent_1.parent();
  26927. }
  26928. }
  26929. return dispatcherArgs;
  26930. },
  26931. on: function (name, callback, prepend) {
  26932. return getEventDispatcher(this).on(name, callback, prepend);
  26933. },
  26934. off: function (name, callback) {
  26935. return getEventDispatcher(this).off(name, callback);
  26936. },
  26937. once: function (name, callback) {
  26938. return getEventDispatcher(this).once(name, callback);
  26939. },
  26940. hasEventListeners: function (name) {
  26941. return getEventDispatcher(this).has(name);
  26942. }
  26943. };
  26944. var DOM$8 = DOMUtils$1.DOM;
  26945. var customEventRootDelegates;
  26946. var getEventTarget = function (editor, eventName) {
  26947. if (eventName === 'selectionchange') {
  26948. return editor.getDoc();
  26949. }
  26950. if (!editor.inline && /^mouse|touch|click|contextmenu|drop|dragover|dragend/.test(eventName)) {
  26951. return editor.getDoc().documentElement;
  26952. }
  26953. var eventRoot = getEventRoot(editor);
  26954. if (eventRoot) {
  26955. if (!editor.eventRoot) {
  26956. editor.eventRoot = DOM$8.select(eventRoot)[0];
  26957. }
  26958. return editor.eventRoot;
  26959. }
  26960. return editor.getBody();
  26961. };
  26962. var isListening = function (editor) {
  26963. return !editor.hidden && !isReadOnly$1(editor);
  26964. };
  26965. var fireEvent = function (editor, eventName, e) {
  26966. if (isListening(editor)) {
  26967. editor.fire(eventName, e);
  26968. } else if (isReadOnly$1(editor)) {
  26969. preventReadOnlyEvents(editor, e);
  26970. }
  26971. };
  26972. var bindEventDelegate = function (editor, eventName) {
  26973. var delegate;
  26974. if (!editor.delegates) {
  26975. editor.delegates = {};
  26976. }
  26977. if (editor.delegates[eventName] || editor.removed) {
  26978. return;
  26979. }
  26980. var eventRootElm = getEventTarget(editor, eventName);
  26981. if (getEventRoot(editor)) {
  26982. if (!customEventRootDelegates) {
  26983. customEventRootDelegates = {};
  26984. editor.editorManager.on('removeEditor', function () {
  26985. if (!editor.editorManager.activeEditor) {
  26986. if (customEventRootDelegates) {
  26987. each$1(customEventRootDelegates, function (_value, name) {
  26988. editor.dom.unbind(getEventTarget(editor, name));
  26989. });
  26990. customEventRootDelegates = null;
  26991. }
  26992. }
  26993. });
  26994. }
  26995. if (customEventRootDelegates[eventName]) {
  26996. return;
  26997. }
  26998. delegate = function (e) {
  26999. var target = e.target;
  27000. var editors = editor.editorManager.get();
  27001. var i = editors.length;
  27002. while (i--) {
  27003. var body = editors[i].getBody();
  27004. if (body === target || DOM$8.isChildOf(target, body)) {
  27005. fireEvent(editors[i], eventName, e);
  27006. }
  27007. }
  27008. };
  27009. customEventRootDelegates[eventName] = delegate;
  27010. DOM$8.bind(eventRootElm, eventName, delegate);
  27011. } else {
  27012. delegate = function (e) {
  27013. fireEvent(editor, eventName, e);
  27014. };
  27015. DOM$8.bind(eventRootElm, eventName, delegate);
  27016. editor.delegates[eventName] = delegate;
  27017. }
  27018. };
  27019. var EditorObservable = __assign(__assign({}, Observable), {
  27020. bindPendingEventDelegates: function () {
  27021. var self = this;
  27022. Tools.each(self._pendingNativeEvents, function (name) {
  27023. bindEventDelegate(self, name);
  27024. });
  27025. },
  27026. toggleNativeEvent: function (name, state) {
  27027. var self = this;
  27028. if (name === 'focus' || name === 'blur') {
  27029. return;
  27030. }
  27031. if (state) {
  27032. if (self.initialized) {
  27033. bindEventDelegate(self, name);
  27034. } else {
  27035. if (!self._pendingNativeEvents) {
  27036. self._pendingNativeEvents = [name];
  27037. } else {
  27038. self._pendingNativeEvents.push(name);
  27039. }
  27040. }
  27041. } else if (self.initialized) {
  27042. self.dom.unbind(getEventTarget(self, name), name, self.delegates[name]);
  27043. delete self.delegates[name];
  27044. }
  27045. },
  27046. unbindAllNativeEvents: function () {
  27047. var self = this;
  27048. var body = self.getBody();
  27049. var dom = self.dom;
  27050. if (self.delegates) {
  27051. each$1(self.delegates, function (value, name) {
  27052. self.dom.unbind(getEventTarget(self, name), name, value);
  27053. });
  27054. delete self.delegates;
  27055. }
  27056. if (!self.inline && body && dom) {
  27057. body.onload = null;
  27058. dom.unbind(self.getWin());
  27059. dom.unbind(self.getDoc());
  27060. }
  27061. if (dom) {
  27062. dom.unbind(body);
  27063. dom.unbind(self.getContainer());
  27064. }
  27065. }
  27066. });
  27067. var defaultModes = [
  27068. 'design',
  27069. 'readonly'
  27070. ];
  27071. var switchToMode = function (editor, activeMode, availableModes, mode) {
  27072. var oldMode = availableModes[activeMode.get()];
  27073. var newMode = availableModes[mode];
  27074. try {
  27075. newMode.activate();
  27076. } catch (e) {
  27077. console.error('problem while activating editor mode ' + mode + ':', e);
  27078. return;
  27079. }
  27080. oldMode.deactivate();
  27081. if (oldMode.editorReadOnly !== newMode.editorReadOnly) {
  27082. toggleReadOnly(editor, newMode.editorReadOnly);
  27083. }
  27084. activeMode.set(mode);
  27085. fireSwitchMode(editor, mode);
  27086. };
  27087. var setMode = function (editor, availableModes, activeMode, mode) {
  27088. if (mode === activeMode.get()) {
  27089. return;
  27090. } else if (!has(availableModes, mode)) {
  27091. throw new Error('Editor mode \'' + mode + '\' is invalid');
  27092. }
  27093. if (editor.initialized) {
  27094. switchToMode(editor, activeMode, availableModes, mode);
  27095. } else {
  27096. editor.on('init', function () {
  27097. return switchToMode(editor, activeMode, availableModes, mode);
  27098. });
  27099. }
  27100. };
  27101. var registerMode = function (availableModes, mode, api) {
  27102. var _a;
  27103. if (contains(defaultModes, mode)) {
  27104. throw new Error('Cannot override default mode ' + mode);
  27105. }
  27106. return __assign(__assign({}, availableModes), (_a = {}, _a[mode] = __assign(__assign({}, api), {
  27107. deactivate: function () {
  27108. try {
  27109. api.deactivate();
  27110. } catch (e) {
  27111. console.error('problem while deactivating editor mode ' + mode + ':', e);
  27112. }
  27113. }
  27114. }), _a));
  27115. };
  27116. var create$5 = function (editor) {
  27117. var activeMode = Cell('design');
  27118. var availableModes = Cell({
  27119. design: {
  27120. activate: noop,
  27121. deactivate: noop,
  27122. editorReadOnly: false
  27123. },
  27124. readonly: {
  27125. activate: noop,
  27126. deactivate: noop,
  27127. editorReadOnly: true
  27128. }
  27129. });
  27130. registerReadOnlyContentFilters(editor);
  27131. registerReadOnlySelectionBlockers(editor);
  27132. return {
  27133. isReadOnly: function () {
  27134. return isReadOnly$1(editor);
  27135. },
  27136. set: function (mode) {
  27137. return setMode(editor, availableModes.get(), activeMode, mode);
  27138. },
  27139. get: function () {
  27140. return activeMode.get();
  27141. },
  27142. register: function (mode, api) {
  27143. availableModes.set(registerMode(availableModes.get(), mode, api));
  27144. }
  27145. };
  27146. };
  27147. var each$g = Tools.each, explode$3 = Tools.explode;
  27148. var keyCodeLookup = {
  27149. f1: 112,
  27150. f2: 113,
  27151. f3: 114,
  27152. f4: 115,
  27153. f5: 116,
  27154. f6: 117,
  27155. f7: 118,
  27156. f8: 119,
  27157. f9: 120,
  27158. f10: 121,
  27159. f11: 122,
  27160. f12: 123
  27161. };
  27162. var modifierNames = Tools.makeMap('alt,ctrl,shift,meta,access');
  27163. var Shortcuts = function () {
  27164. function Shortcuts(editor) {
  27165. this.shortcuts = {};
  27166. this.pendingPatterns = [];
  27167. this.editor = editor;
  27168. var self = this;
  27169. editor.on('keyup keypress keydown', function (e) {
  27170. if ((self.hasModifier(e) || self.isFunctionKey(e)) && !e.isDefaultPrevented()) {
  27171. each$g(self.shortcuts, function (shortcut) {
  27172. if (self.matchShortcut(e, shortcut)) {
  27173. self.pendingPatterns = shortcut.subpatterns.slice(0);
  27174. if (e.type === 'keydown') {
  27175. self.executeShortcutAction(shortcut);
  27176. }
  27177. return true;
  27178. }
  27179. });
  27180. if (self.matchShortcut(e, self.pendingPatterns[0])) {
  27181. if (self.pendingPatterns.length === 1) {
  27182. if (e.type === 'keydown') {
  27183. self.executeShortcutAction(self.pendingPatterns[0]);
  27184. }
  27185. }
  27186. self.pendingPatterns.shift();
  27187. }
  27188. }
  27189. });
  27190. }
  27191. Shortcuts.prototype.add = function (pattern, desc, cmdFunc, scope) {
  27192. var self = this;
  27193. var func = self.normalizeCommandFunc(cmdFunc);
  27194. each$g(explode$3(Tools.trim(pattern)), function (pattern) {
  27195. var shortcut = self.createShortcut(pattern, desc, func, scope);
  27196. self.shortcuts[shortcut.id] = shortcut;
  27197. });
  27198. return true;
  27199. };
  27200. Shortcuts.prototype.remove = function (pattern) {
  27201. var shortcut = this.createShortcut(pattern);
  27202. if (this.shortcuts[shortcut.id]) {
  27203. delete this.shortcuts[shortcut.id];
  27204. return true;
  27205. }
  27206. return false;
  27207. };
  27208. Shortcuts.prototype.normalizeCommandFunc = function (cmdFunc) {
  27209. var self = this;
  27210. var cmd = cmdFunc;
  27211. if (typeof cmd === 'string') {
  27212. return function () {
  27213. self.editor.execCommand(cmd, false, null);
  27214. };
  27215. } else if (Tools.isArray(cmd)) {
  27216. return function () {
  27217. self.editor.execCommand(cmd[0], cmd[1], cmd[2]);
  27218. };
  27219. } else {
  27220. return cmd;
  27221. }
  27222. };
  27223. Shortcuts.prototype.parseShortcut = function (pattern) {
  27224. var key;
  27225. var shortcut = {};
  27226. each$g(explode$3(pattern.toLowerCase(), '+'), function (value) {
  27227. if (value in modifierNames) {
  27228. shortcut[value] = true;
  27229. } else {
  27230. if (/^[0-9]{2,}$/.test(value)) {
  27231. shortcut.keyCode = parseInt(value, 10);
  27232. } else {
  27233. shortcut.charCode = value.charCodeAt(0);
  27234. shortcut.keyCode = keyCodeLookup[value] || value.toUpperCase().charCodeAt(0);
  27235. }
  27236. }
  27237. });
  27238. var id = [shortcut.keyCode];
  27239. for (key in modifierNames) {
  27240. if (shortcut[key]) {
  27241. id.push(key);
  27242. } else {
  27243. shortcut[key] = false;
  27244. }
  27245. }
  27246. shortcut.id = id.join(',');
  27247. if (shortcut.access) {
  27248. shortcut.alt = true;
  27249. if (Env.mac) {
  27250. shortcut.ctrl = true;
  27251. } else {
  27252. shortcut.shift = true;
  27253. }
  27254. }
  27255. if (shortcut.meta) {
  27256. if (Env.mac) {
  27257. shortcut.meta = true;
  27258. } else {
  27259. shortcut.ctrl = true;
  27260. shortcut.meta = false;
  27261. }
  27262. }
  27263. return shortcut;
  27264. };
  27265. Shortcuts.prototype.createShortcut = function (pattern, desc, cmdFunc, scope) {
  27266. var shortcuts = Tools.map(explode$3(pattern, '>'), this.parseShortcut);
  27267. shortcuts[shortcuts.length - 1] = Tools.extend(shortcuts[shortcuts.length - 1], {
  27268. func: cmdFunc,
  27269. scope: scope || this.editor
  27270. });
  27271. return Tools.extend(shortcuts[0], {
  27272. desc: this.editor.translate(desc),
  27273. subpatterns: shortcuts.slice(1)
  27274. });
  27275. };
  27276. Shortcuts.prototype.hasModifier = function (e) {
  27277. return e.altKey || e.ctrlKey || e.metaKey;
  27278. };
  27279. Shortcuts.prototype.isFunctionKey = function (e) {
  27280. return e.type === 'keydown' && e.keyCode >= 112 && e.keyCode <= 123;
  27281. };
  27282. Shortcuts.prototype.matchShortcut = function (e, shortcut) {
  27283. if (!shortcut) {
  27284. return false;
  27285. }
  27286. if (shortcut.ctrl !== e.ctrlKey || shortcut.meta !== e.metaKey) {
  27287. return false;
  27288. }
  27289. if (shortcut.alt !== e.altKey || shortcut.shift !== e.shiftKey) {
  27290. return false;
  27291. }
  27292. if (e.keyCode === shortcut.keyCode || e.charCode && e.charCode === shortcut.charCode) {
  27293. e.preventDefault();
  27294. return true;
  27295. }
  27296. return false;
  27297. };
  27298. Shortcuts.prototype.executeShortcutAction = function (shortcut) {
  27299. return shortcut.func ? shortcut.func.call(shortcut.scope) : null;
  27300. };
  27301. return Shortcuts;
  27302. }();
  27303. var create$6 = function () {
  27304. var buttons = {};
  27305. var menuItems = {};
  27306. var popups = {};
  27307. var icons = {};
  27308. var contextMenus = {};
  27309. var contextToolbars = {};
  27310. var sidebars = {};
  27311. var add = function (collection, type) {
  27312. return function (name, spec) {
  27313. return collection[name.toLowerCase()] = __assign(__assign({}, spec), { type: type });
  27314. };
  27315. };
  27316. var addIcon = function (name, svgData) {
  27317. return icons[name.toLowerCase()] = svgData;
  27318. };
  27319. return {
  27320. addButton: add(buttons, 'button'),
  27321. addGroupToolbarButton: add(buttons, 'grouptoolbarbutton'),
  27322. addToggleButton: add(buttons, 'togglebutton'),
  27323. addMenuButton: add(buttons, 'menubutton'),
  27324. addSplitButton: add(buttons, 'splitbutton'),
  27325. addMenuItem: add(menuItems, 'menuitem'),
  27326. addNestedMenuItem: add(menuItems, 'nestedmenuitem'),
  27327. addToggleMenuItem: add(menuItems, 'togglemenuitem'),
  27328. addAutocompleter: add(popups, 'autocompleter'),
  27329. addContextMenu: add(contextMenus, 'contextmenu'),
  27330. addContextToolbar: add(contextToolbars, 'contexttoolbar'),
  27331. addContextForm: add(contextToolbars, 'contextform'),
  27332. addSidebar: add(sidebars, 'sidebar'),
  27333. addIcon: addIcon,
  27334. getAll: function () {
  27335. return {
  27336. buttons: buttons,
  27337. menuItems: menuItems,
  27338. icons: icons,
  27339. popups: popups,
  27340. contextMenus: contextMenus,
  27341. contextToolbars: contextToolbars,
  27342. sidebars: sidebars
  27343. };
  27344. }
  27345. };
  27346. };
  27347. var registry = function () {
  27348. var bridge = create$6();
  27349. return {
  27350. addAutocompleter: bridge.addAutocompleter,
  27351. addButton: bridge.addButton,
  27352. addContextForm: bridge.addContextForm,
  27353. addContextMenu: bridge.addContextMenu,
  27354. addContextToolbar: bridge.addContextToolbar,
  27355. addIcon: bridge.addIcon,
  27356. addMenuButton: bridge.addMenuButton,
  27357. addMenuItem: bridge.addMenuItem,
  27358. addNestedMenuItem: bridge.addNestedMenuItem,
  27359. addSidebar: bridge.addSidebar,
  27360. addSplitButton: bridge.addSplitButton,
  27361. addToggleButton: bridge.addToggleButton,
  27362. addGroupToolbarButton: bridge.addGroupToolbarButton,
  27363. addToggleMenuItem: bridge.addToggleMenuItem,
  27364. getAll: bridge.getAll
  27365. };
  27366. };
  27367. var each$h = Tools.each, trim$4 = Tools.trim;
  27368. var queryParts = 'source protocol authority userInfo user password host port relative path directory file query anchor'.split(' ');
  27369. var DEFAULT_PORTS = {
  27370. ftp: 21,
  27371. http: 80,
  27372. https: 443,
  27373. mailto: 25
  27374. };
  27375. var URI = function () {
  27376. function URI(url, settings) {
  27377. url = trim$4(url);
  27378. this.settings = settings || {};
  27379. var baseUri = this.settings.base_uri;
  27380. var self = this;
  27381. if (/^([\w\-]+):([^\/]{2})/i.test(url) || /^\s*#/.test(url)) {
  27382. self.source = url;
  27383. return;
  27384. }
  27385. var isProtocolRelative = url.indexOf('//') === 0;
  27386. if (url.indexOf('/') === 0 && !isProtocolRelative) {
  27387. url = (baseUri ? baseUri.protocol || 'http' : 'http') + '://mce_host' + url;
  27388. }
  27389. if (!/^[\w\-]*:?\/\//.test(url)) {
  27390. var baseUrl = this.settings.base_uri ? this.settings.base_uri.path : new URI(document.location.href).directory;
  27391. if (this.settings.base_uri && this.settings.base_uri.protocol == '') {
  27392. url = '//mce_host' + self.toAbsPath(baseUrl, url);
  27393. } else {
  27394. var match = /([^#?]*)([#?]?.*)/.exec(url);
  27395. url = (baseUri && baseUri.protocol || 'http') + '://mce_host' + self.toAbsPath(baseUrl, match[1]) + match[2];
  27396. }
  27397. }
  27398. url = url.replace(/@@/g, '(mce_at)');
  27399. var urlMatch = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@\/]*):?([^:@\/]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/.exec(url);
  27400. each$h(queryParts, function (v, i) {
  27401. var part = urlMatch[i];
  27402. if (part) {
  27403. part = part.replace(/\(mce_at\)/g, '@@');
  27404. }
  27405. self[v] = part;
  27406. });
  27407. if (baseUri) {
  27408. if (!self.protocol) {
  27409. self.protocol = baseUri.protocol;
  27410. }
  27411. if (!self.userInfo) {
  27412. self.userInfo = baseUri.userInfo;
  27413. }
  27414. if (!self.port && self.host === 'mce_host') {
  27415. self.port = baseUri.port;
  27416. }
  27417. if (!self.host || self.host === 'mce_host') {
  27418. self.host = baseUri.host;
  27419. }
  27420. self.source = '';
  27421. }
  27422. if (isProtocolRelative) {
  27423. self.protocol = '';
  27424. }
  27425. }
  27426. URI.parseDataUri = function (uri) {
  27427. var type;
  27428. var uriComponents = decodeURIComponent(uri).split(',');
  27429. var matches = /data:([^;]+)/.exec(uriComponents[0]);
  27430. if (matches) {
  27431. type = matches[1];
  27432. }
  27433. return {
  27434. type: type,
  27435. data: uriComponents[1]
  27436. };
  27437. };
  27438. URI.getDocumentBaseUrl = function (loc) {
  27439. var baseUrl;
  27440. if (loc.protocol.indexOf('http') !== 0 && loc.protocol !== 'file:') {
  27441. baseUrl = loc.href;
  27442. } else {
  27443. baseUrl = loc.protocol + '//' + loc.host + loc.pathname;
  27444. }
  27445. if (/^[^:]+:\/\/\/?[^\/]+\//.test(baseUrl)) {
  27446. baseUrl = baseUrl.replace(/[\?#].*$/, '').replace(/[\/\\][^\/]+$/, '');
  27447. if (!/[\/\\]$/.test(baseUrl)) {
  27448. baseUrl += '/';
  27449. }
  27450. }
  27451. return baseUrl;
  27452. };
  27453. URI.prototype.setPath = function (path) {
  27454. var pathMatch = /^(.*?)\/?(\w+)?$/.exec(path);
  27455. this.path = pathMatch[0];
  27456. this.directory = pathMatch[1];
  27457. this.file = pathMatch[2];
  27458. this.source = '';
  27459. this.getURI();
  27460. };
  27461. URI.prototype.toRelative = function (uri) {
  27462. var output;
  27463. if (uri === './') {
  27464. return uri;
  27465. }
  27466. var relativeUri = new URI(uri, { base_uri: this });
  27467. if (relativeUri.host !== 'mce_host' && this.host !== relativeUri.host && relativeUri.host || this.port !== relativeUri.port || this.protocol !== relativeUri.protocol && relativeUri.protocol !== '') {
  27468. return relativeUri.getURI();
  27469. }
  27470. var tu = this.getURI(), uu = relativeUri.getURI();
  27471. if (tu === uu || tu.charAt(tu.length - 1) === '/' && tu.substr(0, tu.length - 1) === uu) {
  27472. return tu;
  27473. }
  27474. output = this.toRelPath(this.path, relativeUri.path);
  27475. if (relativeUri.query) {
  27476. output += '?' + relativeUri.query;
  27477. }
  27478. if (relativeUri.anchor) {
  27479. output += '#' + relativeUri.anchor;
  27480. }
  27481. return output;
  27482. };
  27483. URI.prototype.toAbsolute = function (uri, noHost) {
  27484. var absoluteUri = new URI(uri, { base_uri: this });
  27485. return absoluteUri.getURI(noHost && this.isSameOrigin(absoluteUri));
  27486. };
  27487. URI.prototype.isSameOrigin = function (uri) {
  27488. if (this.host == uri.host && this.protocol == uri.protocol) {
  27489. if (this.port == uri.port) {
  27490. return true;
  27491. }
  27492. var defaultPort = DEFAULT_PORTS[this.protocol];
  27493. if (defaultPort && (this.port || defaultPort) == (uri.port || defaultPort)) {
  27494. return true;
  27495. }
  27496. }
  27497. return false;
  27498. };
  27499. URI.prototype.toRelPath = function (base, path) {
  27500. var breakPoint = 0, out = '', i, l;
  27501. var normalizedBase = base.substring(0, base.lastIndexOf('/')).split('/');
  27502. var items = path.split('/');
  27503. if (normalizedBase.length >= items.length) {
  27504. for (i = 0, l = normalizedBase.length; i < l; i++) {
  27505. if (i >= items.length || normalizedBase[i] !== items[i]) {
  27506. breakPoint = i + 1;
  27507. break;
  27508. }
  27509. }
  27510. }
  27511. if (normalizedBase.length < items.length) {
  27512. for (i = 0, l = items.length; i < l; i++) {
  27513. if (i >= normalizedBase.length || normalizedBase[i] !== items[i]) {
  27514. breakPoint = i + 1;
  27515. break;
  27516. }
  27517. }
  27518. }
  27519. if (breakPoint === 1) {
  27520. return path;
  27521. }
  27522. for (i = 0, l = normalizedBase.length - (breakPoint - 1); i < l; i++) {
  27523. out += '../';
  27524. }
  27525. for (i = breakPoint - 1, l = items.length; i < l; i++) {
  27526. if (i !== breakPoint - 1) {
  27527. out += '/' + items[i];
  27528. } else {
  27529. out += items[i];
  27530. }
  27531. }
  27532. return out;
  27533. };
  27534. URI.prototype.toAbsPath = function (base, path) {
  27535. var i, nb = 0, o = [], outPath;
  27536. var tr = /\/$/.test(path) ? '/' : '';
  27537. var normalizedBase = base.split('/');
  27538. var normalizedPath = path.split('/');
  27539. each$h(normalizedBase, function (k) {
  27540. if (k) {
  27541. o.push(k);
  27542. }
  27543. });
  27544. normalizedBase = o;
  27545. for (i = normalizedPath.length - 1, o = []; i >= 0; i--) {
  27546. if (normalizedPath[i].length === 0 || normalizedPath[i] === '.') {
  27547. continue;
  27548. }
  27549. if (normalizedPath[i] === '..') {
  27550. nb++;
  27551. continue;
  27552. }
  27553. if (nb > 0) {
  27554. nb--;
  27555. continue;
  27556. }
  27557. o.push(normalizedPath[i]);
  27558. }
  27559. i = normalizedBase.length - nb;
  27560. if (i <= 0) {
  27561. outPath = reverse(o).join('/');
  27562. } else {
  27563. outPath = normalizedBase.slice(0, i).join('/') + '/' + reverse(o).join('/');
  27564. }
  27565. if (outPath.indexOf('/') !== 0) {
  27566. outPath = '/' + outPath;
  27567. }
  27568. if (tr && outPath.lastIndexOf('/') !== outPath.length - 1) {
  27569. outPath += tr;
  27570. }
  27571. return outPath;
  27572. };
  27573. URI.prototype.getURI = function (noProtoHost) {
  27574. if (noProtoHost === void 0) {
  27575. noProtoHost = false;
  27576. }
  27577. var s;
  27578. if (!this.source || noProtoHost) {
  27579. s = '';
  27580. if (!noProtoHost) {
  27581. if (this.protocol) {
  27582. s += this.protocol + '://';
  27583. } else {
  27584. s += '//';
  27585. }
  27586. if (this.userInfo) {
  27587. s += this.userInfo + '@';
  27588. }
  27589. if (this.host) {
  27590. s += this.host;
  27591. }
  27592. if (this.port) {
  27593. s += ':' + this.port;
  27594. }
  27595. }
  27596. if (this.path) {
  27597. s += this.path;
  27598. }
  27599. if (this.query) {
  27600. s += '?' + this.query;
  27601. }
  27602. if (this.anchor) {
  27603. s += '#' + this.anchor;
  27604. }
  27605. this.source = s;
  27606. }
  27607. return this.source;
  27608. };
  27609. return URI;
  27610. }();
  27611. var DOM$9 = DOMUtils$1.DOM;
  27612. var extend$3 = Tools.extend, each$i = Tools.each;
  27613. var resolve$3 = Tools.resolve;
  27614. var ie$1 = Env.ie;
  27615. var Editor = function () {
  27616. function Editor(id, settings, editorManager) {
  27617. var _this = this;
  27618. this.plugins = {};
  27619. this.contentCSS = [];
  27620. this.contentStyles = [];
  27621. this.loadedCSS = {};
  27622. this.isNotDirty = false;
  27623. this.editorManager = editorManager;
  27624. this.documentBaseUrl = editorManager.documentBaseURL;
  27625. extend$3(this, EditorObservable);
  27626. this.settings = getEditorSettings(this, id, this.documentBaseUrl, editorManager.defaultSettings, settings);
  27627. if (this.settings.suffix) {
  27628. editorManager.suffix = this.settings.suffix;
  27629. }
  27630. this.suffix = editorManager.suffix;
  27631. if (this.settings.base_url) {
  27632. editorManager._setBaseUrl(this.settings.base_url);
  27633. }
  27634. this.baseUri = editorManager.baseURI;
  27635. if (this.settings.referrer_policy) {
  27636. ScriptLoader.ScriptLoader._setReferrerPolicy(this.settings.referrer_policy);
  27637. DOMUtils$1.DOM.styleSheetLoader._setReferrerPolicy(this.settings.referrer_policy);
  27638. }
  27639. AddOnManager$1.languageLoad = this.settings.language_load;
  27640. AddOnManager$1.baseURL = editorManager.baseURL;
  27641. this.id = id;
  27642. this.setDirty(false);
  27643. this.documentBaseURI = new URI(this.settings.document_base_url, { base_uri: this.baseUri });
  27644. this.baseURI = this.baseUri;
  27645. this.inline = !!this.settings.inline;
  27646. this.shortcuts = new Shortcuts(this);
  27647. this.editorCommands = new EditorCommands(this);
  27648. if (this.settings.cache_suffix) {
  27649. Env.cacheSuffix = this.settings.cache_suffix.replace(/^[\?\&]+/, '');
  27650. }
  27651. this.ui = {
  27652. registry: registry(),
  27653. styleSheetLoader: undefined,
  27654. show: noop,
  27655. hide: noop
  27656. };
  27657. var self = this;
  27658. var modeInstance = create$5(self);
  27659. this.mode = modeInstance;
  27660. this.setMode = modeInstance.set;
  27661. editorManager.fire('SetupEditor', { editor: this });
  27662. this.execCallback('setup', this);
  27663. this.$ = DomQuery.overrideDefaults(function () {
  27664. return {
  27665. context: _this.inline ? _this.getBody() : _this.getDoc(),
  27666. element: _this.getBody()
  27667. };
  27668. });
  27669. }
  27670. Editor.prototype.render = function () {
  27671. render(this);
  27672. };
  27673. Editor.prototype.focus = function (skipFocus) {
  27674. focus$1(this, skipFocus);
  27675. };
  27676. Editor.prototype.hasFocus = function () {
  27677. return hasFocus$1(this);
  27678. };
  27679. Editor.prototype.execCallback = function (name) {
  27680. var x = [];
  27681. for (var _i = 1; _i < arguments.length; _i++) {
  27682. x[_i - 1] = arguments[_i];
  27683. }
  27684. var self = this;
  27685. var callback = self.settings[name], scope;
  27686. if (!callback) {
  27687. return;
  27688. }
  27689. if (self.callbackLookup && (scope = self.callbackLookup[name])) {
  27690. callback = scope.func;
  27691. scope = scope.scope;
  27692. }
  27693. if (typeof callback === 'string') {
  27694. scope = callback.replace(/\.\w+$/, '');
  27695. scope = scope ? resolve$3(scope) : 0;
  27696. callback = resolve$3(callback);
  27697. self.callbackLookup = self.callbackLookup || {};
  27698. self.callbackLookup[name] = {
  27699. func: callback,
  27700. scope: scope
  27701. };
  27702. }
  27703. return callback.apply(scope || self, x);
  27704. };
  27705. Editor.prototype.translate = function (text) {
  27706. return I18n.translate(text);
  27707. };
  27708. Editor.prototype.getParam = function (name, defaultVal, type) {
  27709. return getParam(this, name, defaultVal, type);
  27710. };
  27711. Editor.prototype.hasPlugin = function (name, loaded) {
  27712. var hasPlugin = contains(getPlugins(this).split(/[ ,]/), name);
  27713. if (hasPlugin) {
  27714. return loaded ? PluginManager.get(name) !== undefined : true;
  27715. } else {
  27716. return false;
  27717. }
  27718. };
  27719. Editor.prototype.nodeChanged = function (args) {
  27720. this._nodeChangeDispatcher.nodeChanged(args);
  27721. };
  27722. Editor.prototype.addCommand = function (name, callback, scope) {
  27723. this.editorCommands.addCommand(name, callback, scope);
  27724. };
  27725. Editor.prototype.addQueryStateHandler = function (name, callback, scope) {
  27726. this.editorCommands.addQueryStateHandler(name, callback, scope);
  27727. };
  27728. Editor.prototype.addQueryValueHandler = function (name, callback, scope) {
  27729. this.editorCommands.addQueryValueHandler(name, callback, scope);
  27730. };
  27731. Editor.prototype.addShortcut = function (pattern, desc, cmdFunc, scope) {
  27732. this.shortcuts.add(pattern, desc, cmdFunc, scope);
  27733. };
  27734. Editor.prototype.execCommand = function (cmd, ui, value, args) {
  27735. return this.editorCommands.execCommand(cmd, ui, value, args);
  27736. };
  27737. Editor.prototype.queryCommandState = function (cmd) {
  27738. return this.editorCommands.queryCommandState(cmd);
  27739. };
  27740. Editor.prototype.queryCommandValue = function (cmd) {
  27741. return this.editorCommands.queryCommandValue(cmd);
  27742. };
  27743. Editor.prototype.queryCommandSupported = function (cmd) {
  27744. return this.editorCommands.queryCommandSupported(cmd);
  27745. };
  27746. Editor.prototype.show = function () {
  27747. var self = this;
  27748. if (self.hidden) {
  27749. self.hidden = false;
  27750. if (self.inline) {
  27751. self.getBody().contentEditable = 'true';
  27752. } else {
  27753. DOM$9.show(self.getContainer());
  27754. DOM$9.hide(self.id);
  27755. }
  27756. self.load();
  27757. self.fire('show');
  27758. }
  27759. };
  27760. Editor.prototype.hide = function () {
  27761. var self = this, doc = self.getDoc();
  27762. if (!self.hidden) {
  27763. if (ie$1 && doc && !self.inline) {
  27764. doc.execCommand('SelectAll');
  27765. }
  27766. self.save();
  27767. if (self.inline) {
  27768. self.getBody().contentEditable = 'false';
  27769. if (self === self.editorManager.focusedEditor) {
  27770. self.editorManager.focusedEditor = null;
  27771. }
  27772. } else {
  27773. DOM$9.hide(self.getContainer());
  27774. DOM$9.setStyle(self.id, 'display', self.orgDisplay);
  27775. }
  27776. self.hidden = true;
  27777. self.fire('hide');
  27778. }
  27779. };
  27780. Editor.prototype.isHidden = function () {
  27781. return !!this.hidden;
  27782. };
  27783. Editor.prototype.setProgressState = function (state, time) {
  27784. this.fire('ProgressState', {
  27785. state: state,
  27786. time: time
  27787. });
  27788. };
  27789. Editor.prototype.load = function (args) {
  27790. var self = this;
  27791. var elm = self.getElement(), html;
  27792. if (self.removed) {
  27793. return '';
  27794. }
  27795. if (elm) {
  27796. args = args || {};
  27797. args.load = true;
  27798. var value = isTextareaOrInput(elm) ? elm.value : elm.innerHTML;
  27799. html = self.setContent(value, args);
  27800. args.element = elm;
  27801. if (!args.no_events) {
  27802. self.fire('LoadContent', args);
  27803. }
  27804. args.element = elm = null;
  27805. return html;
  27806. }
  27807. };
  27808. Editor.prototype.save = function (args) {
  27809. var self = this;
  27810. var elm = self.getElement(), html, form;
  27811. if (!elm || !self.initialized || self.removed) {
  27812. return;
  27813. }
  27814. args = args || {};
  27815. args.save = true;
  27816. args.element = elm;
  27817. html = args.content = self.getContent(args);
  27818. if (!args.no_events) {
  27819. self.fire('SaveContent', args);
  27820. }
  27821. if (args.format === 'raw') {
  27822. self.fire('RawSaveContent', args);
  27823. }
  27824. html = args.content;
  27825. if (!isTextareaOrInput(elm)) {
  27826. if (args.is_removing || !self.inline) {
  27827. elm.innerHTML = html;
  27828. }
  27829. if (form = DOM$9.getParent(self.id, 'form')) {
  27830. each$i(form.elements, function (elm) {
  27831. if (elm.name === self.id) {
  27832. elm.value = html;
  27833. return false;
  27834. }
  27835. });
  27836. }
  27837. } else {
  27838. elm.value = html;
  27839. }
  27840. args.element = elm = null;
  27841. if (args.set_dirty !== false) {
  27842. self.setDirty(false);
  27843. }
  27844. return html;
  27845. };
  27846. Editor.prototype.setContent = function (content, args) {
  27847. return setContent$2(this, content, args);
  27848. };
  27849. Editor.prototype.getContent = function (args) {
  27850. return getContent$2(this, args);
  27851. };
  27852. Editor.prototype.insertContent = function (content, args) {
  27853. if (args) {
  27854. content = extend$3({ content: content }, args);
  27855. }
  27856. this.execCommand('mceInsertContent', false, content);
  27857. };
  27858. Editor.prototype.resetContent = function (initialContent) {
  27859. if (initialContent === undefined) {
  27860. setContent$2(this, this.startContent, { format: 'raw' });
  27861. } else {
  27862. setContent$2(this, initialContent);
  27863. }
  27864. this.undoManager.reset();
  27865. this.setDirty(false);
  27866. this.nodeChanged();
  27867. };
  27868. Editor.prototype.isDirty = function () {
  27869. return !this.isNotDirty;
  27870. };
  27871. Editor.prototype.setDirty = function (state) {
  27872. var oldState = !this.isNotDirty;
  27873. this.isNotDirty = !state;
  27874. if (state && state !== oldState) {
  27875. this.fire('dirty');
  27876. }
  27877. };
  27878. Editor.prototype.getContainer = function () {
  27879. var self = this;
  27880. if (!self.container) {
  27881. self.container = DOM$9.get(self.editorContainer || self.id + '_parent');
  27882. }
  27883. return self.container;
  27884. };
  27885. Editor.prototype.getContentAreaContainer = function () {
  27886. return this.contentAreaContainer;
  27887. };
  27888. Editor.prototype.getElement = function () {
  27889. if (!this.targetElm) {
  27890. this.targetElm = DOM$9.get(this.id);
  27891. }
  27892. return this.targetElm;
  27893. };
  27894. Editor.prototype.getWin = function () {
  27895. var self = this;
  27896. var elm;
  27897. if (!self.contentWindow) {
  27898. elm = self.iframeElement;
  27899. if (elm) {
  27900. self.contentWindow = elm.contentWindow;
  27901. }
  27902. }
  27903. return self.contentWindow;
  27904. };
  27905. Editor.prototype.getDoc = function () {
  27906. var self = this;
  27907. var win;
  27908. if (!self.contentDocument) {
  27909. win = self.getWin();
  27910. if (win) {
  27911. self.contentDocument = win.document;
  27912. }
  27913. }
  27914. return self.contentDocument;
  27915. };
  27916. Editor.prototype.getBody = function () {
  27917. var doc = this.getDoc();
  27918. return this.bodyElement || (doc ? doc.body : null);
  27919. };
  27920. Editor.prototype.convertURL = function (url, name, elm) {
  27921. var self = this, settings = self.settings;
  27922. if (settings.urlconverter_callback) {
  27923. return self.execCallback('urlconverter_callback', url, elm, true, name);
  27924. }
  27925. if (!settings.convert_urls || elm && elm.nodeName === 'LINK' || url.indexOf('file:') === 0 || url.length === 0) {
  27926. return url;
  27927. }
  27928. if (settings.relative_urls) {
  27929. return self.documentBaseURI.toRelative(url);
  27930. }
  27931. url = self.documentBaseURI.toAbsolute(url, settings.remove_script_host);
  27932. return url;
  27933. };
  27934. Editor.prototype.addVisual = function (elm) {
  27935. var self = this;
  27936. var settings = self.settings;
  27937. var dom = self.dom;
  27938. var cls;
  27939. elm = elm || self.getBody();
  27940. if (self.hasVisual === undefined) {
  27941. self.hasVisual = settings.visual;
  27942. }
  27943. each$i(dom.select('table,a', elm), function (elm) {
  27944. var value;
  27945. switch (elm.nodeName) {
  27946. case 'TABLE':
  27947. cls = settings.visual_table_class || 'mce-item-table';
  27948. value = dom.getAttrib(elm, 'border');
  27949. if ((!value || value === '0') && self.hasVisual) {
  27950. dom.addClass(elm, cls);
  27951. } else {
  27952. dom.removeClass(elm, cls);
  27953. }
  27954. return;
  27955. case 'A':
  27956. if (!dom.getAttrib(elm, 'href')) {
  27957. value = dom.getAttrib(elm, 'name') || elm.id;
  27958. cls = settings.visual_anchor_class || 'mce-item-anchor';
  27959. if (value && self.hasVisual) {
  27960. dom.addClass(elm, cls);
  27961. } else {
  27962. dom.removeClass(elm, cls);
  27963. }
  27964. }
  27965. return;
  27966. }
  27967. });
  27968. self.fire('VisualAid', {
  27969. element: elm,
  27970. hasVisual: self.hasVisual
  27971. });
  27972. };
  27973. Editor.prototype.remove = function () {
  27974. remove$7(this);
  27975. };
  27976. Editor.prototype.destroy = function (automatic) {
  27977. destroy(this, automatic);
  27978. };
  27979. Editor.prototype.uploadImages = function (callback) {
  27980. return this.editorUpload.uploadImages(callback);
  27981. };
  27982. Editor.prototype._scanForImages = function () {
  27983. return this.editorUpload.scanForImages();
  27984. };
  27985. Editor.prototype.addButton = function () {
  27986. throw new Error('editor.addButton has been removed in tinymce 5x, use editor.ui.registry.addButton or editor.ui.registry.addToggleButton or editor.ui.registry.addSplitButton instead');
  27987. };
  27988. Editor.prototype.addSidebar = function () {
  27989. throw new Error('editor.addSidebar has been removed in tinymce 5x, use editor.ui.registry.addSidebar instead');
  27990. };
  27991. Editor.prototype.addMenuItem = function () {
  27992. throw new Error('editor.addMenuItem has been removed in tinymce 5x, use editor.ui.registry.addMenuItem instead');
  27993. };
  27994. Editor.prototype.addContextToolbar = function () {
  27995. throw new Error('editor.addContextToolbar has been removed in tinymce 5x, use editor.ui.registry.addContextToolbar instead');
  27996. };
  27997. return Editor;
  27998. }();
  27999. var DOM$a = DOMUtils$1.DOM;
  28000. var explode$4 = Tools.explode, each$j = Tools.each, extend$4 = Tools.extend;
  28001. var instanceCounter = 0, boundGlobalEvents = false;
  28002. var beforeUnloadDelegate;
  28003. var legacyEditors = [];
  28004. var editors = [];
  28005. var isValidLegacyKey = function (id) {
  28006. return id !== 'length';
  28007. };
  28008. var globalEventDelegate = function (e) {
  28009. var type = e.type;
  28010. each$j(EditorManager.get(), function (editor) {
  28011. switch (type) {
  28012. case 'scroll':
  28013. editor.fire('ScrollWindow', e);
  28014. break;
  28015. case 'resize':
  28016. editor.fire('ResizeWindow', e);
  28017. break;
  28018. }
  28019. });
  28020. };
  28021. var toggleGlobalEvents = function (state) {
  28022. if (state !== boundGlobalEvents) {
  28023. if (state) {
  28024. DomQuery(window).on('resize scroll', globalEventDelegate);
  28025. } else {
  28026. DomQuery(window).off('resize scroll', globalEventDelegate);
  28027. }
  28028. boundGlobalEvents = state;
  28029. }
  28030. };
  28031. var removeEditorFromList = function (targetEditor) {
  28032. var oldEditors = editors;
  28033. delete legacyEditors[targetEditor.id];
  28034. for (var i = 0; i < legacyEditors.length; i++) {
  28035. if (legacyEditors[i] === targetEditor) {
  28036. legacyEditors.splice(i, 1);
  28037. break;
  28038. }
  28039. }
  28040. editors = filter(editors, function (editor) {
  28041. return targetEditor !== editor;
  28042. });
  28043. if (EditorManager.activeEditor === targetEditor) {
  28044. EditorManager.activeEditor = editors.length > 0 ? editors[0] : null;
  28045. }
  28046. if (EditorManager.focusedEditor === targetEditor) {
  28047. EditorManager.focusedEditor = null;
  28048. }
  28049. return oldEditors.length !== editors.length;
  28050. };
  28051. var purgeDestroyedEditor = function (editor) {
  28052. if (editor && editor.initialized && !(editor.getContainer() || editor.getBody()).parentNode) {
  28053. removeEditorFromList(editor);
  28054. editor.unbindAllNativeEvents();
  28055. editor.destroy(true);
  28056. editor.removed = true;
  28057. editor = null;
  28058. }
  28059. return editor;
  28060. };
  28061. var isQuirksMode = document.compatMode !== 'CSS1Compat';
  28062. var EditorManager = __assign(__assign({}, Observable), {
  28063. baseURI: null,
  28064. baseURL: null,
  28065. defaultSettings: {},
  28066. documentBaseURL: null,
  28067. suffix: null,
  28068. $: DomQuery,
  28069. majorVersion: '5',
  28070. minorVersion: '5.1',
  28071. releaseDate: '2020-10-01',
  28072. editors: legacyEditors,
  28073. i18n: I18n,
  28074. activeEditor: null,
  28075. focusedEditor: null,
  28076. settings: {},
  28077. setup: function () {
  28078. var self = this;
  28079. var baseURL, documentBaseURL, suffix = '';
  28080. documentBaseURL = URI.getDocumentBaseUrl(document.location);
  28081. if (/^[^:]+:\/\/\/?[^\/]+\//.test(documentBaseURL)) {
  28082. documentBaseURL = documentBaseURL.replace(/[\?#].*$/, '').replace(/[\/\\][^\/]+$/, '');
  28083. if (!/[\/\\]$/.test(documentBaseURL)) {
  28084. documentBaseURL += '/';
  28085. }
  28086. }
  28087. var preInit = window.tinymce || window.tinyMCEPreInit;
  28088. if (preInit) {
  28089. baseURL = preInit.base || preInit.baseURL;
  28090. suffix = preInit.suffix;
  28091. } else {
  28092. var scripts = document.getElementsByTagName('script');
  28093. for (var i = 0; i < scripts.length; i++) {
  28094. var src = scripts[i].src || '';
  28095. if (src === '') {
  28096. continue;
  28097. }
  28098. var srcScript = src.substring(src.lastIndexOf('/'));
  28099. if (/tinymce(\.full|\.jquery|)(\.min|\.dev|)\.js/.test(src)) {
  28100. if (srcScript.indexOf('.min') !== -1) {
  28101. suffix = '.min';
  28102. }
  28103. baseURL = src.substring(0, src.lastIndexOf('/'));
  28104. break;
  28105. }
  28106. }
  28107. if (!baseURL && document.currentScript) {
  28108. var src = document.currentScript.src;
  28109. if (src.indexOf('.min') !== -1) {
  28110. suffix = '.min';
  28111. }
  28112. baseURL = src.substring(0, src.lastIndexOf('/'));
  28113. }
  28114. }
  28115. self.baseURL = new URI(documentBaseURL).toAbsolute(baseURL);
  28116. self.documentBaseURL = documentBaseURL;
  28117. self.baseURI = new URI(self.baseURL);
  28118. self.suffix = suffix;
  28119. setup$2(self);
  28120. },
  28121. overrideDefaults: function (defaultSettings) {
  28122. var baseUrl = defaultSettings.base_url;
  28123. if (baseUrl) {
  28124. this._setBaseUrl(baseUrl);
  28125. }
  28126. var suffix = defaultSettings.suffix;
  28127. if (defaultSettings.suffix) {
  28128. this.suffix = suffix;
  28129. }
  28130. this.defaultSettings = defaultSettings;
  28131. var pluginBaseUrls = defaultSettings.plugin_base_urls;
  28132. if (pluginBaseUrls !== undefined) {
  28133. each$1(pluginBaseUrls, function (pluginBaseUrl, pluginName) {
  28134. AddOnManager$1.PluginManager.urls[pluginName] = pluginBaseUrl;
  28135. });
  28136. }
  28137. },
  28138. init: function (settings) {
  28139. var self = this;
  28140. var result;
  28141. var invalidInlineTargets = Tools.makeMap('area base basefont br col frame hr img input isindex link meta param embed source wbr track ' + 'colgroup option table tbody tfoot thead tr th td script noscript style textarea video audio iframe object menu', ' ');
  28142. var isInvalidInlineTarget = function (settings, elm) {
  28143. return settings.inline && elm.tagName.toLowerCase() in invalidInlineTargets;
  28144. };
  28145. var createId = function (elm) {
  28146. var id = elm.id;
  28147. if (!id) {
  28148. id = get(elm, 'name').filter(function (name) {
  28149. return !DOM$a.get(name);
  28150. }).getOrThunk(DOM$a.uniqueId);
  28151. elm.setAttribute('id', id);
  28152. }
  28153. return id;
  28154. };
  28155. var execCallback = function (name) {
  28156. var callback = settings[name];
  28157. if (!callback) {
  28158. return;
  28159. }
  28160. return callback.apply(self, Array.prototype.slice.call(arguments, 2));
  28161. };
  28162. var hasClass = function (elm, className) {
  28163. return className.constructor === RegExp ? className.test(elm.className) : DOM$a.hasClass(elm, className);
  28164. };
  28165. var findTargets = function (settings) {
  28166. var targets = [];
  28167. if (Env.browser.isIE() && Env.browser.version.major < 11) {
  28168. initError('TinyMCE does not support the browser you are using. For a list of supported' + ' browsers please see: https://www.tinymce.com/docs/get-started/system-requirements/');
  28169. return [];
  28170. } else if (isQuirksMode) {
  28171. initError('Failed to initialize the editor as the document is not in standards mode. ' + 'TinyMCE requires standards mode.');
  28172. return [];
  28173. }
  28174. if (settings.types) {
  28175. each$j(settings.types, function (type) {
  28176. targets = targets.concat(DOM$a.select(type.selector));
  28177. });
  28178. return targets;
  28179. } else if (settings.selector) {
  28180. return DOM$a.select(settings.selector);
  28181. } else if (settings.target) {
  28182. return [settings.target];
  28183. }
  28184. switch (settings.mode) {
  28185. case 'exact':
  28186. var l = settings.elements || '';
  28187. if (l.length > 0) {
  28188. each$j(explode$4(l), function (id) {
  28189. var elm = DOM$a.get(id);
  28190. if (elm) {
  28191. targets.push(elm);
  28192. } else {
  28193. each$j(document.forms, function (f) {
  28194. each$j(f.elements, function (e) {
  28195. if (e.name === id) {
  28196. id = 'mce_editor_' + instanceCounter++;
  28197. DOM$a.setAttrib(e, 'id', id);
  28198. targets.push(e);
  28199. }
  28200. });
  28201. });
  28202. }
  28203. });
  28204. }
  28205. break;
  28206. case 'textareas':
  28207. case 'specific_textareas':
  28208. each$j(DOM$a.select('textarea'), function (elm) {
  28209. if (settings.editor_deselector && hasClass(elm, settings.editor_deselector)) {
  28210. return;
  28211. }
  28212. if (!settings.editor_selector || hasClass(elm, settings.editor_selector)) {
  28213. targets.push(elm);
  28214. }
  28215. });
  28216. break;
  28217. }
  28218. return targets;
  28219. };
  28220. var provideResults = function (editors) {
  28221. result = editors;
  28222. };
  28223. var initEditors = function () {
  28224. var initCount = 0;
  28225. var editors = [];
  28226. var targets;
  28227. var createEditor = function (id, settings, targetElm) {
  28228. var editor = new Editor(id, settings, self);
  28229. editors.push(editor);
  28230. editor.on('init', function () {
  28231. if (++initCount === targets.length) {
  28232. provideResults(editors);
  28233. }
  28234. });
  28235. editor.targetElm = editor.targetElm || targetElm;
  28236. editor.render();
  28237. };
  28238. DOM$a.unbind(window, 'ready', initEditors);
  28239. execCallback('onpageload');
  28240. targets = DomQuery.unique(findTargets(settings));
  28241. if (settings.types) {
  28242. each$j(settings.types, function (type) {
  28243. Tools.each(targets, function (elm) {
  28244. if (DOM$a.is(elm, type.selector)) {
  28245. createEditor(createId(elm), extend$4({}, settings, type), elm);
  28246. return false;
  28247. }
  28248. return true;
  28249. });
  28250. });
  28251. return;
  28252. }
  28253. Tools.each(targets, function (elm) {
  28254. purgeDestroyedEditor(self.get(elm.id));
  28255. });
  28256. targets = Tools.grep(targets, function (elm) {
  28257. return !self.get(elm.id);
  28258. });
  28259. if (targets.length === 0) {
  28260. provideResults([]);
  28261. } else {
  28262. each$j(targets, function (elm) {
  28263. if (isInvalidInlineTarget(settings, elm)) {
  28264. initError('Could not initialize inline editor on invalid inline target element', elm);
  28265. } else {
  28266. createEditor(createId(elm), settings, elm);
  28267. }
  28268. });
  28269. }
  28270. };
  28271. self.settings = settings;
  28272. DOM$a.bind(window, 'ready', initEditors);
  28273. return new promiseObj(function (resolve) {
  28274. if (result) {
  28275. resolve(result);
  28276. } else {
  28277. provideResults = function (editors) {
  28278. resolve(editors);
  28279. };
  28280. }
  28281. });
  28282. },
  28283. get: function (id) {
  28284. if (arguments.length === 0) {
  28285. return editors.slice(0);
  28286. } else if (isString(id)) {
  28287. return find(editors, function (editor) {
  28288. return editor.id === id;
  28289. }).getOr(null);
  28290. } else if (isNumber(id)) {
  28291. return editors[id] ? editors[id] : null;
  28292. } else {
  28293. return null;
  28294. }
  28295. },
  28296. add: function (editor) {
  28297. var self = this;
  28298. var existingEditor = legacyEditors[editor.id];
  28299. if (existingEditor === editor) {
  28300. return editor;
  28301. }
  28302. if (self.get(editor.id) === null) {
  28303. if (isValidLegacyKey(editor.id)) {
  28304. legacyEditors[editor.id] = editor;
  28305. }
  28306. legacyEditors.push(editor);
  28307. editors.push(editor);
  28308. }
  28309. toggleGlobalEvents(true);
  28310. self.activeEditor = editor;
  28311. self.fire('AddEditor', { editor: editor });
  28312. if (!beforeUnloadDelegate) {
  28313. beforeUnloadDelegate = function (e) {
  28314. var event = self.fire('BeforeUnload');
  28315. if (event.returnValue) {
  28316. e.preventDefault();
  28317. e.returnValue = event.returnValue;
  28318. return event.returnValue;
  28319. }
  28320. };
  28321. window.addEventListener('beforeunload', beforeUnloadDelegate);
  28322. }
  28323. return editor;
  28324. },
  28325. createEditor: function (id, settings) {
  28326. return this.add(new Editor(id, settings, this));
  28327. },
  28328. remove: function (selector) {
  28329. var self = this;
  28330. var i, editor;
  28331. if (!selector) {
  28332. for (i = editors.length - 1; i >= 0; i--) {
  28333. self.remove(editors[i]);
  28334. }
  28335. return;
  28336. }
  28337. if (isString(selector)) {
  28338. each$j(DOM$a.select(selector), function (elm) {
  28339. editor = self.get(elm.id);
  28340. if (editor) {
  28341. self.remove(editor);
  28342. }
  28343. });
  28344. return;
  28345. }
  28346. editor = selector;
  28347. if (isNull(self.get(editor.id))) {
  28348. return null;
  28349. }
  28350. if (removeEditorFromList(editor)) {
  28351. self.fire('RemoveEditor', { editor: editor });
  28352. }
  28353. if (editors.length === 0) {
  28354. window.removeEventListener('beforeunload', beforeUnloadDelegate);
  28355. }
  28356. editor.remove();
  28357. toggleGlobalEvents(editors.length > 0);
  28358. return editor;
  28359. },
  28360. execCommand: function (cmd, ui, value) {
  28361. var self = this, editor = self.get(value);
  28362. switch (cmd) {
  28363. case 'mceAddEditor':
  28364. if (!self.get(value)) {
  28365. new Editor(value, self.settings, self).render();
  28366. }
  28367. return true;
  28368. case 'mceRemoveEditor':
  28369. if (editor) {
  28370. editor.remove();
  28371. }
  28372. return true;
  28373. case 'mceToggleEditor':
  28374. if (!editor) {
  28375. self.execCommand('mceAddEditor', 0, value);
  28376. return true;
  28377. }
  28378. if (editor.isHidden()) {
  28379. editor.show();
  28380. } else {
  28381. editor.hide();
  28382. }
  28383. return true;
  28384. }
  28385. if (self.activeEditor) {
  28386. return self.activeEditor.execCommand(cmd, ui, value);
  28387. }
  28388. return false;
  28389. },
  28390. triggerSave: function () {
  28391. each$j(editors, function (editor) {
  28392. editor.save();
  28393. });
  28394. },
  28395. addI18n: function (code, items) {
  28396. I18n.add(code, items);
  28397. },
  28398. translate: function (text) {
  28399. return I18n.translate(text);
  28400. },
  28401. setActive: function (editor) {
  28402. var activeEditor = this.activeEditor;
  28403. if (this.activeEditor !== editor) {
  28404. if (activeEditor) {
  28405. activeEditor.fire('deactivate', { relatedTarget: editor });
  28406. }
  28407. editor.fire('activate', { relatedTarget: activeEditor });
  28408. }
  28409. this.activeEditor = editor;
  28410. },
  28411. _setBaseUrl: function (baseUrl) {
  28412. this.baseURL = new URI(this.documentBaseURL).toAbsolute(baseUrl.replace(/\/+$/, ''));
  28413. this.baseURI = new URI(this.baseURL);
  28414. }
  28415. });
  28416. EditorManager.setup();
  28417. var min = Math.min, max = Math.max, round$1 = Math.round;
  28418. var relativePosition = function (rect, targetRect, rel) {
  28419. var x = targetRect.x;
  28420. var y = targetRect.y;
  28421. var w = rect.w;
  28422. var h = rect.h;
  28423. var targetW = targetRect.w;
  28424. var targetH = targetRect.h;
  28425. var relChars = (rel || '').split('');
  28426. if (relChars[0] === 'b') {
  28427. y += targetH;
  28428. }
  28429. if (relChars[1] === 'r') {
  28430. x += targetW;
  28431. }
  28432. if (relChars[0] === 'c') {
  28433. y += round$1(targetH / 2);
  28434. }
  28435. if (relChars[1] === 'c') {
  28436. x += round$1(targetW / 2);
  28437. }
  28438. if (relChars[3] === 'b') {
  28439. y -= h;
  28440. }
  28441. if (relChars[4] === 'r') {
  28442. x -= w;
  28443. }
  28444. if (relChars[3] === 'c') {
  28445. y -= round$1(h / 2);
  28446. }
  28447. if (relChars[4] === 'c') {
  28448. x -= round$1(w / 2);
  28449. }
  28450. return create$7(x, y, w, h);
  28451. };
  28452. var findBestRelativePosition = function (rect, targetRect, constrainRect, rels) {
  28453. var pos, i;
  28454. for (i = 0; i < rels.length; i++) {
  28455. pos = relativePosition(rect, targetRect, rels[i]);
  28456. if (pos.x >= constrainRect.x && pos.x + pos.w <= constrainRect.w + constrainRect.x && pos.y >= constrainRect.y && pos.y + pos.h <= constrainRect.h + constrainRect.y) {
  28457. return rels[i];
  28458. }
  28459. }
  28460. return null;
  28461. };
  28462. var inflate = function (rect, w, h) {
  28463. return create$7(rect.x - w, rect.y - h, rect.w + w * 2, rect.h + h * 2);
  28464. };
  28465. var intersect = function (rect, cropRect) {
  28466. var x1 = max(rect.x, cropRect.x);
  28467. var y1 = max(rect.y, cropRect.y);
  28468. var x2 = min(rect.x + rect.w, cropRect.x + cropRect.w);
  28469. var y2 = min(rect.y + rect.h, cropRect.y + cropRect.h);
  28470. if (x2 - x1 < 0 || y2 - y1 < 0) {
  28471. return null;
  28472. }
  28473. return create$7(x1, y1, x2 - x1, y2 - y1);
  28474. };
  28475. var clamp$1 = function (rect, clampRect, fixedSize) {
  28476. var x1 = rect.x;
  28477. var y1 = rect.y;
  28478. var x2 = rect.x + rect.w;
  28479. var y2 = rect.y + rect.h;
  28480. var cx2 = clampRect.x + clampRect.w;
  28481. var cy2 = clampRect.y + clampRect.h;
  28482. var underflowX1 = max(0, clampRect.x - x1);
  28483. var underflowY1 = max(0, clampRect.y - y1);
  28484. var overflowX2 = max(0, x2 - cx2);
  28485. var overflowY2 = max(0, y2 - cy2);
  28486. x1 += underflowX1;
  28487. y1 += underflowY1;
  28488. if (fixedSize) {
  28489. x2 += underflowX1;
  28490. y2 += underflowY1;
  28491. x1 -= overflowX2;
  28492. y1 -= overflowY2;
  28493. }
  28494. x2 -= overflowX2;
  28495. y2 -= overflowY2;
  28496. return create$7(x1, y1, x2 - x1, y2 - y1);
  28497. };
  28498. var create$7 = function (x, y, w, h) {
  28499. return {
  28500. x: x,
  28501. y: y,
  28502. w: w,
  28503. h: h
  28504. };
  28505. };
  28506. var fromClientRect = function (clientRect) {
  28507. return create$7(clientRect.left, clientRect.top, clientRect.width, clientRect.height);
  28508. };
  28509. var Rect = {
  28510. inflate: inflate,
  28511. relativePosition: relativePosition,
  28512. findBestRelativePosition: findBestRelativePosition,
  28513. intersect: intersect,
  28514. clamp: clamp$1,
  28515. create: create$7,
  28516. fromClientRect: fromClientRect
  28517. };
  28518. var awaiter = function (resolveCb, rejectCb, timeout) {
  28519. if (timeout === void 0) {
  28520. timeout = 1000;
  28521. }
  28522. var done = false;
  28523. var timer = null;
  28524. var complete = function (completer) {
  28525. return function () {
  28526. var args = [];
  28527. for (var _i = 0; _i < arguments.length; _i++) {
  28528. args[_i] = arguments[_i];
  28529. }
  28530. if (!done) {
  28531. done = true;
  28532. if (timer !== null) {
  28533. clearTimeout(timer);
  28534. timer = null;
  28535. }
  28536. completer.apply(null, args);
  28537. }
  28538. };
  28539. };
  28540. var resolve = complete(resolveCb);
  28541. var reject = complete(rejectCb);
  28542. var start = function () {
  28543. var args = [];
  28544. for (var _i = 0; _i < arguments.length; _i++) {
  28545. args[_i] = arguments[_i];
  28546. }
  28547. if (!done && timer === null) {
  28548. timer = setTimeout(function () {
  28549. return reject.apply(null, args);
  28550. }, timeout);
  28551. }
  28552. };
  28553. return {
  28554. start: start,
  28555. resolve: resolve,
  28556. reject: reject
  28557. };
  28558. };
  28559. var create$8 = function () {
  28560. var tasks = {};
  28561. var resultFns = {};
  28562. var load = function (id, url) {
  28563. var loadErrMsg = 'Script at URL "' + url + '" failed to load';
  28564. var runErrMsg = 'Script at URL "' + url + '" did not call `tinymce.Resource.add(\'' + id + '\', data)` within 1 second';
  28565. if (tasks[id] !== undefined) {
  28566. return tasks[id];
  28567. } else {
  28568. var task = new promiseObj(function (resolve, reject) {
  28569. var waiter = awaiter(resolve, reject);
  28570. resultFns[id] = waiter.resolve;
  28571. ScriptLoader.ScriptLoader.loadScript(url, function () {
  28572. return waiter.start(runErrMsg);
  28573. }, function () {
  28574. return waiter.reject(loadErrMsg);
  28575. });
  28576. });
  28577. tasks[id] = task;
  28578. return task;
  28579. }
  28580. };
  28581. var add = function (id, data) {
  28582. if (resultFns[id] !== undefined) {
  28583. resultFns[id](data);
  28584. delete resultFns[id];
  28585. }
  28586. tasks[id] = promiseObj.resolve(data);
  28587. };
  28588. return {
  28589. load: load,
  28590. add: add
  28591. };
  28592. };
  28593. var Resource = create$8();
  28594. var each$k = Tools.each, extend$5 = Tools.extend;
  28595. var extendClass, initializing;
  28596. var Class = function () {
  28597. };
  28598. Class.extend = extendClass = function (props) {
  28599. var self = this;
  28600. var _super = self.prototype;
  28601. var Class = function () {
  28602. var i, mixins, mixin;
  28603. var self = this;
  28604. if (!initializing) {
  28605. if (self.init) {
  28606. self.init.apply(self, arguments);
  28607. }
  28608. mixins = self.Mixins;
  28609. if (mixins) {
  28610. i = mixins.length;
  28611. while (i--) {
  28612. mixin = mixins[i];
  28613. if (mixin.init) {
  28614. mixin.init.apply(self, arguments);
  28615. }
  28616. }
  28617. }
  28618. }
  28619. };
  28620. var dummy = function () {
  28621. return this;
  28622. };
  28623. var createMethod = function (name, fn) {
  28624. return function () {
  28625. var self = this;
  28626. var tmp = self._super;
  28627. self._super = _super[name];
  28628. var ret = fn.apply(self, arguments);
  28629. self._super = tmp;
  28630. return ret;
  28631. };
  28632. };
  28633. initializing = true;
  28634. var prototype = new self();
  28635. initializing = false;
  28636. if (props.Mixins) {
  28637. each$k(props.Mixins, function (mixin) {
  28638. for (var name_1 in mixin) {
  28639. if (name_1 !== 'init') {
  28640. props[name_1] = mixin[name_1];
  28641. }
  28642. }
  28643. });
  28644. if (_super.Mixins) {
  28645. props.Mixins = _super.Mixins.concat(props.Mixins);
  28646. }
  28647. }
  28648. if (props.Methods) {
  28649. each$k(props.Methods.split(','), function (name) {
  28650. props[name] = dummy;
  28651. });
  28652. }
  28653. if (props.Properties) {
  28654. each$k(props.Properties.split(','), function (name) {
  28655. var fieldName = '_' + name;
  28656. props[name] = function (value) {
  28657. var self = this;
  28658. if (value !== undefined) {
  28659. self[fieldName] = value;
  28660. return self;
  28661. }
  28662. return self[fieldName];
  28663. };
  28664. });
  28665. }
  28666. if (props.Statics) {
  28667. each$k(props.Statics, function (func, name) {
  28668. Class[name] = func;
  28669. });
  28670. }
  28671. if (props.Defaults && _super.Defaults) {
  28672. props.Defaults = extend$5({}, _super.Defaults, props.Defaults);
  28673. }
  28674. each$1(props, function (member, name) {
  28675. if (typeof member === 'function' && _super[name]) {
  28676. prototype[name] = createMethod(name, member);
  28677. } else {
  28678. prototype[name] = member;
  28679. }
  28680. });
  28681. Class.prototype = prototype;
  28682. Class.constructor = Class;
  28683. Class.extend = extendClass;
  28684. return Class;
  28685. };
  28686. var min$1 = Math.min, max$1 = Math.max, round$2 = Math.round;
  28687. var Color = function (value) {
  28688. var self = {};
  28689. var r = 0, g = 0, b = 0;
  28690. var rgb2hsv = function (r, g, b) {
  28691. var h, s, v;
  28692. h = 0;
  28693. s = 0;
  28694. v = 0;
  28695. r = r / 255;
  28696. g = g / 255;
  28697. b = b / 255;
  28698. var minRGB = min$1(r, min$1(g, b));
  28699. var maxRGB = max$1(r, max$1(g, b));
  28700. if (minRGB === maxRGB) {
  28701. v = minRGB;
  28702. return {
  28703. h: 0,
  28704. s: 0,
  28705. v: v * 100
  28706. };
  28707. }
  28708. var d = r === minRGB ? g - b : b === minRGB ? r - g : b - r;
  28709. h = r === minRGB ? 3 : b === minRGB ? 1 : 5;
  28710. h = 60 * (h - d / (maxRGB - minRGB));
  28711. s = (maxRGB - minRGB) / maxRGB;
  28712. v = maxRGB;
  28713. return {
  28714. h: round$2(h),
  28715. s: round$2(s * 100),
  28716. v: round$2(v * 100)
  28717. };
  28718. };
  28719. var hsvToRgb = function (hue, saturation, brightness) {
  28720. hue = (parseInt(hue, 10) || 0) % 360;
  28721. saturation = parseInt(saturation, 10) / 100;
  28722. brightness = parseInt(brightness, 10) / 100;
  28723. saturation = max$1(0, min$1(saturation, 1));
  28724. brightness = max$1(0, min$1(brightness, 1));
  28725. if (saturation === 0) {
  28726. r = g = b = round$2(255 * brightness);
  28727. return;
  28728. }
  28729. var side = hue / 60;
  28730. var chroma = brightness * saturation;
  28731. var x = chroma * (1 - Math.abs(side % 2 - 1));
  28732. var match = brightness - chroma;
  28733. switch (Math.floor(side)) {
  28734. case 0:
  28735. r = chroma;
  28736. g = x;
  28737. b = 0;
  28738. break;
  28739. case 1:
  28740. r = x;
  28741. g = chroma;
  28742. b = 0;
  28743. break;
  28744. case 2:
  28745. r = 0;
  28746. g = chroma;
  28747. b = x;
  28748. break;
  28749. case 3:
  28750. r = 0;
  28751. g = x;
  28752. b = chroma;
  28753. break;
  28754. case 4:
  28755. r = x;
  28756. g = 0;
  28757. b = chroma;
  28758. break;
  28759. case 5:
  28760. r = chroma;
  28761. g = 0;
  28762. b = x;
  28763. break;
  28764. default:
  28765. r = g = b = 0;
  28766. }
  28767. r = round$2(255 * (r + match));
  28768. g = round$2(255 * (g + match));
  28769. b = round$2(255 * (b + match));
  28770. };
  28771. var toHex = function () {
  28772. var hex = function (val) {
  28773. val = parseInt(val, 10).toString(16);
  28774. return val.length > 1 ? val : '0' + val;
  28775. };
  28776. return '#' + hex(r) + hex(g) + hex(b);
  28777. };
  28778. var toRgb = function () {
  28779. return {
  28780. r: r,
  28781. g: g,
  28782. b: b
  28783. };
  28784. };
  28785. var toHsv = function () {
  28786. return rgb2hsv(r, g, b);
  28787. };
  28788. var parse = function (value) {
  28789. var matches;
  28790. if (typeof value === 'object') {
  28791. if ('r' in value) {
  28792. r = value.r;
  28793. g = value.g;
  28794. b = value.b;
  28795. } else if ('v' in value) {
  28796. hsvToRgb(value.h, value.s, value.v);
  28797. }
  28798. } else {
  28799. if (matches = /rgb\s*\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)[^\)]*\)/gi.exec(value)) {
  28800. r = parseInt(matches[1], 10);
  28801. g = parseInt(matches[2], 10);
  28802. b = parseInt(matches[3], 10);
  28803. } else if (matches = /#([0-F]{2})([0-F]{2})([0-F]{2})/gi.exec(value)) {
  28804. r = parseInt(matches[1], 16);
  28805. g = parseInt(matches[2], 16);
  28806. b = parseInt(matches[3], 16);
  28807. } else if (matches = /#([0-F])([0-F])([0-F])/gi.exec(value)) {
  28808. r = parseInt(matches[1] + matches[1], 16);
  28809. g = parseInt(matches[2] + matches[2], 16);
  28810. b = parseInt(matches[3] + matches[3], 16);
  28811. }
  28812. }
  28813. r = r < 0 ? 0 : r > 255 ? 255 : r;
  28814. g = g < 0 ? 0 : g > 255 ? 255 : g;
  28815. b = b < 0 ? 0 : b > 255 ? 255 : b;
  28816. return self;
  28817. };
  28818. if (value) {
  28819. parse(value);
  28820. }
  28821. self.toRgb = toRgb;
  28822. self.toHsv = toHsv;
  28823. self.toHex = toHex;
  28824. self.parse = parse;
  28825. return self;
  28826. };
  28827. var serialize = function (obj) {
  28828. var data = JSON.stringify(obj);
  28829. if (!isString(data)) {
  28830. return data;
  28831. }
  28832. return data.replace(/[\u0080-\uFFFF]/g, function (match) {
  28833. var hexCode = match.charCodeAt(0).toString(16);
  28834. return '\\u' + '0000'.substring(hexCode.length) + hexCode;
  28835. });
  28836. };
  28837. var JSONUtils = {
  28838. serialize: serialize,
  28839. parse: function (text) {
  28840. try {
  28841. return JSON.parse(text);
  28842. } catch (ex) {
  28843. }
  28844. }
  28845. };
  28846. var JSONP = {
  28847. callbacks: {},
  28848. count: 0,
  28849. send: function (settings) {
  28850. var self = this, dom = DOMUtils$1.DOM, count = settings.count !== undefined ? settings.count : self.count;
  28851. var id = 'tinymce_jsonp_' + count;
  28852. self.callbacks[count] = function (json) {
  28853. dom.remove(id);
  28854. delete self.callbacks[count];
  28855. settings.callback(json);
  28856. };
  28857. dom.add(dom.doc.body, 'script', {
  28858. id: id,
  28859. src: settings.url,
  28860. type: 'text/javascript'
  28861. });
  28862. self.count++;
  28863. }
  28864. };
  28865. var XHR = __assign(__assign({}, Observable), {
  28866. send: function (settings) {
  28867. var xhr, count = 0;
  28868. var ready = function () {
  28869. if (!settings.async || xhr.readyState === 4 || count++ > 10000) {
  28870. if (settings.success && count < 10000 && xhr.status === 200) {
  28871. settings.success.call(settings.success_scope, '' + xhr.responseText, xhr, settings);
  28872. } else if (settings.error) {
  28873. settings.error.call(settings.error_scope, count > 10000 ? 'TIMED_OUT' : 'GENERAL', xhr, settings);
  28874. }
  28875. xhr = null;
  28876. } else {
  28877. Delay.setTimeout(ready, 10);
  28878. }
  28879. };
  28880. settings.scope = settings.scope || this;
  28881. settings.success_scope = settings.success_scope || settings.scope;
  28882. settings.error_scope = settings.error_scope || settings.scope;
  28883. settings.async = settings.async !== false;
  28884. settings.data = settings.data || '';
  28885. XHR.fire('beforeInitialize', { settings: settings });
  28886. xhr = new XMLHttpRequest();
  28887. if (xhr.overrideMimeType) {
  28888. xhr.overrideMimeType(settings.content_type);
  28889. }
  28890. xhr.open(settings.type || (settings.data ? 'POST' : 'GET'), settings.url, settings.async);
  28891. if (settings.crossDomain) {
  28892. xhr.withCredentials = true;
  28893. }
  28894. if (settings.content_type) {
  28895. xhr.setRequestHeader('Content-Type', settings.content_type);
  28896. }
  28897. if (settings.requestheaders) {
  28898. Tools.each(settings.requestheaders, function (header) {
  28899. xhr.setRequestHeader(header.key, header.value);
  28900. });
  28901. }
  28902. xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
  28903. xhr = XHR.fire('beforeSend', {
  28904. xhr: xhr,
  28905. settings: settings
  28906. }).xhr;
  28907. xhr.send(settings.data);
  28908. if (!settings.async) {
  28909. return ready();
  28910. }
  28911. Delay.setTimeout(ready, 10);
  28912. }
  28913. });
  28914. var extend$6 = Tools.extend;
  28915. var JSONRequest = function () {
  28916. function JSONRequest(settings) {
  28917. this.settings = extend$6({}, settings);
  28918. this.count = 0;
  28919. }
  28920. JSONRequest.sendRPC = function (o) {
  28921. return new JSONRequest().send(o);
  28922. };
  28923. JSONRequest.prototype.send = function (args) {
  28924. var ecb = args.error, scb = args.success;
  28925. var xhrArgs = extend$6(this.settings, args);
  28926. xhrArgs.success = function (c, x) {
  28927. c = JSONUtils.parse(c);
  28928. if (typeof c === 'undefined') {
  28929. c = { error: 'JSON Parse error.' };
  28930. }
  28931. if (c.error) {
  28932. ecb.call(xhrArgs.error_scope || xhrArgs.scope, c.error, x);
  28933. } else {
  28934. scb.call(xhrArgs.success_scope || xhrArgs.scope, c.result);
  28935. }
  28936. };
  28937. xhrArgs.error = function (ty, x) {
  28938. if (ecb) {
  28939. ecb.call(xhrArgs.error_scope || xhrArgs.scope, ty, x);
  28940. }
  28941. };
  28942. xhrArgs.data = JSONUtils.serialize({
  28943. id: args.id || 'c' + this.count++,
  28944. method: args.method,
  28945. params: args.params
  28946. });
  28947. xhrArgs.content_type = 'application/json';
  28948. XHR.send(xhrArgs);
  28949. };
  28950. return JSONRequest;
  28951. }();
  28952. var create$9 = function () {
  28953. return function () {
  28954. var data = {};
  28955. var keys = [];
  28956. var storage = {
  28957. getItem: function (key) {
  28958. var item = data[key];
  28959. return item ? item : null;
  28960. },
  28961. setItem: function (key, value) {
  28962. keys.push(key);
  28963. data[key] = String(value);
  28964. },
  28965. key: function (index) {
  28966. return keys[index];
  28967. },
  28968. removeItem: function (key) {
  28969. keys = keys.filter(function (k) {
  28970. return k === key;
  28971. });
  28972. delete data[key];
  28973. },
  28974. clear: function () {
  28975. keys = [];
  28976. data = {};
  28977. },
  28978. length: 0
  28979. };
  28980. Object.defineProperty(storage, 'length', {
  28981. get: function () {
  28982. return keys.length;
  28983. },
  28984. configurable: false,
  28985. enumerable: false
  28986. });
  28987. return storage;
  28988. }();
  28989. };
  28990. var localStorage;
  28991. try {
  28992. var test = '__storage_test__';
  28993. localStorage = window.localStorage;
  28994. localStorage.setItem(test, test);
  28995. localStorage.removeItem(test);
  28996. } catch (e) {
  28997. localStorage = create$9();
  28998. }
  28999. var LocalStorage = localStorage;
  29000. var publicApi = {
  29001. geom: { Rect: Rect },
  29002. util: {
  29003. Promise: promiseObj,
  29004. Delay: Delay,
  29005. Tools: Tools,
  29006. VK: VK,
  29007. URI: URI,
  29008. Class: Class,
  29009. EventDispatcher: EventDispatcher,
  29010. Observable: Observable,
  29011. I18n: I18n,
  29012. XHR: XHR,
  29013. JSON: JSONUtils,
  29014. JSONRequest: JSONRequest,
  29015. JSONP: JSONP,
  29016. LocalStorage: LocalStorage,
  29017. Color: Color
  29018. },
  29019. dom: {
  29020. EventUtils: EventUtils,
  29021. Sizzle: Sizzle,
  29022. DomQuery: DomQuery,
  29023. TreeWalker: DomTreeWalker,
  29024. TextSeeker: TextSeeker,
  29025. DOMUtils: DOMUtils$1,
  29026. ScriptLoader: ScriptLoader,
  29027. RangeUtils: RangeUtils$1,
  29028. Serializer: DomSerializer,
  29029. StyleSheetLoader: StyleSheetLoader,
  29030. ControlSelection: ControlSelection,
  29031. BookmarkManager: BookmarkManager$1,
  29032. Selection: EditorSelection,
  29033. Event: EventUtils.Event
  29034. },
  29035. html: {
  29036. Styles: Styles,
  29037. Entities: Entities,
  29038. Node: AstNode,
  29039. Schema: Schema,
  29040. SaxParser: SaxParser$1,
  29041. DomParser: DomParser,
  29042. Writer: Writer,
  29043. Serializer: HtmlSerializer
  29044. },
  29045. Env: Env,
  29046. AddOnManager: AddOnManager$1,
  29047. Annotator: Annotator,
  29048. Formatter: Formatter,
  29049. UndoManager: UndoManager,
  29050. EditorCommands: EditorCommands,
  29051. WindowManager: WindowManager,
  29052. NotificationManager: NotificationManager,
  29053. EditorObservable: EditorObservable,
  29054. Shortcuts: Shortcuts,
  29055. Editor: Editor,
  29056. FocusManager: FocusManager,
  29057. EditorManager: EditorManager,
  29058. DOM: DOMUtils$1.DOM,
  29059. ScriptLoader: ScriptLoader.ScriptLoader,
  29060. PluginManager: PluginManager,
  29061. ThemeManager: ThemeManager,
  29062. IconManager: IconManager,
  29063. Resource: Resource,
  29064. trim: Tools.trim,
  29065. isArray: Tools.isArray,
  29066. is: Tools.is,
  29067. toArray: Tools.toArray,
  29068. makeMap: Tools.makeMap,
  29069. each: Tools.each,
  29070. map: Tools.map,
  29071. grep: Tools.grep,
  29072. inArray: Tools.inArray,
  29073. extend: Tools.extend,
  29074. create: Tools.create,
  29075. walk: Tools.walk,
  29076. createNS: Tools.createNS,
  29077. resolve: Tools.resolve,
  29078. explode: Tools.explode,
  29079. _addCacheSuffix: Tools._addCacheSuffix,
  29080. isOpera: Env.opera,
  29081. isWebKit: Env.webkit,
  29082. isIE: Env.ie,
  29083. isGecko: Env.gecko,
  29084. isMac: Env.mac
  29085. };
  29086. var tinymce = Tools.extend(EditorManager, publicApi);
  29087. var exportToModuleLoaders = function (tinymce) {
  29088. if (typeof module === 'object') {
  29089. try {
  29090. module.exports = tinymce;
  29091. } catch (_) {
  29092. }
  29093. }
  29094. };
  29095. var exportToWindowGlobal = function (tinymce) {
  29096. window.tinymce = tinymce;
  29097. window.tinyMCE = tinymce;
  29098. };
  29099. exportToWindowGlobal(tinymce);
  29100. exportToModuleLoaders(tinymce);
  29101. }());